Skip to main content

engenho_controllers/
owner.rs

1//! Owner-reference helpers.
2//!
3//! K8s controllers track parent/child relationships via
4//! `metadata.ownerReferences[].controller=true`. The owner pattern
5//! shows up in: ReplicaSet→Pod, Deployment→ReplicaSet,
6//! Service→Endpoints, etc. — extract once + reuse.
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::meta::{ObjectMeta, ShapeError, array_mut};
12
13/// Where a child's owner references live.
14pub const OWNER_REFERENCES: &[&str] = &["metadata", "ownerReferences"];
15
16/// K8s `OwnerReference` shape.
17#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18pub struct OwnerReference {
19    #[serde(rename = "apiVersion")]
20    pub api_version: String,
21    pub kind: String,
22    pub name: String,
23    pub uid: String,
24    /// True if this owner is the "controller" of the resource —
25    /// only one ownerRef per child can have controller=true.
26    #[serde(default, skip_serializing_if = "is_false")]
27    pub controller: bool,
28    /// True if deletion of the owner should garbage-collect this
29    /// child. Default true for controller-style ownership.
30    #[serde(
31        rename = "blockOwnerDeletion",
32        default,
33        skip_serializing_if = "is_false"
34    )]
35    pub block_owner_deletion: bool,
36}
37
38fn is_false(b: &bool) -> bool {
39    !*b
40}
41
42impl OwnerReference {
43    /// The wire object: the same bytes `serde_json::to_value` produces for
44    /// this type (pinned by `to_value_matches_serde_for_every_flag`), built
45    /// without a fallible serializer so writing a reference cannot fail.
46    #[must_use]
47    pub fn to_value(&self) -> Value {
48        let mut out = Map::new();
49        out.insert("apiVersion".into(), Value::from(self.api_version.as_str()));
50        out.insert("kind".into(), Value::from(self.kind.as_str()));
51        out.insert("name".into(), Value::from(self.name.as_str()));
52        out.insert("uid".into(), Value::from(self.uid.as_str()));
53        if self.controller {
54            out.insert("controller".into(), Value::Bool(true));
55        }
56        if self.block_owner_deletion {
57            out.insert("blockOwnerDeletion".into(), Value::Bool(true));
58        }
59        Value::Object(out)
60    }
61}
62
63/// Write an `ownerReferences` entry into `child`'s metadata,
64/// pointing at `owner`. Idempotent — won't duplicate an existing
65/// reference with the same uid.
66///
67/// Mutates `child` in place. Returns `Ok(true)` if a reference was added,
68/// `Ok(false)` if one with the same uid was already there.
69///
70/// Total over the child's shape (see [`crate::meta::array_mut`]): an absent
71/// or `null` `metadata` or `ownerReferences` is treated as empty.
72///
73/// # Errors
74///
75/// [`ShapeError`] when `child`, its `metadata`, or its `ownerReferences`
76/// holds the wrong JSON type. The child is left unchanged, and the caller
77/// skips that object; it used to panic here, taking every object after it
78/// in the sweep down with it.
79pub fn set_owner_reference(
80    child: &mut Value,
81    owner_ref: OwnerReference,
82) -> Result<bool, ShapeError> {
83    let refs = array_mut(child, OWNER_REFERENCES)?;
84    let already_present = refs
85        .iter()
86        .any(|r| r.get("uid").and_then(Value::as_str) == Some(owner_ref.uid.as_str()));
87    if already_present {
88        return Ok(false);
89    }
90    refs.push(owner_ref.to_value());
91    Ok(true)
92}
93
94/// Read the controlling owner of `child` (the ownerRef with
95/// controller=true) if any. A controller ref with an empty uid names no
96/// object, so it is no owner.
97#[must_use]
98pub fn controlling_owner(child: &Value) -> Option<OwnerReference> {
99    child
100        .get("metadata")
101        .and_then(|m| m.get("ownerReferences"))
102        .and_then(|r| r.as_array())
103        .and_then(|arr| {
104            arr.iter().find_map(|r| {
105                let is_ctrl = r
106                    .get("controller")
107                    .and_then(serde_json::Value::as_bool)
108                    .unwrap_or(false);
109                if is_ctrl {
110                    serde_json::from_value::<OwnerReference>(r.clone())
111                        .ok()
112                        .filter(|o| !o.uid.is_empty())
113                } else {
114                    None
115                }
116            })
117        })
118}
119
120/// Returns true if `child` has `owner_uid` as its controlling owner.
121#[must_use]
122pub fn is_owned_by(child: &Value, owner_uid: &str) -> bool {
123    controlling_owner(child).is_some_and(|o| o.uid == owner_uid)
124}
125
126/// Build a controller-style [`OwnerReference`] pointing at `parent`
127/// for the given `api_version` + `kind`.
128///
129/// `controller` + `block_owner_deletion` are both `true` — the
130/// standard "this object owns + garbage-collects its child" shape
131/// every workload controller (ReplicaSet→Pod, Deployment→ReplicaSet,
132/// StatefulSet→Pod, Job→Pod, Service→Endpoints) uses. Each controller
133/// passes its own `api_version`/`kind` literals.
134///
135/// Returns `None` when `parent` lacks a `metadata.name` or
136/// `metadata.uid` — a freshly minted parent the apiserver has not
137/// finished stamping; the caller then skips this tick rather than
138/// minting a child with a dangling owner ref.
139#[must_use]
140pub fn owner_ref_for(parent: &Value, api_version: &str, kind: &str) -> Option<OwnerReference> {
141    Some(OwnerReference {
142        api_version: api_version.to_string(),
143        kind: kind.to_string(),
144        name: parent.name()?.to_string(),
145        uid: parent.uid()?.to_string(),
146        controller: true,
147        block_owner_deletion: true,
148    })
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use serde_json::json;
155
156    fn rs_owner() -> OwnerReference {
157        OwnerReference {
158            api_version: "apps/v1".into(),
159            kind: "ReplicaSet".into(),
160            name: "podinfo-abc".into(),
161            uid: "uid-rs-1".into(),
162            controller: true,
163            block_owner_deletion: true,
164        }
165    }
166
167    #[test]
168    fn set_owner_reference_adds_new_entry() {
169        let mut pod = json!({"metadata": {"name": "p1"}, "spec": {}});
170        let added = set_owner_reference(&mut pod, rs_owner()).unwrap();
171        assert!(added);
172        let refs = pod
173            .get("metadata")
174            .unwrap()
175            .get("ownerReferences")
176            .unwrap()
177            .as_array()
178            .unwrap();
179        assert_eq!(refs.len(), 1);
180        assert_eq!(refs[0].get("uid").unwrap(), "uid-rs-1");
181        assert_eq!(refs[0].get("controller").unwrap(), true);
182    }
183
184    #[test]
185    fn set_owner_reference_is_idempotent_by_uid() {
186        let mut pod = json!({"metadata": {"name": "p1"}});
187        assert!(set_owner_reference(&mut pod, rs_owner()).unwrap());
188        // Second call returns false (no-op).
189        assert!(!set_owner_reference(&mut pod, rs_owner()).unwrap());
190        let refs = pod
191            .get("metadata")
192            .unwrap()
193            .get("ownerReferences")
194            .unwrap()
195            .as_array()
196            .unwrap();
197        assert_eq!(refs.len(), 1);
198    }
199
200    #[test]
201    fn controlling_owner_returns_ctrl_ref() {
202        let mut pod = json!({"metadata": {"name": "p"}});
203        set_owner_reference(&mut pod, rs_owner()).unwrap();
204        let owner = controlling_owner(&pod).expect("owner");
205        assert_eq!(owner.uid, "uid-rs-1");
206        assert_eq!(owner.kind, "ReplicaSet");
207    }
208
209    #[test]
210    fn controlling_owner_skips_non_controller_refs() {
211        let pod = json!({
212            "metadata": {
213                "ownerReferences": [
214                    {"apiVersion": "v1", "kind": "Pod", "name": "x",
215                     "uid": "u1", "controller": false}
216                ]
217            }
218        });
219        assert!(controlling_owner(&pod).is_none());
220    }
221
222    #[test]
223    fn an_empty_uid_neither_owns_nor_is_owned() {
224        let parent = json!({"metadata": {"name": "web", "uid": ""}});
225        assert!(owner_ref_for(&parent, "apps/v1", "Deployment").is_none());
226        let rs = json!({"metadata": {"name": "web-abc", "ownerReferences": [
227            {"apiVersion": "apps/v1", "kind": "Deployment", "name": "web",
228             "uid": "", "controller": true}
229        ]}});
230        assert!(controlling_owner(&rs).is_none());
231        assert!(!is_owned_by(&rs, ""));
232    }
233
234    #[test]
235    fn is_owned_by_matches_uid() {
236        let mut pod = json!({"metadata": {"name": "p"}});
237        set_owner_reference(&mut pod, rs_owner()).unwrap();
238        assert!(is_owned_by(&pod, "uid-rs-1"));
239        assert!(!is_owned_by(&pod, "uid-other"));
240    }
241
242    #[test]
243    fn owner_ref_for_builds_controller_ref() {
244        let parent = json!({"metadata": {"name": "podinfo-abc", "uid": "uid-rs-1"}});
245        let r = owner_ref_for(&parent, "apps/v1", "ReplicaSet").expect("ref");
246        assert_eq!(r.api_version, "apps/v1");
247        assert_eq!(r.kind, "ReplicaSet");
248        assert_eq!(r.name, "podinfo-abc");
249        assert_eq!(r.uid, "uid-rs-1");
250        assert!(r.controller);
251        assert!(r.block_owner_deletion);
252    }
253
254    #[test]
255    fn owner_ref_for_none_without_name_or_uid() {
256        let no_uid = json!({"metadata": {"name": "x"}});
257        assert!(owner_ref_for(&no_uid, "apps/v1", "ReplicaSet").is_none());
258        let no_name = json!({"metadata": {"uid": "u"}});
259        assert!(owner_ref_for(&no_name, "apps/v1", "ReplicaSet").is_none());
260    }
261
262    /// `null` metadata or ownerReferences is the empty case: the reference
263    /// is written. On HEAD before T4.3 both panicked ("ownerReferences must
264    /// be array" / "metadata must be object").
265    #[test]
266    fn null_metadata_or_owner_references_is_written_not_a_panic() {
267        for mut child in [
268            json!({"metadata": {"name": "p", "ownerReferences": null}}),
269            json!({"metadata": null}),
270            json!({}),
271        ] {
272            assert_eq!(set_owner_reference(&mut child, rs_owner()), Ok(true));
273            assert!(is_owned_by(&child, "uid-rs-1"), "{child}");
274        }
275    }
276
277    /// The wrong type is an error naming the path, and the child is left
278    /// exactly as it was.
279    #[test]
280    fn a_wrong_shape_is_an_error_and_writes_nothing() {
281        for (child, path) in [
282            (
283                json!({"metadata": {"ownerReferences": "x"}}),
284                "metadata.ownerReferences",
285            ),
286            (
287                json!({"metadata": {"ownerReferences": {}}}),
288                "metadata.ownerReferences",
289            ),
290            (json!({"metadata": 3}), "metadata"),
291            (json!("not-an-object"), "the object itself"),
292        ] {
293            let mut written = child.clone();
294            let err = set_owner_reference(&mut written, rs_owner()).unwrap_err();
295            assert!(err.to_string().starts_with(path), "{err}");
296            assert_eq!(written, child, "nothing written on a shape error");
297        }
298    }
299
300    /// The hand-built wire object is byte-identical to serde's, for every
301    /// combination of the two skip-if-false flags.
302    #[test]
303    fn to_value_matches_serde_for_every_flag() {
304        for controller in [false, true] {
305            for block_owner_deletion in [false, true] {
306                let r = OwnerReference {
307                    controller,
308                    block_owner_deletion,
309                    ..rs_owner()
310                };
311                assert_eq!(r.to_value(), serde_json::to_value(&r).unwrap());
312            }
313        }
314    }
315
316    #[test]
317    fn owner_reference_serde_round_trips() {
318        let o = rs_owner();
319        let s = serde_json::to_string(&o).unwrap();
320        let back: OwnerReference = serde_json::from_str(&s).unwrap();
321        assert_eq!(back, o);
322        assert!(s.contains("\"controller\":true"));
323        assert!(s.contains("\"blockOwnerDeletion\":true"));
324    }
325}