如何自动测试 Prometheus 警报?

How to automatically test Prometheus alerts?

我们即将设置 Prometheus 来监控我们的云服务并发出警报,包括 Prometheus 服务的持续集成和部署管道以及警报规则/阈值等配置。为此,我正在考虑为 3 个类别编写自动化测试:

  1. 部署期间配置的基本语法检查(我们已经使用 promtool and amtool 执行此操作)
  2. 在部署期间测试警报规则(什么导致警报)
  3. 在部署期间测试警报路由(谁收到什么警报)
  4. 定期检查警报系统是否在生产中正常工作

现在对我来说最重要的部分是测试警报规则(类别 1),但我没有找到执行此操作的工具。我可以想象在部署期间设置一个 Prometheus 实例,为其提供一些度量样本(担心我将如何使用 Prometheus 的 Pull 架构来做到这一点?)然后 运行 查询它。

目前我唯一找到的是与第三类相关的blog post about monitoring the Prometheus Alertmanager chain as a whole

有没有人做过类似的事情或者有什么我遗漏的吗?

新版 Prometheus (2.5) 允许编写警报测试,这里是 link。您可以检查第 1 点和第 2 点。 您必须定义数据和预期输出(例如 test.yml):

rule_files:
    - alerts.yml
evaluation_interval: 1m
tests:
# Test 1.
- interval: 1m
  # Series data.
  input_series:
      - series: 'up{job="prometheus", instance="localhost:9090"}'
        values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0'
      - series: 'up{job="node_exporter", instance="localhost:9100"}'
        values: '1+0x6 0 0 0 0 0 0 0 0' # 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0

  # Unit test for alerting rules.
  alert_rule_test:
      # Unit test 1.
      - eval_time: 10m
        alertname: InstanceDown
        exp_alerts:
            # Alert 1.
            - exp_labels:
                  severity: page
                  instance: localhost:9090
                  job: prometheus
              exp_annotations:
                  summary: "Instance localhost:9090 down"
                  description: "localhost:9090 of job prometheus has been down for more than 5 minutes."

您可以 运行 测试使用 docker:

docker run \
-v $PROJECT/testing:/tmp \
--entrypoint "/bin/promtool" prom/prometheus:v2.5.0 \
test rules /tmp/test.yml

promtool 将验证文件 alerts.yml 中的警报 InstanceDown 是否处于活动状态。这种方法的优点是您不必启动 Prometheus。