engenho_controllers/csi_provisioner.rs
1//! The CSI provisioning seam — dynamic `CreateVolume` from a `StorageClass`.
2//!
3//! ★ WHY A NARROW TRAIT HERE RATHER THAN A DEPENDENCY ON `engenho-csi`.
4//! `engenho-kubelet` depends on `engenho-controllers`, so the arrow cannot
5//! be reversed. The same shape `EventStore` already takes in this crate:
6//! the controller declares the *verbs it needs*, and the crate that owns
7//! the transport supplies them. It also keeps every protobuf type out of
8//! the binder, so the binder's tests stay pure JSON.
9//!
10//! ★ WHY THIS IS NOT `VolumeRuntime`, WHICH ALREADY EXISTS AND LOOKS RIGHT.
11//! Measured, not assumed. `VolumeRuntime::mount(&VolumeSpec) ->
12//! MountedVolume` has provisioning-shaped INPUTS (storage class, size,
13//! access mode, parameters — very nearly a `CreateVolumeRequest`) and
14//! mounting-shaped OUTPUTS (`mount_path`, a host directory). CSI's
15//! `CreateVolume` returns a volume ID and no path, because at provision
16//! time no node has mounted anything and there IS no path.
17//!
18//! That is the org rule's "same goal, different shapes" case: forcing them
19//! into one type would make a bad abstraction that looks well-motivated,
20//! and every caller would then carry a `mount_path` that is empty exactly
21//! when it matters. So the rule is written down instead —
22//! [`crate::csi_provisioner`] owns provisioning, the kubelet's
23//! `CsiVolumeMaterializer` owns the node path, and `VolumeRuntime` is
24//! superseded by both. Per ★★ MODULARIZE, DON'T DELETE the declaration
25//! stays; its header carries the note.
26
27use async_trait::async_trait;
28use std::collections::BTreeMap;
29
30/// What the binder asks a driver to create.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct CsiCreateRequest {
33 /// The driver to call (`StorageClass.provisioner`).
34 pub driver: String,
35 /// The volume NAME the driver should key idempotency on.
36 ///
37 /// ★ THIS IS WHY RETRIES DO NOT LEAK DISKS. `CreateVolume` is specified
38 /// as idempotent on `name`: calling it twice with the same name and
39 /// compatible capacity returns the SAME volume. A random name per
40 /// attempt would provision a new EBS volume on every reconcile after a
41 /// transient failure, and nothing would ever delete the orphans.
42 pub name: String,
43 /// Requested bytes; 0 means the claim named no size.
44 pub capacity_bytes: i64,
45 /// `StorageClass.parameters`, passed through verbatim.
46 pub parameters: BTreeMap<String, String>,
47 /// Whether the claim wants multi-node write access.
48 pub multi_node: bool,
49}
50
51/// What the driver created.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct CsiCreatedVolume {
54 /// The driver's id for the volume. Becomes `PV.spec.csi.volumeHandle`.
55 pub volume_handle: String,
56 /// Actual capacity, which may EXCEED the request (a driver rounds up to
57 /// its allocation unit). Recorded as the PV's capacity so a later
58 /// binding check compares against what exists, not what was asked for.
59 pub capacity_bytes: i64,
60 /// The opaque bag the driver wants handed back at publish time.
61 pub volume_attributes: BTreeMap<String, String>,
62}
63
64/// The provisioning verbs the binder needs.
65#[async_trait]
66pub trait CsiProvisioner: Send + Sync {
67 /// Whether a driver by this name is registered and can provision.
68 ///
69 /// Asked BEFORE `create_volume` so the binder can leave a PVC Pending
70 /// with an honest reason instead of turning an absent driver into a
71 /// failed provision — the first is "waiting for your driver", the
72 /// second reads as "your storage is broken".
73 async fn can_provision(&self, driver: &str) -> bool;
74
75 /// `Controller.CreateVolume`.
76 ///
77 /// # Errors
78 /// A human-readable reason; the binder surfaces it and retries.
79 async fn create_volume(&self, req: &CsiCreateRequest) -> Result<CsiCreatedVolume, String>;
80
81 /// `Controller.DeleteVolume`.
82 ///
83 /// # Errors
84 /// A human-readable reason.
85 async fn delete_volume(&self, driver: &str, volume_handle: &str) -> Result<(), String>;
86}
87
88/// A provisioner that serves nothing.
89///
90/// The honest default for a binder with no CSI plane wired: every CSI
91/// `StorageClass` stays Pending, which is exactly what happens today and
92/// what an external provisioner would eventually handle.
93#[derive(Debug, Default, Clone, Copy)]
94pub struct NoCsiProvisioner;
95
96#[async_trait]
97impl CsiProvisioner for NoCsiProvisioner {
98 async fn can_provision(&self, _driver: &str) -> bool {
99 false
100 }
101
102 async fn create_volume(&self, req: &CsiCreateRequest) -> Result<CsiCreatedVolume, String> {
103 Err(format!(
104 "no CSI plane is wired on this node: cannot provision through driver {}",
105 req.driver
106 ))
107 }
108
109 async fn delete_volume(&self, driver: &str, _handle: &str) -> Result<(), String> {
110 Err(format!(
111 "no CSI plane is wired: cannot delete through {driver}"
112 ))
113 }
114}
115
116/// Parse a Kubernetes quantity string (`"1Gi"`, `"500M"`, `"1000"`) to bytes.
117///
118/// ★ THE TWO SUFFIX FAMILIES ARE NOT THE SAME AND THE DIFFERENCE IS REAL
119/// MONEY. `Gi` is 2^30 and `G` is 10^9 — a 7.4% gap. Treating `G` as `Gi`
120/// under-provisions every volume by that margin, and the failure surfaces
121/// as a disk full at 93% with a monitoring system that says there is room.
122///
123/// Returns `None` for anything unparseable rather than a guess: a wrong
124/// size silently provisions the wrong disk.
125#[must_use]
126pub fn parse_quantity(q: &str) -> Option<i64> {
127 let q = q.trim();
128 if q.is_empty() {
129 return None;
130 }
131 // Longest suffix first: "Ki" must not match "K".
132 const SUFFIXES: &[(&str, i64)] = &[
133 ("Ki", 1024),
134 ("Mi", 1024 * 1024),
135 ("Gi", 1024 * 1024 * 1024),
136 ("Ti", 1024_i64.pow(4)),
137 ("Pi", 1024_i64.pow(5)),
138 ("Ei", 1024_i64.pow(6)),
139 ("k", 1_000),
140 ("K", 1_000),
141 ("M", 1_000_000),
142 ("G", 1_000_000_000),
143 ("T", 1_000_000_000_000),
144 ("P", 1_000_000_000_000_000),
145 ("E", 1_000_000_000_000_000_000),
146 ];
147 for (suffix, mult) in SUFFIXES {
148 if let Some(head) = q.strip_suffix(suffix) {
149 let n: i64 = head.trim().parse().ok()?;
150 return n.checked_mul(*mult);
151 }
152 }
153 q.parse().ok()
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159
160 #[test]
161 fn binary_and_decimal_suffixes_are_not_confused() {
162 // The 7.4% gap that presents as a disk full at 93% while monitoring
163 // says there is room.
164 assert_eq!(parse_quantity("1Gi"), Some(1_073_741_824));
165 assert_eq!(parse_quantity("1G"), Some(1_000_000_000));
166 assert_ne!(parse_quantity("1Gi"), parse_quantity("1G"));
167 }
168
169 #[test]
170 fn the_longest_suffix_wins_so_ki_is_not_read_as_k() {
171 assert_eq!(parse_quantity("1Ki"), Some(1024));
172 assert_eq!(parse_quantity("1k"), Some(1_000));
173 assert_eq!(parse_quantity("1K"), Some(1_000));
174 }
175
176 #[test]
177 fn a_bare_number_is_bytes() {
178 assert_eq!(parse_quantity("1000"), Some(1000));
179 assert_eq!(parse_quantity(" 2048 "), Some(2048));
180 }
181
182 #[test]
183 fn an_unparseable_quantity_is_none_never_a_guess() {
184 // A guessed size silently provisions the wrong disk.
185 for bad in ["", " ", "abc", "1.5Gi", "Gi", "-", "1Gib", "9999999999Ei"] {
186 assert_eq!(parse_quantity(bad), None, "{bad:?}");
187 }
188 }
189
190 #[tokio::test]
191 async fn the_default_provisioner_refuses_by_name() {
192 let p = NoCsiProvisioner;
193 assert!(!p.can_provision("ebs.csi.aws.com").await);
194 let e = p
195 .create_volume(&CsiCreateRequest {
196 driver: "ebs.csi.aws.com".into(),
197 name: "pvc-1".into(),
198 capacity_bytes: 1,
199 parameters: BTreeMap::new(),
200 multi_node: false,
201 })
202 .await
203 .unwrap_err();
204 assert!(e.contains("ebs.csi.aws.com"), "{e}");
205 }
206}