首页 > 其他分享 >Prometheus 同步告警到企业微信机器人

Prometheus 同步告警到企业微信机器人

时间:2024-03-13 18:35:17浏览次数:17  
标签:status name 微信 labels Prometheus output 告警 data docker

方法1:

一、使用webhook-adapter同步信息到企业微信

1.编辑alertmanager.yml文件

global:
  resolve_timeout: 5m
  scrape_interval: 15s

templates:
  - '/data/prometheus/alertmanager/template/*.tmpl'

route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 30s
  receiver: 'web.hook'
receivers:
- name: 'web.hook'
  webhook_configs:
  - url: 'http://127.0.0.1:8080/adapter/wx'
    send_resolved: true
inhibit_rules:
  - source_match:
      alertname: 'ApplicationDown'
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname',"target","job","instance"]

2.docker安装企业微信报警插件(webhook-adapter),启用一个企微机器人。

docker run -d --name wechat \
--restart always -p 8080:80 \
guyongquan/webhook-adapter \
--adapter=/app/prometheusalert/wx.js=/wx=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0eb7......68

二、使用

1.设置alertmanager配置文件

global:
  resolve_timeout: 5m
  scrape_interval: 15s
route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 30s
  receiver: 'ops_notify'

  routes:
  - receiver: ops_notify
    group_wait: 10s
    match_re:
      alertname: 'NodeStatsAlert'

receivers:
- name: 'ops_notify'
  webhook_configs:
  - url: 'http://10.0.xx.101:5000'
    send_resolved: true

inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

    设置rules/mysql.yml(要添加node_name标签,不然会报错)

groups:
- name: Mysql-rules
  rules:
  - alert: Mysql status
    expr: mysql_up == 0
    for: 5s
    labels:
      severity: error
      node_name: "{{ $labels.instance }}"
    annotations:
      summary: "您的 {{ $labels.instance }} 的Mysql已停止运行!"
      description: "Mysql数据库宕机,请检查"

  - alert: Mysql slave io thread status
    expr: mysql_slave_status_slave_io_running == 0
    for: 5s
    labels:
      severity: error
      node_name: "{{ $labels.instance }}"
    annotations:
      summary: "您的 {{ $labels.instance }} Mysql slave io thread已停止"
      description: "Mysql主从IO线程故障,请检测"

  - alert: Mysql slave sql thread status
    expr: mysql_slave_status_slave_sql_running == 0
    for: 5s
    labels:
      severity: error
      node_name: "{{ $labels.instance }}"
    annotations:
      summary: "您的 {{ $labels.instance }} Mysql slave sql thread已停止"
      description: "Mysql主从sql线程故障,请检测"

2.在webhook-wechat目录下,有如下脚本文件:

    app.py

# -*- coding: utf-8 -*-
import os
import json
import requests
import arrow

from flask import Flask
from flask import request

app = Flask(__name__)

def bytes2json(data_bytes):
    data = data_bytes.decode('utf8').replace("'", '"')
    return json.loads(data)

def makealertdata(data):
    for output in data['alerts'][:]:
        try:
            pod_name = output['labels']['pod']
        except KeyError:
            try:
                pod_name = output['labels']['pod_name']
            except KeyError:
                pod_name = 'null'

        try:
            namespace = output['labels']['namespace']
        except KeyError:
            namespace = 'null'

        try:
            message = output['annotations']['message']
        except KeyError:
            try:
                message = output['annotations']['description']
            except KeyError:
                message = 'null'

        if output['status'] == 'firing':
            status_zh = '报警'
            title = '【%s】xxxx环境 %s 有新的报警' % (status_zh, output['labels']['alertname'])
            send_data = {
                "msgtype": "markdown",
                "markdown": {
                    "content": "## %s \n\n" %title +
                            ">**告警级别**: %s \n\n" % output['labels']['severity'] +
                            ">**告警类型**: %s \n\n" % output['labels']['alertname'] +
                            ">**告警主机**: %s \n\n" % output['labels']['node_name'] +
                            ">**告警详情**: %s \n\n" % message +
                            ">**告警状态**: %s \n\n" % output['status'] +
                            ">**触发时间**: %s \n\n" % arrow.get(output['startsAt']).to('Asia/Shanghai').format(
                        'YYYY-MM-DD HH:mm:ss ZZ')

                }
            }
        elif output['status'] == 'resolved':
            status_zh = '恢复'
            title = '【%s】xxxx环境 %s 有报警恢复' % (status_zh, output['labels']['alertname'])
            send_data = {
                "msgtype": "markdown",
                "markdown": {
                    "content": "## %s \n\n" %title +
                            ">**告警级别**: %s \n\n" % output['labels']['severity'] +
                            ">**告警类型**: %s \n\n" % output['labels']['alertname'] +
                            ">**告警主机**: %s \n\n" % output['labels']['node_name'] +
                            ">**告警详情**: %s \n\n" % message +
                            ">**告警状态**: %s \n\n" % output['status'] +
                            ">**触发时间**: %s \n\n" % arrow.get(output['startsAt']).to('Asia/Shanghai').format(
                        'YYYY-MM-DD HH:mm:ss ZZ') +
                            ">**触发结束时间**: %s \n" % arrow.get(output['endsAt']).to('Asia/Shanghai').format(
                        'YYYY-MM-DD HH:mm:ss ZZ')
                }
            }
        return send_data
def send_alert(data):
  #此处获取环境变量“ROBOT_TOKEN”,会在docker-compose的配置文件中配置,docker-compose启动docker时向docker容器注入环境变量
    token = os.getenv('ROBOT_TOKEN')
    if not token:
        print('you must set ROBOT_TOKEN env')
        return
    url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s' % token

    send_data = makealertdata(data)
    req = requests.post(url, json=send_data)
    result = req.json()
    if result['errcode'] != 0:
        print('notify dingtalk error: %s' % result['errcode'])


@app.route('/', methods=['POST', 'GET'])
def send():
    if request.method == 'POST':
        post_data = request.get_data()
        send_alert(bytes2json(post_data))
        return 'success'
    else:
        return 'weclome to use prometheus alertmanager dingtalk webhook server!'


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

    requirements.txt

certifi==2018.10.15
chardet==3.0.4
Click==7.0
Flask==1.0.2
idna==2.7
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
requests==2.20.1
urllib3==1.24.1
Werkzeug==0.14.1
arrow==0.13.1

     Dockerfile

FROM python:3.6.4
​
# set working directory
WORKDIR /src
​
# add app
ADD . /src
​
# install requirements
RUN pip install -r requirements.txt
​
EXPOSE 5000
​
# run server
CMD python app.py

    docker-compose.yml

version: "2"
networks:
    monitor:
        driver: bridge
services:
  prometheus-webhook-alert:
    build: .
    restart: always
    volumes:
    - /etc/localtime:/etc/localtime
    - ./app.py:/src/app.py
    ports:
    - "5000:5000"
    environment:
    # 此处设置的环境变量会被app.py运行时获取到
      ROBOT_TOKEN: "0eb7......68"
    networks:
    - monitor

3.各个程序都已经写好了,开始启动

[root@ webhook-wechat]# ls
app.py  docker-compose.yml  Dockerfile  requirements.txt

  启动并查看日志

# 启动
]# docker-compose up -d 
#检查是否启动,一下三种方式都能启动
]# docker-compose status
]# docker ps -a 
]# ss -luntp |grep 5000
​
# 日志查看,一下两种都可查看,-f 支持输出日志
]# docker-compose logs 
]# docker-compose logs -f

 

标签:status,name,微信,labels,Prometheus,output,告警,data,docker
From: https://www.cnblogs.com/jiangxm157/p/18071280

相关文章

  • 微信小程序(七)条件渲染
    wx:if.wx:elif,wx:else  ......
  • 微信小程序开发基础
    一、小程序的基本目录结构1、pages:存放全部的页面文件,有两子目录index与logs2、utils:存放一些公共的.js文件(例如:格式化时间的自定义模块)3、app.json:小程序公共设置文件,配置小程序全局设置4、app.js:小程序逻辑文件,用来小程序全局实例5、app.wxss:小程序主样式表文件6、proj......
  • 微信小程序(六)事件绑定
             ......
  • Taro微信小程序使用表单组件rc-field-form
    安装rc-field-formyarnaddrc-field-form使用import{View,Button,Input}from"@tarojs/components";importForm,{Field,useForm}from"rc-field-form";exportdefaultfunctionInstallParameter(){const[form]=useForm();co......
  • 19113133262(微信同号)2024年环境能源与全球市场营销国际学术会议(ICEEGM 2024)
    2024年环境能源与全球市场营销国际学术会议(ICEEGM2024)会议主题:(主题包括但不限于,更多主题请咨询会务组苏老师)节能技术煤矿工程与技术能源存储技术可再生能源热能与动力工程 能源工程与环境工程 可再生能源技术和系统能源安全和清洁利用 矿产资源与采矿工......
  • java毕业设计基于微信小程序的新闻管理系统
    本系统(程序+源码)带文档lw万字以上  文末可领取本课题的JAVA源码参考系统程序文件列表系统的选题背景和意义选题背景:随着移动互联网技术的飞速发展,智能手机的普及率日益增高,人们获取信息的方式也发生了翻天覆地的变化。微信小程序作为一种新型的应用形态,因其无需下载安装......
  • 微信小程序开发:上传网络图片到阿里云oss
    上文遇到的问题,用户上传的人像图片在经过人像增强后返回的结果需要再次上传到阿里云的oss。因为是需要下下载,再上传,这个域名我们没有在MP后台配置download域名,所以报错了: 但是MP后台只能配置https的域名,而人像增强的却返回的时http的,所以先下载人像增强返回的图片是行不通的......
  • 2024基于协同过滤算法springboot微信订餐小程序项目
    项目介绍基于springboot开发的订餐小程序,用户在微信小程序里面进行注册登录,点餐,收藏,评论等,管理员在后台网页端进行对菜品,分类,订单,用户,角色,评论等进行管理,小程序界面通过协同过滤算法给用户推荐菜品技术栈后端:springboot+JPA+Mysql8+redis+maven+idea前端:后台:HTML+JS+CSS......
  • 微信小程序:从零入门,这篇文章让你快速上手微信小程序开发
    小程序配置文件一个小程序应用程序会包括最基本的两种配置文件。一种是全局的app.json和⻚面自己的page.json全局配置app.json包括了小程序的所有⻚面路径、界面表现、网络超时时间、底部tab等pages字段用于描述当前小程序所有⻚面路径,这是为了让微信客戶端知道当前你的小......
  • 微信小程序(五)常用组件
    text与rich-text 按钮的样式image组件的使用 ......