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    res(
128        "coordination.k8s.io",
129        "v1",
130        "leases",
131        "lease",
132        "Lease",
133        true,
134    ),
135    ResDef {
136        verbs: &["create"],
137        stored: false,
138        ..res(
139            "authorization.k8s.io",
140            "v1",
141            "selfsubjectaccessreviews",
142            "selfsubjectaccessreview",
143            "SelfSubjectAccessReview",
144            false,
145        )
146    },
147    ResDef {
148        verbs: &["get", "list"],
149        stored: false,
150        ..res(
151            "metrics.k8s.io",
152            "v1beta1",
153            "nodes",
154            "",
155            "NodeMetrics",
156            false,
157        )
158    },
159    ResDef {
160        verbs: &["get", "list"],
161        stored: false,
162        ..res("metrics.k8s.io", "v1beta1", "pods", "", "PodMetrics", true)
163    },
164];
165
166impl ResDef {
167    pub fn api_version(&self) -> String {
168        if self.group.is_empty() {
169            self.version.to_string()
170        } else {
171            format!("{}/{}", self.group, self.version)
172        }
173    }
174
175    pub fn can(&self, verb: &str) -> bool {
176        self.verbs.contains(&verb)
177    }
178
179    pub fn has_sub(&self, sub: &str) -> bool {
180        self.subresources.contains(&sub)
181    }
182
183    pub fn qualified(&self) -> String {
184        if self.group.is_empty() {
185            self.plural.to_string()
186        } else {
187            format!("{}.{}", self.plural, self.group)
188        }
189    }
190
191    pub fn prefix(&self, ns: Option<&str>) -> String {
192        match ns {
193            Some(ns) if self.namespaced => format!("{}/{ns}/", self.plural),
194            _ => format!("{}/", self.plural),
195        }
196    }
197
198    pub fn key(&self, ns: Option<&str>, name: &str) -> String {
199        format!("{}{name}", self.prefix(ns))
200    }
201
202    pub fn sub_kind(&self, sub: &str) -> (&'static str, &'static str, &'static str) {
203        match sub {
204            "scale" => ("autoscaling", "v1", "Scale"),
205            _ => (self.group, self.version, self.kind),
206        }
207    }
208
209    pub fn sub_verbs(&self, sub: &str) -> &'static [&'static str] {
210        match sub {
211            "log" => &["get"],
212            "finalize" => &["update"],
213            "attach" => &["get"],
214            "exec" | "portforward" => &["create", "get"],
215            _ => &["get", "patch", "update"],
216        }
217    }
218}
219
220pub fn find(group: &str, version: &str, plural: &str) -> Option<&'static ResDef> {
221    RESOURCES
222        .iter()
223        .find(|r| r.group == group && r.version == version && r.plural == plural)
224}
225
226pub fn group_versions() -> Vec<(&'static str, &'static str)> {
227    let mut out: Vec<(&str, &str)> = Vec::new();
228    for r in RESOURCES {
229        if !r.group.is_empty() && !out.contains(&(r.group, r.version)) {
230            out.push((r.group, r.version));
231        }
232    }
233    out
234}
235
236pub fn in_group(group: &str, version: &str) -> impl Iterator<Item = &'static ResDef> {
237    let (g, v) = (group.to_string(), version.to_string());
238    RESOURCES
239        .iter()
240        .filter(move |r| r.group == g && r.version == v)
241}
242
243pub fn namespaced_stored() -> impl Iterator<Item = &'static ResDef> {
244    RESOURCES.iter().filter(|r| r.stored && r.namespaced)
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn keys_and_lookup() {
253        let d = find("apps", "v1", "deployments").unwrap();
254        assert_eq!(d.key(Some("t1"), "web"), "deployments/t1/web");
255        assert_eq!(d.qualified(), "deployments.apps");
256        let n = find("", "v1", "namespaces").unwrap();
257        assert_eq!(n.key(Some("x"), "t1"), "namespaces/t1");
258        assert!(!find("", "v1", "nodes").unwrap().can("create"));
259        assert_eq!(group_versions()[0], ("apps", "v1"));
260    }
261}