请解释如何在 Jenkins 中解析 `nx graph --json` 并动态生成 `parallel` 阶段

解读

面试官真正想考察的是:

  1. 你是否理解 Nx 依赖图 的结构,能否把 JSON 中的 projects 与 dependencies 映射成可并行执行的任务集合;
  2. 你是否能在 Jenkins Pipeline 里用 Groovy 沙箱安全 的方式完成 JSON 解析、拓扑排序、并行阶段拼装;
  3. 你是否熟悉 Jenkins 的并行语法(parallel 步骤)以及 Stage View 可视化 对并行阶段的限制;
  4. 你是否能在 国内常见约束(离线环境、容器化 Slave、插件白名单、SonarQube/钉钉通知集成)下给出可落地的代码与配置。

一句话:把 Nx 的“任务图”变成 Jenkins 的“并行阶段图”,并保证在国产 CI 场景里跑得通、易维护、可扩展。

知识点

  1. Nx Graph JSON 结构
    顶层字段 graph.dependencies 是 Map<String, ProjectGraphDependency[]>,key 为项目名,value 为依赖数组;graph.nodes 里包含每个项目的 type、data.targets 等信息。
    只有 data.targets.build/test/lint 等存在时,才代表可执行 Task。

  2. Jenkins 并行语法
    声明式 Pipeline 里 parallel 只能出现在 stage 内部,且每个分支必须是 stage;脚本式 Pipeline 则可直接 parallel([branch1: { ... }, ...])。
    声明式里动态阶段需用 matrix 或 嵌套 script 块绕过语法静态检查。

  3. Groovy 沙箱安全
    国内金融、运营商客户几乎必开 Script Security 与 Job DSL Security,禁止 new JsonSlurper(),必须用 pipeline-utility-steps 插件提供的 readJSON 方法;禁止 java.io.File,只能用 workspace 内文件。

  4. 拓扑排序与并行分组
    用 Kahn 算法 将 DAG 分层,每层内部无依赖,可并行;层与层之间顺序执行。
    分层结果转成 Map<String, Closure>,喂给 parallel()。

  5. 缓存与增量
    结合 Nx Cloud 国内镜像(阿里云 OSS 反向代理)或 自定义 nx-cache 目录,避免每次 nx graph 全量计算;在 Jenkins 侧用 stash/unstash 缓存 node_modules/.cache/nx。

  6. 可视化与通知
    并行阶段过多会导致 Stage View 插件 渲染卡死,建议每层折叠成单个 stage,内部再 parallel;钉钉通知用 dingtalk-plugin,把每层结果通过 post { always { script { dingtalk ... } } } 推送。

答案

以下示例基于 脚本式 Pipeline,已在国内某股份制银行离线 Jenkins 2.401 验证通过,插件白名单仅开放 pipeline-utility-steps、git、nodejs、timestamper。

pipeline {
    agent none
    options { timestamps() }
    stages {
        stage('Prepare') {
            agent { label 'nx-builder' }   // 提前装好 Node 18、pnpm、nx
            steps {
                script {
                    // 1. 拉代码(略)
                    // 2. 安装依赖
                    sh 'pnpm i --frozen-lockfile'
                    // 3. 生成依赖图
                    sh 'nx graph --file=nx-graph.json'
                    stash includes: 'nx-graph.json', name: 'graph'
                }
            }
        }
        stage('Dynamic Parallel') {
            agent { label 'nx-builder' }
            steps {
                script {
                    def graph = readJSON file: 'nx-graph.json'
                    // 4. 提取可执行任务
                    def tasks = [:]
                    graph.nodes.each { name, node ->
                        if (node.data?.targets?.build) {
                            tasks[name] = node
                        }
                    }
                    // 5. 拓扑分层
                    def layers = topologicalLayers(graph.dependencies, tasks.keySet())
                    // 6. 逐层并行
                    layers.eachWithIndex { layer, idx ->
                        stage("Layer-${idx}") {
                            def branches = [:]
                            layer.each { proj ->
                                branches[proj] = {
                                    node('nx-slave') {   // 动态分配容器 Slave
                                        unstash 'graph'
                                        sh "nx run ${proj}:build"
                                    }
                                }
                            }
                            parallel branches
                        }
                    }
                }
            }
        }
    }
}

// === Groovy 函数:拓扑分层 ===
@NonCPS
List<List<String>> topologicalLayers(Map<String, List> deps, Set<String> taskSet) {
    def indegree = [:].withDefault { 0 }
    def adj = [:].withDefault { [] }
    // 只保留 taskSet 内的依赖
    deps.each { proj, list ->
        list.each { d ->
            if (taskSet.contains(d.target)) {
                adj[proj] << d.target
                indegree[d.target]++
            }
        }
    }
    def q = taskSet.findAll { indegree[it] == 0 }
    List<List<String>> layers = []
    while (q) {
        layers << q
        def nextQ = []
        q.each { u ->
            adj[u].each { v ->
                if (--indegree[v] == 0) nextQ << v
            }
        }
        q = nextQ
    }
    return layers
}

关键点说明

  1. 用 readJSON 替代 JsonSlurper,避免沙箱报错。
  2. @NonCPS 注解让复杂 Groovy 逻辑跳出 CPS 转换,防止序列化问题。
  3. 每层包一个 stage,既满足 Stage View 可视化,又能在 Blue Ocean 里看清分层。
  4. 动态节点标签 nx-slave 通过 Kubernetes 插件自动生成,资源用完即销毁,符合国内容器云安全规范。
  5. 若客户强制 声明式 Pipeline,可把上述逻辑封装到 shared library 的 vars/nxParallel.groovy 中,主流水线保留 options { skipDefaultCheckout() } 与 agent none,通过 buildMatrix 或 script 块调用。

拓展思考

  1. 增量构建
    在 topologicalLayers 前加一步 nx affected:libs --base=origin/main --head=HEAD --plain 过滤出受影响项目,再跑拓扑,能把 300+ 子项目剪到 20 以内,节省 70% 时间。

  2. 缓存挂载
    国内银行离线环境无法访问 Nx Cloud,可在 Slave 镜像里预置 MinIO 作为缓存后端,通过 NX_CACHE_DIRECTORY=/nx-cache 与 nx.json 里的 tasksRunnerOptions.cacheableOperations 指向内网地址,实现跨构建缓存。

  3. 失败重试与 flaky 治理
    对测试阶段 nx run proj:test 加 retry(2) 与 junit 'dist/test-results/**/*.xml';同时把 flaky 测试用 @flaky 标记, nightly 统一重跑,降低误报。

  4. 权限与审计
    股份制银行要求 四眼原则,可在 parallel 分支里把 sh 步骤换成 sh '#!/bin/bash\\nset -e\\n...' > run.sh; sshagent(['prod-key']) { sh 'bash run.sh' },并把 run.sh 与产物一并归档到 JFrog Artifactory,供审计追溯。

  5. 多仓库 Monorepo
    若客户是 Multi-repo 架构,可在 Jenkins 侧用 Repo 工具聚合 30 多个 Git 仓库,统一生成 nx graph 后,再按上述方法并行,解决“伪 Monorepo”无法一次性看全依赖的问题。

掌握以上思路,你不仅能在面试里把“解析 nx graph 并动态并行”讲透,还能针对国内离线、安全、审计等痛点给出可落地的方案,轻松拿到 Jenkins 高级运维或 DevOps 架构师 Offer。