获取在 kubebuilder 中触发控制器的事件类型

Getting the type of event, that triggered a controller in kubebuilder

我刚刚开始使用 kubebuilder 和 Golang 来使用自定义资源扩展我们的 Kubernetes 集群。我很乐意根据实际调用它的事件在协调器函数中做不同的事情。

资源创建了吗?更新了吗?被删除了吗?

这些事件中的每一个都会触发控制器,但是,我似乎无法找到查看这些事件中哪些事件实际发生的可能性。我可以通过编写这样的协调器来解决这个问题:

func (r *ServiceDescriptorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    service := &batchv1.ServiceDescriptor{}
    if err := r.Get(context.TODO(), req.NamespacedName, service); err != nil && errors.IsNotFound(err) {
        fmt.Println("Resource was not found -> must have been deleted")
    else {
        fmt.Println("No errors found -> Resource must have been created or updated")
    }
}

然而,这感觉有些隐晦而且有点老套。

是否有一种干净的(可能是本机的)方法来获取协调器调用的事件类型?

您将无法做到这一点,因为该系统被设计为基于级别,并且它不是由单个事件更改触发,而是由从 apiserver 获取的实际集群状态触发。

查看 reconcile.go 你会注意到第 #84 行有这样的评论:

Reconciliation is level-based, meaning action isn't driven off changes in individual Events, but instead is driven by actual cluster state read from the apiserver or a local cache. For example if responding to a Pod Delete Event, the Request won't contain that a Pod was deleted,instead the reconcile function observes this when reading the cluster state and seeing the Pod as missing.

并在行 #44:

Request contains the information necessary to reconcile a Kubernetes object. This includes the information to uniquely identify the object - its Name and Namespace. It does NOT contain information about any specific Event or the object contents itself.

你可以试试WithEventFilter(predicate.Funcs{}).

Since the reconiliation loop wasn’t taking any action when invoked after the item is actually deleted the predicate for delete events can simply return false! There is also a handy Funcs type that implements the Predicate interface and allows you to pass in functions you want to use as predicates. Putting it all together to filter out the delete events, we have:

func (r *CronJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
        For(&batch.CronJob{}).
        WithEventFilter(predicate.Funcs{
            DeleteFunc: func(e event.DeleteEvent) bool {
                // The reconciler adds a finalizer so we perform clean-up
                // when the delete timestamp is added
                // Suppress Delete events to avoid filtering them out in the Reconcile function
                return false
            },
        }).
        Complete(r) }

https://stuartleeks.com/posts/kubebuilder-event-filters-part-1-delete/