Alertmanager告警规则配置和自动修复?

解读

国内企业在 OpenLDAP 生产环境中普遍采用 Prometheus + Alertmanager 做统一监控。面试官问“告警规则配置和自动修复”,并不是让你背诵 Alertmanager 的 YAML 语法,而是考察三层能力:

  1. 能否把 LDAP 的业务指标(连接数、绑定失败率、复制延迟、证书有效期、条目一致性)翻译成可落地的 Prometheus 规则;
  2. 能否利用 Alertmanager 的 route、inhibit、webhook 把告警精准送达并降噪;
  3. 能否在“不能重启 slapd”的前提下,用最小代价完成自动修复,同时给出回滚方案。
    一句话:既要让告警“叫得准”,又要让故障“自己好”。

知识点

  1. OpenLDAP 可暴露的指标:
    • 通过 slapd-monitor 后端或 openldap_exporter 拿到 openldap_connections_total、openldap_bind_incoming_errors_rate、openldap_syncrepl_status、openldap_certificate_expiry_seconds、openldap_entry_cache_hit_ratio。
  2. Prometheus 规则关键字段:expr、for、labels.severity、annotations.summary、runbook_url。
  3. Alertmanager 核心对象:group_by、group_wait、group_interval、repeat_interval、receiver、webhook_config、inhibit_rule。
  4. 自动修复通道:
    • 轻量级:webhook 调用 Ansible Tower / AWX 模板,对目标主机执行 ansible-playbook ldap-fix.yml --limit=ldap-node-$instance。
    • 重量级:Kubernetes 环境用 Operator 的 LDAPRemediation CRD,触发一次热加载配置或重启 Sidecar。
  5. 安全合规:自动修复脚本必须走 sudo 免密白名单,禁止直接写数据库文件;所有修复动作要二次审批(ChatOps 两次确认或 OA 工单)。
  6. 回滚策略:修复前自动做 slapcat 全量备份;修复失败阈值≥2 次立即升级人工 On-call。

答案

下面给出一套可直接落地的“最小可用”方案,假设集群为 3 节点 MMR(Multi-Master Replication),Prometheus 已安装完毕。

  1. 指标暴露
    每台 LDAP 服务器部署 openldap_exporter 监听 9330 端口,采集脚本关键段:

    docker run -d --name openldap_exporter \
      -e LDAP_URI="ldaps://localhost:636" \
      -e LDAP_BIND_DN="cn=monitor,dc=example,dc=cn" \
      -e LDAP_BIND_PW="${MONITOR_PW}" \
      -p 9330:9330 quay.io/tomcz/openldap_exporter:latest
    
  2. Prometheus 告警规则(精简 3 条,文件位置 /etc/prometheus/rules/ldap.yml)

    groups:
    - name: openldap_critical
      interval: 30s
      rules:
      - alert: LDAP_BindFail_Rate_High
        expr: rate(openldap_bind_incoming_errors_total[5m]) > 0.05
        for: 2m
        labels:
          severity: critical
          team: infra
          auto_heal: "true"
        annotations:
          summary: "{{ $labels.instance }} LDAP 绑定失败率持续高于 5%"
          runbook: "https://wiki.example.cn/ldap/bind-fail-runbook"
    
      - alert: LDAP_SyncRepl_Lag
        expr: openldap_syncrepl_status != 0
        for: 5m
        labels:
          severity: warning
          auto_heal: "true"
        annotations:
          summary: "{{ $labels.instance }} 复制中断或延迟"
    
      - alert: LDAP_Cert_ExpireSoon
        expr: openldap_certificate_expiry_seconds < 86400 * 30
        labels:
          severity: info
          auto_heal: "false"
        annotations:
          summary: "{{ $labels.instance }} 证书将在 30 天内过期"
    
  3. Alertmanager 路由与抑制(/etc/alertmanager/alertmanager.yml)

    global:
      resolve_timeout: 5m
      wechat_api_url: 'https://qyapi.weixin.qq.com/cgi-bin/'
      wechat_corp_id: 'wwxxxx'
      wechat_api_secret: 'xxxxx'
    
    route:
      group_by: ['alertname', 'instance', 'auto_heal']
      group_wait: 30s
      group_interval: 5m
      repeat_interval: 12h
      receiver: 'wechat-infra'
      routes:
      - match:
          auto_heal: "true"
          severity: critical
        receiver: 'webhook-autoheal'
        continue: true
      - match:
          severity: critical
        receiver: 'wechat-infra'
    
    inhibit_rules:
    - source_match:
        severity: 'critical'
        alertname: 'LDAP_BindFail_Rate_High'
      target_match:
        severity: 'warning'
        alertname: 'LDAP_SyncRepl_Lag'
      equal: ['instance']
    
    receivers:
    - name: 'wechat-infra'
      wechat_configs:
      - send_resolved: true
        to_party: '2'
        message: '{{ template "wechat.default.message" . }}'
    
    - name: 'webhook-autoheal'
      webhook_configs:
      - url: 'http://autoheal.example.cn:8080/api/v1/run-ldap-playbook'
        send_resolved: false
        http_config:
          bearer_token: 'LDAP-HEAL-2024'
    
  4. 自动修复端(Flask 示例,跑在 K8s 内部)

    @app.route('/api/v1/run-ldap-playbook', methods='POST')
    def run_playbook():
        alert = json.loads(request.data)
        instance = alert['commonLabels']['instance']
        r = requests.post('https://awx.example.cn/api/v2/job_templates/15/launch/',
                          headers={'Authorization': 'Bearer '+AWX_TOKEN},
                          json={"limit": instance, "extra_vars": {"repair_type": "bind_retry"}})
        return "ok", 200
    

    Ansible 侧 playbook 只做两件事:
    a) 检测是否由于连接池耗尽,若是则 systemctl reload slapd(热加载);
    b) 若 reload 失败,回滚到上一版本配置并短信通知值班。

  5. 效果验证
    使用 ldapsearch -H ldaps://ldap1.example.cn -x -D "cn=test,dc=example,dc=cn" -w wrongpassword 批量制造绑定错误,2 分钟内 Prometheus 触发告警,Alertmanager 先发送企业微信,再调用 webhook;30 秒内 AWX 返回 job=success,绑定失败率回落,告警自动 resolved,全程无需人工登录服务器。

拓展思考

  1. 灰度修复:生产环境往往不允许“全量 reload”。可以在 Ansible 里先摘流(将节点标记为 maintenance=true,由 Consul 或 Nginx 上游自动剔除),再修复,最后健康检查通过后再回流。
  2. 智能阈值:绑定失败率 5% 在早高峰可能误报,可引入时间窗口函数 avg_over_time 做动态基线,或利用 Prometheus 的 predict_linear 做趋势预测。
  3. 多活容灾:如果 MMR 节点全部触发 SyncRepl_Lag,自动修复脚本必须判断“脑裂”风险,此时应直接熔断写操作、切换为只读,并升级 P1 工单,而非继续重启 slapd。
  4. 审计合规:金融、证券类公司要求“任何自动变更留痕”,可在 webhook 里先把修复计划写入 MySQL 审计表,由值班经理在企微小程序里点“同意”后,再真正下发 Ansible 任务。
  5. 云原生演进:把 OpenLDAP 容器化后,可用 ArgoCD + Prometheus Operator 的 PrometheusRule CRD 管理规则,自动修复则通过 Argo Rollout 的 AnalysisTemplate 做金丝雀发布,实现“告警-修复-灰度-验证”闭环。