File: //usr/lib/python2.7/site-packages/lap/__init__.py
import os
import os.path
import sys
import time
import yaml
import json
import uuid
import syslog
import hashlib
import netifaces
from functools import wraps
from glob import glob as ls
from subprocess import Popen, PIPE
# Cache function
def cached(ttl=60):
cache_home = "/var/cache/locaweb-plugins"
def proxy(f):
@wraps(f)
def caching(*args, **kwargs):
# if len(args) > 0 and 'ttl' in args[0]:
# ttl = args[0].get('ttl')
_hash = os.path.join(cache_home, "%s-%s" % (f.__name__, hashlib.md5("%s%s" % (
repr(args),
repr(kwargs)
)).hexdigest()))
try:
cache = None
ttl = 60
if os.path.isfile(_hash) and ((os.stat(_hash).st_mtime + ttl) > time.time()):
cache = open(_hash).read()
if not cache:
cache = json.dumps(f(*args, **kwargs))
open(_hash, 'w').write(cache)
return json.loads(cache)
except Exception, e:
return f(*args, **kwargs)
return caching
return proxy
def load_plugins():
configdir = os.environ.get("LW_PLUGINS_CONFDIR", "/etc/locaweb/monitoring")
files = ls(os.path.join(configdir, '*.yaml'))
checks = []
for file in files:
data = yaml.load(open(file))
checks.extend([c for c in data.get("monitoring", []) if c.get("check", "") == "local"])
return checks
def call_event_handler(script, service, return_code):
if not os.path.isfile(script):
return "%s not found" % script
infos = Popen([script, service, return_code], shell=False, stdout=PIPE, stderr=PIPE)
return infos.stdout.read().strip()
@cached()
def execute_plugin_local(plugin):
if plugin.endswith(".sh"):
infos = Popen(['bash', plugin], shell=False, stdout=PIPE, stderr=PIPE)
else:
infos = Popen([plugin], shell=False, stdout=PIPE, stderr=PIPE)
return [line.strip() for line in infos.stdout.readlines()]
@cached()
def execute_plugin(check):
try:
if check.get('item') == 'lap':
item = check['plugin']
else:
item = check['item']
plugin = getattr(__import__('lap.%s' % item), item)
start = time.time()
info = plugin.__run__(check)
perfdata = None
if len(info) == 2:
return_code, status_message = info
else:
return_code, status_message, perfdata = info
# Eventhandler
if check.get("event_handler"):
status_message += ", Eventhandler: %s" % call_event_handler(check['event_handler'], check['service'], str(return_code))
end = time.time()
if perfdata:
return(return_code, check['service'], "total_time=%s|status=%s|%s" % ((end - start), return_code, perfdata), status_message)
else:
return(return_code, check['service'], "total_time=%s|status=%s" % ((end - start), return_code), status_message)
except Exception as e:
if 'service' in check:
return(2, check['service'], "total_time=0|status=2", "error: %s data: %s" % (e, json.dumps(check)))
else:
return(2, 'Invalid check %s' % uuid.uuid4(), "total_time=0|status=2", "error: %s data: %s" % (e, json.dumps(check)))
def check_ha(iface):
try:
netifaces.ifaddresses(iface)
return True
except Exception, e:
return False