engenho_controllers/
cni_status.rs1use 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
47pub const INSTALL_ANNOTATION: &str = "engenho.io/cni-install";
49pub const NETWORK_ANNOTATION: &str = "engenho.io/cni-network";
51pub const CONFIG_ANNOTATION: &str = "engenho.io/cni-config";
53pub const NO_NETWORK: &str = "<none>";
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct CniStatus {
59 pub install: CniInstall,
61 pub network: String,
63 pub config: String,
65}
66
67impl CniStatus {
68 #[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 #[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
107pub struct CniStatusController {
109 store: Arc<StoreMesh>,
110 node_name: String,
111 net_d: PathBuf,
112 install: CniInstall,
113}
114
115impl CniStatusController {
116 #[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 #[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 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
184impl 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 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 assert_eq!(once, s.applied_to(&once));
260 }
261
262 #[test]
263 fn a_planned_verdict_never_satisfies_an_invoked_check() {
264 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 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}