FreezeJ' Blog

调用alertmanager API实现静默

2021-08-16

Prometheus提供了一个官方的报警管理组件alertmanager,虽然也有图形化界面,但是页面没有提供定时静默的功能,但是开放了API,可以通过调用API去实现插入静默规则

API文档:https://raw.githubusercontent.com/prometheus/alertmanager/main/api/v2/openapi.yaml
复制到https://editor.swagger.io/即可

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import datetime
import time
import json

datetime_now = datetime.datetime.now()
datetime_start = datetime_now.replace(hour=5, minute=0, second=0, microsecond=0) # 5点开始静默
datetime_start_utc = datetime_start - datetime.timedelta(hours=8)  # 转换时区
datetime_end_utc = datetime_start_utc + datetime.timedelta(hours=5)  # 静默持续时间

url = "http://127.0.0.1:9093/api/v2/silences"

payload_dict = {
    "matchers": [
        {
            "name": "host_type",
            "value": "异地备份",
            "isRegex": False,
            "isEqual": True
        }
    ],
    "startsAt": datetime_start_utc.strftime('%Y-%m-%dT%H:%M:%SZ'),
    "endsAt": datetime_end_utc.strftime('%Y-%m-%dT%H:%M:%SZ'),
    "createdBy": "Freeze",
    "comment": "定时静默异地备份报警"
}
payload = json.dumps(payload_dict).encode('utf-8')

headers = {
#  'Authorization': 'Basic xxxxxxxxxxx',  # 认证
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏