-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapp.py
93 lines (76 loc) · 2.55 KB
/
app.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
86
87
88
89
90
91
92
93
#!/bin/env python3
"""
Line Notify Gateway Application
License: MIT
"""
import logging
import requests
from datetime import datetime
from flask import Flask, render_template, request, jsonify
import manage_logs
LOG_PATH = 'logs/line-notify-gateway.log'
LINE_NOTIFY_URL = 'https://notify-api.line.me/api/notify'
app = Flask(__name__)
def reformat_datetime(datetime):
"""
Reformat of datetime to humand readable.
"""
datetime = datetime.split('T')
date = datetime[0]
time = datetime[1].split('.')[0]
return date + " " + time
def firing_alert(request):
"""
Firing alert to line notification with message payload.
"""
if request.json['status'] == 'firing':
icon = "⛔⛔⛔ 😡 ⛔⛔⛔"
status = "Firing"
time = reformat_datetime(request.json['alerts'][0]['startsAt'])
else:
icon = "🔷🔷🔷 😎 🔷🔷🔷"
status = "Resolved"
time = str(datetime.now().date()) + ' ' + str(datetime.now().time().strftime('%H:%M:%S'))
header = {'Authorization':request.headers['AUTHORIZATION']}
for alert in request.json['alerts']:
msg = "Alertmanger: " + icon + "\nStatus: " + status + "\nSeverity: " + alert['labels']['severity'] + "\nTime: " + time + "\nSummary: " + alert['annotations']['summary'] + "\nDescription: " + alert['annotations']['description']
msg = {'message': msg}
response = requests.post(LINE_NOTIFY_URL, headers=header, data=msg)
@app.route('/')
def index():
"""
Show summary information on web browser.
"""
logging.basicConfig(filename=LOG_PATH, level=logging.DEBUG)
return render_template('index.html', name='index')
@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
"""
Firing message to Line notify API when it's triggered.
"""
logging.basicConfig(filename=LOG_PATH, level=logging.DEBUG)
logging.debug(str(request))
if request.method == 'GET':
return jsonify({'status':'success'}), 200
if request.method == 'POST':
try:
firing_alert(request)
return jsonify({'status':'success'}), 200
except:
return jsonify({'status':'bad request'}), 400
@app.route('/logs')
def logs():
"""
Display logs on web browser.
"""
file = open(LOG_PATH, 'r+')
content = file.read()
return render_template('logs.html', text=content, name='logs')
@app.route('/metrics')
def metrics():
"""
Expose metrics for monitoring tools.
"""
if __name__ == "__main__":
manage_logs.init_log(LOG_PATH)
app.run(host='0.0.0.0')