Kubernetes Go Operator 如何为某个资源生成 Event

How to generate Events for a certain resource Kubernetes Go Operator

我正在用 Go 编写 Kubernetes Operator,我想以与 Pods 相同的方式生成事件,即在协调的每个点,我想编写一个可以使用检查的事件kubectl describe myresource.

我找到了允许我这样做的包,但我不知道如何使用它:https://github.com/kubernetes/client-go/blob/master/tools/record/event.go

示例框架代码:

type MyResourceReconciler struct {
    client.Client
    Log    logr.Logger
    Scheme *runtime.Scheme
}

var logger logr.Logger

func (r *MyResourceReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
        Named("MyResource-controller").
        For(&v1.MyResource{}).
        Complete(r)
}

func (r *MyResourceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    logger = r.Log.V(0).WithValues("MyResource", req.NamespacedName)
    logger.Info("reconcile called")

    // TODO: Record event for req.NamespacedName

    return reconcile.Result{}, nil
}

Kubebuilder v1 一书有一个很好的例子,说明如何使用 EventRecorder 来自 client-go.

Kubebuilder v1 book - Create Events and Write Events