forked from alerta/alerta-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evlistener.py
executable file
·85 lines (72 loc) · 2.64 KB
/
evlistener.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python
import sys
import json
import platform
from alertaclient.api import Client
class Listener(object):
def wait(self):
data = sys.stdin.readline()
headers = dict([x.split(':') for x in data.split()])
data = sys.stdin.read(int(headers['len']))
body = dict([x.split(':') for x in data.split()])
return headers, body
def send_cmd(self, s):
sys.stdout.write(s)
sys.stdout.flush()
def log_stderr(self, s):
sys.stderr.write(s)
sys.stderr.flush()
def main():
api = Client()
listener = Listener()
while True:
listener.send_cmd('READY\n')
headers, body = listener.wait()
event = headers['eventname']
if event.startswith('TICK'):
try:
origin = '{}/{}'.format('supervisord', platform.uname()[1])
api.heartbeat(origin, tags=[headers['ver'], event])
except Exception as e:
listener.log_stderr(e)
listener.send_cmd('RESULT 4\nFAIL')
else:
listener.send_cmd('RESULT 2\nOK')
else:
if event.endswith('FATAL'):
severity = 'critical'
elif event.endswith('BACKOFF'):
severity = 'warning'
elif event.endswith('EXITED'):
severity = 'minor'
else:
severity = 'normal'
try:
api.send_alert(
resource='%s:%s' % (platform.uname()[1], body['processname']),
environment='Production',
service=['supervisord'],
event=event,
correlate=[
'PROCESS_STATE_STARTING',
'PROCESS_STATE_RUNNING',
'PROCESS_STATE_BACKOFF',
'PROCESS_STATE_STOPPING',
'PROCESS_STATE_EXITED',
'PROCESS_STATE_STOPPED',
'PROCESS_STATE_FATAL',
'PROCESS_STATE_UNKNOWN'
],
value='serial=%s' % headers['serial'],
severity=severity,
origin=headers['server'],
text='State changed from %s to %s.' % (body['from_state'], event),
raw_data='%s\n\n%s' % (json.dumps(headers), json.dumps(body))
)
except Exception as e:
listener.log_stderr(e)
listener.send_cmd('RESULT 4\nFAIL')
else:
listener.send_cmd('RESULT 2\nOK')
if __name__ == '__main__':
main()