如何在 orchestrate 中集成 Prometheus 探针,错误率 >1% 自动中断发布?

解读

这道题考察的是 SaltStack 编排层(orchestrate)与可观测体系的联动能力,核心诉求是“灰度发布 + 实时质量守护”。
国内一线互联网公司在做 DevOps 流水线 时,普遍把 SaltStack 当作“最后一把扳手”——负责把制品真正下发到生产环境;而 Prometheus 作为云原生监控的事实标准,承担“裁判员”角色。
面试官想知道:

  1. 你是否理解 orchestrate SLS 的生命周期钩子;
  2. 能否把 PromQL 查询结果 转化为 SaltStack 可识别的 “继续/中断”信号;
  3. 是否具备 失败回滚 的闭环思维。

知识点

  1. orchestrate SLS 文件结构:salt://srv/salt/orch/deploy.sls,使用 salt.state 与 salt.function 两种 runner。
  2. Jinja2 上下文变量:{{ pillar.get('app_name') }}、{{ salt['grains.get']('env') }},可在编排阶段动态注入。
  3. Prometheus HTTP API:http://prometheus.intra/api/v1/query?query=,返回 JSON,字段 result[0].value[1] 即为瞬时错误率。
  4. SaltStack 自定义 runner:放在 _runners/ 目录,通过 salt-run 调用,Python 代码里可直接 import requests 拉取 Prometheus 数据。
  5. failhard 与 retry 机制:failhard: True 让 orchestrate 在单步失败后立刻退出;retry: {attempts: 3, until: True} 可做轮询。
  6. 国内网络合规:Prometheus 通常部署在 内网域名,需走 公司统一接入层(如 Nginx + VPN),避免公网暴露。
  7. 发布回滚:利用 salt.state.apply 回滚到上一版 release_id,并通过 slack_webhook 或 企业微信机器人 通知值班。

答案

  1. 编写自定义 runner prom_probe.py,放到 _runners/ 并同步到 Master:
import requests, json
def check_error_rate(app, duration="2m", threshold=1.0):
    promql = '''
    sum(rate(http_requests_total{app="%s",status=~"5.."}[%s])) 
    / 
    sum(rate(http_requests_total{app="%s"}[%s])) * 100
    ''' % (app, duration, app, duration)
    url = "http://prometheus.intra/api/v1/query"
    resp = requests.get(url, params={"query": promql}, timeout=3)
    if not resp.ok:
        return {"result": False, "msg": "prometheus unreachable"}
    value = float(resp.json()["data"]["result"][0]["value"][1])
    return {"result": value <= threshold, "error_rate": value}
  1. 在 orch/deploy.sls 里编排三段式:
{% set app = pillar['app_name'] %}
{% set tgt = 'G@env:prod and G@app:' + app %}

# 阶段1:灰度 10% 机器
gray_deploy:
  salt.state:
    - tgt: {{ tgt }}
    - tgt_type: compound
    - batch: 10%
    - sls:
      - app.deploy
    - failhard: True

# 阶段2:探针检查
probe_check:
  salt.runner:
    - name: prom_probe.check_error_rate
    - app: {{ app }}
    - threshold: 1.0
    - failhard: True

# 阶段3:全量或回滚
{% if salt['runners.prom_probe.check_error_rate'](app, threshold=1.0)['result'] %}
full_deploy:
  salt.state:
    - tgt: {{ tgt }}
    - sls:
      - app.deploy
{% else %}
rollback:
  salt.state:
    - tgt: {{ tgt }}
    - sls:
      - app.rollback
{% endif %}
  1. 触发命令:
salt-run state.orch orch.deploy pillar='{"app_name":"order"}'
  1. 若错误率 >1%,probe_check 步骤返回非零,orchestrate 立即中断,并因 failhard: True 不再执行后续 full_deploy,实现 自动熔断。

拓展思考

  1. 多集群场景:可在 runner 里增加 cluster 参数,PromQL 加入 cluster=~"${cluster}" 标签,实现 同应用多机房独立校验。
  2. 指标漂移:国内业务常因 晚高峰流量突增 导致错误率瞬时抖动,可引入 二阶条件:连续 2 次探测(间隔 30s)均 >1% 才判定为失败,降低误杀。
  3. 权限治理:Prometheus 查询接口需对接 公司统一 SSO,runner 里使用 requests.auth.HTTPKerberosAuth 或 服务账号 JWT,避免明文账号。
  4. 审计合规:在 runner 中把每次探针结果写入 Kafka 或 ELK,字段包含 app、release_id、error_rate、decision,方便后续 故障复盘与审计。