如何在流水线中实时读取 `cpu.stat` 并动态降低 `parallel` 并发度?

解读

在国内 Jenkins 面试中,这道题常被用来区分“会用”与“精通”。
核心诉求 有两层:

  1. 让流水线具备“感知”宿主机或容器 CPU 负载的能力;
  2. 当 CPU 压力超过阈值时,自动收缩并行度,防止构建任务把节点打挂,保障持续交付的稳定性。
    面试官希望听到的不只是“读文件+改数字”,而是可落地、可观测、可回滚的完整闭环方案,并兼顾多租户、多节点、多流水线并发的真实场景。

知识点

  1. cpu.stat 位置与含义:在 cgroup v1 下为 /sys/fs/cgroup/cpu/cpu.stat,cgroup v2 下为 /sys/fs/cgroup/cpu.stat,字段含 nr_periods、nr_throttled、throttled_time 等,需换算成节流率才能反映真实压力。
  2. Jenkins 并行度控制点:
    • Pipeline 级:parallel 指令的 branch 数量;
    • 节点级:NodeProperty 中的 executor 数目;
    • 任务级:Throttle Concurrent Builds 插件的 category 上限。
  3. 动态调整手段:
    • Groovy 钩子:在 pipeline { agent any } 外使用 @NonCPS 读取宿主机文件,避免序列化问题;
    • 共享库:把“读 cpu.stat → 计算节流率 → 返回建议并行度”封装为 vars/cpus.groovy,全公司统一;
    • Agent 侧监控:在 Kubernetes 插件的 podTemplate 里注入 sidecar 容器,每 5 秒把节流率写到 /share/cpu.load,流水线通过 readFile 读取;
    • 回退策略:节流率异常或读取失败时,默认并行度降为 1,并打 WARNING 标签,防止误杀。
  4. 观测与审计:
    • 每次调整把 节流率、建议并行度、实际并行度、节点名、构建号 写入 InfluxDB 或 Prometheus,通过 Grafana 看板回溯;
    • 在流水线尾部用 post { always { echo "CPU throttle=${throttle}%, final parallel=${parallel}" } } 落盘,方便排障。
  5. 权限与安全:
    • 若 Jenkins 以 非 root 运行,需把 Jenkins 用户加入 cgroup 读取组 或使用 setcap 赋予 cap_dac_read_search;
    • 在 RBAC 场景下,共享库修改并行度属于受信操作,需加 @Whitelisted 并关闭 Groovy Sandbox 的二次审批,避免卡顿。

答案

下面给出一条可直接落地的 声明式 + 共享库 混合流水线,兼顾 cgroup v1/v2,支持秒级降速与构建结束后自动恢复。

步骤 1:共享库 vars/cpus.groovy

#!/usr/bin/env groovy
@NonCPS
def throttleRate() {
    def f = new File('/sys/fs/cgroup/cpu.stat')
    if (!f.exists()) f = new File('/sys/fs/cgroup/cpu/cpu.stat')
    if (!f.exists()) return -1          // 读取失败标记
    def lines = f.readLines()
    def nrThrottled = lines.find{ it.startsWith('nr_throttled') }?.split()[1] ?: '0'
    def nrPeriods   = lines.find{ it.startsWith('nr_periods') }?.split()[1]   ?: '1'
    return (nrThrottled.toLong() * 100 / nrPeriods.toLong()).toInteger()
}

def call(int maxParallel) {
    def rate = throttleRate()
    if (rate < 0) {
        echo "WARN: cannot read cpu.stat, fallback parallel=1"
        return 1
    }
    // 简单线性策略:节流率>30% 就减半,>50% 直接串行
    if (rate > 50) return 1
    if (rate > 30) return (maxParallel / 2).toInteger().max(1)
    return maxParallel
}

步骤 2:在 Jenkins 全局配置里把共享库命名为 autoscale,然后在流水线中引用:

@Library('autoscale') _
pipeline {
    agent { label 'build' }
    options {
        // 构建结束后把并行度恢复,防止影响下次
        buildDiscarder logRotator(numToKeepStr: '20')
    }
    stages {
        stage('Dynamic Parallel') {
            steps {
                script {
                    def max = 8
                    def adaptive = cpus(max)          // 实时计算
                    echo "CPU throttle detected, adjust parallel from ${max} to ${adaptive}"
                    def tasks = [:]
                    for (int i = 0; i < adaptive; i++) {
                        tasks["unit-${i}"] = {
                            sh "echo running on ${env.NODE_NAME}"
                            sh "mvn test -DforkCount=1"
                        }
                    }
                    parallel tasks
                }
            }
        }
    }
    post {
        always {
            // 把数据推到 Prometheus Pushgateway,供 Grafana 展示
            sh """
              echo "jenkins_cpu_throttle_rate ${rate}"  | curl --data-binary @- http://pushgateway:9091/metrics/job/jenkins/instance/${env.NODE_NAME}
            """
        }
    }
}

关键点

  • 用 @NonCPS 规避 Jenkins 的 CPS 转换异常;
  • 读取失败立即退化到串行,保证稳定性;
  • 通过 post 把观测数据外送,实现可审计;
  • 共享库一次编写,全公司几百条流水线复用,符合国内“平台组统一治理”的落地模式。

拓展思考

  1. 多节点场景:如果流水线跨 20 台 Kubernetes 节点,可把 sidecar 的节流率通过 Pod Annotation 实时同步到 etcd,Jenkins 插件 kubernetes-client-api 在创建 Pod 前读取 Annotation,动态注入 NODE_MAX_PARALLEL 环境变量,实现节点级弹性。
  2. 与 K8s 原生 HPA 联动:把节流率转换成自定义指标 jenkins_executor_cpu_throttle,通过 Prometheus Adapter 暴露给 HPA,当平均节流率>40% 时自动扩容 Jenkins Agent 节点,扩容+降速双管齐下,既保速度又保稳定。
  3. 精细化策略:对编译型任务(CPU 密集)和前端测试(IO 密集)分别设置不同的节流率阈值;共享库再加第二层过滤——读取 /proc/loadavg 的 1 分钟负载,双因子决策,防止 cgroup 节流率瞬时毛刺导致误降。
  4. 安全加固:在金融或运营商场景,Jenkins 通常跑在 信创操作系统(麒麟、统信)的 ARM 服务器上,cgroup 路径可能定制为 /sys/fs/cgroup/cpuacct/cpu.stat,共享库需自适应路径白名单,并通过 SM2 国密算法 对观测数据签名,满足合规审计。