Sub topic 17
A custom controller with controller-runtime
This chapter assumes you know the Reconcile model from earlier chapters (watches, informer caches, work queues) and can read basic Go. controller-runtime is a Go library that wires those pieces together, so you write only the reconcile logic.
What the library gives you
A Manager owns the shared cache, the client, and the lifecycle of every controller you register. A Controller connects one watched type to one Reconciler through a work queue. Your Reconciler implements a single method, Reconcile(ctx, req).
The request holds only a name, never the event. Reconcile must read the current object itself, which keeps the controller level-triggered.
The reconciler
This controller watches Namespaces and makes sure each one 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)
}Three behaviors matter here:
client.IgnoreNotFoundtreats a vanished object as success. There is nothing left to reconcile, so retrying would be pointless.CreateOrUpdatereads the object, applies your mutate function, and writes only if something changed. Running it twice has the same effect as running it once, so the method is idempotent.- A returned error makes the work queue retry the request with exponential backoff.
ctrl.Result{}with a nil error means done until the next change.
r.Get reads from the Manager's cache. CreateOrUpdate writes go to the API server, and a stale resourceVersion produces a conflict error that triggers a retry.
The entry point
package main
import (
"os"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"example.com/nsdefaults/controllers"
)
func main() {
ctrl.SetLogger(zap.New())
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
LeaderElection: true,
LeaderElectionID: "namespace-defaults.example.com",
})
if err != nil {
os.Exit(1)
}
r := &controllers.NamespaceDefaultsReconciler{Client: mgr.GetClient()}
if err := r.SetupWithManager(mgr); err != nil {
os.Exit(1)
}
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
os.Exit(1)
}
}Setting LeaderElection lets you run several replicas while only one reconciles at a time.
Common mistakes
- Branching on what kind of event happened. The request does not carry that information.
- Writing to the object you read from the cache without a deep copy.
- Returning an error for a missing object, which causes endless retries.
Exercise
The Reconcile method receives only a namespaced name. Why does controller-runtime not pass the changed object or the event type?
Show answer
Controllers are level-triggered. Several events for one object collapse into a single queued request, and events can be missed or repeated. Reconcile reads the current state and acts on it, so the result is correct regardless of which events happened.