Skip to content
Snippets Groups Projects
Commit 91829b8b authored by jurgenhaas's avatar jurgenhaas
Browse files

Get and set checks on uptime

parent 0f0c3846
No related branches found
No related tags found
No related merge requests found
import json
import requests
import tempfile
import yaml
import ConfigParser
from ansible.errors import AnsibleError as ae
from ansible.plugins.action import ActionBase
from ansible.utils.boolean import boolean
from requests.auth import HTTPBasicAuth
try:
from __main__ import display
......@@ -14,29 +17,18 @@ except ImportError:
class ActionModule(ActionBase):
'''Manage hosts and services monitored at uptime'''
#BYPASS_HOST_LOOP = True
BYPASS_HOST_LOOP = True
TRANSFERS_FILES = False
def __init__(self, task, connection, play_context, loader, templar,
shared_loader_obj):
super(ActionModule, self).__init__(task, connection, play_context,
loader, templar, shared_loader_obj)
self._supports_check_mode = False
self.args = {}
self.vars = {}
configPath = '/etc/uptime.cfg'
config = ConfigParser.ConfigParser()
config.read(configPath)
section = 'Credentials'
if config.has_option(section, 'url') and config.has_option(section, 'username') and config.has_option(section, 'password'):
self.url = config.get(section, 'url')
self.username = config.get(section, 'username')
self.password = config.get(section, 'password')
else:
raise ae('Can not find credentials')
self.checks = self._request('checks')
display.vv('Initialized')
self.pollerParams = ['http_options', 'match', 'tracker_source', 'tracker_username', 'tracker_password', 'tracker_project_include', 'tracker_project_exclude']
def run(self, tmp=None, task_vars=None):
......@@ -51,28 +43,65 @@ class ActionModule(ActionBase):
result['msg'] = 'check mode not supported for this module'
return result
print('RUN')
just_download = boolean(self._task.args.get('readonly'))
configPath = '/etc/uptime.cfg'
self.config = ConfigParser.ConfigParser()
self.config.read(configPath)
section = 'Credentials'
if self.config.has_option(section, 'url') and self.config.has_option(section, 'username') and self.config.has_option(section, 'password'):
self.url = self.config.get(section, 'url')
self.username = self.config.get(section, 'username')
self.password = self.config.get(section, 'password')
else:
raise ae('Can not find credentials')
display.vv('Load checks from Uptime')
self.checks = self._request('checks')
if just_download:
output = self._task.args.get('output', tempfile.mktemp(prefix='uptime_', suffix='.yml'))
with open(output, 'w') as output_file:
yaml.safe_dump(self.checks, output_file, encoding='utf-8', allow_unicode=True)
result['msg'] = 'Downloaded settings to %s' % output
result['changed'] = False
return result
if not self.config.has_section('Domains'):
raise ae('Can not find domain settings')
options = self.config.options('Domains')
display.vv('Process hosts')
for host in self.vars.get('ansible_play_hosts'):
display.vv('- ' + host)
self._host(host, options)
result['msg'] = 'Completed successfully!'
return result
def _request(self, path, data = None, method = 'GET'):
encoder = json.JSONEncoder()
encoder = json.JSONEncoder(encoding=None)
postData = {}
if data:
if method == 'GET':
method = 'POST'
for key in data:
item = data.get(key)
if type(item) is list or type(item) is dict:
if len(item) > 0 or key == 'recipients':
item = encoder.encode(item)
if type(item) is int or type(item) is unicode or type(item) is bool:
if type(item) is list:
item = ','.join(item)
if type(item) is dict:
item = encoder.encode(item)
if type(item) is int:
item = str(item)
if item and type(item) is str and len(item) > 0:
postData.__setitem__(key, item)
if type(item) is bool:
item = str(item).lower()
postData.__setitem__(key, unicode(item))
auth = HTTPBasicAuth(self.username, self.password)
......@@ -100,3 +129,125 @@ class ActionModule(ActionBase):
else:
content = decoder.decode(request_result.content)
return content
def _cleanupCheck(self, check):
check['interval'] = check['interval'] / 1000
return check
def _createCheck(self, check):
self._cleanupCheck(check)
self._request('checks', check, 'PUT')
def _updateCheck(self, existing, check):
changed = False
if 'pollerParams' not in existing:
existing['pollerParams'] = {}
for key, value in check.iteritems():
if key in self.pollerParams:
existing[key] = existing['pollerParams'].get(key, '')
if existing[key] is None:
existing[key] = ''
elif key not in existing:
existing[key] = None
if existing[key] != check[key]:
display.vv(' %s changed: "%s" vs "%s"' % (key, existing[key], check[key]))
existing[key] = check[key]
changed = True
if changed:
existing = self._cleanupCheck(existing)
self._request('checks/' + existing.get('_id'), existing, 'POST')
def _findExistingCheck(self, url):
for check in self.checks:
if (check.get('url') == url):
return check
return False
def _buildUrl(self, item, field):
url = item.get('protocol', 'https') + '://' + item.get(field)
uptime = item.get('uptime')
if uptime:
path = uptime.get('path')
if path:
url += '/' + path
return url
def _defaultCheck(self):
return {
'interval': 60000,
'maxTime': 1500,
'isPaused': False,
'alertTreshold': 5,
}
def _buildCheck(self, item, url):
check = self._defaultCheck()
check['url'] = url
check['type'] = item.get('protocol', 'https')
uptime = item.get('uptime')
if uptime:
for key in self._defaultCheck():
if key in uptime:
check[key] = uptime[key]
if 'name' in uptime:
check['name'] = uptime['name']
if 'tags' in uptime:
check['tags'] = uptime['tags']
if 'pollerParams' in uptime:
for param in self.pollerParams:
check[param] = uptime['pollerParams'].get(param, '')
if 'tags' not in check:
check['tags'] = ['none']
return check
def _host(self, host, options):
host_vars = self.vars['hostvars'][host]
for option in options:
display.vv(' - ' + option)
items = host_vars.get(option)
if items:
parts = self.config.get('Domains', option).split('.')
field = parts.pop()
self._part(items, 0, parts, field)
def _part(self, items, level, parts, field):
if len(parts) > level:
next = parts[level]
level += 1
display.vv(' ' + next)
for item in items:
nextitems = item.get(next)
if nextitems:
self._part(nextitems, level, parts, field)
else:
for item in items:
value = item.get(field)
if value:
display.vv(' ' + value)
self._processItem(item, field)
def _processItem(self, item, field):
url = self._buildUrl(item, field)
check = self._buildCheck(item, url)
existing = self._findExistingCheck(url)
if existing:
self._updateCheck(existing, check)
else:
self._createCheck(check)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment