Skip to content

Commit a5da510

Browse files
author
zzg
committed
init
0 parents  commit a5da510

File tree

6 files changed

+226
-0
lines changed

6 files changed

+226
-0
lines changed

Dockerfile

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
FROM python:3.6.8-stretch
2+
3+
WORKDIR /usr/src/app/
4+
5+
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list && \
6+
sed -i 's/security.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
7+
RUN apt-get -y update && apt-get install -y default-libmysqlclient-dev curl vim
8+
COPY ./requirements.txt /usr/src/app/
9+
RUN pip install --no-cache-dir -r /usr/src/app/requirements.txt
10+
COPY . /usr/src/app/
11+
12+
EXPOSE 8080
13+
14+
CMD ["python", "/usr/src/app/app.py"]
15+

app.py

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
@version: 1.0.0
6+
@author: zheng guang
7+
@contact: zg.zhu@daocloud.io
8+
@time: 2019/7/4 4:56 PM
9+
"""
10+
11+
12+
from flask import Flask, request, Response
13+
import requests
14+
import logging
15+
import json
16+
import os
17+
18+
LOG = logging.getLogger(__name__)
19+
app = Flask(__name__)
20+
21+
URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}"
22+
KEY = os.getenv('ROBOT_KEY', '')
23+
ALEAT_MANAGER_URL = os.getenv('ALEAT_MANAGER_URL', '')
24+
25+
26+
def send_wechat_msg(key, message):
27+
data = {
28+
"msgtype": "markdown",
29+
"markdown": {
30+
"content": message
31+
}
32+
}
33+
if not key and KEY:
34+
key = KEY
35+
if not isinstance(message, str):
36+
data = message
37+
respose = requests.post(URL.format(key), json=data)
38+
LOG.info("send message result: %s:%s", respose.status_code, respose.text)
39+
if respose.status_code == 200:
40+
return True
41+
else:
42+
return False
43+
44+
45+
@app.route('/prometheus_webhook', methods=['POST'])
46+
def prometheus_webhook():
47+
bearer_token = request.headers.get('Authorization', 'bearer_token ').split(" ")
48+
if len(bearer_token) != 2:
49+
get_result(error="bearer_token can not null")
50+
receiver = bearer_token[1]
51+
52+
data = request.get_json()
53+
msg = ""
54+
for alert in data.get('alerts'):
55+
status = alert.get('status')
56+
status_color = 'warning' if status == 'firing' else 'info'
57+
status = '告警' if status == 'firing' else '已恢复'
58+
labels = alert.get('labels', {})
59+
annotations = alert.get('annotations', {})
60+
61+
title = "{namespace}{resource_name}: {alertname}".format(
62+
namespace="{}/".format(labels.get("namespace")) if labels.get("namespace") else '',
63+
resource_name=labels.get("pod", labels.get("pod_name", labels.get("instance", 'cluster'))),
64+
alertname=labels.get("alertname", ' '))
65+
66+
message = annotations.get("message", annotations.get("description", ''))
67+
68+
msg += '''
69+
<font color="{_status_color}">{_status}</font>: [{_title}]({alert_namager_url}) \n
70+
>描述: <font color="comment">{_message}</font>
71+
>开始时间: <font color="comment">{startsAt}</font>
72+
>结束时间: <font color="comment">{endsAt}</font>
73+
\n
74+
'''.format(_title=title, _status_color=status_color, _status=status, _message=message,
75+
startsAt=alert.get('startsAt', ' '), endsAt=alert.get('endsAt', ' '),
76+
alert_namager_url=ALEAT_MANAGER_URL if ALEAT_MANAGER_URL else alert.get('generatorURL', ' '))
77+
78+
result = send_wechat_msg(receiver, msg)
79+
80+
return get_result(error=result)
81+
82+
83+
def get_result(text='', receiver='', error=""):
84+
if isinstance(error, bool):
85+
if error:
86+
error = ""
87+
else:
88+
error = "send alert failed"
89+
result = {
90+
"receiver": receiver,
91+
"text": text,
92+
}
93+
if error:
94+
return Response(json.dumps({"error": error}), mimetype='application/json', status=400)
95+
return Response(json.dumps(result), mimetype='application/json')
96+
97+
98+
if __name__ == '__main__':
99+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)-8s %(message)s')
100+
LOG.info("app started")
101+
app.run('0.0.0.0', '8080')

deployment.yaml

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
apiVersion: apps/v1
2+
kind: Deployment
3+
metadata:
4+
name: work-wechat-robot
5+
namespace: monitoring
6+
labels:
7+
app: work-wechat-robot
8+
spec:
9+
replicas: 1
10+
selector:
11+
matchLabels:
12+
app: work-wechat-robot
13+
template:
14+
metadata:
15+
labels:
16+
app: work-wechat-robot
17+
spec:
18+
serviceAccountName: work-wechat-robot
19+
containers:
20+
- name: work-wechat-robot
21+
image: daozzg/work-wechat-robot
22+
ports:
23+
- containerPort: 8080
24+
---
25+
apiVersion: v1
26+
kind: Service
27+
metadata:
28+
name: work-wechat-robot
29+
namespace: monitoring
30+
spec:
31+
ports:
32+
- name: web
33+
port: 80
34+
targetPort: 8080
35+
selector:
36+
app: work-wechat-robot

docker-compose.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
work_wechat_robot:
2+
build: .
3+
#image: daozzg/work-wechat-robot
4+
ports:
5+
- "8888:8080"

readme.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
2+
### 运行
3+
1. k8s
4+
```bash
5+
kubectl apply -f deployment.yaml
6+
```
7+
8+
1. docker-compose
9+
```bash
10+
docker-compose up -d
11+
```
12+
13+
1. docker:
14+
```bash
15+
docker run -d --name=work_wechat_robot -p 8080:8080 daozzg/work_wechat_robot
16+
```
17+
18+
19+
### promethues webhook 配置
20+
1. 创建robot,获得robot的key,根据自己的alertmanager 规则,修改如下alertmanager的配置:
21+
1. <your robot key>: 你的robot的key
22+
1. <work-wechat-robot>: 部署本服务的地址,如果是同k8s的[deployment部署](./deployment.yaml),写service名即可,如: http://http://work-wechat-robot/prometheus_webhook
23+
```bash
24+
"global":
25+
"resolve_timeout": "5m"
26+
"route":
27+
"group_by":
28+
- "job"
29+
"group_interval": "5m"
30+
"group_wait": "30s"
31+
"receiver": "default"
32+
"repeat_interval": "12h"
33+
"routes":
34+
- "match":
35+
"alertname": "DeadMansSwitch"
36+
"receiver": "null"
37+
"receivers":
38+
- "name": "default"
39+
"webhook_configs":
40+
- "send_resolved": true
41+
"url": "http://<work-wechat-robot>/prometheus_webhook"
42+
"http_config":
43+
"bearer_token": "<your robot key>"
44+
```
45+
46+
### 开发
47+
```
48+
git clone {this_url}
49+
cd work_wechat_robot
50+
# please install pip (ubuntu: `apt-get install python-pip`,mac: `brew install python-pip` )
51+
pip install virtualenv
52+
virtualenv venv
53+
source venv/bin/activate
54+
55+
pip install -r requirements.txt
56+
python app.py
57+
58+
```

requirements.txt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
certifi==2019.6.16
2+
chardet==3.0.4
3+
Click==7.0
4+
Flask==1.0.3
5+
idna==2.8
6+
itsdangerous==1.1.0
7+
Jinja2==2.10.1
8+
MarkupSafe==1.1.1
9+
requests==2.22.0
10+
urllib3==1.25.3
11+
Werkzeug==0.15.4

0 commit comments

Comments
 (0)