agent-module-architecture
Agent 构建机模块架构指南(Go 语言),涵盖 Agent 启动流程、心跳机制、任务领取执行、升级更新、与 Dispatch 交互。当用户开发 Agent 功能、修改心跳逻辑、处理任务执行或实现 Agent 升级时使用。
Install
mkdir -p .claude/skills/agent-module-architecture && curl -L -o skill.zip "https://mcp.directory/api/skills/download/2688" && unzip -o skill.zip -d .claude/skills/agent-module-architecture && rm skill.zipInstalls to .claude/skills/agent-module-architecture
About this skill
Agent 构建机模块架构指南
模块定位: Agent 是 BK-CI 的构建机核心组件,由 Go 语言编写,负责与后端服务通信、接收构建任务、拉起 Worker 进程执行构建。
一、模块概述
1.1 核心职责
| 职责 | 说明 |
|---|---|
| 进程管理 | Daemon 守护 Agent 进程,确保持续运行 |
| 任务调度 | 从 Dispatch 服务拉取构建任务并执行 |
| Worker 管理 | 拉起 Worker(Kotlin JAR)执行实际构建逻辑 |
| 心跳上报 | 定期向后端上报 Agent 状态和环境信息 |
| 自动升级 | 检测并自动升级 Agent、Worker、JDK |
| 数据采集 | 通过 Telegraf 采集构建机指标数据 |
| Docker 构建 | 支持 Docker 容器化构建(Linux) |
1.2 与 Worker 的关系
┌─────────────────────────────────────────────────────────────┐
│ 构建机 (Build Machine) │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────┐ 守护 ┌─────────┐ │
│ │ Daemon │ ───────────▶ │ Agent │ │
│ │ (Go) │ │ (Go) │ │
│ └─────────┘ └────┬────┘ │
│ │ 拉起 │
│ ▼ │
│ ┌─────────┐ │
│ │ Worker │ │
│ │(Kotlin) │ │
│ └────┬────┘ │
│ │ 执行 │
│ ▼ │
│ ┌──────────────────────┐ │
│ │ 插件任务 / 脚本任务 │ │
│ └──────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
- Agent (Go): 负责进程调度、与后端通信、环境管理
- Worker (Kotlin): 负责具体构建任务执行、插件运行、日志上报
二、目录结构
src/agent/
├── agent/ # 主 Agent 模块
│ ├── src/
│ │ ├── cmd/ # 入口程序
│ │ │ ├── agent/main.go # Agent 主程序入口
│ │ │ ├── daemon/main.go # Daemon 守护进程入口
│ │ │ ├── installer/main.go # 安装程序入口
│ │ │ └── upgrader/main.go # 升级程序入口
│ │ ├── pkg/ # 核心包
│ │ │ ├── agent/ # Agent 核心逻辑
│ │ │ ├── api/ # API 客户端
│ │ │ ├── collector/ # 数据采集
│ │ │ ├── config/ # 配置管理
│ │ │ ├── cron/ # 定时任务
│ │ │ ├── i18n/ # 国际化
│ │ │ ├── imagedebug/ # Docker 镜像调试
│ │ │ ├── job/ # 构建任务管理
│ │ │ ├── job_docker/ # Docker 构建
│ │ │ ├── pipeline/ # Pipeline 任务
│ │ │ ├── upgrade/ # 升级逻辑
│ │ │ ├── upgrader/ # 升级器实现
│ │ │ └── util/ # 工具函数
│ │ └── third_components/ # 第三方组件管理
│ ├── go.mod
│ ├── Makefile
│ └── README.md
├── agent-slim/ # 轻量版 Agent
│ └── cmd/slim.go
└── common/ # 公共工具库
└── utils/
├── fileutil/
└── slice.go
三、核心组件详解
3.1 Daemon 守护进程
文件: src/cmd/daemon/main.go
Daemon 负责守护 Agent 进程,确保其持续运行:
// Unix 实现:通过文件锁检测 Agent 是否存活
func watch(isDebug bool) {
totalLock := flock.New(fmt.Sprintf("%s/%s.lock", systemutil.GetRuntimeDir(), systemutil.TotalLock))
// 首次立即检查
totalLock.Lock()
doCheckAndLaunchAgent(isDebug)
totalLock.Unlock()
// 定时检查(5秒间隔)
checkTimeTicker := time.NewTicker(agentCheckGap)
for ; ; totalLock.Unlock() {
select {
case <-checkTimeTicker.C:
if err := totalLock.Lock(); err != nil {
continue
}
doCheckAndLaunchAgent(isDebug)
}
}
}
// 检查并拉起 Agent
func doCheckAndLaunchAgent(isDebug bool) {
agentLock := flock.New(fmt.Sprintf("%s/agent.lock", systemutil.GetRuntimeDir()))
locked, err := agentLock.TryLock()
if err == nil && locked {
// 能获取锁说明 Agent 未运行,需要拉起
logs.Warn("agent is not available, will launch it")
process, err := launch(workDir+"/"+config.AgentFileClientLinux, isDebug)
if err != nil {
logs.WithError(err).Error("launch agent failed")
}
}
}
Windows 实现: 使用 github.com/kardianos/service 库实现 Windows Service
3.2 Agent 核心流程
文件: src/pkg/agent/agent.go
func Run(isDebug bool) {
// 1. 初始化配置
config.Init(isDebug)
third_components.Init()
// 2. 初始化国际化
i18n.InitAgentI18n()
// 3. 上报启动(重试直到成功)
_, err := job.AgentStartup()
if err != nil {
for {
_, err = job.AgentStartup()
if err == nil {
break
}
time.Sleep(5 * time.Second)
}
}
// 4. 启动后台任务
go collector.Collect() // 数据采集
go cron.CleanJob() // 定期清理
go cron.CleanDebugContainer() // 清理调试容器
// 5. 主循环:Ask 请求
for {
doAsk()
config.LoadAgentIp()
time.Sleep(5 * time.Second)
}
}
3.3 Ask 统一请求模式
Agent 使用 Ask 模式统一处理多种任务:
func doAsk() {
// 构建 Ask 请求
enable := genAskEnable()
heart, upgrad := genHeartInfoAndUpgrade(enable.Upgrade, exiterror)
result, err := api.Ask(&api.AskInfo{
Enable: enable, // 启用的功能
Heart: heart, // 心跳信息
Upgrade: upgrad, // 升级信息
})
// 处理响应
resp := new(api.AskResp)
util.ParseJsonToData(result.Data, &resp)
// 执行各类任务
doAgentJob(enable, resp)
}
func doAgentJob(enable api.AskEnable, resp *api.AskResp) {
// 心跳响应处理
if resp.Heart != nil {
go agentHeartbeat(resp.Heart)
}
// 构建任务
hasBuild := (enable.Build != api.NoneBuildType) && (resp.Build != nil)
if hasBuild {
go job.DoBuild(resp.Build)
}
// 升级任务
if enable.Upgrade && resp.Upgrade != nil {
go upgrade.AgentUpgrade(resp.Upgrade, hasBuild)
}
// Pipeline 任务
if enable.Pipeline && resp.Pipeline != nil {
go pipeline.RunPipeline(resp.Pipeline)
}
// Docker 调试
if enable.DockerDebug && resp.Debug != nil {
go imagedebug.DoImageDebug(resp.Debug)
}
}
3.4 构建任务执行
文件: src/pkg/job/build.go
// DoBuild 执行构建任务
func DoBuild(buildInfo *api.ThirdPartyBuildInfo) {
// 获取任务锁
BuildTotalManager.Lock.Lock()
// 检查并发数
dockerCanRun, normalCanRun := CheckParallelTaskCount()
if buildInfo.DockerBuildInfo != nil && dockerCanRun {
// Docker 构建
GBuildDockerManager.AddBuild(buildInfo.BuildId, &api.ThirdPartyDockerTaskInfo{...})
BuildTotalManager.Lock.Unlock()
runDockerBuild(buildInfo)
return
}
if normalCanRun {
// 普通构建
GBuildManager.AddPreInstance(buildInfo.BuildId)
BuildTotalManager.Lock.Unlock()
runBuild(buildInfo)
}
}
// runBuild 启动 Worker 进程
func runBuild(buildInfo *api.ThirdPartyBuildInfo) error {
// 检查 worker.jar 是否存在
agentJarPath := config.BuildAgentJarPath()
if !fileutil.Exists(agentJarPath) {
// 尝试自愈
upgradeWorkerFile := systemutil.GetUpgradeDir() + "/" + config.WorkAgentFile
if fileutil.Exists(upgradeWorkerFile) {
fileutil.CopyFile(upgradeWorkerFile, agentJarPath, true)
}
}
// 设置环境变量
goEnv := map[string]string{
"DEVOPS_AGENT_VERSION": config.AgentVersion,
"DEVOPS_WORKER_VERSION": third_components.Worker.GetVersion(),
"DEVOPS_PROJECT_ID": buildInfo.ProjectId,
"DEVOPS_BUILD_ID": buildInfo.BuildId,
"DEVOPS_VM_SEQ_ID": buildInfo.VmSeqId,
"DEVOPS_FILE_GATEWAY": config.GAgentConfig.FileGateway,
"DEVOPS_GATEWAY": config.GetGateWay(),
"BK_CI_LOCALE_LANGUAGE": config.GAgentConfig.Language,
"DEVOPS_AGENT_JDK_8_PATH": third_components.Jdk.Jdk8.GetJavaOrNull(),
"DEVOPS_AGENT_JDK_17_PATH": third_components.Jdk.Jdk17.GetJavaOrNull(),
}
// 创建临时目录并启动构建
tmpDir, _ := systemutil.MkBuildTmpDir()
doBuild(buildInfo, tmpDir, workDir, goEnv, runUser)
}
3.5 配置管理
文件: src/pkg/config/config.go
Agent 配置从 .agent.properties 文件加载:
// 配置键定义
const (
KeyProjectId = "devops.project.id"
KeyAgentId = "devops.agent.id"
KeySecretKey = "devops.agent.secret.key"
KeyDevopsGateway = "landun.gateway"
KeyDevopsFileGateway = "landun.fileGateway"
KeyTaskCount = "devops.parallel.task.count"
KeyEnvType = "landun.env"
KeySlaveUser = "devops.slave.user"
KeyDockerTaskCount = "devops.docker.parallel.task.count"
KeyLanguage = "devops.language"
// ...
)
// AgentConfig 配置结构
type AgentConfig struct {
Gateway string
FileGateway string
BuildType string
ProjectId string
AgentId string
SecretKey string
ParallelTaskCount int
DockerParallelTaskCount int
EnableDockerBuild bool
Language string
// ...
}
// AgentEnv 环境信息
type AgentEnv struct {
OsName string
agentIp string
HostName string
AgentVersion string
AgentInstallPath string
OsVersion string
CPUProductInfo string
GPUProductInfo string
}
3.6 API 客户端
文件: src/pkg/api/api.go
// 构建 URL
func buildUrl(url string) string {
return config.GetGateWay() + url
}
// Agent 启动上报
func AgentStartup() (*httputil.DevopsResult, error) {
url := buildUrl("/ms/environment/api/buildAgent/agent/thirdPartyAgent/startup")
startInfo := &ThirdPartyAgentStartInfo{
HostName: config.GAgentEnv.HostName,
HostIp: config.GAgentEnv.GetAgentIp(),
DetectOs: config.GAgentEnv.OsName,
MasterVersion: config.AgentVersion,
SlaveVersion: third_components.Worker.GetVersion(),
}
return httputil.NewHttpClient().Po
---
*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.
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.