深入解读 Knative 自定义事件源控制器:从代码生成到 NewController 实现
深入解读 Knative 自定义事件源控制器:从代码生成到 NewController 实现
导读
本文聚焦 Knative Eventing 中自定义事件源(Custom Event Source)的控制器(Controller)实现,以 knative-extensions/sample-source 样板仓库为蓝本,系统讲解如何通过代码生成与注入工具(generate-groups.sh、generate-knative.sh)生成 clientset、informers、listers 等基础设施,如何在 NewController 中组装 Reconciler、注册事件处理器,以及如何将控制器接入 sharedmain 运行入口。读完本文,你将能够复刻 Knative 官方推荐的控制器开发流程,并理解控制器如何协同 Receive Adapter 与 SinkBinding 完成事件源资源的最终调谐。
自定义事件源的整体架构:控制器是承上启下的枢纽
在 自定义事件源总览 中,Knative 将自定义事件源拆解为三个必备组件:
| 组件 | 职责 |
|---|---|
| Receive Adapter(接收适配器) | 包含从事件生产者获取事件、确定 sink URI、将事件转换为 CloudEvent 格式的逻辑 |
| Kubernetes 控制器(Controller) | 管理事件源资源(CR),调谐其底层的 Receive Adapter Deployment |
| 自定义资源定义(CRD) | 提供控制器管理 Receive Adapter 时所用的配置结构 |
控制器在这三者中处于枢纽位置:用户通过 kubectl 提交一个自定义事件源 CR(例如 SampleSource),控制器监听到该 CR 的变化后,负责创建/更新/删除底层的 Receive Adapter Deployment,并通过 SinkBinding 把该 Deployment 与用户指定的 sink 绑定起来。控制器本身是一个标准的 Kubernetes controller 进程,运行时以 Deployment 的形式部署在集群中(即文档中提到的 sample-source-controller-manager)。
相比 SinkBinding 或 ContainerSource 这类"通用容器"集成方式,自定义事件源需要编写更多代码,但换来的是:以 CRD 暴露语义化的配置项(如 interval、serviceAccountName),隐藏实现细节,为用户提供最平滑的使用体验。
控制器脚手架:用官方脚本生成与注入基础设施
Knative 的控制器开发约定基于 Kubernetes 官方 code-generator 与 Knative 自身的 injection 框架。样板仓库 sample-source 提供了 hack/update-codegen.sh 脚本,一键完成两个阶段的工作。
第一阶段:生成 clientset / informers / lister / deepcopy
运行以下命令生成 CRD 类型相关的深拷贝方法、客户端集、Informer 与 Lister:
${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \
knative.dev/sample-source/pkg/client knative.dev/sample-source/pkg/apis \
"samples:v1alpha1" \
--go-header-file ${REPO_ROOT}/hack/boilerplate/boilerplate.go.txt
参数说明:
"deepcopy,client,informer,lister":指定要生成的组件类别,分别对应zz_generated.deepcopy.go、clientset、informers与listers;- 第一个 Go 包路径是客户端代码的输出位置(
pkg/client); - 第二个 Go 包路径是 API 类型所在的包(
pkg/apis); "samples:v1alpha1"声明分组(Group)与版本,即samples.knative.dev/v1alpha1;--go-header-file指定生成文件的许可证头部模板,一般位于hack/boilerplate/boilerplate.go.txt。
生成出的 clientset 用于对事件源 CR 做读写操作,informers 提供监听与本地缓存能力,listers 提供只读查询。这些正是控制器注入框架要使用的组件。
第二阶段:生成并注入 injection 代码
# Injection
${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \
knative.dev/sample-source/pkg/client knative.dev/sample-source/pkg/apis \
"samples:v1alpha1" \
--go-header-file ${REPO_ROOT}/hack/boilerplate/boilerplate.go.txt
这一步调用 Knative 的 generate-knative.sh,在上一阶段产物之上生成 injection 包装。injection 是 Knative 控制器框架的核心机制:通过 Go 的初始化副作用(init())与 Get(ctx) 约定,让控制器无需手动管理全局单例,而是从 context.Context 中按需取出已经初始化好的 clientset、informers、listers 等组件。
注入完成后,控制器代码里就可以直接这样取用基础设施:
import (
// ...
sampleSourceClient "knative.dev/sample-source/pkg/client/injection/client"
samplesourceinformer "knative.dev/sample-source/pkg/client/injection/informers/samples/v1alpha1/samplesource"
)
// ...
func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl {
sampleSourceInformer := samplesourceinformer.Get(ctx)
r := &Reconciler{
// ...
samplesourceClientSet: sampleSourceClient.Get(ctx),
samplesourceLister: sampleSourceInformer.Lister(),
// ...
}
}
其中 sampleSourceClient.Get(ctx) 返回生成的事件源 clientset,sampleSourceInformer.Lister() 返回 SampleSource 的 Lister,供 Reconciler 在调谐时读取资源的期望状态。
控制器进程入口:接入 sharedmain
生成并注入完基础设施后,需要让控制器进程真正跑起来。Knative 提供 knative.dev/pkg/injection/sharedmain 作为控制器进程的共享 main 函数,它统一负责启动 profiling、配置 ConfigMap 监听、运行注入的 controllers 等杂事。开发者只需把自己实现的 NewController 传进去:
import (
// The set of controllers this controller process runs.
"knative.dev/sample-source/pkg/reconciler/sample"
// This defines the shared main for injected controllers.
"knative.dev/pkg/injection/sharedmain"
)
func main() {
sharedmain.Main("sample-source-controller", sample.NewController)
}
sharedmain.Main 的第一个参数是控制器进程的名字(对应 Deployment 名称中的 sample-source-controller),第二个参数是可变参数,可传入一个或多个 NewController 工厂函数。按 sample-repo 文件清单 的说明,cmd/controller/main.go 只负责这一件事——将事件源的 NewController 实现传递给共享 main 方法。
编写 NewController:装配 Reconciler 与依赖
NewController 是控制器初始化的核心函数,签名固定为 func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl。文档给出的关键实现如下:
func NewController(
ctx context.Context,
cmw configmap.Watcher,
) *controller.Impl {
// ...
deploymentInformer := deploymentinformer.Get(ctx)
sinkBindingInformer := sinkbindinginformer.Get(ctx)
sampleSourceInformer := samplesourceinformer.Get(ctx)
r := &Reconciler{
dr: &reconciler.DeploymentReconciler{KubeClientSet: kubeclient.Get(ctx)},
sbr: &reconciler.SinkBindingReconciler{EventingClientSet: eventingclient.Get(ctx)},
// Config accessor takes care of tracing/config/logging config propagation to the receive adapter
configAccessor: reconcilersource.WatchConfigurations(ctx, "sample-source", cmw),
}
// ...
}
逐一拆解这段代码的含义:
ctx是注入上下文的载体,注入的 informers 都通过xxx.Get(ctx)从其中取出;cmw(configmap.Watcher)用于监听 Knative 的配置 ConfigMap(如日志、追踪、指标配置);deploymentInformer监听集群中所有Deployment的变化,用于跟踪由事件源创建出来的 Receive Adapter Deployment;sinkBindingInformer监听SinkBinding的变化,用于跟踪绑定 Receive Adapter 与 sink 的 SinkBinding 对象;sampleSourceInformer监听用户提交的SampleSourceCR,这是控制器调谐的"主资源";r.dr是DeploymentReconciler,持有KubeClientSet,负责对 Deployment 做增删改查;r.sbr是SinkBindingReconciler,持有EventingClientSet,负责对 SinkBinding 做增删改查;r.configAccessor通过reconcilersource.WatchConfigurations(ctx, "sample-source", cmw)创建,它监听配置并负责把 tracing/config/logging/metrics 相关的环境变量传播到 Receive Adapter 的 Pod 中。
这里使用的 reconcilersource 来自 knative.dev/eventing/pkg/reconciler/source 依赖包,需要显式导入:
import (
// ...
reconcilersource "knative.dev/eventing/pkg/reconciler/source"
// ...
)
从源码结构可以推断,Reconciler 结构体通过组合 DeploymentReconciler 与 SinkBindingReconciler 这两个内嵌子 reconciler,把"管理 Deployment"和"管理 SinkBinding"这两类次级资源的调谐逻辑复用起来,这也是 Knative 官方扩展(extensions)仓库中普遍采用的模式。
注册事件处理器:让控制器对资源变化做出反应
NewController 的最后一类职责是为各类 informer 注册事件处理器(Event Handler),把资源变化转化为对调谐队列的入队操作。
主资源:SampleSource
对于用户提交的 SampleSource CR,任何增删改都直接触发对该资源的调谐:
sampleSourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue))
controller.HandleAll 包装了 Add/Update/Delete 三类事件,impl.Enqueue 把事件对应的资源键(namespace/name)放入调谐队列。
次级资源:Deployment 与 SinkBinding
Receive Adapter Deployment 和 SinkBinding 属于事件源创建的"下属资源"。Knative 约定:只有那些被当前事件源"拥有"(owner)的次级资源变化才应该触发主资源重新调谐,因此这里使用带过滤的事件处理器:
deploymentInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: controller.FilterGroupKind(v1alpha1.Kind("SampleSource")),
Handler: controller.HandleAll(impl.EnqueueControllerOf),
})
sinkBindingInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: controller.FilterGroupKind(v1alpha1.Kind("SampleSource")),
Handler: controller.HandleAll(impl.EnqueueControllerOf),
})
说明:
cache.FilteringResourceEventHandler来自k8s.io/client-go/tools/cache,先经FilterFunc过滤,再交给Handler处理;controller.FilterGroupKind(v1alpha1.Kind("SampleSource"))只保留"其 owner 是 SampleSource 类型"的 Deployment / SinkBinding 事件,避免无关资源变化引发无意义调谐;impl.EnqueueControllerOf在通过过滤后,取出事件的 owner 引用(即 SampleSource)并对其入队,实现"下属资源变化 → 主资源重新调谐"的级联。
与 Receive Adapter 的协同:控制器调谐的完整闭环
控制器本身并不产生事件,真正往 sink 发事件的是 Receive Adapter。控制器在调谐过程中会同步完成 Receive Adapter Deployment 与 SinkBinding 的创建、更新与状态回写,完整流程见 创建 Receive Adapter 教程,其要点包括:
- 初始化状态:调谐开始时执行
src.Status.InitializeConditions()与src.Status.ObservedGeneration = src.Generation(定义在samplesource_lifecycle.go与samplesource_types.go); - 组装 ReceiveAdapterArgs:构造
resources.ReceiveAdapterArgs,其中Image来自r.ReceiveAdapterImage,AdditionalEnvs来自r.configAccessor.ToEnvVars()——这正是把 tracing/logging/metrics 配置注入 Receive Adapter Pod 的落点; - 保证 Deployment 存在且一致:先
Get现有 Deployment,不存在则Create,spec 不一致则用r.podSpecImageSync检测镜像变化后Update,并记录DeploymentUpdated事件,最终通过src.Status.PropagateDeploymentAvailability(ra)把 Deployment 的就绪状态传播到 SampleSource 的状态条件中; - 创建 SinkBinding:以 Receive Adapter Deployment 作为 SinkBinding 的 subject(
tracker.Reference{APIVersion: appsv1.SchemeGroupVersion.String(), Kind: "Deployment", ...}),同样遵循 Get → Create/Update 的幂等流程,最后用src.Status.MarkSink(sb.Status.SinkURI)把解析出的 sink URI 写回状态; - 收尾:返回
SampleSourceReconciled事件,宣告本次调谐完成。
可见,控制器通过 DeploymentReconciler 与 SinkBindingReconciler 这两个内嵌子 reconciler 完成了对次级资源的全部管理动作,这与 NewController 中的装配完全对应。
发布到集群并验证
控制器开发完成后,可按 发布事件源教程 将其发布到本地集群验证:
minikube start
eval $(minikube docker-env)
export KO_DOCKER_REPO=ko.local
ko apply -f config
待 sample-source-controller-manager 在 knative-samples 命名空间运行后,通过 ko apply -f example.yaml 应用一个每 10 秒向 event-display Knative Service 发送事件的 SampleSource:
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: event-display
namespace: knative-samples
spec:
template:
spec:
containers:
- image: gcr.io/knative-releases/knative.dev/eventing/cmd/event_display
---
apiVersion: samples.knative.dev/v1alpha1
kind: SampleSource
metadata:
name: sample-source
namespace: knative-samples
spec:
interval: "10s"
sink:
ref:
apiVersion: serving.knative.dev/v1
kind: Service
name: event-display
观察 sink 日志,可以看到控制器与 Receive Adapter 协同产出的合法 CloudEvent:
kubectl -n knative-samples logs -l serving.knative.dev/service=event-display -c user-container -f
输出示例:
☁️ cloudevents.Event
Validation: valid
Context Attributes,
specversion: 1.0
type: dev.knative.sample
source: http://sample.knative.dev/heartbeat-source
id: d4619592-363e-4a41-82d1-b1586c390e24
time: 2019-12-17T01:31:10.795588888Z
datacontenttype: application/json
Data,
{
"Sequence": 0,
"Heartbeat": "10s"
}
配套文件清单与开发前置条件
按 sample-repo 使用指南,样板仓库中与控制器直接相关的文件包括:
cmd/controller/main.go:把事件源的NewController传给 shared main;pkg/reconciler/sample/controller.go:NewController的实现本体;pkg/reconciler/sample/samplesource.go:针对 Receive Adapter 的调谐函数;pkg/apis/samples/VERSION/samplesource_types.go:API 类型 schema,资源 YAML 中的字段在此定义(如interval、serviceAccountName、内嵌的duckv1.SourceSpec);pkg/apis/samples/VERSION/samplesource_lifecycle.go:状态条件与生命周期函数(InitializeConditions、MarkSink、MarkNoSink等)。
开发前置条件:熟悉 Kubernetes 与 Go 开发,安装 Git 与 Go,并克隆 sample-source 仓库;可选安装 ko、kubectl 以及 minikube 或 kind 用于本地验证。
注意事项与推荐实践
- 先类型后控制器:
SampleSourceSpec中的interval、serviceAccountName等字段是控制器与用户之间的契约,务必在samplesource_types.go中定义完整(例如interval默认"10s",支持ns/us/ms/s/m/h单位)后再写NewController; - 幂等调谐:Deployment 与 SinkBinding 的 Get → Create → Update 流程确保控制器在重复调谐时不会产生副作用,
podSpecImageSync等辅助函数用于精确判断 spec 是否真的变化; - 配置传播:不要忘记
configAccessor——它把集群级 tracing/logging/metrics 配置注入 Receive Adapter,是自定义事件源可观测性成立的前提; - 事件过滤:次级资源的事件处理器必须使用
FilterGroupKind+EnqueueControllerOf,否则任何无关 Deployment/SinkBinding 变化都会触发不必要的调谐。
完成控制器、Receive Adapter 与 CRD 三件套后,你便拥有了一个语义化、可观测、可平滑消费的自定义事件源;若它不是 Knative 核心自带源,可进一步参考 事件源清单 了解如何将新源加入第三方源列表,供社区共享。