Saltar a contenido

Week 10 - controller-runtime and Kubebuilder

10.1 Conceptual Core

  • controller-runtime is the modern, opinionated framework for controllers. Built atop client-go, it provides:
  • Manager (informer factory + leader election + metrics + healthz wired together).
  • Reconciler (typed reconcile method).
  • Client (cached read, direct write).
  • Webhook scaffolding (mutating + validating + conversion).
  • Finalizers helpers.
  • Kubebuilder is a CLI on top of controller-runtime that scaffolds projects from CRD definitions. The de facto starting point for new operators.

10.2 Mechanical Detail

  • Project structure (kubebuilder init && kubebuilder create api):
    api/v1/         # CRD types (Go structs annotated for codegen)
    config/         # YAML scaffolds (CRDs, RBAC, kustomize bases)
    internal/controller/
                    # Reconciler implementations
    cmd/main.go     # Manager bootstrap
    
  • The Reconcile method is the hot path; it should be idempotent and make no assumption about why it was called. Re-derive everything each call.
  • controllerutil.CreateOrUpdate-the reliable upsert helper.
  • Owner references-when a controller creates a child object, it sets the parent as the owner. Garbage collection handles cascading deletion.
  • Finalizers-string keys on metadata.finalizers. Block deletion until the controller removes the finalizer (after performing cleanup). The pattern for cleaning up external resources before the K8s object disappears.
  • Status subresource-separates spec writes from status writes; allows least-privilege RBAC.

10.3 Lab-"Rebuild Week 9 in controller-runtime"

Take week 9's mirror controller; rebuild with kubebuilder + controller-runtime. Compare LOC and verbosity. The framework should save substantial code.

10.4 Hardening Drill

  • Use controller-runtime's metric and health endpoints. Configure leader election with a non-default lease duration appropriate to your environment.

10.5 Operations Slice

  • Wire controller_runtime_reconcile_* metrics. Establish dashboards: reconcile rate, error rate, average reconcile duration per controller.

Comments