AIOps2.0全链路自愈运维系统搭建
动手前先备好这些组件
搭建AIOps2.0全链路自愈运维系统的前提是一套能采集指标、设定告警并自动执行修复命令的工具链。
以下是你需要准备的环境:
- 一台 Linux 服务器(CentOS 7+ 或 Ubuntu 20.04+,建议 2 核 4G 以上)
- Docker 和 Docker Compose(用于快速拉起 Prometheus 和 Alertmanager)
- 基本的 Shell / Python 编程能力(只需能写简单脚本)
- 目标业务服务的访问权限(比如需要重启 Nginx、清理日志等)
如果还没有 Docker,执行以下命令安装:
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo systemctl start docker
sudo systemctl enable docker
让Prometheus学会“报警”的关键配置
Prometheus 负责采集服务器指标,Alertmanager 负责处理告警并触发自愈。
先用 Docker 启动它们:
mkdir -p /opt/prometheus /opt/alertmanager
cd /opt/prometheus
创建 prometheus.yml:
global:
scrape_interval: 15s
rule_files:
- "rules/*.yml"
alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']
scrape_configs:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
创建 rules/node_alerts.yml:
groups:
- name: node_alerts
rules:
- alert: HighCpuUsage
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 2m
labels:
severity: critical
annotations:
summary: "CPU 使用率超过 80%"
然后启动容器(使用 docker-compose.yml):
version: '3'
services:
prometheus:
image: prom/prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./rules:/etc/prometheus/rules
ports:
- "9090:9090"
alertmanager:
image: prom/alertmanager
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml
ports:
- "9093:9093"
Alertmanager 的配置文件 alertmanager.yml 需要指定自愈的 webhook 地址:
route:
receiver: 'webhook'
receivers:
- name: 'webhook'
webhook_configs:
- url: 'http://localhost:5000/selfheal'
执行 docker-compose up -d 启动所有服务。
自愈脚本——让服务器自己修自己
用 Python 写一个简单的 webhook 服务,接收告警并执行修复命令。
创建 /opt/selfheal/app.py:
from flask import Flask, request, jsonify
import subprocess
import json
app = Flask(__name__)
@app.route('/selfheal', methods=['POST'])
def selfheal():
data = request.json
alerts = data.get('alerts', [])
for alert in alerts:
alert_name = alert['labels']['alertname']
if alert_name == 'HighCpuUsage':
# 示例:重启高消耗进程(实际需要根据业务调整)
subprocess.run(['systemctl', 'restart', 'nginx'])
return jsonify({'status': 'fix executed'})
return jsonify({'status': 'no action'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
安装依赖并运行:
pip install flask
python app.py &
可以用 curl 测试 webhook 是否正常:
curl -X POST http://localhost:5000/selfheal -H "Content-Type: application/json" -d '{"alerts":[{"labels":{"alertname":"HighCpuUsage"}}]}'
新手最容易踩的四个坑
- 告警规则表达式写错:先用 Prometheus 的表达式浏览器(
http://服务器IP:9090/graph)验证指标是否存在、值是否合理。 - webhook 地址写错:Alertmanager 容器内部无法通过
localhost访问宿主机的 Python 服务,需要将url改为宿主机的实际 IP(如http://192.168.1.100:5000/selfheal)。 - 脚本权限不足:如果自愈脚本需要
systemctl restart等特权命令,务必用sudo或在 Python 中配置免密码 sudo。 - 告警重复触发:使用
for: 2m避免短时波动触发多次修复,同时在脚本中增加去重逻辑。
亲手触发一次故障,看系统如何自愈
在服务器上模拟 CPU 高负载:
dd if=/dev/zero of=/dev/null &
等待 2 分钟后,Prometheus 告警规则触发,Alertmanager 将告警推送到你的 webhook 服务,脚本自动执行重启 Nginx 或清理进程。
通过 journalctl -u nginx 查看是否被重启过。
验证成功后,用 killall dd 停止压力。
至此,AIOps2.0全链路自愈运维系统的基础搭建就完成了。
后续你可以根据业务需要扩展更多指标和修复规则。