LoginSignup
1

More than 5 years have passed since last update.

Prometheusのすすめ - Grafanaでアラート発生時にジョブ実行 Python+Flaskでwebhook recieve-

Posted at

Prometheusのすすめとか書いてますが、本記事はPrometheusについて一切触れていません。
Grafanaのアラート時のwebhookを受信してアラート内容に沿った処理をするwebhook recieveを作りました。

Postされる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」にアクセスするとpythonにwsgiプロトコル経由で実行されるように設定しています。

コード

app.py
#!/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'

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1