Controller logic
- Docker & Kubernetes course
- Expert
- Lesson 14/47
- 4 min
Learn the controller logic of an Operator.
Controller logic
The heart of an operator is the Reconcile function. It's called every time the custom resource changes (or an object it owns changes) and follows these steps:
- Read the custom resource; if it was deleted, exit.
- Calculate the needed child objects (Deployment, Service, CronJob).
- Create them if missing, update them if different.
- Update the status; requeue after a while if needed.
func (r *YedekReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var y v1.Yedek
if err := r.Get(ctx, req.NamespacedName, &y); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
cj := cronJobOlustur(&y) // desired child object
ctrl.SetControllerReference(&y, cj, r.Scheme) // ownership
// CreateOrUpdate ... update status ...
return ctrl.Result{RequeueAfter: time.Hour}, nil
}Ownership and garbage collection
ownerReferences links a child object to its owner. When the owner (the custom resource) is deleted, Kubernetes's garbage collector deletes the child objects too; also, when a child object changes, the owner's Reconcile is triggered. To clean up external resources before deletion, a finalizer is used:
metadata:
ownerReferences:
- apiVersion: ornek.com/v1
kind: Yedek
name: magaza-gece
controller: true
blockOwnerDeletion: true
# finalizer
metadata:
finalizers: ["ornek.com/s3-temizle"]Practice Inspect ownership
Write three commands: print the owner's kind of the magaza-gece-yedek CronJob in magaza with jsonpath='{.metadata.ownerReferences[0].kind}'; delete the magaza-gece Yedek in magaza; list the CronJobs in magaza.
Starter code
# buraya yazSample solution
kubectl get cronjob magaza-gece-yedek -n magaza -o jsonpath='{.metadata.ownerReferences[0].kind}'
kubectl delete yedek magaza-gece -n magaza
kubectl get cronjobs -n magazaExpected output
Yedek yedek.ornek.com "magaza-gece" deleted No resources found in magaza namespace.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why must the Reconcile function be safe to call again and again with the same input (idempotent)?
- For speed
- For memory
- It isn't required
- The controller is called many times for the same object in undefined order; each call must reach the same result Correct answer
Explanation: Instead of "create", you write "create if missing, conform if present".
2 Write the field linking the child object to its owner.
metadata:
____:
- apiVersion: ornek.com/v1
kind: Yedek
name: magaza-gece
metadata:
ownerReferences:
- apiVersion: ornek.com/v1
kind: Yedek
name: magaza-gece
Explanation: ownerReferences enables garbage collection.
3 Match.
| Term | Meaning |
|---|---|
Reconcile |
Reconcile function |
ownerReferences |
Ownership |
finalizer |
Cleanup before deletion |
RequeueAfter |
Retry later |