Guide
How it works
A Kubernetes operator, one piece at a time, each tied to the file in the repository that does it. Written for someone who knows how to run services, and wants to know what happens inside the control plane.
1. What an operator is
Kubernetes is a database of objects (Deployments, Services, Pods) plus controllers that keep reality in line with them. You write the desired state; a controller watches the objects and acts until the world matches. A Deployment controller creates ReplicaSets, a ReplicaSet controller creates Pods, the kubelet runs containers.
An operator is the same pattern for your own domain: a new kind of object (a custom resource, defined by a CustomResourceDefinition) and a controller that knows what it means. Here the object is a StreamProbe, and what it means is "keep watching this stream and tell me how it is".
That makes streamprobe an observing operator: it creates nothing in the cluster. Its whole output is the object's status, events and metrics. Most operators provision things (a database, a certificate); the reconcile loop is the same either way, and an observing one is the shortest path to learning it.
2. The custom resource
The type is plain Go in api/v1alpha1/streamprobe_types.go: a Spec (what the user wants) and a Status (what the controller found). The schema the API server enforces is generated from it by controller-gen (make manifests), driven by comments called markers:
// +kubebuilder:validation:Pattern=`^https?://`
// +required
URL string `json:"url"`
// +kubebuilder:default="30s"
// +optional
Interval metav1.Duration `json:"interval,omitzero"`
Validation and defaults live in the CRD's OpenAPI schema, so the API server applies them, before any controller sees the object: kubectl apply of a file:// URL is refused at the door, and an object without interval is stored with 30s. Other markers add the columns of kubectl get and the short name sp.
The +kubebuilder:subresource:status marker splits the object in two endpoints. Users write spec; the controller writes status through /status. Two consequences matter later: they can have different permissions, and a status write does not change the object's generation, which counts spec changes only.
3. The reconcile loop
A controller is a function, Reconcile(ctx, request), in internal/controller/streamprobe_controller.go. The request carries only a namespace and a name; the controller reads the object fresh every time and decides what to do from what it sees now. This is what level-based means: the controller reacts to the current state, not to the event that woke it up. If ten changes happen while it is busy, it is called once and sees the last one. If the operator restarts, nothing is lost: everything it needs is in the API.
controller-runtime does the plumbing: a watch on StreamProbes feeds a work queue, which de-duplicates requests and retries failed ones with exponential back-off. Reconcile returns a Result: nothing, an error (retry with back-off), or RequeueAfter: d (call me again in d).
A deleted object comes in as a "not found" on the read: the controller drops what it holds for it (here, its metric series) and returns.
4. Periodic work in a level-based loop
A stream must be checked every 30 seconds whether or not anything changed in the cluster. The tempting design is a goroutine with a ticker per probe; it would lose its schedule on every restart, double up when two replicas run, and hide its state from kubectl. Instead the schedule lives in the object:
reconcile(probe):
if status.lastCheckTime + interval > now and status.observedGeneration == generation:
return RequeueAfter(the rest of the interval) # not due yet
check the stream
write status (lastCheckTime = now, observedGeneration = generation, …)
return RequeueAfter(interval) # the next check
Every reconcile is safe to call at any time: early, it only reschedules; late (after a restart), it checks at once. When the user edits the spec, the generation moves past observedGeneration and the next reconcile checks immediately with the new settings. The interval has a floor of five seconds in code: a typo must not turn the operator into a load test of someone's origin.
5. Not waking up on its own writes
Writing the status is an update to the object, and the watch delivers every update. Left alone, the controller would wake up after each of its own writes, find the check not due, and go back to sleep: harmless, but a reconcile for nothing every time. The watch is filtered with GenerationChangedPredicate:
For(&streamingv1alpha1.StreamProbe{}, builder.WithPredicates(predicate.GenerationChangedPredicate{}))
Status writes leave the generation alone (that is what the status subresource bought us), so only spec changes, creations and deletions get through. The periodic calls come from RequeueAfter, which does not need an event.
6. The check and the verdict
The check itself knows nothing about Kubernetes (internal/probe): fetch the playlist, follow the first variant of a multivariant one, read the target duration, the media sequence and the segments, and ask the origin for the last segment, reading only its first kilobyte. The parser (internal/hls) reads only the tags that matter.
What a check means is decided by one pure function, evaluate in internal/controller/evaluate.go: previous status, check and time in; next status and verdict out. Pure means every rule is a row in a table test, no cluster and no network.
"Is the stream moving" is measured on the live edge, the sequence number of the last segment: media sequence plus segments minus one. Watching #EXT-X-MEDIA-SEQUENCE alone would call a healthy EVENT playlist stale, because it keeps its media sequence and only appends segments. An edge that goes backwards is an encoder restart, and counts as movement. Without movement for staleAfter (default three target durations) the stream is Stale.
7. Conditions, events and metrics
Conditions
status.conditions is the Kubernetes convention for "how is this object": a list of metav1.Condition, each a type, a status (True, False, Unknown), a machine-readable reason and a human message. streamprobe has one, Ready. Generic tools understand it without knowing streamprobe: kubectl wait --for=condition=Ready sp/channel-1 works as it does for a Deployment.
Events
Events are the object's history, the lines at the bottom of kubectl describe. They are written through the events.k8s.io API, with the recorder controller-runtime gives the manager. streamprobe records one only when the verdict changes: a stream stuck for a day would otherwise write an event every 30 seconds.
Metrics
controller-runtime already serves /metrics (work-queue depth, reconcile durations, API client latency). streamprobe adds its own gauges, histogram and counter to the same registry, one series per probe. A deleted probe's series are dropped by the reconcile that finds it gone, so no finalizer is needed: a finalizer is for state outside the operator (a cloud resource) that must be cleaned up before the object may disappear.
8. Permissions from markers
The operator's ServiceAccount can do exactly what three markers on the controller say, and make manifests writes the ClusterRole from them:
// +kubebuilder:rbac:groups=streaming.allan-nava.github.io,resources=streamprobes,verbs=get;list;watch
// +kubebuilder:rbac:groups=streaming.allan-nava.github.io,resources=streamprobes/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
Read the probes, write their status, write events. It cannot edit a spec, and it cannot touch anything else in the cluster. A new need is a new marker, never a hand-written Role.
9. Testing without a cluster, then with one
- Pure tests. The parser, and every rule of
evaluate, as tables. - The check against a fake origin. The prober runs against
httptestservers: a multivariant playlist followed to its variant, a missing segment, an HTML page instead of a playlist. - envtest. A real
kube-apiserverandetcd, started by the test as plain processes: no Docker, no nodes, no Pods. The CRD is installed for real, so its defaults and its validation are tested as the API server applies them. The reconcile loop runs against it with a fake prober and a fake clock: Live, then Stale when the edge stops, one event per change, failures counted and cleared, a spec change checked at once, metrics dropped on delete. - End to end on kind. In CI the suite builds the image and deploys the operator into a kind cluster, the way a user would. Next to it runs a fake live origin: a Python script in a ConfigMap that serves a playlist of one-second segments whose live edge moves with the clock, until a
GET /stopfreezes it. The test creates a StreamProbe for it, waits forLive, freezes the stream, waits forStale, then checks the two events and reads the probe's series from the manager's metrics endpoint. This is the part envtest cannot do: real Pods, a Service, cluster DNS, the operator's own RBAC and image.
10. If you know Nomad
Most ideas exist on both sides, under different names. This is the map used while writing streamprobe, coming from Nomad and Consul:
| Nomad / Consul | Kubernetes | In streamprobe |
|---|---|---|
| Job specification (HCL) | An object's spec (YAML) | StreamProbe.spec |
Allocation status, nomad job status | status, conditions, kubectl get/describe | Ready with its reason |
| The scheduler's evaluations and the eval broker | Controllers, the work queue and its back-off | Reconcile |
| A periodic job | A CronJob, or RequeueAfter in a controller | RequeueAfter(interval) |
| Consul health checks | Probes on Pods; conditions on objects | a health check for a stream, as an object |
| Job and node events | Events (events.k8s.io) | one per change of verdict |
| ACL policies | RBAC: Role, ClusterRole, binding | generated from markers |
| Writing a custom scheduler or a sidecar | A CRD and an operator | this repository |
The biggest difference is where logic lives. Nomad schedules what you declare and stops there; anything domain-specific runs as a job of its own and keeps its state where it likes. Kubernetes lets you extend the API: the stream becomes an object like a Deployment, with the same tools, permissions and history.