Home  >  Article  >  Backend Development  >  How to monitor external custom resource changes in kubebuilder without importing external types

How to monitor external custom resource changes in kubebuilder without importing external types

WBOY
WBOYforward
2024-02-06 10:00:11578browse

如何在 kubebuilder 中监视外部自定义资源更改而不导入外部类型

Question content

Suppose I have the following code snippet, which sets up a coordinator that monitors the external resource "external":

// SetupWithManager sets up the controller with the Manager.
func (r *SomethingReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
        For(&api.Something{}).
        WithOptions(controller.Options{
            MaxConcurrentReconciles: stdruntime.NumCPU(),
            RecoverPanic:            true,
        }).
        Watches(
            &source.Kind{Type: &somev1.External{}},
            handler.EnqueueRequestsFromMapFunc(r.findInternalObjectsForExternal),
            builder.WithPredicates(predicate.Funcs{
                UpdateFunc: func(ue event.UpdateEvent) bool { return true },
                DeleteFunc: func(de event.DeleteEvent) bool { return true },
            }),
        ).
        Complete(r)
}

My problem is that I cannot import the somev1.external type into my project because importing the go module containing this type would break my current project's dependencies.

Is there a way in kubebuilder to monitor external resources without explicitly importing their types? Like gvk or something?


Correct answer


Yes, it is possible.

You can create a rest client for your resource in main.go like this:

gvkexternal := schema.groupversionkind{
    group:   "some.group.io",
    version: "v1",
    kind:    "external",
}

restclient, err := apiutil.restclientforgvk(gvkexternal, false, mgr.getconfig(), serializer.newcodecfactory(mgr.getscheme()))
if err != nil {
    setuplog.error(err, "unable to create rest client")
}

Then add the fields of this rest client (rest.interface) to your coordinator (yournativeresource_controller.go) structure, for example:

type yournativeresourcereconciler struct {
    client.client
    scheme        *runtime.scheme
    // add this
    restclient    rest.interface
}

Finally, initialize your coordinator using this rest client (main.go):

if err = (&controllers.yournativeresourcereconciler{
    client:        mgr.getclient(),
    scheme:        mgr.getscheme(),
    restclient:    restclient,
}).setupwithmanager(mgr); err != nil {
    setuplog.error(err, "unable to create controller", "controller", "yournativeresource")
    os.exit(1)
}

Don't forget to add the rbac tag to your project (preferably the coordinator), it will generate rbac rules that allow you to manipulate external Resources:

//+kubebuilder:rbac:groups=some.group.io,resources=externals,verbs=get;list;watch;create;update;patch;delete

After completing these steps, you can use a rest client to manipulate external resources through the yournativeresource coordinator (using r.restclient.

)

edit:

If you want to watch the resource, a dynamic client may be helpful. Create a dynamic client in main.go:

dynamicclient, err := dynamic.newforconfig(mgr.getconfig())
if err != nil {
    setuplog.error(err, "unable to create dynamic client")
}

Apply the above steps, add it to your coordinator etc. You will then be able to watch external resources like this:

resourceInterface := r.DynamicClient.Resource(schema.GroupVersionResource{
    Group:    "some.group.io",
    Version:  "",
    Resource: "externals",
})
externalWatcher, err := resourceInterface.Watch(ctx, metav1.ListOptions{})
if err != nil {
    return err
}

defer externalWatcher.Stop()

select {
case event := <-externalWatcher.ResultChan():
    if event.Type == watch.Deleted {
        logger.Info("FINALIZER: An external resource is deleted.")
    }
}

The above is the detailed content of How to monitor external custom resource changes in kubebuilder without importing external types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Attach to pointer sliceNext article:Attach to pointer slice