Newer
Older
#!/usr/bin/env python3
import os
import sys
from dateutil import parser
import json, logging
from flask import Flask, request
from rocketchat_API.rocketchat import RocketChat
from requests import sessions
listenPort = 29120
listenIP = '::1'
botUser = '{{ prometheus_alertmanager.rocketchatbot.user }}'
botPass = '{{ prometheus_alertmanager.rocketchatbot.pass }}'
botChatURL ='{{ prometheus_alertmanager.rocketchatbot.url }}'
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
86
87
88
89
90
91
92
93
template_alert = """:warning: [**firing**] monitoring.cccv.de probe for https://shells.darmstadt.ccc.de/~psy/alerttest.html failed @here
Instance: monitoring.cccv.de
Started: 2021-01-04 10:47:30
labels:
```
alertname : ProbeFailed
ansible_group_ungrouped : 1
instance : monitoring.cccv.de
job : blackbox
module : http_2xx
scraper : monitoring.cccv.de
severity : critical
target : https://shells.darmstadt.ccc.de/~psy/alerttest.html
```"""
template_resolved = """:white_check_mark: [**resolved**] monitoring.cccv.de probe for https://shells.darmstadt.ccc.de/~psy/alerttest.html failed
Instance: monitoring.cccv.de
Resolved: 2021-01-04 11:44:30
labels:
```
alertname : ProbeFailed
ansible_group_ungrouped : 1
instance : monitoring.cccv.de
job : blackbox
module : http_2xx
scraper : monitoring.cccv.de
severity : critical
target : https://shells.darmstadt.ccc.de/~psy/alerttest.html
```"""
template_unknown = """:white_check_mark: [**resolved**] monitoring.cccv.de probe for https://shells.darmstadt.ccc.de/~psy/alerttest.html failed
Instance: monitoring.cccv.de
Resolved: 2021-01-04 11:44:30
labels:
```
alertname : ProbeFailed
ansible_group_ungrouped : 1
instance : monitoring.cccv.de
job : blackbox
module : http_2xx
scraper : monitoring.cccv.de
severity : critical
target : https://shells.darmstadt.ccc.de/~psy/alerttest.html
```"""
'''
message.attachement = [{
"color": "#ff0000",
"text": "Yay for gruggy!",
"ts": "2016-12-09T16:53:06.761Z",
"thumb_url": "http://res.guggy.com/logo_128.png",
"message_link": "https://google.com",
"collapsed": false,
"author_name": "Bradley Hilton",
"author_link": "https://rocket.chat/",
"author_icon": "https://avatars.githubusercontent.com/u/850391?v=3",
"title": "Attachment Example",
"title_link": "https://youtube.com",
"title_link_download": true,
"image_url": "http://res.guggy.com/logo_128.png",
"audio_url": "http://www.w3schools.com/tags/horse.mp3",
"video_url": "http://www.w3schools.com/tags/movie.mp4",
"fields": [{
"short": true,
"title": "Test",
"value": "Testing out something or other"
},{
"short": true,
"title": "Another Test",
"value": "[Link](https://google.com/) something and this and that."
}]
}]
'''
app = Flask(__name__)
app.secret_key = os.urandom(128)
api_session = sessions.Session()
api = RocketChat(botUser, botPass, server_url=botChatURL, session=api_session)
@app.route('/<chatName>/alert', methods = ['POST'])
def postAlertmanager(chatName):
try:
content = json.loads(request.get_data())
for alert in content['alerts']:
if 'description' in alert['annotations']:
message += alert['annotations']['description']
if alert['status'] == "firing":
if 'name' in alert['labels']:
message += "Instance: "+alert['labels'].get('instance', 'unknown')+"("+alert['labels']['name']+")\n"
else:
message += "Instance: "+alert['labels'].get('instance', 'unknown')+"\n"
if 'info' in alert['annotations']:
message += "Info: "+alert['annotations']['info']+"\n"
if 'summary' in alert['annotations']:
message += "Summary: "+alert['annotations']['summary']+"\n"
if alert['status'] == "resolved":
correctDate = parser.parse(alert['endsAt']).strftime('%Y-%m-%d %H:%M:%S')
message += "Resolved: "+correctDate+"\n"
elif alert['status'] == "firing":
correctDate = parser.parse(alert['startsAt']).strftime('%Y-%m-%d %H:%M:%S')
message += "Started: "+correctDate+"\n"
message += "labels: \n"
message += "```\n"
labels = ""
for l in alert['labels']:
labels += l + " : "+alert['labels'][l] + "\n"
if api.chat_post_message(message, channel=chatName, alias='Alertmanager').ok:
return "Alert OK", 200
else:
return "Alert fail", 200
except Exception as error:
bot.sendMessage(chat_id=chatID, text="Error to read json: "+str(error))
app.logger.info("\t%s",error)
return "Alert fail", 200
if __name__ == '__main__':
if len(sys.argv) == 1:
logging.basicConfig(level=logging.INFO)
app.run(host=listenIP, port=listenPort)
else:
from gevent.pywsgi import WSGIServer
http_server = WSGIServer((listenIP, listenPort), app)
http_server.serve_forever()