Skip to main content

krab_api/
registry.rs

1pub struct ResDef {
2    pub group: &'static str,
3    pub version: &'static str,
4    pub plural: &'static str,
5    pub singular: &'static str,
6    pub kind: &'static str,
7    pub namespaced: bool,
8    pub verbs: &'static [&'static str],
9    pub short: &'static [&'static str],
10    pub categories: &'static [&'static str],
11    pub subresources: &'static [&'static str],
12    pub stored: bool,
13}
14
15const RW: &[&str] = &[
16    "create",
17    "delete",
18    "deletecollection",
19    "get",
20    "list",
21    "patch",
22    "update",
23    "watch",
24];
25const RO: &[&str] = &["get", "list", "watch"];
26const ALL: &[&str] = &["all"];
27
28const fn res(
29    group: &'static str,
30    version: &'static str,
31    plural: &'static str,
32    singular: &'static str,
33    kind: &'static str,
34    namespaced: bool,
35) -> ResDef {
36    ResDef {
37        group,
38        version,
39        plural,
40        singular,
41        kind,
42        namespaced,
43        verbs: RW,
44        short: &[],
45        categories: &[],
46        subresources: &[],
47        stored: true,
48    }
49}
50
51pub static RESOURCES: &[ResDef] = &[
52    ResDef {
53        short: &["ns"],
54        subresources: &["status", "finalize"],
55        verbs: &[
56            "create", "delete", "get", "list", "patch", "update", "watch",
57        ],
58        ..res("", "v1", "namespaces", "namespace", "Namespace", false)
59    },
60    ResDef {
61        short: &["no"],
62        verbs: RO,
63        ..res("", "v1", "nodes", "node", "Node", false)
64    },
65    ResDef {
66        short: &["po"],
67        categories: ALL,
68        subresources: &["status", "log", "exec", "attach", "portforward"],
69        ..res("", "v1", "pods", "pod", "Pod", true)
70    },
71    ResDef {
72        short: &["svc"],
73        categories: ALL,
74        subresources: &["status"],
75        ..res("", "v1", "services", "service", "Service", true)
76    },
77    ResDef {
78        short: &["ep"],
79        ..res("", "v1", "endpoints", "endpoints", "Endpoints", true)
80    },
81    ResDef {
82        short: &["cm"],
83        ..res("", "v1", "configmaps", "configmap", "ConfigMap", true)
84    },
85    res("", "v1", "secrets", "secret", "Secret", true),
86    ResDef {
87        short: &["sa"],
88        ..res(
89            "",
90            "v1",
91            "serviceaccounts",
92            "serviceaccount",
93            "ServiceAccount",
94            true,
95        )
96    },
97    ResDef {
98        short: &["ev"],
99        ..res("", "v1", "events", "event", "Event", true)
100    },
101    ResDef {
102        short: &["deploy"],
103        categories: ALL,
104        subresources: &["status", "scale"],
105        ..res(
106            "apps",
107            "v1",
108            "deployments",
109            "deployment",
110            "Deployment",
111            true,
112        )
113    },
114    ResDef {
115        short: &["rs"],
116        categories: ALL,
117        subresources: &["status", "scale"],
118        ..res(
119            "apps",
120            "v1",
121            "replicasets",
122            "replicaset",
123            "ReplicaSet",
124            true,
125        )
126    },
127    ResDef {
128        short: &["pvc"],
129        subresources: &["status"],
130        ..res(
131            "",
132            "v1",
133            "persistentvolumeclaims",
134            "persistentvolumeclaim",
135            "PersistentVolumeClaim",
136            true,
137        )
138    },
139    ResDef {
140        short: &["pv"],
141        subresources: &["status"],
142        ..res(
143            "",
144            "v1",
145            "persistentvolumes",
146            "persistentvolume",
147            "PersistentVolume",
148            false,
149        )
150    },
151    ResDef {
152        short: &["sc"],
153        ..res(
154            "storage.k8s.io",
155            "v1",
156            "storageclasses",
157            "storageclass",
158            "StorageClass",
159            false,
160        )
161    },
162    res(
163        "coordination.k8s.io",
164        "v1",
165        "leases",
166        "lease",
167        "Lease",
168        true,
169    ),
170    ResDef {
171        verbs: &["create"],
172        stored: false,
173        ..res(
174            "authorization.k8s.io",
175            "v1",
176            "selfsubjectaccessreviews",
177            "selfsubjectaccessreview",
178            "SelfSubjectAccessReview",
179            false,
180        )
181    },
182    ResDef {
183        verbs: &["get", "list"],
184        stored: false,
185        ..res(
186            "metrics.k8s.io",
187            "v1beta1",
188            "nodes",
189            "",
190            "NodeMetrics",
191            false,
192        )
193    },
194    ResDef {
195        verbs: &["get", "list"],
196        stored: false,
197        ..res("metrics.k8s.io", "v1beta1", "pods", "", "PodMetrics", true)
198    },
199];
200
201impl ResDef {
202    pub fn api_version(&self) -> String {
203        if self.group.is_empty() {
204            self.version.to_string()
205        } else {
206            format!("{}/{}", self.group, self.version)
207        }
208    }
209
210    pub fn can(&self, verb: &str) -> bool {
211        self.verbs.contains(&verb)
212    }
213
214    pub fn has_sub(&self, sub: &str) -> bool {
215        self.subresources.contains(&sub)
216    }
217
218    pub fn qualified(&self) -> String {
219        if self.group.is_empty() {
220            self.plural.to_string()
221        } else {
222            format!("{}.{}", self.plural, self.group)
223        }
224    }
225
226    pub fn prefix(&self, ns: Option<&str>) -> String {
227        match ns {
228            Some(ns) if self.namespaced => format!("{}/{ns}/", self.plural),
229            _ => format!("{}/", self.plural),
230        }
231    }
232
233    pub fn key(&self, ns: Option<&str>, name: &str) -> String {
234        format!("{}{name}", self.prefix(ns))
235    }
236
237    pub fn sub_kind(&self, sub: &str) -> (&'static str, &'static str, &'static str) {
238        match sub {
239            "scale" => ("autoscaling", "v1", "Scale"),
240            _ => (self.group, self.version, self.kind),
241        }
242    }
243
244    pub fn sub_verbs(&self, sub: &str) -> &'static [&'static str] {
245        match sub {
246            "log" => &["get"],
247            "finalize" => &["update"],
248            "attach" => &["get"],
249            "exec" | "portforward" => &["create", "get"],
250            _ => &["get", "patch", "update"],
251        }
252    }
253}
254
255pub fn find(group: &str, version: &str, plural: &str) -> Option<&'static ResDef> {
256    RESOURCES
257        .iter()
258        .find(|r| r.group == group && r.version == version && r.plural == plural)
259}
260
261pub fn group_versions() -> Vec<(&'static str, &'static str)> {
262    let mut out: Vec<(&str, &str)> = Vec::new();
263    for r in RESOURCES {
264        if !r.group.is_empty() && !out.contains(&(r.group, r.version)) {
265            out.push((r.group, r.version));
266        }
267    }
268    out
269}
270
271pub fn in_group(group: &str, version: &str) -> impl Iterator<Item = &'static ResDef> {
272    let (g, v) = (group.to_string(), version.to_string());
273    RESOURCES
274        .iter()
275        .filter(move |r| r.group == g && r.version == v)
276}
277
278pub fn namespaced_stored() -> impl Iterator<Item = &'static ResDef> {
279    RESOURCES.iter().filter(|r| r.stored && r.namespaced)
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn keys_and_lookup() {
288        let d = find("apps", "v1", "deployments").unwrap();
289        assert_eq!(d.key(Some("t1"), "web"), "deployments/t1/web");
290        assert_eq!(d.qualified(), "deployments.apps");
291        let n = find("", "v1", "namespaces").unwrap();
292        assert_eq!(n.key(Some("x"), "t1"), "namespaces/t1");
293        assert!(!find("", "v1", "nodes").unwrap().can("create"));
294        assert_eq!(
295            find("", "v1", "persistentvolumeclaims")
296                .unwrap()
297                .key(Some("t1"), "data"),
298            "persistentvolumeclaims/t1/data"
299        );
300        assert_eq!(
301            find("storage.k8s.io", "v1", "storageclasses")
302                .unwrap()
303                .key(Some("t1"), "local-path"),
304            "storageclasses/local-path"
305        );
306        assert_eq!(group_versions()[0], ("apps", "v1"));
307    }
308}