gpt4 book ai didi

azure - 监视特定对象的事件

转载 作者:行者123 更新时间:2023-12-02 22:52:33 27 4
gpt4 key购买 nike

我们有一个 k8s 运算符(基于 kubebuilder),它按预期工作,现在我们需要支持监听集群上的 secret 。

以下代码正在运行,但是我收到了集群中所有 secret 的事件,该事件效率不高

我想要仅针对特定 secret 获取事件,假设具有特定标签/注释的 secret ,我们该怎么做?

func (r *InvReconciler) SetupWithManager(mgr ctrl.Manager) error {
manager := ctrl.NewControllerManagedBy(mgr).
For(&corev1alpha1.Inv{}, builder.WithPredicates(predicate.Or(predicate.GenerationChangedPredicate{}, predicate.AnnotationChangedPredicate{}))).
WithOptions(controller.Options{
})

manager = manager.Watches(&source.Kind{Type: &v1.Secret{}}, handler.EnqueueRequestsFromMapFunc(func(a client.Object) []reconcile.Request {
return r.secretHandler.GetSecret(a.GetNamespace(), a.GetName())
}))

return manager.Complete(r)
}

这就是函数

func (secretReq secretHandler) GetSecret(namespace string, name string) []reconcile.Request {

fmt.Println("secret is: ", namespace, "--", name)
return nil
}

让我们说如下 secret ,并且仅针对此 secret (带有标签 foo: bar ),我将在创建或修改它时获取事件

apiVersion: v1
kind: Secret
metadata:
labels:
foo: bar
name: mysecret
namespace: dev
type: Opaque
data:
USER_NAME: YWRtaW4=
PASSWORD: dGVzdBo=

在收到事件后,我不会谈论 if 语句,因为它已经带来了集群中的所有 secret 事件。

最佳答案

根据这个github源,您应该能够使用 EnqueueRequestForObject 选择特定对象(例如 secret )。但是,(目前)不可能仅监视特定的 secret CRUD 更改。

EnqueueRequestForObject to watch for your CRD resource changes. Inyour CRD reconciler, you'd fetch all of the TLS secrets using a labelselector based on the search definition and then run your merge logicwith the matched secrets.

EnqueueRequestFromMapFunc to watch forsecret changes and trigger a reconcile of one or more CRs. In yourmapper function, you'd fetch all of the CRs. For each CR that has asearch definition that matches the passed in secret, you'd create anew reconcile.Request for the CR, and return the list of requests,which would trigger your CRD reconciler for each CR that matched.

最干净的方法是使用标签选择器,然后将结果与现有代码合并。 post 中给出了使用标签选择器的示例。 :

func GetSecret(version string) (retVal interface{}, err error){
clientset := GetClientOutOfCluster()
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

listOptions := metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
Limit: 100,
}
secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
retVal = secretList.Items[0]
return retVal, err
}

关于azure - 监视特定对象的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73884118/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com