4. 环境准备:安装 Prometheus、Alertmanager、Grafana、自愈 API 服务

本章是课程的技术基础环节。我们将在一台 CentOS 7.9+ 或 Ubuntu 20.04+ 服务器上,依次部署 Prometheus、Alertmanager、Grafana 以及自愈 API 服务。所有组件均以二进制或容器方式安装,确保后续告警触发自愈流程的链路完整可用。

环境基线: 建议 4 核 8 GB 内存、50 GB 磁盘、可访问互联网。以下操作默认使用 /opt 作为安装根目录。

4.1 整体架构与组件关系

下图展示了四个核心服务之间的数据流与控制流:Prometheus 采集指标并触发告警规则,将告警推送至 Alertmanager;Alertmanager 经过分组、抑制、静默后,通过 webhook 调用自愈 API;自愈 API 执行恢复动作并将结果写回 Prometheus(通过 Pushgateway 或自定义指标);Grafana 从 Prometheus 读取数据,提供可视化面板。

Prometheus 告警自愈组件架构 告警自愈组件架构与数据流 Prometheus 指标采集 + 告警规则 Alertmanager 分组 / 抑制 / 静默 自愈 API 恢复动作执行 Grafana 可视化面板 说明: 实线为告警推送路径,虚线为指标回写与查询路径。 自愈 API 执行后通过 Pushgateway 将恢复状态写回 Prometheus。

4.2 安装 Prometheus

Prometheus 是整套系统的核心,负责指标采集与告警评估。我们使用官方二进制包安装,便于后续配置 systemd 管理。

步骤命令 / 操作说明
1wget https://github.com/prometheus/prometheus/releases/download/v2.53.0/prometheus-2.53.0.linux-amd64.tar.gz下载稳定版本
2tar xzf prometheus-2.53.0.linux-amd64.tar.gz -C /opt/解压到 /opt
3ln -s /opt/prometheus-2.53.0.linux-amd64 /opt/prometheus创建软链接
4useradd -r -s /sbin/nologin prometheus创建专用系统用户
5chown -R prometheus:prometheus /opt/prometheus*授权

创建 systemd 服务文件 /etc/systemd/system/prometheus.service:

[Unit]
Description=Prometheus Monitoring System
Documentation=https://prometheus.io/docs/
After=network.target

[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/opt/prometheus/prometheus \
  --config.file=/opt/prometheus/prometheus.yml \
  --storage.tsdb.path=/opt/prometheus/data \
  --web.listen-address=0.0.0.0:9090
Restart=always

[Install]
WantedBy=multi-user.target

启动并验证:

systemctl daemon-reload
systemctl enable --now prometheus
curl http://localhost:9090/-/ready   # 应返回 Ready

4.3 安装 Alertmanager

Alertmanager 负责接收 Prometheus 推送的告警,执行分组、抑制、静默后,通过 webhook 发送到自愈 API。

步骤命令 / 操作说明
1wget https://github.com/prometheus/alertmanager/releases/download/v0.27.0/alertmanager-0.27.0.linux-amd64.tar.gz下载
2tar xzf alertmanager-0.27.0.linux-amd64.tar.gz -C /opt/解压
3ln -s /opt/alertmanager-0.27.0.linux-amd64 /opt/alertmanager软链接
4useradd -r -s /sbin/nologin alertmanager专用用户
5chown -R alertmanager:alertmanager /opt/alertmanager*授权

创建 systemd 服务文件 /etc/systemd/system/alertmanager.service:

[Unit]
Description=Alertmanager for Prometheus
After=network.target

[Service]
User=alertmanager
Group=alertmanager
Type=simple
ExecStart=/opt/alertmanager/alertmanager \
  --config.file=/opt/alertmanager/alertmanager.yml \
  --storage.path=/opt/alertmanager/data
Restart=always

[Install]
WantedBy=multi-user.target

启动并验证:

systemctl daemon-reload
systemctl enable --now alertmanager
curl http://localhost:9093/-/ready

4.4 安装 Grafana

Grafana 提供可视化仪表盘,便于观察告警趋势与自愈效果。我们使用官方 YUM 仓库安装(CentOS 示例)。

# 添加 Grafana 仓库
cat <<EOF | tee /etc/yum.repos.d/grafana.repo
[grafana]
name=Grafana
baseurl=https://packages.grafana.com/oss/rpm
repo_gpgcheck=1
enabled=1
gpgcheck=1
gpgkey=https://packages.grafana.com/gpg.key
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
EOF

# 安装
yum install -y grafana

# 启动
systemctl enable --now grafana-server

访问 http://<服务器IP>:3000,默认用户名/密码为 admin/admin。首次登录后请立即修改密码。

数据源配置: 在 Grafana 中添加 Prometheus 数据源,URL 填写 http://localhost:9090,保存并测试。

4.5 部署自愈 API 服务

自愈 API 是一个轻量级 Python/Go 服务,接收 Alertmanager 的 webhook 请求,执行预定义的恢复动作(如重启服务、清理磁盘、扩容容器)。我们以 Python Flask 为例快速搭建。

项目结构:

/opt/self-healing-api/
├── app.py              # 主入口
├── requirements.txt    # 依赖
├── actions/            # 恢复动作模块
│   ├── __init__.py
│   ├── restart_service.py
│   └── clean_disk.py
└── config.yml          # 动作映射配置

requirements.txt:

flask==3.0.0
gunicorn==21.2.0
pyyaml==6.0.1
requests==2.31.0

app.py 核心代码:

from flask import Flask, request, jsonify
import yaml
import importlib

app = Flask(__name__)

with open('config.yml', 'r') as f:
    config = yaml.safe_load(f)

@app.route('/webhook', methods=['POST'])
def webhook():
    alert_data = request.json
    alerts = alert_data.get('alerts', [])
    for alert in alerts:
        action_name = alert.get('labels', {}).get('action')
        if action_name and action_name in config['actions']:
            module = importlib.import_module(f"actions.{action_name}")
            module.execute(alert)
    return jsonify({"status": "ok"}), 200

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

使用 systemd 管理自愈 API:

[Unit]
Description=Self-Healing API
After=network.target

[Service]
User=root
WorkingDirectory=/opt/self-healing-api
ExecStart=/usr/local/bin/gunicorn -w 2 -b 0.0.0.0:5000 app:app
Restart=always

[Install]
WantedBy=multi-user.target

启动验证:

systemctl daemon-reload
systemctl enable --now self-healing-api
curl -X POST http://localhost:5000/webhook -H "Content-Type: application/json" -d '{"alerts":[]}'
# 应返回 {"status":"ok"}

4.6 配置 Alertmanager 调用自愈 API

修改 /opt/alertmanager/alertmanager.yml,添加 webhook 接收器:

route:
  receiver: 'self-healing'
  group_wait: 10s
  group_interval: 30s
  repeat_interval: 5m

receivers:
- name: 'self-healing'
  webhook_configs:
  - url: 'http://localhost:5000/webhook'
    send_resolved: true

重启 Alertmanager 使配置生效:

systemctl restart alertmanager
注意: 生产环境中建议为 webhook 添加认证(如 Bearer ),避免未授权调用。同时确保 Alertmanager 与自愈 API 之间的网络连通性。

4.7 验证全链路连通性

在 Prometheus 中创建一条测试告警规则,触发后观察是否成功调用自愈 API。

在 /opt/prometheus/prometheus.yml 中添加规则文件:

rule_files:
  - "rules/*.yml"

创建测试规则 /opt/prometheus/rules/test_alert.yml:

groups:
- name: test
  rules:
  - alert: TestAlert
    expr: vector(1)
    for: 10s
    labels:
      severity: critical
      action: restart_service
    annotations:
      summary: "测试告警 - 触发自愈"

重启 Prometheus:

systemctl restart prometheus

等待约 30 秒后,检查自愈 API 日志:

journalctl -u self-healing-api -f
# 应看到类似 "Executing action restart_service for alert TestAlert"

同时可在 Grafana 的 Explore 页面查询 ALERTS{alertname="TestAlert"} 确认告警状态。

4.8 组件端口与服务清单

组件端口服务名配置文件路径
Prometheus9090prometheus/opt/prometheus/prometheus.yml
Alertmanager9093alertmanager/opt/alertmanager/alertmanager.yml
Grafana3000grafana-server/etc/grafana/grafana.ini
自愈 API5000self-healing-api/opt/self-healing-api/config.yml