worker-module-architecture
Worker 构建执行器模块架构指南,涵盖插件执行引擎、任务分发、日志上报、制品上传、Worker 生命周期。当用户开发 Worker 功能、实现插件执行、处理任务分发或优化执行器性能时使用。
Install
mkdir -p .claude/skills/worker-module-architecture && curl -L -o skill.zip "https://mcp.directory/api/skills/download/2191" && unzip -o skill.zip -d .claude/skills/worker-module-architecture && rm skill.zipInstalls to .claude/skills/worker-module-architecture
About this skill
Worker 构建执行器模块架构指南
模块概述
Worker 模块是 BK-CI 构建执行器的核心组件,运行在构建机(Agent)上,负责接收并执行流水线任务。它是连接 CI 服务端与构建环境的桥梁,实现了任务调度、插件执行、日志上报、心跳维护等关键功能。
核心职责
- 任务执行:接收并执行流水线中的各类任务(脚本、插件等)
- 日志服务:收集构建日志并上报到 Log 服务
- 心跳维护:定期向服务端发送心跳,维持构建状态
- 变量管理:管理构建过程中的环境变量和上下文
- 制品归档:将构建产物上传到制品库
- 插件运行:下载并执行研发商店中的插件
运行模式
Worker 支持三种构建类型:
| 类型 | 说明 | 场景 |
|---|---|---|
DOCKER | Docker 容器构建 | 公共构建资源池 |
AGENT | 第三方构建机 | 用户自有构建机 |
WORKER | 无编译环境 | 轻量级任务执行 |
目录结构
src/backend/ci/core/worker/
├── build.gradle.kts # 模块构建配置
├── worker-agent/ # Agent 启动入口
│ ├── src/main/kotlin/
│ │ └── com/tencent/devops/agent/
│ │ ├── Application.kt # 主入口,根据构建类型启动
│ │ ├── AgentVersion.kt # 版本信息
│ │ └── service/
│ │ └── BuildLessStarter.kt # 无编译构建启动器
│ └── src/test/kotlin/ # 测试代码
├── worker-common/ # 公共组件库
│ ├── src/main/kotlin/
│ │ └── com/tencent/devops/worker/common/
│ │ ├── Runner.kt # 核心运行器
│ │ ├── WorkRunner.kt # 第三方构建机运行器
│ │ ├── api/ # API 客户端
│ │ ├── env/ # 环境变量管理
│ │ ├── heartbeat/ # 心跳服务
│ │ ├── logger/ # 日志服务
│ │ ├── service/ # 业务服务
│ │ ├── task/ # 任务执行框架
│ │ ├── utils/ # 工具类
│ │ └── constants/ # 常量定义
│ └── src/main/kotlin/
│ └── com/tencent/devops/plugin/worker/task/
│ ├── archive/ # 归档任务
│ ├── scm/ # 代码拉取任务
│ └── image/ # 镜像任务
└── worker-api-sdk/ # API SDK 实现
└── src/main/kotlin/
└── com/tencent/devops/worker/common/api/
├── archive/ # 制品库 API
├── atom/ # 插件 API
├── log/ # 日志 API
├── process/ # 流水线 API
└── ... # 其他 API
核心组件
1. Runner - 核心运行器
Runner.kt 是 Worker 的核心入口,负责整个构建生命周期管理:
object Runner {
fun run(workspaceInterface: WorkspaceInterface, systemExit: Boolean = true) {
// 1. 获取构建变量
val buildVariables = getBuildVariables()
// 2. 准备工作空间、启动日志服务、启动心跳
val workspacePathFile = prepareWorker(buildVariables, workspaceInterface)
// 3. 循环获取并执行任务
loopPickup(workspacePathFile, buildVariables)
// 4. 清理并结束构建
finishWorker(buildVariables)
}
}
核心流程:
┌─────────────────────────────────────────────────────────────┐
│ Worker 启动流程 │
├─────────────────────────────────────────────────────────────┤
│ 1. EngineService.setStarted() → 上报启动状态,获取构建变量 │
│ 2. LoggerService.start() → 启动日志服务 │
│ 3. Heartbeat.start() → 启动心跳监控 │
│ 4. loopPickup() → 循环领取任务 │
│ ├── claimTask() → 获取待执行任务 │
│ ├── TaskFactory.create() → 创建任务执行器 │
│ ├── taskDaemon.run() → 执行任务 │
│ └── completeTask() → 上报任务结果 │
│ 5. finishWorker() → 结束构建 │
└─────────────────────────────────────────────────────────────┘
2. TaskFactory - 任务工厂
任务工厂负责根据任务类型创建对应的执行器:
object TaskFactory {
private val taskMap = ConcurrentHashMap<String, KClass<out ITask>>()
fun init() {
// 注册内置任务类型
register(LinuxScriptElement.classType, LinuxScriptTask::class)
register(WindowsScriptElement.classType, WindowsScriptTask::class)
register(MarketBuildAtomElement.classType, MarketAtomTask::class)
// 通过反射扫描注册插件任务
val reflections = Reflections("com.tencent.devops.plugin.worker.task")
// ...
}
fun create(type: String): ITask {
val clazz = taskMap[type] ?: return EmptyTask(type)
return clazz.primaryConstructor?.call() ?: EmptyTask(type)
}
}
3. ITask - 任务接口
所有任务执行器的基类:
abstract class ITask {
private val environment = HashMap<String, String>()
// 任务执行入口
fun run(buildTask: BuildTask, buildVariables: BuildVariables, workspace: File) {
execute(buildTask, buildVariables, workspace)
}
// 子类实现具体执行逻辑
protected abstract fun execute(
buildTask: BuildTask,
buildVariables: BuildVariables,
workspace: File
)
// 添加环境变量(输出变量)
protected fun addEnv(env: Map<String, String>) {
// 校验只读变量、变量名合法性
environment.putAll(env)
}
fun getAllEnv(): Map<String, String> = environment
}
4. LoggerService - 日志服务
负责构建日志的收集、缓冲和上报:
object LoggerService {
private val uploadQueue = LinkedBlockingQueue<LogMessage>(2000)
fun addNormalLine(message: String) {
// 1. 处理日志前缀(DEBUG/ERROR/WARN)
// 2. 敏感信息过滤
// 3. 本地落盘(如需要)
// 4. 放入上报队列
uploadQueue.put(logMessage)
}
fun addErrorLine(message: String) {
addNormalLine("$LOG_ERROR_FLAG$message")
}
fun addWarnLine(message: String) {
addNormalLine("$LOG_WARN_FLAG$message")
}
// 日志折叠
fun addFoldStartLine(foldName: String) {
addLog(LogMessage(message = "##[group]$foldName", ...))
}
fun addFoldEndLine(foldName: String) {
addLog(LogMessage(message = "##[endgroup]$foldName", ...))
}
}
5. Heartbeat - 心跳服务
维持与服务端的连接,监控任务超时:
object Heartbeat {
fun start(jobTimeoutMills: Long, executeCount: Int) {
// 定时心跳(每2秒)
executor.scheduleWithFixedDelay({
val heartBeatInfo = EngineService.heartbeat(...)
// 处理取消任务
if (!heartBeatInfo.cancelTaskIds.isNullOrEmpty()) {
KillBuildProcessTree.killProcessTree(...)
}
}, 10, 2, TimeUnit.SECONDS)
// Job 超时监控
executor.scheduleWithFixedDelay({
LoggerService.addErrorLine("Job timeout")
EngineService.timeout()
exitProcess(99)
}, jobTimeoutMills, jobTimeoutMills, TimeUnit.MILLISECONDS)
}
}
6. EngineService - 引擎服务
与 Process 服务通信的客户端:
object EngineService {
// 上报启动状态
fun setStarted(): BuildVariables
// 领取任务
fun claimTask(): BuildTask
// 完成任务
fun completeTask(taskResult: BuildTaskResult)
// 结束构建
fun endBuild(variables: Map<String, String>, result: BuildJobResult)
// 心跳
fun heartbeat(executeCount: Int, jobHeartbeatRequest: JobHeartbeatRequest): HeartBeatInfo
// 超时上报
fun timeout()
// 错误上报
fun submitError(errorInfo: ErrorInfo)
}
任务类型
内置任务
| 任务类型 | 类名 | 说明 |
|---|---|---|
linuxScript | LinuxScriptTask | Linux Shell 脚本 |
windowsScript | WindowsScriptTask | Windows Bat 脚本 |
marketBuild | MarketAtomTask | 研发商店插件 |
marketBuildLess | MarketAtomTask | 无编译环境插件 |
插件任务(plugin 包)
| 任务类型 | 类名 | 说明 |
|---|---|---|
reportArchive | ReportArchiveTask | 报告归档 |
singleFileArchive | SingleFileArchiveTask | 单文件归档 |
buildArchiveGet | BuildArchiveGetTask | 获取构建产物 |
customizeArchiveGet | CustomizeArchiveGetTask | 获取自定义产物 |
codeGitPull | CodeGitPullTask | Git 代码拉取 |
codeGitlabPull | CodeGitlabPullTask | GitLab 代码拉取 |
codeSvnPull | CodeSvnPullTask | SVN 代码拉取 |
githubPull | GithubPullTask | GitHub 代码拉取 |
MarketAtomTask - 插件执行
研发商店插件的执行流程:
┌─────────────────────────────────────────────────────────────┐
│ 插件执行流程 │
├─────────────────────────────────────────────────────────────┤
│ 1. 获取插件信息 │
│ atomApi.getAtomEnv(projectCode, atomCode, atomVersion) │
│ │
│ 2. 准备执行环境 │
│ ├── 创建临时工作目录 │
│ ├── 下载/缓存插件包 │
│ └── 校验 SHA 完整性 │
│ │
│ 3. 准备输入参数 │
│ ├── 解析 input.json │
│ ├── 替换变量和凭据 │
│ └── 写入 .sdk.json(SDK 环境信息) │
│ │
│ 4. 执行插件 │
│ ├── Linux: ShellUtil.execute() │
│ └── Windows: BatScriptUtil.execute() │
│ │
│ 5. 处理输出 │
│ ├── 读取 output.json │
│ ├── 处理输出变量 │
│ ├── 归档制品(artifact 类型) │
│ └── 归档报告(report 类型) │
└─────────────────────────────────────────────────────────────┘
插件 SDK 环境
Worker 为插件提供的 SDK 环境信息(.sdk.json):
data class SdkEnv(
val buildType: BuildType, // 构建类型
val projectId: String, // 项目ID(english_name)
val agentId: String, // 构建机ID
val secretKey: String, // 密钥
val gateway: String, // 网关地址
val buildId: String, // 构建ID
val vmSeqId: String, // 虚拟机序号
val fileGateway: String, // 文件网关
val taskId: String, // 任务ID
val executeCount: Int // 执行次数
)
插件输出处理
// output.json 格式
{
"status": "success", // success/failure
"data": {
"outVar1": {
"type": "string",
"value": "xxx"
},
"outVar2": {
"type": "artifact",
"value": ["file1.zi
---
*Content truncated.*
More by TencentBlueKing
View all skills by TencentBlueKing →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversManage resources in the Cloudflare Workers Platform easily by connecting to your Worker via Bindings.
Cloudflare Observability offers advanced network monitoring software, delivering insights and trends for smarter network
Easily manage and gain insights into your Cloudflare Workers Builds with integrated tools. Optimize and monitor your Clo
Access Cloudflare documentation fast via a Cloudflare Worker using an indexed Vectorize DB. Ideal for Cloudflare API doc
Cloudflare Workers empowers MCP to deploy scalable, low-latency AI services at the network edge for optimal performance.
Integrate Readwise to retrieve notes and search highlights, enhancing knowledge work—ideal for recovering deleted note o
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.