Skip to main content

engenho_controllers/
daemonset.rs

1//! `DaemonSetController` — ensures exactly ONE Pod per schedulable
2//! node, owned by the `DaemonSet`.
3//!
4//! ## The `DaemonSet` contract (distinct from `ReplicaSet`)
5//!
6//! A `DaemonSet` does NOT have a `spec.replicas` knob. Its desired pod
7//! set is "one pod on every schedulable node" — node-pinned, scheduler-
8//! bypassing. So unlike ReplicaSet/StatefulSet (which clone N pods the
9//! scheduler then binds), the `DaemonSet` controller:
10//!
11//!   1. enumerates schedulable Nodes (cluster-scoped `Node` objects,
12//!      skipping those with `spec.unschedulable == true`),
13//!   2. for each node WITHOUT an owned pod, creates one pod from
14//!      `spec.template` with `spec.nodeName` PRE-SET to that node (the
15//!      scheduler never touches it — `DaemonSet` pods are node-pinned),
16//!   3. for each owned pod on a node that no longer exists / is now
17//!      unschedulable, deletes it (node removed → pod GC'd; owner-ref
18//!      GC also covers `DaemonSet` deletion).
19//!
20//! Pod name: `{ds}-{node}` — deterministic (one pod per node, so the
21//! node name is a natural unique key). Production K8s uses a hash
22//! suffix; we keep it deterministic + readable for tests + operators,
23//! the same way `ReplicaSet` uses `{rs}-{index}`.
24//!
25//! Self-heal: a deleted pod is recreated on its node on the next tick
26//! (the node still exists + has no owned pod → step 2 fires).
27//!
28//! ## Updates (`spec.updateStrategy`)
29//!
30//! Every pod is stamped with the revision of the template it was built from
31//! ([`crate::rollout`]). Under `RollingUpdate` (the default, as upstream,
32//! with `maxUnavailable: 1`) an out-of-date pod is deleted and its node gets
33//! a pod from the current template; out-of-date pods that are not Ready go at
34//! once, Ready ones one budget's worth at a time. Under `OnDelete` a pod is
35//! only replaced once something else deletes it. A pod in phase `Failed` is
36//! deleted and replaced under either strategy, with a per-node backoff.
37//!
38//! This is what turns a template change — a new image after the daemon
39//! restarts onto a new release — into replaced pods without an operator.
40//! Before it, a node with a pod was covered whatever the pod was built from,
41//! and a pod whose image had been garbage-collected waited forever.
42//!
43//! ## Why node enumeration lives in `reconcile_one`
44//!
45//! The shared [`OwnedChildrenReconciler`] blanket hands each parent its
46//! owned children, but a `DaemonSet`'s desired set is a function of the
47//! NODE list (not the child count). The controller reads the cluster's
48//! Nodes from `self.store()` inside `reconcile_one` — the one place the
49//! per-parent delta is computed. Nodes are cluster-scoped, so the read
50//! is `list("", "v1", "Node", None)` regardless of the DS's namespace.
51
52use std::sync::Arc;
53
54use async_trait::async_trait;
55use engenho_store::{
56    StoreMesh,
57    command::{Reason, ResourceCommand},
58    resource::ResourceKey,
59};
60use serde_json::{Value, json};
61use tracing::{debug, info};
62
63use crate::error::ControllerError;
64use crate::event_recorder::Reason as EventReason;
65use crate::meta::{ObjectMeta, ShapeError};
66use crate::owned_children::{
67    OwnedChildrenReconciler, ParentGvk, ReconcileDelta, live_children, pod_from_template,
68    template_object_mut,
69};
70use crate::owner::{OwnerReference, owner_ref_for};
71use crate::reads::gvk;
72use crate::rollout::{TemplateRevision, UpdateStrategy, pod_is_failed};
73use crate::status::pod_is_ready;
74use crate::sweep::{Sweep, impl_sweep_event_sink};
75use engenho_substrate::Clock;
76use engenho_types::kind::GroupVersionKind;
77
78/// `DaemonSet` controller — one node-pinned Pod per schedulable node.
79pub struct DaemonSetController {
80    store: Arc<StoreMesh>,
81    namespace: Option<String>,
82    /// Per-DaemonSet isolation (`FailedCreate` on a malformed template).
83    sweep: Sweep,
84    /// The clock the failed-pod backoff reads.
85    clock: Arc<dyn Clock>,
86    /// How soon a node's failed pod may be deleted again.
87    failed_backoff: FailedPodBackoff,
88}
89
90impl_sweep_event_sink!(DaemonSetController);
91
92impl DaemonSetController {
93    /// Construct with optional namespace scope (`None` = all namespaces).
94    #[must_use]
95    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
96        Self {
97            store,
98            namespace,
99            sweep: Sweep::new("daemonset-controller", EventReason::FailedCreate),
100            clock: Arc::new(engenho_substrate::WallClock),
101            failed_backoff: FailedPodBackoff::default(),
102        }
103    }
104
105    /// Builder: the clock the failed-pod backoff reads (tests pin one).
106    #[must_use]
107    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
108        self.clock = clock;
109        self
110    }
111
112    /// A node's `metadata.name`, if present.
113    fn node_name_of(node: &Value) -> Option<&str> {
114        node.name()
115    }
116
117    /// True iff a node is schedulable — i.e. NOT cordoned
118    /// (`spec.unschedulable != true`). Mirrors the self-registered
119    /// node's `spec.unschedulable == false` shape the runtime stamps.
120    fn node_is_schedulable(node: &Value) -> bool {
121        !node
122            .get("spec")
123            .and_then(|s| s.get("unschedulable"))
124            .and_then(serde_json::Value::as_bool)
125            .unwrap_or(false)
126    }
127
128    /// Build a node-pinned Pod from the `DaemonSet` template for `node`.
129    /// The name is `{ds_name}-{node}`; `spec.nodeName` is PRE-SET to the
130    /// node (the scheduler is bypassed — `DaemonSet` pods are node-pinned).
131    ///
132    /// The Pod lives in the SAME namespace as its parent `DaemonSet` — the
133    /// namespace the blanket gathers owned pods from. Never the
134    /// controller's scope namespace (an all-namespace controller has
135    /// none). Mirrors `ReplicaSetController::build_pod_from_template`.
136    ///
137    /// `Ok(None)` when the `DaemonSet` has no name or no template.
138    ///
139    /// # Errors
140    ///
141    /// [`ShapeError`] when the template (or its `spec`) has the wrong JSON
142    /// shape. It used to skip such a template's `spec` silently, creating a
143    /// pod the scheduler would then place on ANY node.
144    fn build_pod_for_node(
145        ds: &Value,
146        node_name: &str,
147        owner: OwnerReference,
148    ) -> Result<Option<(String, Value)>, ShapeError> {
149        let Some(ds_name) = ds.name() else {
150            return Ok(None);
151        };
152        let ds_namespace = ds.namespace().unwrap_or("default");
153        let pod_name = format!("{ds_name}-{node_name}");
154        let Some(mut pod) = pod_from_template(ds, &pod_name, ds_namespace, owner)? else {
155            return Ok(None);
156        };
157        // Node-pin: pre-set spec.nodeName so the scheduler never binds it.
158        template_object_mut(&mut pod, &["spec"])?.insert("nodeName".into(), Value::from(node_name));
159        Ok(Some((pod_name, pod)))
160    }
161
162    /// The failed pods to delete this pass.
163    ///
164    /// Upstream's `podsShouldBeOnNode` deletes a daemon pod in phase `Failed`
165    /// so the node gets a fresh one from the CURRENT template. engenho kept
166    /// it forever: the node was covered by name. A native pod whose closure
167    /// is gone fails as `ImageUnavailable`, so this is also what recovers a
168    /// node from a garbage-collected image. Rate-limited per node, as
169    /// upstream's `failedPodsBackoff` is, so a template that fails every
170    /// time does not create and delete at the loop's speed; a node whose pod
171    /// is Ready is forgiven.
172    fn failed_deletions<'o>(
173        &self,
174        ds_name: &str,
175        ds_uid: &str,
176        owned: &'o [(ResourceKey, Value)],
177        deleting: &std::collections::BTreeSet<&ResourceKey>,
178    ) -> Vec<&'o ResourceKey> {
179        let mut out = Vec::new();
180        for (pod_key, pod_value) in live_children(owned) {
181            let node = Self::pod_node(pod_value).unwrap_or_default();
182            if pod_is_ready(pod_value) {
183                self.failed_backoff.clear(ds_uid, node);
184            }
185            if deleting.contains(pod_key) || !pod_is_failed(pod_value) {
186                continue;
187            }
188            if self
189                .failed_backoff
190                .admit(ds_uid, node, self.clock.unix_ms())
191            {
192                info!(
193                    daemonset = %ds_name,
194                    pod = %pod_key.label(),
195                    node,
196                    reason = pod_value
197                        .pointer("/status/reason")
198                        .and_then(serde_json::Value::as_str)
199                        .unwrap_or(""),
200                    "deleting failed daemon pod so its node gets a fresh one"
201                );
202                out.push(pod_key);
203            }
204        }
205        out
206    }
207
208    /// The node an owned pod is pinned to (`spec.nodeName`), if present.
209    fn pod_node(pod: &Value) -> Option<&str> {
210        pod.get("spec")
211            .and_then(|s| s.get("nodeName"))
212            .and_then(|n| n.as_str())
213            .filter(|s| !s.is_empty())
214    }
215}
216
217#[async_trait]
218impl OwnedChildrenReconciler for DaemonSetController {
219    fn name(&self) -> &'static str {
220        "daemonset"
221    }
222
223    fn parent_gvk(&self) -> ParentGvk {
224        ParentGvk::new("apps", "v1", "DaemonSet", "apps/v1")
225    }
226
227    fn child_kinds(&self) -> &'static [GroupVersionKind] {
228        const CHILD_KINDS: &[GroupVersionKind] = &[gvk("", "v1", "Pod")];
229        CHILD_KINDS
230    }
231
232    /// The Nodes it places one pod on each of.
233    fn also_reads(&self) -> &'static [GroupVersionKind] {
234        const ALSO: &[GroupVersionKind] = &[gvk("", "v1", "Node")];
235        ALSO
236    }
237
238    fn store(&self) -> &StoreMesh {
239        &self.store
240    }
241
242    fn namespace(&self) -> Option<&str> {
243        self.namespace.as_deref()
244    }
245
246    fn sweep(&self) -> &Sweep {
247        &self.sweep
248    }
249
250    async fn reconcile_one(
251        &self,
252        ds_value: &Value,
253        owned: &[(ResourceKey, Value)],
254    ) -> Result<ReconcileDelta, ControllerError> {
255        // No name / owner-ref → no-op (parent freshly minted; the blanket
256        // already skipped no-uid parents).
257        let Some(ds_name) = ds_value.name() else {
258            return Ok(ReconcileDelta::none());
259        };
260        let Some(owner_ref) = owner_ref_for(ds_value, "apps/v1", "DaemonSet") else {
261            return Ok(ReconcileDelta::none());
262        };
263        // A strategy engenho cannot read refuses THIS DaemonSet (an Event on
264        // it), before anything is created or deleted for it.
265        let strategy = UpdateStrategy::of(ds_value)?;
266        let revision = TemplateRevision::of(ds_value);
267        let generation = crate::status::generation_of(ds_value).ok();
268
269        // Enumerate schedulable nodes (cluster-scoped). The desired set is
270        // one pod per schedulable node — node-pinned.
271        let nodes = self.store.list("", "v1", "Node", None).await;
272        let schedulable: std::collections::BTreeSet<String> = nodes
273            .iter()
274            .filter(|(_, n)| Self::node_is_schedulable(n))
275            .filter_map(|(_, n)| Self::node_name_of(n).map(String::from))
276            .collect();
277
278        let pod_ns = crate::owned_children::child_namespace(ds_value, self.namespace.as_deref());
279
280        // The nodes already covered by an owned pod. A Terminating pod
281        // still covers its node: its replacement would take the same name
282        // (`{ds}-{node}`), so it waits for the old one to go. Upstream names
283        // daemon pods by hash and replaces at once. Deleting a Terminating
284        // pod again is left out by the blanket (I3). A Failed pod covers its
285        // node too, until the delete below has removed it.
286        let covered: std::collections::BTreeSet<String> = owned
287            .iter()
288            .filter_map(|(_, p)| Self::pod_node(p).map(String::from))
289            .collect();
290
291        let mut commands = Vec::new();
292        let mut deleting: std::collections::BTreeSet<&ResourceKey> =
293            std::collections::BTreeSet::new();
294
295        // Create one pod per schedulable node NOT yet covered, stamped with
296        // the template revision it is built from.
297        for node_name in &schedulable {
298            if covered.contains(node_name) {
299                continue;
300            }
301            let Some((pod_name, mut pod)) =
302                Self::build_pod_for_node(ds_value, node_name, owner_ref.clone())?
303            else {
304                continue;
305            };
306            if let Some(rev) = &revision {
307                rev.stamp(&mut pod, generation)
308                    .map_err(|e| e.under(crate::owned_children::TEMPLATE))?;
309            }
310            let pod_key = ResourceKey::namespaced("", "v1", "Pod", &pod_ns, &pod_name);
311            debug!(node = %node_name, pod = %pod_name, "creating node-pinned daemon pod");
312            commands.push(ResourceCommand::Put {
313                key: pod_key,
314                value: pod,
315                expected: None,
316                reason: Reason::Controller,
317            });
318        }
319
320        // Delete owned pods whose node no longer exists / is unschedulable
321        // (node removed → pod GC'd). Owner-ref GC covers DS deletion; this
322        // covers the per-node case.
323        for (pod_key, pod_value) in owned {
324            let on_scheduled_node =
325                Self::pod_node(pod_value).is_some_and(|n| schedulable.contains(n));
326            if !on_scheduled_node {
327                debug!(pod = %pod_key.label(), "deleting daemon pod on missing/unschedulable node");
328                commands.push(ResourceCommand::delete(pod_key.clone(), Reason::Controller));
329                deleting.insert(pod_key);
330            }
331        }
332
333        // ── ★ A FAILED DAEMON POD IS REPLACED (see `failed_deletions`) ──────
334        let ds_uid = ds_value.uid().unwrap_or(ds_name);
335        for key in self.failed_deletions(ds_name, ds_uid, owned, &deleting) {
336            commands.push(ResourceCommand::delete(key.clone(), Reason::Controller));
337            deleting.insert(key);
338        }
339
340        // ── ★ ROLLING UPDATE ───────────────────────────────────────────────
341        if let (
342            Some(rev),
343            UpdateStrategy::RollingUpdate {
344                max_unavailable, ..
345            },
346        ) = (&revision, strategy)
347        {
348            let budget = max_unavailable.resolve(schedulable.len());
349            for (pod_key, pod_value) in
350                rolling_deletions(rev, budget, &schedulable, owned, &deleting)
351            {
352                info!(
353                    daemonset = %ds_name,
354                    pod = %pod_key.label(),
355                    node = Self::pod_node(pod_value).unwrap_or_default(),
356                    from = TemplateRevision::of_pod(pod_value).unwrap_or("<none>"),
357                    to = rev.as_str(),
358                    max_unavailable = budget,
359                    "rolling update: replacing out-of-date daemon pod"
360                );
361                commands.push(ResourceCommand::delete(pod_key.clone(), Reason::Controller));
362            }
363        }
364
365        Ok(ReconcileDelta::from_commands(commands))
366    }
367
368    fn compute_status(
369        &self,
370        ds_value: &Value,
371        owned_now: &[(ResourceKey, Value)],
372        observed_generation: i64,
373    ) -> Option<Value> {
374        // Status from the LIVE owned pods AFTER the reconcile.
375        //   desiredNumberScheduled = # schedulable nodes is NOT re-derived
376        //     here (the blanket re-lists owned children, not nodes); we
377        //     report the OWNED-pod-derived counts, which after a converged
378        //     tick equal the desired set. `desiredNumberScheduled` ==
379        //     `currentNumberScheduled` == owned pod count (one per node);
380        //     `numberReady` counts Ready=True owned pods;
381        //     `updatedNumberScheduled` counts the pods built from the
382        //     CURRENT template revision — the number `kubectl rollout status`
383        //     waits on.
384        let scheduled = i64::try_from(owned_now.len()).unwrap_or(i64::MAX);
385        let ready = i64::try_from(owned_now.iter().filter(|(_, p)| pod_is_ready(p)).count())
386            .unwrap_or(i64::MAX);
387        let updated = TemplateRevision::of(ds_value).map_or(scheduled, |rev| {
388            i64::try_from(owned_now.iter().filter(|(_, p)| rev.is_current(p)).count())
389                .unwrap_or(i64::MAX)
390        });
391        Some(json!({
392            "desiredNumberScheduled": scheduled,
393            "currentNumberScheduled": scheduled,
394            "numberReady": ready,
395            "numberAvailable": ready,
396            "numberUnavailable": scheduled - ready,
397            "updatedNumberScheduled": updated,
398            "observedGeneration": observed_generation,
399        }))
400    }
401}
402
403/// The out-of-date pods a `RollingUpdate` deletes this pass — upstream's
404/// `DaemonSetsController.rollingUpdate`, with the budget counted per
405/// schedulable node:
406///
407/// * a node whose pod is missing, Terminating or already being deleted is
408///   UNAVAILABLE. Upstream does not count a node with no pod, because it
409///   names the replacement by hash and creates it at once; engenho's
410///   replacement takes the same name and waits for the old pod to go, so the
411///   gap between delete and create is real downtime and is charged;
412/// * a node whose pod is current and not Ready is unavailable;
413/// * an out-of-date pod that is not Ready is deleted WHATEVER the budget —
414///   it serves nothing, so replacing it costs nothing. This is the arm that
415///   frees a node whose pod can never start (its image is gone);
416/// * an out-of-date Ready pod is deleted only while the budget has room.
417///
418/// Candidates are taken in node order, so the choice is deterministic.
419fn rolling_deletions<'o>(
420    rev: &TemplateRevision,
421    budget: usize,
422    schedulable: &std::collections::BTreeSet<String>,
423    owned: &'o [(ResourceKey, Value)],
424    deleting: &std::collections::BTreeSet<&ResourceKey>,
425) -> Vec<&'o (ResourceKey, Value)> {
426    let mut unavailable = 0usize;
427    let mut replace_now = Vec::new();
428    let mut candidates = Vec::new();
429    for node in schedulable {
430        let on_node: Vec<&(ResourceKey, Value)> = owned
431            .iter()
432            .filter(|(_, p)| DaemonSetController::pod_node(p) == Some(node.as_str()))
433            .collect();
434        let live: Vec<&(ResourceKey, Value)> = on_node
435            .iter()
436            .copied()
437            .filter(|(k, p)| !p.is_terminating() && !deleting.contains(k) && !pod_is_failed(p))
438            .collect();
439        let [pod] = live.as_slice() else {
440            // No live pod (missing, Terminating, Failed or being deleted), or
441            // more than one: the node is not serving a current pod.
442            unavailable += 1;
443            continue;
444        };
445        let (_, value) = pod;
446        match (rev.is_current(value), pod_is_ready(value)) {
447            (true, true) => {}
448            (true, false) => unavailable += 1,
449            (false, false) => replace_now.push(*pod),
450            (false, true) => candidates.push(*pod),
451        }
452    }
453    let room = budget.saturating_sub(unavailable + replace_now.len());
454    replace_now.extend(candidates.into_iter().take(room));
455    replace_now
456}
457
458/// Per-node backoff before a failed daemon pod is deleted again: upstream's
459/// `failedPodsBackoff` (1 s doubling to 15 min), keyed by `DaemonSet` uid and
460/// node. The first failure on a node is replaced at once; a node whose pod
461/// comes up Ready is forgiven.
462#[derive(Debug, Default)]
463struct FailedPodBackoff {
464    entries: std::sync::Mutex<std::collections::BTreeMap<(String, String), (u32, u64)>>,
465}
466
467impl FailedPodBackoff {
468    const INITIAL_MS: u64 = 1_000;
469    const MAX_MS: u64 = 15 * 60 * 1_000;
470
471    /// Whether a failed pod on `node` may be deleted at `now_ms`; records the
472    /// deletion when it may.
473    fn admit(&self, ds_uid: &str, node: &str, now_ms: u64) -> bool {
474        let Ok(mut entries) = self.entries.lock() else {
475            return true;
476        };
477        let key = (ds_uid.to_string(), node.to_string());
478        let admit = entries.get(&key).is_none_or(|&(n, last)| {
479            let wait = Self::INITIAL_MS
480                .saturating_mul(1u64 << (n.saturating_sub(1)).min(20))
481                .min(Self::MAX_MS);
482            now_ms.saturating_sub(last) >= wait
483        });
484        if admit {
485            let n = entries.get(&key).map_or(0, |&(n, _)| n);
486            entries.insert(key, (n.saturating_add(1), now_ms));
487        }
488        admit
489    }
490
491    fn clear(&self, ds_uid: &str, node: &str) {
492        if let Ok(mut entries) = self.entries.lock() {
493            entries.remove(&(ds_uid.to_string(), node.to_string()));
494        }
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use crate::controller::Controller; // brings `.tick()` (blanket via OwnedChildrenReconciler) into scope
502    use engenho_store::command::Reason;
503    use engenho_store::{InProcessRouter, default_config};
504    use serde_json::json;
505    use std::time::Duration;
506
507    async fn test_store() -> Arc<StoreMesh> {
508        let router = InProcessRouter::new();
509        let cfg = default_config("controllers-daemonset").unwrap();
510        let store = Arc::new(
511            StoreMesh::start(1, "in-process://1".into(), router, cfg)
512                .await
513                .unwrap(),
514        );
515        store.initialize_singleton().await.unwrap();
516        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
517        store
518    }
519
520    /// Seed a schedulable Node into the store.
521    async fn seed_node(store: &StoreMesh, name: &str, schedulable: bool) {
522        let key = ResourceKey::cluster_scoped("", "v1", "Node", name);
523        store
524            .propose(ResourceCommand::put(
525                key,
526                json!({
527                    "kind": "Node", "apiVersion": "v1",
528                    "metadata": {"name": name},
529                    "spec": {"unschedulable": !schedulable}
530                }),
531                Reason::Operator,
532            ))
533            .await
534            .unwrap();
535    }
536
537    /// Seed a `DaemonSet` into the store (so it gets a uid the controller
538    /// can owner-ref against).
539    async fn seed_ds(store: &StoreMesh, ns: &str, name: &str) -> String {
540        let key = ResourceKey::namespaced("apps", "v1", "DaemonSet", ns, name);
541        store
542            .propose(ResourceCommand::put(
543                key.clone(),
544                json!({
545                    "kind": "DaemonSet", "apiVersion": "apps/v1",
546                    "metadata": {"name": name, "namespace": ns},
547                    "spec": {"template": {
548                        "metadata": {"labels": {"app": name}},
549                        "spec": {"containers": [{"name": "c", "image": "img"}]}
550                    }}
551                }),
552                Reason::Operator,
553            ))
554            .await
555            .unwrap();
556        store.get(&key).await.unwrap().uid().unwrap().to_string()
557    }
558
559    fn ds_owner() -> OwnerReference {
560        OwnerReference {
561            api_version: "apps/v1".into(),
562            kind: "DaemonSet".into(),
563            name: "ds".into(),
564            uid: "uid-ds".into(),
565            controller: true,
566            block_owner_deletion: true,
567        }
568    }
569
570    // ── unit: pure helpers ────────────────────────────────────────────
571
572    #[test]
573    fn node_is_schedulable_default_and_cordon() {
574        assert!(DaemonSetController::node_is_schedulable(
575            &json!({"spec": {}})
576        ));
577        assert!(DaemonSetController::node_is_schedulable(&json!({})));
578        assert!(DaemonSetController::node_is_schedulable(
579            &json!({"spec": {"unschedulable": false}})
580        ));
581        assert!(!DaemonSetController::node_is_schedulable(
582            &json!({"spec": {"unschedulable": true}})
583        ));
584    }
585
586    #[test]
587    fn build_pod_for_node_pins_node_and_inherits_namespace() {
588        let ds = json!({
589            "metadata": {"name": "vector", "namespace": "observability"},
590            "spec": {"template": {
591                "metadata": {"labels": {"app": "vector"}},
592                "spec": {"containers": [{"name": "c", "image": "img"}]}
593            }}
594        });
595        let (name, pod) = DaemonSetController::build_pod_for_node(&ds, "node-A", ds_owner())
596            .unwrap()
597            .unwrap();
598        assert_eq!(name, "vector-node-A");
599        assert_eq!(
600            pod["status"]["phase"], "Pending",
601            "a controller-built pod is born with status: {pod}"
602        );
603        assert_eq!(pod.get("kind").unwrap(), "Pod");
604        // Namespace inherited from the parent DS — NOT "default".
605        assert_eq!(
606            pod.get("metadata").unwrap().get("namespace").unwrap(),
607            "observability"
608        );
609        // Node-pinned: spec.nodeName pre-set (scheduler bypassed).
610        assert_eq!(pod.get("spec").unwrap().get("nodeName").unwrap(), "node-A");
611        // Template labels survive.
612        assert_eq!(
613            pod.get("metadata")
614                .unwrap()
615                .get("labels")
616                .unwrap()
617                .get("app")
618                .unwrap(),
619            "vector"
620        );
621    }
622
623    #[test]
624    fn build_pod_for_node_defaults_namespace_when_parent_has_none() {
625        let ds = json!({
626            "metadata": {"name": "ds"},
627            "spec": {"template": {"spec": {"containers": []}}}
628        });
629        let (_, pod) = DaemonSetController::build_pod_for_node(&ds, "n1", ds_owner())
630            .unwrap()
631            .unwrap();
632        assert_eq!(
633            pod.get("metadata").unwrap().get("namespace").unwrap(),
634            "default"
635        );
636    }
637
638    // ── integration over the store ────────────────────────────────────
639
640    #[tokio::test]
641    async fn one_pod_per_schedulable_node_namespace_inherited() {
642        let store = test_store().await;
643        seed_node(&store, "node-A", true).await;
644        seed_node(&store, "node-B", true).await;
645        seed_node(&store, "node-C", false).await; // cordoned → no pod
646        let uid = seed_ds(&store, "observability", "vector").await;
647
648        let c = DaemonSetController::new(store.clone(), None);
649        c.tick().await.unwrap();
650
651        // Exactly 2 pods (one per schedulable node), both in the DS namespace,
652        // both node-pinned + owned by the DS.
653        let pods = store.list("", "v1", "Pod", Some("observability")).await;
654        let owned: Vec<_> = pods
655            .iter()
656            .filter(|(_, p)| crate::owner::is_owned_by(p, &uid))
657            .collect();
658        assert_eq!(owned.len(), 2, "one pod per schedulable node (C cordoned)");
659
660        for (key, pod) in &owned {
661            assert_eq!(key.namespace.as_deref(), Some("observability"));
662            let node = DaemonSetController::pod_node(pod).unwrap();
663            assert!(
664                node == "node-A" || node == "node-B",
665                "pinned to a schedulable node"
666            );
667        }
668        // No pod on the cordoned node-C.
669        assert!(
670            !owned
671                .iter()
672                .any(|(_, p)| DaemonSetController::pod_node(p) == Some("node-C")),
673            "cordoned node must get no daemon pod"
674        );
675    }
676
677    #[tokio::test]
678    async fn self_heal_recreates_deleted_pod_on_its_node() {
679        let store = test_store().await;
680        seed_node(&store, "node-A", true).await;
681        let uid = seed_ds(&store, "default", "ds").await;
682
683        let c = DaemonSetController::new(store.clone(), None);
684        c.tick().await.unwrap();
685        let pod_key = ResourceKey::namespaced("", "v1", "Pod", "default", "ds-node-A");
686        assert!(
687            store.get(&pod_key).await.is_some(),
688            "first tick creates the pod"
689        );
690
691        // Operator/chaos deletes the pod.
692        store
693            .propose(ResourceCommand::delete(pod_key.clone(), Reason::Operator))
694            .await
695            .unwrap();
696        assert!(store.get(&pod_key).await.is_none(), "pod gone");
697
698        // Next tick recreates it on node-A.
699        c.tick().await.unwrap();
700        let pod = store.get(&pod_key).await.expect("pod recreated");
701        assert!(crate::owner::is_owned_by(&pod, &uid));
702        assert_eq!(DaemonSetController::pod_node(&pod), Some("node-A"));
703    }
704
705    #[tokio::test]
706    async fn removed_node_gcs_its_pod() {
707        let store = test_store().await;
708        seed_node(&store, "node-A", true).await;
709        seed_node(&store, "node-B", true).await;
710        let _uid = seed_ds(&store, "default", "ds").await;
711
712        let c = DaemonSetController::new(store.clone(), None);
713        c.tick().await.unwrap();
714        assert!(
715            store
716                .get(&ResourceKey::namespaced(
717                    "",
718                    "v1",
719                    "Pod",
720                    "default",
721                    "ds-node-B"
722                ))
723                .await
724                .is_some()
725        );
726
727        // node-B disappears (drained / removed from the cluster).
728        store
729            .propose(ResourceCommand::delete(
730                ResourceKey::cluster_scoped("", "v1", "Node", "node-B"),
731                Reason::Operator,
732            ))
733            .await
734            .unwrap();
735
736        // Next tick deletes the orphaned pod on node-B (node A's stays).
737        c.tick().await.unwrap();
738        assert!(
739            store
740                .get(&ResourceKey::namespaced(
741                    "",
742                    "v1",
743                    "Pod",
744                    "default",
745                    "ds-node-B"
746                ))
747                .await
748                .is_none(),
749            "pod on removed node must be GC'd"
750        );
751        assert!(
752            store
753                .get(&ResourceKey::namespaced(
754                    "",
755                    "v1",
756                    "Pod",
757                    "default",
758                    "ds-node-A"
759                ))
760                .await
761                .is_some(),
762            "pod on surviving node stays"
763        );
764    }
765
766    #[tokio::test]
767    async fn no_thrash_stable_across_ticks() {
768        let store = test_store().await;
769        seed_node(&store, "node-A", true).await;
770        seed_node(&store, "node-B", true).await;
771        let _uid = seed_ds(&store, "default", "ds").await;
772
773        let c = DaemonSetController::new(store.clone(), None);
774        c.tick().await.unwrap();
775        let rev_a = store.current_revision().await;
776        // Several idle ticks: at the fixpoint nothing is proposed.
777        for _ in 0..3 {
778            c.tick().await.unwrap();
779        }
780        let rev_b = store.current_revision().await;
781        assert_eq!(rev_a, rev_b, "converged DaemonSet must not thrash");
782    }
783
784    #[tokio::test]
785    async fn status_counts_scheduled_pods() {
786        let store = test_store().await;
787        seed_node(&store, "node-A", true).await;
788        seed_node(&store, "node-B", true).await;
789        seed_ds(&store, "default", "ds").await;
790
791        let c = DaemonSetController::new(store.clone(), None);
792        c.tick().await.unwrap();
793
794        let ds = store
795            .get(&ResourceKey::namespaced(
796                "apps",
797                "v1",
798                "DaemonSet",
799                "default",
800                "ds",
801            ))
802            .await
803            .unwrap();
804        let status = ds.get("status").expect("status written");
805        assert_eq!(status.get("desiredNumberScheduled").unwrap(), 2);
806        assert_eq!(status.get("currentNumberScheduled").unwrap(), 2);
807        // Pods aren't Ready (no kubelet in this test) → numberReady == 0.
808        assert_eq!(status.get("numberReady").unwrap(), 0);
809    }
810}