This repository has been archived by the owner on Oct 25, 2021. It is now read-only.
/
webhook.py
67 lines (52 loc) · 1.67 KB
/
webhook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, request
from alert import PrometheusAlert
import posix_ipc as ipc
import json
import logging
import os
from common import load_config, QUEUE_ENCODING
LOG_FORMAT = os.path.basename(__file__) + ' %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
service = Flask(__name__)
conf = None
@service.route('/test', methods=['GET'])
def xmpp_test():
global conf
if not conf:
conf = load_config()
if not push_in_queue(construct_message(conf['xmpp_recipients'], 'test message for: %s' % conf['xmpp_recipients'])):
return '', 500
return '', 204
@service.route('/alert', methods=['POST'])
def prometheus_alert():
global conf
if not conf:
conf = load_config()
msg = PrometheusAlert(request.data.decode()).plain()
html = PrometheusAlert(request.data.decode()).html()
push_in_queue(construct_message(conf['xmpp_recipients'], msg, html))
return '', 204
def construct_message(recipients, msg, html=None):
if html:
return json.dumps({'recipients': recipients, 'message': msg, 'html': html})
return json.dumps({'recipients': recipients, 'message': msg})
def push_in_queue(msg):
global conf
try:
queue = ipc.MessageQueue(name=conf['mq_name'])
queue.send(msg.encode(encoding=QUEUE_ENCODING), timeout=0)
except ipc.ExistentialError:
queue.close()
return False
except ipc.BusyError:
queue.close()
return False
return True
def main():
global conf
conf = load_config()
service.run(host=conf['flask_host'], port=conf['flask_port'])
if __name__ == '__main__':
main()