MySQL, Oracle, Linux, 软件架构及大数据技术知识分享平台

网站首页 > 精选文章 / 正文

Zabbix集成Alertmanager

2024-11-30 22:22 huorong 精选文章 10 ℃ 0 评论

Zabbix是一款老牌的监控软件,其一直保持活跃更新,使用比较广泛。公司使用Zabbix来监控服务器的性能和资源使用情况,在使用过程中,经常出现告警轰炸,影响告警的可读性,而且告警抑制操作也不灵活,为解决这个问题,使用Alertmanager作为Zabbix的告警通道。

Alertmanager使用比较流行,除了因为其支持的告警通道较多外,还有就是Alertmanager可以提供告警分组、抑制和静默功能,让告警更加高效。

原理

首先在Zabbix中配置“脚本”类型的“告警媒介类型”,脚本用来处理Zabbix内部发出的告警,然后将告警内容Post到Alertmanager的API(Alertmanager的API有v1和v2两个版本,本文使用v1版本,具体可参见官方文档:https://prometheus.io/docs/alerting/latest/clients/)。Post到Alertmanager的消息格式,

[
  {
    "labels": {
      "alertname": "<requiredAlertName>",
      "<labelname>": "<labelvalue>",
      ...
    },
    "annotations": {
      "<labelname>": "<labelvalue>",
    },
    "startsAt": "<rfc3339>",
    "endsAt": "<rfc3339>",
    "generatorURL": "<generator_url>"
  },
  ...
]

Zabbix配置

Zabbix的版本为5.0.17

  • 报警媒介类型

打开Zabbix的Web UI,进入“管理”->“报警媒介类型”,配置如下,

  • 配置用户告警媒介

“收件人”取个有意义的名字即可,实际不会用到。

  • 配置动作

这里的“步骤”其实也可以一并交给Alertmanager来控制,

其中“消息”是Post到Alertmanager的内容,如下,

{
    "labels": {
       "alertname": "{ITEM.NAME}",
       "instance": "{HOST.NAME}",
       "severity": "{TRIGGER.SEVERITY}",
       "id":"{EVENT.ID}",
       "source":"zabbix",
       "stakeholder":"jichu"
     },
     "annotations": {
        "info": "{ITEM.NAME}:{ITEM.VALUE}"
      },
     "failure_time": "{EVENT.DATE} {EVENT.TIME}",
     "status": "{TRIGGER.STATUS}"
}

因Alertmanager同时作为Prometheus的告警通道,还有为了将告警发送给处理故障的组,这里增加了“source”和“stakeholder”两个额外的label。

告警恢复的配置,

消息内容如下,

{
    "labels": {
       "alertname": "{ITEM.NAME}",
       "instance": "{HOST.NAME}",
       "severity": "{TRIGGER.SEVERITY}",
        "id":"{EVENT.ID}",
        "source":"zabbix",
        "stakeholder":"jichu"
     },
     "annotations": {
        "info": "{ITEM.NAME}:{ITEM.VALUE}"
      },
     "failure_time": "{EVENT.DATE} {EVENT.TIME}",
     "recovery_time": "{EVENT.RECOVERY.DATE} {EVENT.RECOVERY.TIME}",
     "status": "{TRIGGER.STATUS}"
}
  • Zabbix配置文件修改

操作完Web UI后,还需要修改Zabbix Server的配置文件,将脚本“post-alertmanager.py”放到目录“/usr/lib/zabbix/alertscripts”内(具体位置见zabbix配置文件的选项“AlertScriptsPath”),修改完成后重启Zabbix Server。

脚本“post-alertmanager.py”,

#!/bin/python3.7
# -*- coding: utf-8 -*-

import sys
import json

from http.client import HTTPConnection
from urllib.parse import urlsplit
from datetime import datetime, timedelta

url = "http://127.0.0.1:9093"
api_url = f"{url}/api/v2/alerts"
headers = {"Content-Type": "application/json"}


def to_rfc_3339(dt, flag=False):
    """以 rfc-3339 标准格式化时间
    AlertManager 接口只接受 rfc-3339 标准的时间
    """
    _d, _t = dt.split()
    y, m, d = (int(i) for i in _d.split('.'))
    H, M, S = (int(i) for i in _t.split(':'))
    t = datetime(y, m, d, H, M, S)
    if flag:
        new = t + timedelta(days=2)
    else:
        new = t
    return new.isoformat() + "+08:00"


def post(url, data, headers):
    u = urlsplit(url)
    if not isinstance(data, str):
        data = json.dumps(data)
    conn = HTTPConnection(u.netloc)
    conn.request('POST', u.path, data, headers)
    response = conn.getresponse()
    text = response.read().decode()
    print(text)


def main(msg):
    try:
        msg = json.loads(msg)
    except Exception as e:
        with open('/tmp/alert.txt', 'a') as f:
            f.write(f"{datetime.now().isoformat(' ')} {str(e)}\n")

    alert_msg = {}
    if msg['status'] == "OK":
        alert_msg['endsAt'] = to_rfc_3339(msg['recovery_time'])
    else:
        alert_msg['startsAt'] = to_rfc_3339(msg['failure_time'])
        alert_msg['endsAt'] = to_rfc_3339(msg['failure_time'], True)

    alert_msg['labels'] = msg['labels']
    alert_msg['annotations'] = msg['annotations']

    post(api_url, [alert_msg], headers)


if __name__ == "__main__":
    main(sys.argv[1])

Alertmanager配置

Alertmanager的部署比较简单,下面给出一个样例配置文件,

global:
  resolve_timeout: 5m
  wechat_api_url: 'https://qyapi.weixin.qq.com/cgi-bin/'
  wechat_api_corp_id: 'corp_id'
  smtp_smarthost: 'mail.example.com:25'
  smtp_from: 'xufu@example.com'
  smtp_auth_username: 'xufu'
  smtp_auth_password: 'password'
  smtp_require_tls: false
  
templates:
  - '/etc/alertmanager/*.tmpl'
route:
  receiver: yunweifromprom
  group_wait: 30s
  group_interval: 3m
  repeat_interval: 2h
  group_by: [alertname]

  routes:
    # 示例告警通道
    - matchers:
          - alertchannel="mail"
      receiver: toxufu

    # alerts come from zabbix
    - matchers:
          - source="zabbix"
      receiver: yunweifromzabbix
      continue: true
      routes:
        - matchers:
            - stakeholder="jichu"
          receiver: jichufromzabbix

receivers:
- name: yunweifromprom
  wechat_configs:
  - to_tag: 1 
    message: '{{ template "wechat.message" . }}'
    send_resolved: true
    agent_id: 1000001
    message_type: markdown
    api_secret: longlongstring
    
- name: toxufu
  email_configs:
  - to: 'xufu@example.com'

- name: yunweifromzabbix
  wechat_configs:
  - to_tag: 1 
    message: '{{ template "wechat.default.message" . }}'
    send_resolved: true
    agent_id: 1000001
    message_type: markdown
    api_secret: longlongstring

- name: jichufromzabbix
  wechat_configs:
  - to_tag: 2 
    message: '{{ template "wechat.default.message" . }}'
    send_resolved: true
    agent_id: 1000001
    message_type: markdown
    api_secret: longlongstring

这里有个小技巧,可以通过配置“stakeholder”来控制告警接收者,实现原理通过receivers[0]["wechat_configs"][0]["to_tag"]来指定接收者。企业微信支持通过tag来创建逻辑组,每个标签可以包含部门或成员,标签通过“标签ID”来区分,用在Alertmanager告警对象非常的灵活。

模板文件有两个,第一个,

{{ define "wechat.message" }}
{{- if gt (len .Alerts.Firing) 0 -}}
{{- range $index, $alert := .Alerts -}}
{{- if eq $index 0 -}}
# 报警项: {{ $alert.Labels.alertname }}
{{- end }}
> `===告警详情===` 
> 告警级别: {{ $alert.Labels.severity }}
> 告警详情: <font color="comment">{{ index $alert.Annotations "description" }}{{ $alert.Annotations.message }}</font>
> 故障时间: <font color="warning">{{ ($alert.StartsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}</font>
> 故障实例: <font color="info">{{ $alert.Labels.instance }}</font>
{{- end }}
{{- end }}
{{- if gt (len .Alerts.Resolved) 0 -}}
{{- range $index, $alert := .Alerts -}}
{{- if eq $index 0 -}}
# 恢复项: {{ $alert.Labels.alertname }}
{{- end }}
> `===恢复详情===` 
> 告警级别: {{ $alert.Labels.severity }}
> 告警详情: <font color="comment">{{ index $alert.Annotations "description" }}{{ $alert.Annotations.message }}</font>
> 故障时间: <font color="warning">{{ ($alert.StartsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}</font>
> 恢复时间: <font color="warning">{{ ($alert.EndsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}</font>
> 故障实例: <font color="info">{{ $alert.Labels.instance }}</font>
{{- end }}
{{- end }}
{{- end }}

第二个,

{{ define "wechat.default.message" }}
{{- if gt (len .Alerts.Firing) 0 -}}
{{/* 从 .Alerts.Firing 中取数据可以防止发送恢复通知时数据重复 */}}
{{- range $index, $alert := .Alerts.Firing -}}
{{- if eq $index 0 -}}
**********告警通知**********
告警类型: {{ $alert.Labels.alertname }}
告警级别: {{ $alert.Labels.severity }}
{{- end }}
告警详情: {{ $alert.Annotations.info }}
故障时间: {{ ($alert.StartsAt).Format "2006-01-02 15:04:05" }}
{{ if gt (len $alert.Labels.instance) 0 -}}
故障实例: {{ $alert.Labels.instance }}
事件ID: {{ $alert.Labels.id }}{{- end -}}
{{- end }}
{{- end }}

{{- if gt (len .Alerts.Resolved) 0 -}}
{{- range $index, $alert := .Alerts.Resolved -}}
{{- if eq $index 0 -}}

**********恢复通知**********
告警类型: {{ $alert.Labels.alertname }}
告警级别: {{ $alert.Labels.severity }}
{{- end }}
告警详情: {{ $alert.Annotations.info }}
故障时间: {{ ($alert.StartsAt).Format "2006-01-02 15:04:05" }}
恢复时间: {{ ($alert.EndsAt).Format "2006-01-02 15:04:05" }}
{{ if gt (len $alert.Labels.instance) 0 -}}
故障实例: {{ $alert.Labels.instance }}
事件ID: {{ $alert.Labels.id }}{{- end -}}
{{- end }}
{{- end }}
{{- end }}

模板文件可以根据需要自行修改,注意处理时间,将时间转换为本地时间。

总结

通过Alertmanager作为统一的告警通道,将Prometheus和Zabbix告警信息放在一起管理,可以减少很多的工作量,值得一试!

Tags:alertmanager配置详解

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言