Week 9 - client-go Internals and a Bare Controller¶
9.1 Conceptual Core¶
client-gois the Kubernetes Go client library-typed clients, informers, work queues, leader election, the lot.- Building a controller "from scratch" in
client-gois verbose but instructive-every other framework hides these primitives. - The pattern (the informer + workqueue pattern):
- Create a
SharedInformerFactoryfor the resources you watch. - For each kind, register
OnAdd/OnUpdate/OnDeletehandlers that compute a key (namespace/name) andAddit to aRateLimitingQueue. - Start N workers that pull keys from the queue and run
reconcile(key). reconcile: list-from-cache (never call apiserver in the hot path), compute diff, apply changes, requeue on error with backoff.
9.2 Mechanical Detail¶
- The informer's resync period: re-deliver every cached object every N (default 10 minutes). Belt-and-suspenders against missed events.
- Indexers (
cache.Indexer): O(1) lookup by namespace, by label, by custom key. Free with the informer. - Listers (
<group>/<version>/<resource>/lister.goin generated client code): typed accessors over the indexer. - Leader election (
tools/leaderelection): only one replica of the controller acts; others stand by. Uses aLeaseresource as the lock. - Generated clients: for built-in types,
client-goships them. For your own CRDs, generate withcontroller-genorkubebuilder(week 10).
9.3 Lab-"Controller From Scratch"¶
Build a controller that watches ConfigMaps with the label mirror=true and copies them into every namespace whose name matches a configurable prefix.
- Use client-go informers + workqueue directly.
- Add leader election.
- Idempotent: same input twice produces same result.
- Handle deletions: when the source is deleted, delete all mirrors.
- Run as a Deployment in the cluster.
9.4 Hardening Drill¶
- Define a minimum RBAC: only
get/list/watchonconfigmapsandnamespaces, pluscreate/update/deleteonconfigmaps(constrained by namespace prefix? Use admission webhooks or namespace selectors).
9.5 Operations Slice¶
- Expose
controller_runtime_* - style metrics: queue depth, work duration, error rate. Add a/healthzand/readyz. Run with/livez` probe.