> For the complete documentation index, see [llms.txt](https://pshizhsysu.gitbook.io/prometheus/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pshizhsysu.gitbook.io/prometheus/ff08-san-ff09-prometheus-gao-jing-chu-li/kuo-zhan-yue-du/prometheusfa-song-gao-jing-ji-zhi.md).

# Prometheus发送告警机制

我们先来看一下在Prometheus中，告警（Alert）的数据结构是什么样子的。

<https://github.com/prometheus/prometheus/blob/master/rules/alerting.go>

在上面的这个文件中，我们可以找到Alert的定义，如下：

```
type Alert struct {
    State AlertState    # Inactive Pending Firing
    Labels      labels.Labels
    Annotations labels.Labels
    Value float64            # The value at the last evaluation of the alerting expression    
    ActiveAt   time.Time    
    FiredAt    time.Time
    ResolvedAt time.Time    # ResolvedAt will be 0 to indicate a still active alert
    LastSentAt time.Time
    ValidUntil time.Time
}
```

* `Labels`：可以用来唯一标识一个Alert
* `State`：Alert的状态，有Inactive、Pending、Firing三种状态
* `Value`：该条Alert最后一次计算得到的值

假设我们定义了如下的一条告警规则：

```
groups:
- name: Node
  rules:
  - alert: NodeCpuPressure
    expr: 100 * (1 - avg(irate(node_cpu_seconds_total{mode="idle"}[2m])) by(instance)) > 80
    for: 2m
    annotations:
      summary: "NodeCpuPressure, Node: {{$labels.node}}, Value: {{$value}}, Threshold: 80%"
```

并用在prometheus.yml中配置了两个NodeExporter：

```
scrape_configs:
  - job_name: "node-exporter"
    static_configs:
    - targets: ['192.168.2.101:9100']
      labels:
        node: 192.168.2.101
    - targets: ['192.168.2.102:9100']
      labels:
        node: 192.168.2.102
```

那么，prometheus便会生成两个Alert。这两个Alert的`Labels`分别是`{alertname=NodeCpuPressure, node=192.168.2.101, ...}`（假设我们命名为Alert1）与`{alertname=NodeCpuPressure, node=192.168.2.102, ...}`（假设我们命名为Alert2）。

假设在T时刻，Prometheus计算（Evaluate）得到节点101的CPU使用率为85%，那么Alert1的`ActiveAt`便会被设置为时刻T。两分钟后如果CPU的使用率还是大于80%，那么便会设置`FiredAt`的值与`LastSentAt`的值，并且向AlertManager发送告警。

如果节点101的CPU持续在80%以上，那么prometheus会每隔一段时间（30s \~ 3m）把Alert1发送一次。

如果在K时刻计算得到101节点的CPU小于了80%，那么Prometheus便会设置`ResolvedAt`值，并立即向AlertManager发送一个告警。
