1use crate::util::{
2 self, Recorder, controller_kind, controller_uid, created, map_matches, name, now_secs, ns,
3 owner_ref, pod_active, pod_available, pod_ready, s, terminating, uid,
4};
5use krab_store::MemStore;
6use serde_json::{Value, json};
7use std::collections::HashSet;
8use std::sync::Arc;
9use std::time::Duration;
10
11const BURST: i64 = 500;
12
13pub fn sync_all(store: &MemStore, rec: &Recorder) {
14 let pods = util::list(store, "pods/");
15 let rss = util::list(store, "replicasets/");
16 let uids: HashSet<&str> = rss.iter().map(|(_, r)| uid(r)).collect();
17 for (key, pod) in &pods {
18 if controller_kind(pod) == Some("ReplicaSet")
19 && controller_uid(pod).is_some_and(|u| !uids.contains(u))
20 && !terminating(pod)
21 {
22 util::delete_pod(store, key);
23 }
24 }
25 for (key, rs) in &rss {
26 if !terminating(rs) {
27 sync_one(store, rec, key, rs, &pods);
28 }
29 }
30}
31
32fn delete_rank(p: &Value) -> (u8, u8, u8, i64) {
33 let unscheduled = s(p, "/spec/nodeName").is_empty();
34 let phase = match s(p, "/status/phase") {
35 "Pending" | "" => 0,
36 "Unknown" => 1,
37 _ => 2,
38 };
39 (
40 if unscheduled { 0 } else { 1 },
41 phase,
42 if pod_ready(p) { 1 } else { 0 },
43 -created(p),
44 )
45}
46
47pub fn new_pod(owner: &Value, kind: &str, api: &str, template: &Value, pod_name: &str) -> Value {
48 let mut meta = template["metadata"].clone();
49 if !meta.is_object() {
50 meta = json!({});
51 }
52 meta["name"] = json!(pod_name);
53 meta["namespace"] = json!(ns(owner));
54 meta["generateName"] = json!(format!("{}-", name(owner)));
55 meta["ownerReferences"] = json!([owner_ref(api, kind, owner)]);
56 if let Some(m) = meta.as_object_mut() {
57 m.remove("uid");
58 m.remove("resourceVersion");
59 m.remove("creationTimestamp");
60 }
61 let mut spec = template["spec"].clone();
62 if spec["restartPolicy"].is_null() {
63 spec["restartPolicy"] = json!("Always");
64 }
65 json!({"apiVersion": "v1", "kind": "Pod", "metadata": meta, "spec": spec, "status": {"phase": "Pending"}})
66}
67
68fn sync_one(store: &MemStore, rec: &Recorder, key: &str, rs: &Value, pods: &[(String, Value)]) {
69 let namespace = ns(rs);
70 let rs_uid = uid(rs);
71 let want = rs["spec"]["replicas"].as_i64().unwrap_or(1).max(0);
72 let mut active: Vec<(String, Value)> = pods
73 .iter()
74 .filter(|(_, p)| ns(p) == namespace && controller_uid(p) == Some(rs_uid) && pod_active(p))
75 .cloned()
76 .collect();
77 let diff = want - active.len() as i64;
78 if diff > 0 {
79 let template = &rs["spec"]["template"];
80 for _ in 0..diff.min(BURST) {
81 let pname = loop {
82 let n = format!("{}-{}", name(rs), util::rand_suffix(5));
83 if store.get(&format!("pods/{namespace}/{n}")).is_none() {
84 break n;
85 }
86 };
87 let pod = new_pod(rs, "ReplicaSet", "apps/v1", template, &pname);
88 if let Some(p) = util::create(store, &format!("pods/{namespace}/{pname}"), pod) {
89 rec.event(
90 store,
91 rs,
92 "SuccessfulCreate",
93 &format!("Created pod: {pname}"),
94 false,
95 );
96 active.push((format!("pods/{namespace}/{pname}"), p));
97 }
98 }
99 } else if diff < 0 {
100 active.sort_by_key(|(_, p)| delete_rank(p));
101 let victims: Vec<(String, Value)> = active.drain(..(-diff) as usize).collect();
102 for (k, p) in victims {
103 util::delete_pod(store, &k);
104 rec.event(
105 store,
106 rs,
107 "SuccessfulDelete",
108 &format!("Deleted pod: {}", name(&p)),
109 false,
110 );
111 }
112 }
113 let now = now_secs();
114 let min_ready = rs["spec"]["minReadySeconds"].as_i64().unwrap_or(0);
115 let tpl_labels = &rs["spec"]["template"]["metadata"]["labels"];
116 let status = json!({
117 "replicas": active.len(),
118 "fullyLabeledReplicas": active.iter().filter(|(_, p)| map_matches(tpl_labels, &p["metadata"]["labels"])).count(),
119 "readyReplicas": active.iter().filter(|(_, p)| pod_ready(p)).count(),
120 "availableReplicas": active.iter().filter(|(_, p)| pod_available(p, min_ready, now)).count(),
121 "observedGeneration": rs["metadata"]["generation"].as_i64().unwrap_or(1),
122 });
123 util::update(store, key, |r| {
124 if uid(r) != rs_uid {
125 return false;
126 }
127 let mut changed = false;
128 for (k, v) in status.as_object().unwrap() {
129 if &r["status"][k] != v {
130 r["status"][k] = v.clone();
131 changed = true;
132 }
133 }
134 changed
135 });
136}
137
138pub async fn run(store: Arc<MemStore>, rec: Arc<Recorder>) {
139 let st = store.clone();
140 util::level_loop(
141 &store,
142 &["pods/", "replicasets/"],
143 Duration::from_secs(5),
144 || sync_all(&st, &rec),
145 )
146 .await
147}
148
149#[cfg(test)]
150pub mod tests {
151 use super::*;
152
153 pub fn mark_ready(st: &MemStore, key: &str, ready: bool) {
154 util::update(st, key, |p| {
155 p["spec"]["nodeName"] = json!("n1");
156 p["status"]["phase"] = json!("Running");
157 p["status"]["podIP"] = json!("10.0.0.1");
158 util::set_condition(p, "Ready", ready, "", "")
159 });
160 }
161
162 pub fn owned(st: &MemStore, owner_uid: &str) -> Vec<(String, Value)> {
163 util::list(st, "pods/")
164 .into_iter()
165 .filter(|(_, p)| controller_uid(p) == Some(owner_uid) && pod_active(p))
166 .collect()
167 }
168
169 fn rs(replicas: i64) -> Value {
170 json!({
171 "apiVersion": "apps/v1", "kind": "ReplicaSet",
172 "metadata": {"name": "web", "namespace": "default"},
173 "spec": {"replicas": replicas, "selector": {"matchLabels": {"app": "web"}},
174 "template": {"metadata": {"labels": {"app": "web"}}, "spec": {"containers": [{"name": "c", "image": "nginx"}]}}}
175 })
176 }
177
178 #[test]
179 fn scale_up_down_and_status() {
180 let st = MemStore::new(1 << 22, 256);
181 let rec = Recorder::default();
182 let r = util::create(&st, "replicasets/default/web", rs(3)).unwrap();
183 let ruid = uid(&r).to_string();
184 sync_all(&st, &rec);
185 let pods = owned(&st, &ruid);
186 assert_eq!(pods.len(), 3);
187 assert!(
188 pods.iter()
189 .all(|(_, p)| name(p).starts_with("web-") && name(p).len() == 9)
190 );
191 assert_eq!(pods[0].1["metadata"]["labels"]["app"], "web");
192 sync_all(&st, &rec);
193 assert_eq!(owned(&st, &ruid).len(), 3);
194 mark_ready(&st, &pods[0].0, true);
195 mark_ready(&st, &pods[1].0, true);
196 sync_all(&st, &rec);
197 let r = util::get(&st, "replicasets/default/web").unwrap();
198 assert_eq!(r["status"]["replicas"], 3);
199 assert_eq!(r["status"]["readyReplicas"], 2);
200 assert_eq!(r["status"]["availableReplicas"], 2);
201 assert_eq!(r["status"]["fullyLabeledReplicas"], 3);
202 util::update(&st, "replicasets/default/web", |r| {
203 r["spec"]["replicas"] = json!(1);
204 true
205 });
206 sync_all(&st, &rec);
207 let left = owned(&st, &ruid);
208 assert_eq!(left.len(), 1);
209 assert!(pod_ready(&left[0].1));
210 let terminating_pods = util::list(&st, "pods/")
211 .into_iter()
212 .filter(|(_, p)| terminating(p))
213 .count();
214 assert_eq!(terminating_pods, 1);
215 assert_eq!(util::list(&st, "pods/").len(), 2);
216 }
217
218 #[test]
219 fn orphans_are_collected() {
220 let st = MemStore::new(1 << 22, 256);
221 let rec = Recorder::default();
222 util::create(&st, "replicasets/default/web", rs(2));
223 sync_all(&st, &rec);
224 util::delete(&st, "replicasets/default/web");
225 sync_all(&st, &rec);
226 assert!(util::list(&st, "pods/").is_empty());
227 }
228}