Sub topic 9
Anatomy of a Reconcile function
This chapter assumes you know the control loop pattern, the difference between spec and status, and how a work queue hands keys to a controller. You should also be able to read simple Go.
What Reconcile receives
A Reconcile function receives a request that holds only a namespace and a name. It does not receive the object, the event type, or the old and new values. This follows from level-triggered design. The function must work out what to do from the current state of the cluster, not from a description of what changed.
The function returns a ctrl.Result and an error. The return value tells the work queue what to do next.
The usual shape
Most reconcilers follow the same five steps:
- Read the object named by the request.
- Stop if the object is gone or being deleted.
- Read the dependent state that exists now.
- Create, update or delete objects until reality matches the spec.
- Return a result, or an error if something failed.
A working example
This reconciler makes sure every Namespace has a ConfigMap named defaults.
package controllers
import (
"context"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
type NamespaceDefaultsReconciler struct {
client.Client
}
func (r *NamespaceDefaultsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var ns corev1.Namespace
if err := r.Get(ctx, req.NamespacedName, &ns); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if !ns.DeletionTimestamp.IsZero() {
return ctrl.Result{}, nil
}
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "defaults", Namespace: ns.Name}}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, cm, func() error {
cm.Data = map[string]string{"managed-by": "namespace-defaults"}
return nil
})
return ctrl.Result{}, err
}
func (r *NamespaceDefaultsReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).For(&corev1.Namespace{}).Complete(r)
}Reading the code
- Get and IgnoreNotFound. The key can outlive the object. If the Namespace was deleted after the key was queued,
Getreturns a not-found error. That is not a failure, so the function returnsniland the key is dropped. - DeletionTimestamp check. An object being deleted still exists until its finalizers finish. This reconciler skips work on it.
- CreateOrUpdate. It reads the ConfigMap, applies your mutate function, and writes only if something differs. Running it ten times gives the same result as running it once.
- Returned error. A non-nil error makes the queue retry the key with exponential backoff. Do not log and swallow errors, because that stops the retry.
- SetupWithManager.
Forregisters the watch on Namespaces. Each change, and each periodic resync, queues a request for that Namespace.
Return values
| Return | Meaning |
|---|---|
| `Result{}, nil` | Done. Wait for the next change. |
| `Result{RequeueAfter: d}, nil` | Done for now, check again after `d`. |
| `Result{}, err` | Failed. Retry with backoff. |
Exercise
A reconciler's Get call returns a not-found error for the requested key. Should it return that error? Why or why not?
Show answer
No. It should return nil (for example with client.IgnoreNotFound). Not-found means the object was deleted after the key was queued, so there is nothing left to reconcile. Returning the error would cause pointless retries with backoff.