Format Python code

This commit is contained in:
Scott Wallace 2020-10-24 09:39:25 +01:00
parent 8e71192d0f
commit 440e211723
2 changed files with 37 additions and 24 deletions

View file

@ -32,6 +32,7 @@ class HTTPHandler(SimpleHTTPRequestHandler):
""" """
Class to handle the HTTP requests from a client Class to handle the HTTP requests from a client
""" """
config = None config = None
def _alerts(self): def _alerts(self):
@ -53,14 +54,13 @@ class HTTPHandler(SimpleHTTPRequestHandler):
self._respond(400, f'Bad JSON: {error}') self._respond(400, f'Bad JSON: {error}')
return return
logging.debug('Received from Alertmanager:\n%s', logging.debug('Received from Alertmanager:\n%s', json.dumps(am_msg, indent=2))
json.dumps(am_msg, indent=2))
gotify_client = gotify.Gotify( gotify_client = gotify.Gotify(
self.config.get('gotify_server'), self.config.get('gotify_server'),
self.config.get('gotify_port'), self.config.get('gotify_port'),
self.config.get('gotify_key'), self.config.get('gotify_key'),
self.config.get('gotify_client') self.config.get('gotify_client'),
) )
for alert in am_msg['alerts']: for alert in am_msg['alerts']:
@ -69,7 +69,9 @@ class HTTPHandler(SimpleHTTPRequestHandler):
if self.config.get('disable_resolved'): if self.config.get('disable_resolved'):
logging.info('Ignoring resolved messages') logging.info('Ignoring resolved messages')
self._respond( self._respond(
200, 'Ignored. "resolved" messages are disabled') 200,
'Ignored. "resolved" messages are disabled',
)
continue continue
if self.config.get('delete_onresolve'): if self.config.get('delete_onresolve'):
@ -77,13 +79,11 @@ class HTTPHandler(SimpleHTTPRequestHandler):
if alert_id: if alert_id:
response = gotify_client.delete(alert_id) response = gotify_client.delete(alert_id)
continue continue
logging.debug( logging.debug('Could not find a matching message to delete.')
'Could not find a matching message to delete.')
prefix = 'Resolved' prefix = 'Resolved'
else: else:
prefix = alert['labels'].get( prefix = alert['labels'].get('severity', 'warning').capitalize()
'severity', 'warning').capitalize()
gotify_msg = { gotify_msg = {
'title': '{}: {}'.format( 'title': '{}: {}'.format(
@ -97,9 +97,9 @@ class HTTPHandler(SimpleHTTPRequestHandler):
'priority': int(alert['labels'].get('priority', 5)), 'priority': int(alert['labels'].get('priority', 5)),
'extras': { 'extras': {
'alertify': { 'alertify': {
'fingerprint': alert.get('fingerprint', None) 'fingerprint': alert.get('fingerprint', None),
}
} }
},
} }
except KeyError as error: except KeyError as error:
logging.error('KeyError: %s', error) logging.error('KeyError: %s', error)
@ -154,9 +154,11 @@ def healthy(config):
""" """
Simple function to return if all the requirements are met Simple function to return if all the requirements are met
""" """
return all([ return all(
len(config.get('gotify_key', '')) [
]) len(config.get('gotify_key', '')),
]
)
@functools.lru_cache @functools.lru_cache
@ -188,6 +190,7 @@ def parse_config(configfile):
if __name__ == '__main__': if __name__ == '__main__':
def parse_cli(): def parse_cli():
""" """
Function to parse the CLI Function to parse the CLI
@ -201,18 +204,20 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
description='Bridge between Prometheus Alertmanager and Gotify\n', description='Bridge between Prometheus Alertmanager and Gotify\n',
epilog='The following environment variables will override any config or default:\n' + epilog='The following environment variables will override any config or default:\n'
'\n'.join(defaults) + '\n'.join(defaults),
) )
parser.add_argument( parser.add_argument(
'-c', '--config', '-c',
'--config',
default=f'{os.path.splitext(__file__)[0]}.yaml', default=f'{os.path.splitext(__file__)[0]}.yaml',
help=f'path to config YAML. (default: {os.path.splitext(__file__)[0]}.yaml)', help=f'path to config YAML. (default: {os.path.splitext(__file__)[0]}.yaml)',
) )
parser.add_argument( parser.add_argument(
'-H', '--healthcheck', '-H',
'--healthcheck',
action='store_true', action='store_true',
help='simply exit with 0 for healthy or 1 when unhealthy', help='simply exit with 0 for healthy or 1 when unhealthy',
) )
@ -223,7 +228,10 @@ if __name__ == '__main__':
""" """
main() main()
""" """
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) logging.basicConfig(
format='%(levelname)s: %(message)s',
level=logging.INFO,
)
args = parse_cli() args = parse_cli()
config = parse_config(args.config) config = parse_config(args.config)
@ -240,7 +248,7 @@ if __name__ == '__main__':
logging.debug( logging.debug(
'Config:\n%s', 'Config:\n%s',
yaml.dump(config, explicit_start=True, default_flow_style=False) yaml.dump(config, explicit_start=True, default_flow_style=False),
) )
logging.info('Starting web server on port %d', listen_port) logging.info('Starting web server on port %d', listen_port)

View file

@ -39,13 +39,13 @@ class Gotify:
logging.error(error) logging.error(error)
return { return {
'status': error.errno, 'status': error.errno,
'reason': error.strerror 'reason': error.strerror,
} }
resp_obj = { resp_obj = {
'status': response.status, 'status': response.status,
'reason': response.reason, 'reason': response.reason,
'json': None 'json': None,
} }
rawbody = response.read() rawbody = response.read()
if len(rawbody) > 0: if len(rawbody) > 0:
@ -82,7 +82,10 @@ class Gotify:
if old_fingerprint == new_fingerprint: if old_fingerprint == new_fingerprint:
return old_message['id'] return old_message['id']
except KeyError: except KeyError:
logging.debug('No fingerprint found in message ID: %s', old_message['id']) logging.debug(
'No fingerprint found in message ID: %s',
old_message['id'],
)
continue continue
logging.debug('No fingerprint matched.') logging.debug('No fingerprint matched.')
@ -93,7 +96,9 @@ class Gotify:
Method to return a list of messages from the Gotify server Method to return a list of messages from the Gotify server
""" """
if not self.client_key: if not self.client_key:
logging.debug('No client key is configured. No messages could be retrieved.') logging.debug(
'No client key is configured. No messages could be retrieved.'
)
return [] return []
logging.debug('Fetching existing messages from Gotify') logging.debug('Fetching existing messages from Gotify')
return self._call('GET', '/message')['json'].get('messages', []) return self._call('GET', '/message')['json'].get('messages', [])