BlueKing CMDB 业务集容器查询接口 `ListKubeContainerInBizSet` 深度解析
后端企业应用运维【免费下载链接】bk-cmdb蓝鲸智云配置平台(BlueKing CMDB)项目地址https://gitcode.com/gh_mirrors/bk/bk-cmdb点击查看免费下载导读本文面向使用蓝鲸智云配置平台BlueKing CMDB的开发者围绕 apigw 后端接口list_kube_container_in_biz_set查询业务集下的容器信息展开完整讲解其请求/响应协议、参数校验规则、权限模型与底层实现链路。读完本文你将掌握如何通过该接口跨多个业务一次性批量查询容器及其关联 Pod、宿主机的关键信息并理解其专供 bk-ops 场景使用的设计约束与数据边界校验逻辑。接口概述该接口的官方定义见仓库文档 list_kube_container_in_biz_set.md核心信息如下功能查询某个业务集Biz Set下所有符合条件的容器信息同时返回容器所在的 Pod 与宿主机Host的指定字段版本要求v3.14.8权限要求业务集访问权限biz set access使用限制该接口专供 bk-ops 使用可能随时调整请勿用于其他业务服务。从源码看这一专供定位在路由注册处也有明确注释。在 service_initfunc.go 中// NOTE: this is a special API only for bk-ops utility.AddHandler(rest.Action{Verb: http.MethodPost, Path: /findmany/biz_set/{bk_biz_set_id}/kube/containers, Handler: s.ListKubeContainerInBizSet})由此可以确认接口的实际 HTTP 形态为POST /api/v3/findmany/biz_set/{bk_biz_set_id}/kube/containers即业务集 ID 作为 URL 路径参数传递其余查询条件放在请求体中。请求参数说明接口共 5 个请求参数全部必填定义如下与官方文档一致名称类型必填说明bk_biz_set_idint64是业务集 ID路径参数bk_container_idsint64 数组是容器 ID 列表最大 500 个container_fieldsstring 数组是需要返回的容器属性列表pod_fieldsstring 数组是需要返回的 Pod 属性列表host_fieldsstring 数组是需要返回的宿主机属性列表其中bk_container_ids的 500 上限并非文档约定而是由服务端代码强制校验的。在 pod.go 的ListKubeContainerInBizSetOption.Validate方法中func (opt *ListKubeContainerInBizSetOption) Validate(bizSetID int64) ccErr.RawErrorInfo { if bizSetID 0 { return ccErr.RawErrorInfo{ErrCode: common.CCErrCommParamsNeedSet, Args: []interface{}{common.BKBizSetIDField}} } if len(opt.ContainerIDs) 0 { return ccErr.RawErrorInfo{ErrCode: common.CCErrCommParamsNeedSet, Args: []interface{}{bk_container_ids}} } if len(opt.ContainerIDs) 500 { return ccErr.RawErrorInfo{ErrCode: common.CCErrCommXXExceedLimit, Args: []interface{}{bk_container_ids, 500}} } if len(opt.ContainerFields) 0 { /* ... */ } if len(opt.PodFields) 0 { /* ... */ } if len(opt.HostFields) 0 { /* ... */ } return ccErr.RawErrorInfo{} }即校验规则包括bk_biz_set_id不能为 0否则报参数缺失错误CCErrCommParamsNeedSetbk_container_ids既不能为空也不能超过 500 条超限时报CCErrCommXXExceedLimit错误码常量定义见 errInfo.go值为 1199035container_fields、pod_fields、host_fields三个字段列表均不允许为空确保调用方明确指定需要返回的字段避免默认返回全量数据。请求体 JSON 示例如下官方示例{ bk_biz_set_id: 1, bk_container_ids: [ 1, 2 ], container_fields: [ id, name, container_uid ], pod_fields: [ id, name ], host_fields: [ bk_host_id, bk_agent_id, bk_cloud_id ] }响应结构解析成功时接口返回标准 CMDB 通用响应包装data为容器信息数组。官方响应示例{ result: true, code: 0, message: success, permission: null, data: [ { container: { id: 1, name: container1, container_uid: uid }, pod: { id: 1, name: pod1 }, host: { bk_host_id: 1, bk_agent_id: xxxxxxxxxxx, bk_cloud_id: 0 } } ] }通用响应字段名称类型说明resultbool请求是否成功true成功false失败codeint错误码0表示成功0表示失败messagestring失败时返回的错误信息permissionobject权限信息data[x] 结构每个数组元素包含三层嵌套对象名称类型说明containerobject容器数据podobjectPod 数据hostobject宿主机数据这一结构与源码中定义的返回类型一一对应。在 pod.go 中type ListKubeContainerInBizSetRes struct { Container *Container json:container Pod *Pod json:pod Host mapstr.MapStr json:host }data[x].container 字段名称类型说明idintCMDB 中的唯一自增 IDnamestring容器名称container_uidstring容器 UID第三方平台中的唯一标识imagestring容器镜像portsobject 数组容器端口格式见 KubernetesContainerPort定义argsstring 数组启动参数startedtimestamp启动时间limitsobject资源上限Resource limitsrequestsobject资源请求量Resource requestslivenessobject存活探针Liveness probeenvironmentobject 数组环境变量mountsobject 数组卷挂载Volume mounts对照源码中的Container结构体pod.go这些字段分别映射到type Container struct { ID int64 json:id,omitempty bson:id PodID int64 json:bk_pod_id,omitempty bson:bk_pod_id BizID int64 json:bk_biz_id,omitempty bson:bk_biz_id ClusterID int64 json:bk_cluster_id,omitempty bson:bk_cluster_id NamespaceID int64 json:bk_namespace_id,omitempty bson:bk_namespace_id Ref *Reference json:ref,omitempty bson:ref SupplierAccount string json:bk_supplier_account bson:bk_supplier_account Name *string json:name,omitempty bson:name ContainerID *string json:container_uid,omitempty bson:container_uid Image *string json:image,omitempty bson:image Ports *[]ContainerPort json:ports,omitempty bson:ports HostPorts *[]ContainerPort json:host_ports,omitempty bson:host_ports Args *[]string json:args,omitempty bson:args Started *int64 json:started,omitempty bson:started Limits *ResourceList json:limits,omitempty bson:limits Requests *ResourceList json:requests,omitempty bson:requests Liveness *Probe json:liveness,omitempty bson:liveness Environment *[]EnvVar json:environment,omitempty bson:environment Mounts *[]VolumeMount json:mounts,omitempty bson:mounts }值得注意container_uid字段在 types.go 中被定义为ContainerUIDField注释明确其为第三方平台中容器的唯一标识。data[x].pod 字段名称类型说明idintCMDB 中的唯一自增 IDnamestringPod 名称priorityint优先级labelsstring map标签key/value 均为字符串ipstring容器网络 IPipsobject 数组容器网络 IP 数组PodIPvolumesobject 数组使用的卷信息qos_classenumQoS 等级node_selectorsstring map节点标签选择器tolerationsobject 数组容忍度Tolerationoperatorstring 数组Pod 的 operator 信息containersobject 数组容器数据对应源码中的Pod结构体pod.gotype Pod struct { ID int64 json:id,omitempty bson:id SysSpec json:,inline bson:,inline Name *string json:name,omitempty bson:name Priority *int32 json:priority,omitempty bson:priority Labels *map[string]string json:labels,omitempty bson:labels IP *string json:ip,omitempty bson:ip IPs *[]PodIP json:ips,omitempty bson:ips Volumes *[]Volume json:volumes,omitempty bson:volumes QOSClass *PodQOSClass json:qos_class,omitempty bson:qos_class NodeSelectors *map[string]string json:node_selectors,omitempty bson:node_selectors Tolerations *[]Toleration json:tolerations,omitempty bson:tolerations Operator *[]string json:operator,omitempty bson:operator table.Revision json:,inline bson:,inline }data[x].host 字段名称类型说明bk_host_idint宿主机 IDbk_agent_idstringAgent IDbk_cloud_idint云区域 ID其他字段属性类型其他用户自定义字段由模型属性定义host对象的特殊之处在于它由mapstr.MapStr承载见上文ListKubeContainerInBizSetRes定义因此除了内置的bk_host_id、bk_agent_id、bk_cloud_id等标准字段外调用方在host_fields中请求的任何用户自定义主机属性都会被原样返回这也是该接口适合做跨系统数据对账的原因。服务端处理流程与源码级原理该接口的实现位于 inst_business_set.go 的ListKubeContainerInBizSet方法整体分为六个阶段1. 请求解码与参数校验opt : new(types.ListKubeContainerInBizSetOption) if err : ctx.DecodeInto(opt); err ! nil { ... } bizSetID, err : strconv.ParseInt(ctx.Request.PathParameter(common.BKBizSetIDField), 10, 64) if err ! nil { ... } if rawErr : opt.Validate(bizSetID); rawErr.ErrCode ! 0 { ... }先解析 URL 路径中的bk_biz_set_id再对请求体做结构化解码最后调用上文提到的Validate完成全部参数校验。2. 权限鉴权if resp, authorized : s.AuthManager.Authorize(ctx.Kit, meta.ResourceAttribute{Basic: meta.Basic{Type: meta.BizSet, Action: meta.AccessBizSet, InstanceID: bizSetID}}); !authorized { ctx.RespNoAuth(resp) return }这里对BizSet 资源 AccessBizSet访问业务集动作进行鉴权与文档声明的权限业务集访问权限完全一致。调用方如 bk-ops必须拥有目标业务集的访问权限否则返回RespNoAuth。3. 查询容器并强制附加关联字段ctx.SetReadPreference(common.SecondaryPreferredMode) containerFields : append(opt.ContainerFields, common.BKFieldID, types.BKPodIDField, common.BKAppIDField) containers, err : s.getContainerByIDs(ctx.Kit, opt.ContainerIDs, containerFields)两个关键细节SetReadPreference(common.SecondaryPreferredMode)表示本次查询优先读取 Mongo 从节点该模式定义见 definitions.go以降低对主库的压力适合这种批量只读查询服务端会在调用方指定的container_fields之外强制追加id、bk_pod_idPod ID、bk_biz_id业务 ID三个字段因为后续步骤需要靠它们完成 Pod 关联与业务范围校验。getContainerByIDs最终通过CoreService().Kube().ListContainer以id IN (ids)的条件查询容器并关闭 countDisableCounter: true以提升性能。4. 业务范围校验防止越权访问这是该接口最重要的安全逻辑。接口要求所有被查询的容器必须真实属于该业务集的范围否则整次请求失败if err s.validateResBizInBizSet(ctx.Kit, bizSetID, bizIDs); err ! nil { ... }校验流程为从容器结果中取出所有bk_biz_id去重后得到业务 ID 列表调用getBizSetBizCondinst_business_set.go读取业务集的Scope定义将其转换为 Mongo 查询条件统计这些业务是否全部命中业务集范围若数量不一致则报错resources are not all in biz set。业务集的范围定义BizSetScopetoposerver.go支持两种形态type BizSetScope struct { MatchAll bool json:match_all bson:match_all Filter *querybuilder.QueryFilter json:filter bson:filter,omitempty }match_all true业务集包含所有业务但默认排除资源池业务与已停用业务源码中附加条件bk_default ! 默认值、bk_data_status ! disabledmatch_all false业务集仅包含满足filter条件的业务源码会把该 querybuilder 过滤器转换为 Mongo 条件后做精确匹配。也就是说即使调用方知道某个容器 ID只要该容器所属业务不在业务集范围内接口就会拒绝返回数据从数据侧杜绝了越权查询。5. 级联查询 Pod 与宿主机pods, err : s.getPodByIDs(ctx.Kit, podIDs, append(opt.PodFields, common.BKFieldID, common.BKHostIDField))按上一步收集的 Pod ID 批量查询 Pod同样会强制追加id与bk_host_id用于后续关联再按 Pod 携带的bk_host_id集合调用getHostMapByIDs查询宿主机这里直接使用调用方传入的host_fields内部自动补上bk_host_id用于组装 map 键。三个子查询container / pod / host都使用了util.IntArrayUnique做 ID 去重避免重复查询。6. 组装返回结果for _, container : range containers { pod : podMap[container.PodID] result append(result, types.ListKubeContainerInBizSetRes{ Container: container, Pod: pod, Host: hostMap[pod.HostID], }) } ctx.RespEntity(result)最终以container → pod → host的三层嵌套结构返回。特殊场景下若按bk_container_ids未查询到任何容器则直接返回空数组而非报错方便调用方做幂等处理。典型使用场景与注意事项使用场景跨业务容器资产盘点一个业务集往往聚合了多个业务的资源通过一次调用即可按container_fields/pod_fields/host_fields精准拉取容器 Pod 宿主机三层关联数据替代多次list_kube_container_by_topo式的逐业务查询运维数据对账结合bk_agent_id、bk_cloud_id、container_uid等标识字段可与其他平台如容器编排系统、监控系统的资产数据进行批量比对。注意事项接口定位约束接口仅供 bk-ops 使用文档与源码均标注可能随时调整接入前应确认依赖的稳定性并做好接口变更兼容数量上限bk_container_ids单次最多 500 个超出将直接返回错误码 1199035CCErrCommXXExceedLimit需自行分批调用字段必须显式声明三个*_fields均不能为空且返回结果只包含这些字段外加服务端必需的关联字段建议按需声明以减小响应体权限前置调用方需具备目标业务集访问权限AccessBizSet否则请求会被拒绝只读语义服务端强制使用从节点读偏好适用于高并发只读场景但极端情况下可能读到略有延迟的从库数据版本前提接口能力自 v3.14.8 起可用使用前请确认部署版本满足要求。结语list_kube_container_in_biz_set是 CMDB 面向 bk-ops 提供的高效批量只读接口协议层上它通过业务集 容器 ID 列表 三组字段白名单的简洁入参一次返回容器、Pod、宿主机三层关联数据实现层上它融合了参数强校验、基于业务集 Scope 的数据范围二次校验、从节点读偏好与批量去重查询等工程实践。理解其请求/响应契约与服务端校验链路能帮助你在对接容器资产数据时少走弯路并正确规避其使用边界。赞分享后端企业应用运维【免费下载链接】bk-cmdb蓝鲸智云配置平台(BlueKing CMDB)项目地址https://gitcode.com/gh_mirrors/bk/bk-cmdb点击查看免费下载相关推荐BlueKing CMDB 主机服务模板 ID 查询接口list_host_service_template_id详解BlueKing CMDB 主机服务模板 ID 查询接口list_host_service_template_id详解 本指南面向 BlueKing CMD后端企业应用运维bk-cmdb 容器拓扑查询接口 list_kube_container_by_topo 实战指南bk cmdb 容器拓扑查询接口 list_kube_container_by_topo 实战指南 本篇指南系统讲解蓝鲸智云配置平台bk cmdb开放 AP后端企业应用运维蓝鲸 CMDB 全量同步缓存条件查询接口 list_cached_res_by_full_sync_cond 深度解析蓝鲸 CMDB 全量同步缓存条件查询接口 list_cached_res_by_full_sync_cond 深度解析 导读 list_cached_res_b后端企业应用运维上一篇Mist告别繁琐三步搞定macOS系统安装与固件管理下一篇Simplenote for Android一款简洁高效的笔记应用创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考