Docker & Kubernetes
Controller logic
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"]
Exercise 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.
Show example 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 magaza
Test yourself
-
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
Show answer
The controller is called many times for the same object in undefined order; each call must reach the same result — Instead of "create", you write "create if missing, conform if present".
-
Write the field linking the child object to its owner.
metadata:
____:
- apiVersion: ornek.com/v1
kind: Yedek
name: magaza-gece
Show answer
metadata:
ownerReferences:
- apiVersion: ornek.com/v1
kind: Yedek
name: magaza-gece
-
Match.
- Reconcile
- Reconcile function
- ownerReferences
- Ownership
- finalizer
- Cleanup before deletion
- RequeueAfter
- Retry later
Next lesson: Operator SDK