/ kubernetes

How to write custom controller for kubernetes

Kubernetes Custom Controller runs inside the Controller Manager on the master node. This controller listens for configuration requests for the custom resource.One of the ways in which you can extend Kubernetes is by writing your own custom controllers. You can write custom controllers that handle in-built Kubernetes objects, such as Deployment, Service, in new ways, or you can add new custom resources within Kubernetes and write a custom controller to handle these new resources.

It is responsible for deploying and maintaining pods that belong to custom resource.
Work flow of custom controller:

  1. Construct informer and shared informer objects
  2. Controller monitor for events on crd
  3. Modify the resource to expected state and perform actions.

Pictorial representation of componentes involvedkubernetes

Construct informer and shared informer objects::

*queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

informer := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return client.CoreV1().Pods(metav1.NamespaceAll).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return client.CoreV1().Pods(metav1.NamespaceAll).Watch(options)
},
},
&apiv1.Pod{},
0, //Skip resync
cache.Indexers{},
)*

Monitor for Events on resources::

informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
DeleteFunc: func(obj interface{}) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
})

Here resource controller push the object keys to worker queue for processing. Controller which is running will pick the object keys from queue and process items as per the business logic.