构建 ILM 违规告警的 Watcher 规则示例

解读

在国内中大型互联网、金融、运营商等生产环境,ILM(Index Lifecycle Management) 是降本增效的刚需:热节点 SSD 存放 7 天内的日志,温节点 SATA 存放 30 天指标,冷节点存放 90 天归档,超期删除。若因配置错误、节点磁盘水位、模板优先级或权限问题导致索引无法按预期滚动、迁移、删除,就会出现 “ILM 违规”——轻则磁盘打满新数据写不进,重则集群 red。面试官让你“写一条 Watcher 规则”并不是考语法,而是看你是否能把 “发现违规 → 定位原因 → 及时告警 → 附带行动” 闭环落地,且规则必须能在 国产化信创环境(aarch64 + JDK17 + Elasticsearch 8.x) 直接投产。

知识点

  1. ILM 运行机理:Policy → Phase(hot/warm/cold/delete)→ Action(rollover/shrink/forcemerge/delete)→ Step(如“check-rollover-ready”、“attempt-rollover”)。每一步失败都会在索引元数据里留下 “step_info” 与 “failed_step”。
  2. 违规特征:索引 settings.index.lifecycle.rollover_alias 存在但 “age”|”docs”|”size”条件已满足却未 rollover;索引 stuck 在 “warm” 阶段超过 30 min;索引被标记为 “index.lifecycle.indexing_complete: true” 却未进入 cold;索引 creation_date 已超过 delete.phase_time 但仍存在。
  3. Watcher 触发模式:schedule → input search → condition compare → transform payload → throttle → actions(webhook/邮件/钉钉/企业微信/飞书)。国内现场通常要求 “钉钉群机器人 + 值班手机” 双通道,且必须带 trace_id 方便跳转到 Kibana ILM UI。
  4. 权限与性能:Watcher 需 cluster:monitor/ 与 indices:admin/ilm/get* 权限;搜索 .ilm-* 系统索引需 allow_restricted_indices: true;规则本身要设置 “throttle_period_in_millis”: 900000(15 min)防止轰炸。
  5. 可观测性:规则要输出 集群 UUID、索引、policy、failed_step、node_id、磁盘使用率、建议命令 六个维度,方便值班 5 分钟内定位。

答案

以下示例基于 Elasticsearch 8.11 国产化发行版,可直接复制到 Kibana → Stack Management → Watcher → Create threshold rule → Advanced(JSON)里使用。规则每 5 分钟扫描一次,发现 “过去 1 小时内有索引因 ILM 失败而停留在 hot 阶段且未 rollover” 即告警,并通过 钉钉群机器人 发送 Markdown 卡片,附带一键诊断链接。

PUT _watcher/watch/ilm_violation_hot_rollover
{
  "trigger": {
    "schedule": { "interval": "5m" }
  },
  "input": {
    "search": {
      "request": {
        "indices": [".ilm-*"],
        "allow_no_indices": true,
        "allow_restricted_indices": true,
        "body": {
          "size": 0,
          "query": {
            "bool": {
              "filter": [
                { "range": { "@timestamp": { "gte": "now-1h" } } },
                { "term":  { "type": "step_info" } },
                { "term":  { "step": "attempt-rollover" } },
                { "exists": { "field": "error" } }
              ]
            }
          },
          "aggs": {
            "by_index": {
              "terms": { "field": "index", "size": 50 },
              "aggs": {
                "top_error": {
                  "top_hits": {
                    "size": 1,
                    "_source": ["index", "policy", "step", "error.stack_trace", "cluster.uuid"],
                    "sort": [{ "@timestamp": { "order": "desc" } }]
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "condition": {
    "compare": { "ctx.payload.aggregations.by_index.buckets.size": { "gt": 0 } }
  },
  "transform": {
    "script": {
      "source": """
        return ctx.payload.aggregations.by_index.buckets.stream().map(b -> {
          def hit = b.top_error.hits.hits[0]._source;
          return [
            'index'      : hit.index,
            'policy'     : hit.policy,
            'failed_step': hit.step,
            'error'      : hit.error.stack_trace,
            'cluster_id' : hit.cluster.uuid
          ];
        }).collect(Collectors.toList());
      """,
      "lang": "painless"
    }
  },
  "throttle_period_in_millis": 900000,
  "actions": {
    "ding_webhook": {
      "webhook": {
        "method": "POST",
        "url": "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
        "headers": { "Content-Type": "application/json" },
        "body": {
          "msgtype": "markdown",
          "markdown": {
            "title": "Elasticsearch ILM 违规告警",
            "text": """
## 🚨 ILM 违规:索引未按时 rollover
**集群 UUID**: {{#ctx.payload._value}}{{cluster_id}}{{/ctx.payload._value}}  
**违规索引**: {{#ctx.payload._value}}{{index}}{{/ctx.payload._value}}  
**策略名称**: {{#ctx.payload._value}}{{policy}}{{/ctx.payload._value}}  
**失败步骤**: {{#ctx.payload._value}}{{failed_step}}{{/ctx.payload._value}}  
**错误信息**:  

{{#ctx.payload._value}}{{error}}{{/ctx.payload._value}}

**建议排查**:  
1. Kibana → Index Management → {{index}} → ILM Explain  
2. 检查 rollover_alias 是否写入新数据  
3. 确认主分片磁盘使用率 < 85%  
4. 手动重试: `POST {{index}}/_ilm/retry`
"""
          }
        }
      }
    }
  }
}

使用要点

  • 将 YOUR_TOKEN 换成实际钉钉群机器人 access_token;如需加签,可在 url 后追加 &timestamp=xxx&sign=xxx。
  • 若集群开启 Security,需给 watcher 用户赋予:
    cluster:monitor/xpack/watcher/watch/put, cluster:monitor/*, indices:admin/ilm/get, indices:monitor/stats。
  • 规则上线后,在 Stack Monitoring → Watcher 确认执行耗时 < 2 s;若索引量大,可把 size 降到 20 并加 “preference”: “_primary” 降低副本压力。

拓展思考

  1. 多集群联邦告警:国内集团化公司往往有 “京沪双活 + 边缘云” 数十个集群,可在 Kibana 中央告警集群 建立 Cross-cluster search 模式,把 .ilm-* 远程索引别名为 ilm-audit,一条 Watcher 即可全局扫描,payload.transform 里再按 cluster_alias 分组,实现 “一张钉钉卡片聚合所有违规”。
  2. 自动修复:在 actions 里增加 “index_retry” 子动作,调用 POST {{index}}/_ilm/retry;若失败 3 次仍卡住,则自动创建 JIRA 工单(通过 webhook 调用内部工单系统 API),实现 L1 无人值守。
  3. 成本治理闭环:将每次违规记录到 独立 metrics 索引,字段包含 “浪费的 SSD 天数”((now - rollover_should_time) * primary_size),再用 Lens 仪表盘 展示各业务团队因 ILM 违规产生的 “额外存储成本”,每月推送给财务与业务负责人,用数据驱动降本,这是国内云厂商和大型银行正在落地的 FinOps 实践。
  4. 国产化适配:在 aarch64 服务器 上,Lucene 9 默认启用 Vector API,Watcher 搜索 .ilm-* 会用到 BKD 树高并发读取,需关闭 -XX:-UseCompressedOops 以避免 32 位指针溢出;同时建议把 heap 设为 31 GB 以内 以保留 Zero-based Compressed Oops 优化,确保规则本身不会成为集群性能瓶颈。