创建一个控制器¶
您可以使用示例存储库 update-codegen.sh 脚本来生成并将所需组件(clientset、cache、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(),
// ...
}
步骤¶
-
通过运行命令生成组件
${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 -
通过运行命令注入组件
# 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 -
将新的控制器实现传递给
sharedmain方法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) } -
定义
NewController实现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), }向此实现传递一个
configmap.Watcher和一个上下文,注入的 lister 会将它们用于 reconciler 结构体参数。 -
从
knative.dev/pkg依赖项导入基础 reconcilerimport ( // ... reconcilersource "knative.dev/eventing/pkg/reconciler/source" // ... ) -
确保事件处理程序被过滤到正确的 informer
sampleSourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) -
确保 informer 已正确配置,以便为示例源用于部署和绑定事件源以及接收适配器所使用的辅助资源进行配置
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), })