K8s Operator 开发全流程
核心概念 Operator 开发完整流程涵盖 CRD 定义、Controller 编写、调谐逻辑、Webhook 配置、部署运维等。 分两大场景:
- 商用现成Operator(GPU Operator / Prometheus Operator / Volcano):直接 Helm 安装 + CR 业务配置(你AI集群日常使用,重点)
- 自研Operator(kopf/kubebuilder):从零开发自定义运维Agent控制器
1. 核心前置概念回顾
- CRD:自定义资源定义,扩展K8s API
- Controller:Operator主程序,执行Reconcile调谐循环
- CR:自定义资源实例(用户编写的业务yaml,如
ClusterPolicy、Prometheus) - Webhook:校验/自动填充CR配置
- RBAC:Operator必须权限,操作Pod/DS/ConfigMap/CRD等资源
第一部分:现成商用Operator标准配置流程(GPU Operator举例,生产最常用)
2. 环境准备
K8s 1.24+,containerd,GPU物理节点,helm3
2.1. 步骤1:添加官方helm仓库
# NVIDIA GPU Operator
helm repo add nvidia https://helm.ngc.nvidia.com/nvidia
helm repo update
2.2. 步骤2:自定义values.yaml(Operator全局配置)
Operator所有全局开关、镜像版本、组件启停、资源配额都在values控制,核心配置项:
# values-gpu.yaml
operator:
# Operator控制器资源限制
resources:
limits:
cpu: "1"
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
# 1. 驱动管理组件
driver:
enabled: true
repo: nvcr.io/nvidia
image: nvidia-driver
# 驱动版本锁定
version: 535.104.05
# 是否自动升级驱动
upgradePolicy: rolling
# 2. CDI与容器虚拟化
containerRuntime:
enabled: true
cdi:
enabled: true
# 3. Device Plugin GPU调度核心
devicePlugin:
enabled: true
# 开启分时切片 vGPU 共享
sharing:
timeSlicing:
enabled: true
replicas: 4 # 单卡虚拟4份
# MIG硬件分片配置(A100/H100开启)
migManager:
enabled: false
# 4. DCGM GPU监控(必开)
dcgm:
enabled: true
exporter:
enabled: true
serviceMonitor:
enabled: true # 自动创建Prometheus抓取规则
# 5. Webhook配置:校验+自动填充配置
validator:
enabled: true
mutator:
enabled: true
2.3. 步骤3:Helm安装Operator
helm install gpu-operator nvidia/gpu-operator \
-n gpu-operator \
--create-namespace \
-f values-gpu.yaml
2.4. 步骤4:CRD自动创建,查看集群自定义资源
# 查看Operator安装的CRD
kubectl get crd | grep nvidia
# GPU Operator核心CR:ClusterPolicy,全局GPU集群配置载体
kubectl get clusterpolicies
2.5. 步骤5:编写CR实例(业务自定义配置,核心配置文件)
CR是你控制Operator行为的核心,Operator持续Reconcile对齐该配置
cluster-policy.yaml
apiVersion: nvidia.com/v1
kind: ClusterPolicy
metadata:
name: gpu-cluster-config
spec:
# 驱动部署配置
driver:
version: "535.104.05"
tolerations:
- key: gpu-node
operator: Equal
value: "true"
effect: NoSchedule
# 容器运行时CDI配置
containerRuntime:
cdi:
enabled: true
# Device Plugin 调度配置
devicePlugin:
config:
sharing:
timeSlicing:
resources:
- name: nvidia.com/gpu
replicas: 4
# DCGM监控开启
dcgm:
exporter:
serviceMonitor:
interval: 15s
# 节点标签、污点自动管理
nodeSelector:
gpu: "true"
下发CR配置,Operator立刻触发调谐循环:
kubectl apply -f cluster-policy.yaml
# 查看CR状态
kubectl describe clusterpolicy gpu-cluster-config
2.6. 步骤6:校验Operator调谐结果
Operator会自动创建以下组件,全部由CR配置控制:
- Driver DaemonSet(节点驱动安装)
- nvidia-device-plugin DaemonSet
- dcgm-exporter DaemonSet + ServiceMonitor
- nvidia-container-toolkit配置、containerd runtime修改
- Webhook校验/突变Pod资源 校验命令:
kubectl get ds -n gpu-operator
kubectl get servicemonitor -n gpu-operator
kubectl describe pod -n gpu-operator gpu-operator-controller
2.7. 步骤7:更新/卸载Operator配置
- 修改CR配置文件重新apply,Operator自动滚动更新全节点组件
kubectl apply -f cluster-policy.yaml
- 卸载
helm uninstall gpu-operator -n gpu-operator
第二部分:Prometheus Operator 配置示例(监控标准Operator)
3. 核心CR资源
- Prometheus:定义监控实例存储、副本、保留时长
- ServiceMonitor:自动抓取Pod metrics(dcgm-exporter、业务Agent)
- PrometheusRule:告警规则CR
- Alertmanager:告警推送配置
4. ServiceMonitor 配置示例(抓取DCGM GPU指标)
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: dcgm-monitor
namespace: monitoring
spec:
selector:
matchLabels:
app: dcgm-exporter
endpoints:
- port: metrics
interval: 15s
下发后Prometheus Operator自动配置抓取任务,无需修改Prometheus配置文件。
第三部分:Operator 四大核心配套组件配置详解
5. RBAC权限配置(Operator必须,否则无法创建资源)
Operator控制器需要操作集群资源,Helm安装会自动生成SA/Role/RoleBinding,自研Operator必须手动定义:
# Role示例:允许操作Pod、DaemonSet、CRD
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: gpu-operator-controller
rules:
- apiGroups: ["apps"]
resources: ["daemonsets","deployments"]
verbs: ["*"]
- apiGroups: ["nvidia.com"]
resources: ["clusterpolicies"]
verbs: ["get","list","watch","create","update","delete"]
- apiGroups: ["monitoring.coreos.com"]
resources: ["servicemonitors"]
verbs: ["create","update"]
6. Webhook 配置(Mutating / Validating)
两种Webhook由Operator自动部署,用于拦截CR/Pod请求:
- ValidatingWebhookConfiguration:校验配置合法性,非法CR直接拒绝
例:禁止MIG与Time-Slicing同时开启、GPU显存配置超限 - MutatingWebhookConfiguration:自动填充默认值、修改Pod配置
例:HAMi Operator自动注入vGPU显存限制环境变量 查看Webhook资源:
kubectl get validatingwebhookconfigurations
kubectl get mutatingwebhookconfigurations
7. Reconcile 调谐循环配置(控制器行为控制)
7.1. 现成Operator调谐参数(values.yaml配置)
- reconcileInterval:默认10分钟强制全量同步一次集群状态
- maxConcurrentReconciles:并行处理CR数量,大集群调大提升性能
- retryDelay:配置错误重试间隔
7.2. 查看控制器日志(排障核心)
kubectl logs -f deployment/gpu-operator-controller -n gpu-operator
# 日志关键字 Reconcile 代表一次调谐循环启动
8. 节点调度容忍与亲和配置
Operator组件(驱动、device-plugin、dcgm-exporter)仅调度GPU节点,通过nodeSelector+tolerations配置:
tolerations:
- key: gpu
operator: Equal
value: "true"
effect: NoSchedule
nodeSelector:
gpu: "true"
第四部分:自研轻量Operator配置(kopf Python,适合你的运维Agent)
如果你要开发自研SRE-Agent Operator,使用kopf框架极简配置:
9. 项目结构
sre-operator/
├── main.py # 控制器逻辑、Reconcile循环
├── crd.yaml # 自定义CRD定义
├── rbac.yaml # 权限
├── deployment.yaml # Operator控制器部署
└── cr.yaml # 用户业务CR配置
10. CRD 定义(crd.yaml)
定义自定义资源SREAgent,用于控制自动化运维Agent实例:
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: sreagents.aiops.local
spec:
group: aiops.local
names:
kind: SREAgent
plural: sreagents
singular: sreagent
shortNames: [sre]
scope: Namespaced
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
gpuEnable:
type: boolean
autoRepair:
type: boolean
monitorInterval:
type: integer
11. 控制器代码核心配置(main.py)
import kopf
# 监听SREAgent CR的增删改事件,触发调谐函数
@kopf.on.create("aiops.local", "v1", "sreagents")
@kopf.on.update("aiops.local", "v1", "sreagents")
@kopf.on.delete("aiops.local", "v1", "sreagents")
def reconcile_agent(spec, name, namespace, **kwargs):
# Reconcile 核心逻辑:
# 1. 获取CR期望配置(是否开启GPU监控、自动修复)
# 2. 查询集群当前Deployment/Pod真实状态
# 3. 对比差异,增删改Agent资源
auto_repair = spec.get("autoRepair", False)
gpu_enable = spec.get("gpuEnable", False)
# 动态创建/更新SRE-Agent Deployment
create_or_update_deployment(name, namespace, auto_repair, gpu_enable)
12. CR业务配置(sre-agent-cr.yaml)
用户声明运维Agent期望能力,Operator自动创建对应服务:
apiVersion: aiops.local/v1
kind: SREAgent
metadata:
name: gpu-monitor-agent
spec:
gpuEnable: true
autoRepair: true
monitorInterval: 15
下发后Operator自动启动带GPU自愈能力的运维Agent Pod。
13. Operator部署yaml(deployment.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
name: sre-operator
spec:
replicas: 1
selector:
matchLabels:
app: sre-operator
template:
metadata:
labels:
app: sre-operator
spec:
serviceAccountName: sre-operator-sa # 绑定RBAC权限
containers:
- name: operator
image: python-sre-operator:v1
command: ["python","main.py"]
resources:
limits:
cpu: 500m
memory: 512Mi
第五部分:Operator 日常排障配置相关问题
14. CR下发后不生效,控制器无Reconcile日志
- RBAC权限缺失,无法watch CR资源 → 补充Role规则
- CRD未正确安装
kubectl get crd - Operator控制器Pod异常,查看logs、describe pod
15. 组件DaemonSet无法调度到GPU节点
values.yaml中nodeSelector/tolerations配置不匹配节点污点标签
16. DCGM-exporter无监控指标
Operator中dcgm.serviceMonitor.enabled未开启,未自动创建ServiceMonitor
17. Webhook校验拒绝CR创建
CR字段不符合OpenAPI schema定义,修改CR spec字段、类型
18. Reconcile循环频繁重试报错
控制器逻辑异常、API访问权限不足、节点资源不足,查看controller日志定位报错。
第六部分:整体配置流程总结(标准流水线)
- 安装Operator helm包,通过values.yaml全局配置组件版本、开关、资源
- 集群自动生成CRD、RBAC、Webhook、控制器Deployment
- 用户编写CR自定义资源yaml,定义业务需求(GPU分片、监控、Agent能力)
- apply CR触发Operator Reconcile调谐循环
- 控制器对比集群真实资源,自动创建/更新DS/Deployment/ConfigMap等组件
- 修改CR或values.yaml配置,自动滚动同步全集群组件状态
关联文档