Skip to main content

engenho_controllers/
cni_status.rs

1//! `CniStatusController` — publishing which CNI this node actually has.
2//!
3//! ★ THE PRODUCER, LANDED WITH THE VOCABULARY. `engenho-cni` would
4//! otherwise be instance #9 of "type + backend + no producer" — the exact
5//! pattern this codebase has now hit eight times, where every symbol exists,
6//! every test passes, and nothing calls it. So the contract ships with
7//! something that reads it.
8//!
9//! ★ WHAT IT PUBLISHES, AND WHY EACH FIELD EARNS ITS PLACE.
10//!
11//! * `engenho.io/cni-install` — `Planned` or `Invoked`. Nothing else in the
12//!   cluster distinguishes a computed chain from an executed one: the pod
13//!   gets an IP either way, `kubectl get pod -o wide` shows it either way,
14//!   and Endpoints lists it either way. On darwin the address comes from
15//!   podman rather than from IPAM, and an operator debugging why a pod is
16//!   unreachable from another node needs to know that BEFORE they start
17//!   reading plugin logs that do not exist.
18//! * `engenho.io/cni-network` — the network name from the winning config
19//!   file, or `<none>`. `net.d` is a shared directory where first-lexical
20//!   wins; when a cluster ends up on the wrong CNI it is almost always
21//!   because a file nobody expected sorted first.
22//! * `engenho.io/cni-config` — the file it came from, so the previous line
23//!   is checkable rather than merely assertable.
24//!
25//! ★ SKIPPED FILES ARE LOGGED, NOT PUBLISHED. A half-written config is a
26//! transient state that would otherwise churn the Node object on every
27//! tick; the diagnostic value is in the log, and the annotation stays a
28//! statement about what IS in effect.
29
30use std::path::PathBuf;
31use std::sync::Arc;
32
33use async_trait::async_trait;
34use serde_json::{Value, json};
35
36use engenho_cni::config::load_conflist_dir;
37use engenho_cni::exec::CniInstall;
38use engenho_store::StoreMesh;
39use engenho_store::command::{Reason, ResourceCommand};
40use engenho_store::resource::ResourceKey;
41
42use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
43use crate::effect::Effect;
44use crate::error::ControllerError;
45use crate::reads::{DeclaresReads, Reads, gvk};
46
47/// Whether the plugin chain is executed or only computed.
48pub const INSTALL_ANNOTATION: &str = "engenho.io/cni-install";
49/// The effective network's name.
50pub const NETWORK_ANNOTATION: &str = "engenho.io/cni-network";
51/// The file the effective configuration came from.
52pub const CONFIG_ANNOTATION: &str = "engenho.io/cni-config";
53/// The value used when no configuration is present at all.
54pub const NO_NETWORK: &str = "<none>";
55
56/// The three annotations this controller maintains, computed.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct CniStatus {
59    /// `Planned` or `Invoked`.
60    pub install: CniInstall,
61    /// Network name, or [`NO_NETWORK`].
62    pub network: String,
63    /// Source file, or [`NO_NETWORK`].
64    pub config: String,
65}
66
67impl CniStatus {
68    /// Whether a Node already carries exactly this status.
69    ///
70    /// Idempotency is not cosmetic here: this controller runs on every tick
71    /// and rewriting an unchanged Node would advance the store revision
72    /// forever — the hot-loop class the node lease already hit once.
73    #[must_use]
74    pub fn already_on(&self, node: &Value) -> bool {
75        let ann = |k: &str| {
76            node.get("metadata")
77                .and_then(|m| m.get("annotations"))
78                .and_then(|a| a.get(k))
79                .and_then(Value::as_str)
80        };
81        ann(INSTALL_ANNOTATION) == Some(self.install.as_str())
82            && ann(NETWORK_ANNOTATION) == Some(self.network.as_str())
83            && ann(CONFIG_ANNOTATION) == Some(self.config.as_str())
84    }
85
86    /// The Node with this status applied.
87    #[must_use]
88    pub fn applied_to(&self, node: &Value) -> Value {
89        let mut out = node.clone();
90        let Some(obj) = out.as_object_mut() else {
91            return out;
92        };
93        let meta = obj.entry("metadata").or_insert_with(|| json!({}));
94        let Some(meta) = meta.as_object_mut() else {
95            return out;
96        };
97        let ann = meta.entry("annotations").or_insert_with(|| json!({}));
98        if let Some(ann) = ann.as_object_mut() {
99            ann.insert(INSTALL_ANNOTATION.into(), json!(self.install.as_str()));
100            ann.insert(NETWORK_ANNOTATION.into(), json!(self.network));
101            ann.insert(CONFIG_ANNOTATION.into(), json!(self.config));
102        }
103        out
104    }
105}
106
107/// Reads `net.d` and publishes the verdict onto this node.
108pub struct CniStatusController {
109    store: Arc<StoreMesh>,
110    node_name: String,
111    net_d: PathBuf,
112    install: CniInstall,
113}
114
115impl CniStatusController {
116    /// New controller for `node_name`, reading `net_d`, reporting `install`.
117    ///
118    /// `install` is passed in rather than detected here: which backend the
119    /// runtime chose is an assembly-time decision, and re-deriving it would
120    /// give two places that can disagree about the one fact this controller
121    /// exists to publish.
122    #[must_use]
123    pub fn new(
124        store: Arc<StoreMesh>,
125        node_name: impl Into<String>,
126        net_d: impl Into<PathBuf>,
127        install: CniInstall,
128    ) -> Self {
129        Self {
130            store,
131            node_name: node_name.into(),
132            net_d: net_d.into(),
133            install,
134        }
135    }
136
137    /// The status this node should carry, read from disk.
138    #[must_use]
139    pub fn observe(&self) -> CniStatus {
140        match load_conflist_dir(&self.net_d) {
141            Ok((Some(cfg), skipped)) => {
142                for (path, err) in &skipped {
143                    // Logged, not published: a half-written file is a
144                    // transient state, and annotating it would churn the
145                    // Node every tick.
146                    tracing::warn!(
147                        file = %path.display(),
148                        error = %err,
149                        "skipping unreadable CNI config"
150                    );
151                }
152                CniStatus {
153                    install: self.install,
154                    network: cfg.name.clone(),
155                    config: cfg.source.display().to_string(),
156                }
157            }
158            Ok((None, skipped)) => {
159                for (path, err) in &skipped {
160                    tracing::warn!(
161                        file = %path.display(),
162                        error = %err,
163                        "skipping unreadable CNI config"
164                    );
165                }
166                CniStatus {
167                    install: self.install,
168                    network: NO_NETWORK.to_string(),
169                    config: NO_NETWORK.to_string(),
170                }
171            }
172            Err(e) => {
173                tracing::warn!(dir = %self.net_d.display(), error = %e, "cannot read CNI config dir");
174                CniStatus {
175                    install: self.install,
176                    network: NO_NETWORK.to_string(),
177                    config: NO_NETWORK.to_string(),
178                }
179            }
180        }
181    }
182}
183
184/// This node's Node object, which it publishes the resolved network onto.
185impl DeclaresReads for CniStatusController {
186    fn reads(&self) -> Reads {
187        Reads::of(&[gvk("", "v1", "Node")])
188    }
189}
190
191#[async_trait]
192impl Controller for CniStatusController {
193    fn name(&self) -> &'static str {
194        "cni-status"
195    }
196
197    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
198        let mut report = ReconcileReport::default();
199        let key = ResourceKey::cluster_scoped("", "v1", "Node", &self.node_name);
200        // No Node yet is not an error: the kubelet registers it, and on a
201        // cold start this controller can legitimately run first.
202        let Some(node) = self.store.get(&key).await else {
203            return Ok(ReconcileOutcome::from(report));
204        };
205        report.objects_examined = 1;
206
207        let status = self.observe();
208        if status.already_on(&node) {
209            report.objects_skipped = 1;
210            return Ok(ReconcileOutcome::from(report));
211        }
212
213        match self
214            .store
215            .propose(ResourceCommand::Put {
216                key,
217                value: status.applied_to(&node),
218                expected: None,
219                reason: Reason::Controller,
220            })
221            .await
222        {
223            Ok(applied) => report.record(Effect::of(applied.op)),
224            Err(_) => report.objects_skipped = 1,
225        }
226        Ok(ReconcileOutcome::from(report))
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    fn node() -> Value {
235        json!({ "apiVersion": "v1", "kind": "Node", "metadata": { "name": "n1" } })
236    }
237
238    fn status(install: CniInstall) -> CniStatus {
239        CniStatus {
240            install,
241            network: "cbr0".into(),
242            config: "/etc/cni/net.d/10-cbr0.conflist".into(),
243        }
244    }
245
246    #[test]
247    fn the_verdict_lands_on_the_node_and_is_idempotent() {
248        let s = status(CniInstall::Planned);
249        assert!(!s.already_on(&node()));
250        let once = s.applied_to(&node());
251        assert_eq!(
252            once["metadata"]["annotations"][INSTALL_ANNOTATION],
253            "Planned"
254        );
255        assert_eq!(once["metadata"]["annotations"][NETWORK_ANNOTATION], "cbr0");
256        assert!(s.already_on(&once));
257        // Rewriting an unchanged Node every tick advances the revision
258        // forever — the hot-loop class the node lease already hit.
259        assert_eq!(once, s.applied_to(&once));
260    }
261
262    #[test]
263    fn a_planned_verdict_never_satisfies_an_invoked_check() {
264        // The direction that matters: a node whose plugins did NOT run must
265        // never read as one whose did.
266        let planned = status(CniInstall::Planned).applied_to(&node());
267        assert!(!status(CniInstall::Invoked).already_on(&planned));
268    }
269
270    #[test]
271    fn a_changed_config_file_is_republished() {
272        // net.d is a shared directory and first-lexical wins; when a
273        // cluster ends up on the wrong CNI it is because a file nobody
274        // expected sorted first. So the SOURCE has to be part of the
275        // identity, not just the network name.
276        let a = status(CniInstall::Planned).applied_to(&node());
277        let b = CniStatus {
278            install: CniInstall::Planned,
279            network: "cbr0".into(),
280            config: "/etc/cni/net.d/00-somebody-elses.conf".into(),
281        };
282        assert!(!b.already_on(&a), "a different source file is a change");
283    }
284
285    #[test]
286    fn existing_annotations_survive() {
287        let mut n = node();
288        n["metadata"]["annotations"] = json!({ "keep": "me" });
289        let out = status(CniInstall::Invoked).applied_to(&n);
290        assert_eq!(out["metadata"]["annotations"]["keep"], "me");
291        assert_eq!(
292            out["metadata"]["annotations"][INSTALL_ANNOTATION],
293            "Invoked"
294        );
295    }
296}