参考答案:用原生的中文重新表达这个句子:推文推介 – 在Grafana中设置警报时执行任务,使用Python+Flask接收Webhook
我写了一篇关于Prometheus的推文,但是这篇文章完全没有提到Prometheus。
我创建了一个能够接收Grafana警报时Webhook的接收器,以执行与警报内容相符的处理。
发布的JSON内容
在我所设定的环境中,当Grafana发生警报时,将会以POST方式发送JSON,其内容如下。
※ 由于环境可能会有所不同,tags部分可能会有所变化,因此最好在查看JSON内容的同时编写Python代码。
{
'ruleName': 'CPU使用率アラートグラフ alert',
'ruleUrl': 'http://XXX.XXX.XXX.XXX:XXXX/d/lCE6nYDmz/all-servers-alert?fullscreen=true&edit=true&tab=alert&panelId=4&orgId=1',
'imageUrl': 'https://s3.ap-northeast-1.amazonaws.com/XXXXXX/69Ima6QI5KACp3NL3Grs.png', 'title': '[Alerting] CPU使用率アラートグラフ alert',
'ruleId': 6,
'state': 'alerting',
'message': '【障害通知】CPU使用率',
'evalMatches': [
{
'value': 96.23523011138367,
'tags':
{
'instance': 'XXX-XXXXX-web01'
},
'metric': 'XXX-XXXXX-web01'
}
]
}
准备Python执行环境(nginx+uwsgi)。
由于数量太多,在这篇文章里选择性省略掉了。
这里可以作为参考。
在我的环境中,我将Prometheus与同一台服务器共存,并将其配置为在访问”http://IP地址/dev”时通过wsgi协议以Python执行。
这是一个反映某种特定行动或过程的代号。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request, redirect, session , make_response
app = Flask(__name__)
import subprocess
import re
@app.route("/dev/webhook", methods = ["POST"])
def webhook():
'''
Grafanaのアラートからスクリプトを実行する為のWebHookRecive
'''
postjson = request.json
if not request.remote_addr == '127.0.0.1':
print("## not local request")
return
elif postjson['state'] == 'alerting':
print("## state: Alerting")
print(postjson)
text = postjson['message']
rulename = postjson['ruleName']
if not postjson['evalMatches'][0]['tags'] == None:
instance = postjson['evalMatches'][0]['tags']['instance']
alert = re.match('ICMP',rulename)
cmd = "sh /usr/script/grafana/"+instance+"_"+alert+".sh"
#/usr/script/grafana/配下にインスタンス名(NameTag)_アラート名.shでスクリプトを配置する。
#内容は再起動なり、SSHでリモートコマンドするなりのスクリプト
subprocess.call(cmd.split())
print(text)
elif:
print("## State: without Alert")
print(postjson)
return 'OK'