在 PagerDuty 中如何按服务分级做 Ruby 告警升级

解读

国内一线互联网公司在做 7×24 运维时,普遍把服务划分为 P0(核心业务)/P1(重要业务)/P2(一般业务) 三级,并规定不同级别的 MTTA(响应时间) 与 MTTR(修复时间)。PagerDuty 作为事件中枢,天然支持 Escaluation Policy(升级策略),但面试官想考察的是:

  1. 能否用 Ruby 代码 把“服务分级”映射到“升级策略”,做到 自动、可回滚、可灰度;
  2. 是否理解 PagerDuty REST API v2 的 services、escalation_policies、rules 三大资源模型;
  3. 是否能在 国内网络环境 下处理好 Token 权限、限流、重试、幂等 等工程细节。

一句话:不是“会不会配网页”,而是“能不能用 Ruby 把分级升级做到 GitOps 级别”。

知识点

  1. PagerDuty 资源模型

    • service → escalation_policy → escalation_rule → target(user/schedule)
    • 一个 service 只能绑定一个 escalation_policy,升级靠 escalation_rule 的 escalation_delay_in_minutes 字段。
  2. 国内常用分级与升级时间

    • P0:1 min 内电话 + 5 min 升级至架构师
    • P1:5 min 内企业微信 + 15 min 升级至值班经理
    • P2:30 min 内邮件 + 2 h 升级至团队负责人
  3. Ruby 实现要点

    • 用 pagerduty_api 官方 gem(或 faraday + net-http-persistent 自封装)做 HTTPS 双向认证;
    • 用 dry-schema 做配置校验,防止手滑把 P0 升级时间写成 100 min;
    • 用 Concurrent::Promise 做批量更新,避免国内到 PagerDuty 的 300 ms RTT 导致超时;
    • 用 Redis + Sidekiq 做幂等重试,key=“pd:ep:#{policy_id}:v#{config_version}”,防止重复提交;
    • 用 GitLab CI 做 canary 发布,先灰度 5% 服务,观察 30 min 无异常再全量。
  4. 合规踩坑

    • 国内账号必须走 PagerDuty 中国加速域名(*.pd-chn.com),否则 20% 概率握手失败;
    • Token 权限最小化:只给 escalation_policies:write、services:read,防止脚本被删库;
    • 审计:每次变更写 Log::Logger 到 Loki,字段带 operator=“ruby-script”/reason=“incident-12345”,方便后续溯源。

答案

以下示例把“服务分级”翻译成三条 Escalation Policy,并自动绑定到对应 Service。代码可直接放进 config/pagerduty/ 目录,由 rake pd:sync 调用。

# config/pagerduty/escalation_mapper.rb
require 'pagerduty_api'
require 'dry-schema'

class EscalationMapper
  SCHEMA = Dry::Schema.Params do
    required(:tier).value(included_in?: %w[P0 P1 P2])
    required(:service_id).filled(:string)
  end

  TIER_RULES = {
    'P0' => [
      { level: 1, delay: 1,  targets: [{ type: 'user', id: 'P0Oncall' }] },
      { level: 2, delay: 5,  targets: [{ type: 'user', id: 'P0Architect' }] }
    ],
    'P1' => [
      { level: 1, delay: 5,  targets: [{ type: 'schedule', id: 'P1Schedule' }] },
      { level: 2, delay: 15, targets: [{ type: 'user', id: 'P1Manager' }] }
    ],
    'P2' => [
      { level: 1, delay: 30, targets: [{ type: 'schedule', id: 'P2Schedule' }] },
      { level: 2, delay: 120, targets: [{ type: 'user', id: 'P2Lead' }] }
    ]
  }.freeze

  def initialize(token)
    @client = PagerDuty::Client.new(token: token, base_url: 'https://api.pd-chn.com')
  end

  def apply!(service_id:, tier:)
    SCHEMA.call(tier: tier, service_id: service_id).to_monad.or do |failure|
      raise ArgumentError, failure.messages.to_h
    end

    policy_name = "Auto-#{tier}-#{service_id}"
    rules       = build_rules(tier)

    # 幂等:先查是否已存在同名 policy
    policy = @client.escalation_policies.list(query: policy_name).dig('escalation_policies', 0)
    if policy
      @client.escalation_policies.update(policy['id'], escalation_rules: rules)
    else
      policy = @client.escalation_policies.create(
        name: policy_name,
        escalation_rules: rules,
        teams: [{ type: 'team', id: 'ops' }]
      )
    end

    # 绑定到 service
    @client.services.update(service_id, escalation_policy: { id: policy['id'], type: 'escalation_policy' })
    { service_id: service_id, policy_id: policy['id'], tier: tier }
  end

  private

  def build_rules(tier)
    TIER_RULES[tier].map do |r|
      {
        escalation_delay_in_minutes: r[:delay],
        targets: r[:targets].map { |t| { id: t[:id], type: t[:type] } }
      }
    end
  end
end

# Rakefile
namespace :pd do
  desc 'Sync escalation policies according to tier'
  task sync: :environment do
    mapper = EscalationMapper.new(ENV['PD_TOKEN'])
    CSV.foreach('config/pagerduty/service_tier.csv', headers: true) do |row|
      mapper.apply!(service_id: row['service_id'], tier: row['tier'])
    end
  end
end

运行 rake pd:sync 后,可在 PagerDuty 控制台看到 Auto-P0-order-service 等策略,且 escalation_delay_in_minutes 与 国内 SRE 手册 完全一致。灰度阶段只需在 CSV 里先放 5% service_id,确认 电话通道 与 企业微信机器人 正常后,再全量推送。

拓展思考

  1. 动态降级:当 P0 服务 1 min 内未认领 且 同一业务集群 3 次升级失败,自动把 escalation_policy 切换为 “P0-Emergency”(包含 CTO 手机号),如何用 Ruby 监听 PagerDuty webhook 并在 50 ms 内完成切换?
  2. 多活容灾:国内合规要求 日志不出境,若 PagerDuty 被墙,如何用 Ruby 把事件双写到 阿里云 SLS + 自研电话网关,并在 网络恢复后 自动回补?
  3. 成本优化:PagerDuty 按 notification 计费,如何用 Ruby 脚本每天凌晨扫描 近 7 天无告警的 P2 服务,自动把 escalation_policy 改成 “静默邮件组”,每月节省 20% 账单?

把这三个场景做成 Sidekiq Cron 任务,就能在下一轮面试里直接聊到 “年省 30 万预算” 的量化结果,稳稳拿到 Offer。