Sub topic 9
Writing an idempotent reconcile loop
This chapter assumes you know Pods, Deployments and labels, can read the WebApp CRD from earlier chapters, and can read basic Go. It covers the Reconcile function that makes a WebApp real.
What reconcile receives
A controller does not get told what changed. It gets a key: the namespace and name of one object. Your function reads the current state, compares it to the desired state, and closes the gap. Because the same key can arrive many times (restarts, resyncs, retries), the function must be idempotent. Running it ten times must give the same result as running it once.
The reconciler
type WebAppReconciler struct {
client.Client
Scheme *runtime.Scheme
}
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var app examplev1.WebApp
if err := r.Get(ctx, req.NamespacedName, &app); err != nil {
// The object was deleted; owned children are garbage collected.
return ctrl.Result{}, client.IgnoreNotFound(err)
}
deploy := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: app.Name, Namespace: app.Namespace},
}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, deploy, func() error {
labels := map[string]string{"app": app.Name}
deploy.Spec.Replicas = &app.Spec.Replicas
deploy.Spec.Selector = &metav1.LabelSelector{MatchLabels: labels}
deploy.Spec.Template.Labels = labels
deploy.Spec.Template.Spec.Containers = []corev1.Container{
{Name: "web", Image: app.Spec.Image},
}
return controllerutil.SetControllerReference(&app, deploy, r.Scheme)
})
if err != nil {
return ctrl.Result{}, err
}
app.Status.ReadyReplicas = deploy.Status.ReadyReplicas
return ctrl.Result{}, r.Status().Update(ctx, &app)
}
func (r *WebAppReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&examplev1.WebApp{}).
Owns(&appsv1.Deployment{}).
Complete(r)
}Why this is idempotent
- Read, don't remember. The function starts from the API server's current state and keeps nothing between calls.
- Declare the end state.
CreateOrUpdatefetches the Deployment. It creates it if missing. Otherwise it applies your mutate function and updates only if something differs. A second run finds no difference and does nothing. - Handle deletion.
IgnoreNotFoundturns "already gone" into success. Garbage collection removes the Deployment because of the owner reference set bySetControllerReference. - Re-trigger on child changes.
Owns(&appsv1.Deployment{})queues the parentWebAppwhenever its Deployment changes. This is howreadyReplicasgets refreshed.
Common errors
- Conflicts.
Updatefails if the object changed since you read it. Returning the error makes the controller retry with backoff. This is normal. - Fighting other writers. If you set a field in the mutate function, another tool that edits it will cause a constant tug of war. Set only fields you own.
- Side effects before the write. Anything that cannot be repeated safely, such as sending an email, will run again on every retry. Record completion in status or make the call itself idempotent.
- Missing selector labels. A Deployment's selector is immutable. Changing the labels in the mutate function later makes the update fail.
Exercise
You scale spec.replicas from 2 to 3. Reconcile runs twice for that one change. What does the second run do to the Deployment?
Show answer
Nothing. CreateOrUpdate finds that the Deployment already has 3 replicas, so it issues no update. The only possible write is the status update, and only if the ready count changed.