'What is the best approach for creating a controller in Kubernetes?
I'm not quite sure if which of the following approaches is the better approach to create a controller in kubernetes however I know that:
- I don't want to create a custom resource by any means.
- I do only want to fetch information about k8s native resources (pods, ...) given that there might be a lot of pods in each namespace
I have seens some patterns like:
ctrl, err := controller.New("name-here", mgr, controller.Options{
Reconciler: &ReconcilePod{Client: mgr.GetClient(), Logger: log},
})
which ReconcilePod
is a struct that has a function Reconcile
that keep whole business logic.
Another approach I have seens is like following:
type Controller struct {
indexer cache.Indexer
queue workqueue.RateLimitingInterface
informer cache.Controller
}
and then defining shared informer
and watcher
etc.
And the third pattern that I have seen is using operators
what I don't get perhaps is what is the main differences between mentioned approaches above and which one fits my need at scale.
Solution 1:[1]
If you don't want to "control" anything, there is no need to create a controller.
If you just want to "read" and "watch" resources, you can use client-go and see e.g. Extend Kubernetes via a shared informer for inspiration about how to read and watch resources.
To stay informed about when these events get triggered you can use a primitive exposed by Kubernetes and the client-go called SharedInformer, inside the cache package. Let’s see how it works in practice.
Controllers are more complex and contains a reconciliation loop since they should realize/manage a desired state.
An "operator" is a controller as well.
Solution 2:[2]
You can simply start with operator-sdk provided to create a controller easily in which the code will be generated and you need to add business logic to your objects. https://sdk.operatorframework.io/docs/building-operators/golang/quickstart/
mkdir memcached-operator
cd memcached-operator
operator-sdk init --domain example.com --repo github.com/example/memcached-operator
You can simply then create controller eith for existing kind or a new kind
operator-sdk create api --group cache --version v1alpha1 --kind Memcached --resource --controller
It is the simplest way to manage kinds and resources using operator sdk and no need to worry about complex code of client set
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonas |
Solution 2 | Himanshu |