如何上报构建时长到 Prometheus?

解读

在国内 CI/CD 流水线中,Prometheus 已成为事实上的监控标准。面试官想知道你是否能把“前端构建”这一黑盒环节纳入 SRE 可观测体系,既要保证数据准确,又要避免侵入 Gulp 本身。核心考点:

  1. 如何无侵入地采集每一次 gulp 任务的耗时;
  2. 如何把指标推送到 Pushgateway(前端 Job 多为短生命周期,无法直接让 Prometheus 来拉);
  3. 如何打标签才能满足国内多项目、多分支、多环境的维度切割需求;
  4. 如何在失败时也能上报,避免“只报喜不报忧”。

知识点

  • Node 性能钩子:perf_hooks.performance.mark() / measure() 可拿到高精度耗时,不受事件循环阻塞影响。
  • Vinyl 文件系统:Gulp 4 的 series() / parallel() 本质上是复合流,可在 taskDone 钩子内统一拦截。
  • Prometheus 指标类型:构建时长用 Histogram(桶:0.5、1、3、5、10、+Inf)比 Summary 更适合国内后续做 P99 告警。
  • Pushgateway 语义:短任务必须 pushAdd 而非 push,否则并发会互相覆盖;job 标签需带 git commitId 保证唯一。
  • 安全合规:国内金融、政务内网要求单向出域,Pushgateway 需放内网,关闭 --web.enable-admin-api,防止指标被删。
  • 错误上报:process.on('unhandledRejection') 里主动 gateway.pushAdd(),确保失败耗时也能进库,方便排障。

答案

  1. 安装依赖
npm i -D prom-client@^14  // 官方 Node SDK
npm i -D axios            // 若 Pushgateway 需带 basic-auth
  1. 创建 lib/metrics.js
const client = require('prom-client');
const gateway = new client.Pushgateway('http://pushgateway.infra.svc.cluster.local:9091');

const buildHistogram = new client.Histogram({
  name: 'gulp_build_duration_seconds',
  help: 'Gulp task build duration in seconds',
  labelNames: ['project', 'branch', 'task', 'status'], // 国内维度
  buckets: [0.5, 1, 3, 5, 10, +Infinity]
});

// 注册到默认 Registry
client.register.registerMetric(buildHistogram);

// 统一上报函数
function report(labels, duration) {
  buildHistogram.observe(labels, duration);
  // 短任务必须 pushAdd,防止并发覆盖
  gateway.pushAdd({ job: `${labels.project}-${labels.branch}-${process.env.CI_COMMIT_SHA}` }, err => {
    if (err) console.error('Pushgateway err:', err.message);
  });
}
module.exports = { report };
  1. 在 gulpfile.js 里无侵入埋点
const { report } = require('./lib/metrics');
const { series, parallel, watch } = require('gulp');

function wrap(taskFn) {
  const start = process.hrtime.bigint();
  return function doneWrapper(cb) {
    function done(err) {
      const dur = Number(process.hrtime.bigint() - start) / 1e9;
      report({
        project: process.env.CI_PROJECT_NAME || 'frontend',
        branch: process.env.CI_COMMIT_REF_NAME || 'dev',
        task: taskFn.name,
        status: err ? 'failure' : 'success'
      }, dur);
      cb(err);
    }
    const ret = taskFn(done);
    if (ret && typeof ret.then === 'function') ret.then(() => done(), done);
  };
}

// 把原有任务包一层
exports.build = series(wrap(clean), wrap(compileSass), wrap(bundleJS));
  1. Prometheus 侧配置
- job_name: 'gulp_pushgateway'
  honor_labels: true
  static_configs:
    - targets: ['pushgateway.infra.svc.cluster.local:9091']
  1. 告警规则(满足国内 SRE 要求)
- alert: GulpBuildP99Slow
  expr: histogram_quantile(0.99, gulp_build_duration_seconds_bucket) > 300
  for: 0m
  annotations:
    summary: '项目 {{ $labels.project }} 分支 {{ $labels.branch }} 构建 P99 超过 5 分钟'

至此,每一次本地或 CI 触发 gulp build 都会把耗时秒级上报,Prometheus 可实时聚合、告警,无需改动原有任务逻辑。

拓展思考

  • 多实例并发:若 GitLab Runner 为 Kubernetes 模式,Pod 名称会频繁复用,需在 job 标签里再加 runner_id 或 pod_name,避免时序错位。
  • 冷启动优化:Node 进程启动本身耗时 200~400 ms,可把 prom-client 初始化和 wrap 函数放独立文件,按需懒加载,减少本地开发感知。
  • 指标持久化:国内部分券商要求7 年以上审计留痕,可把 Histogram 同时远程写到 VictoriaMetrics 或 InfluxDB,通过 dual-write 模式实现。
  • 灰度对比:利用标签 canary= true|false,在 Grafana 做 A/B 构建时长对比,为“升级 Node 18”或“切换 SWC 编译”提供量化依据。
  • 安全加固:Pushgateway 若暴露公网,必须开启 mTLS + 内网 DNS 解析,防止攻击者伪造指标造成磁盘打满;同时给 gateway.delete() 接口加 RBAC,只允许 CI 系统调用。