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

WBOY
Release: 2024-02-06 10:00:11
forward
576 people have browsed it

如何在 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)
}
Copy after login

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")
}
Copy after login

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
}
Copy after login

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)
}
Copy after login

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
Copy after login

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")
}
Copy after login

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.")
    }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!