use super::Shared;
use super::probe::{self, Kind};
use super::spec::{Ctx, VolSrc, container_spec, default_pull_policy, prepare_volumes};
use crate::util::{self, name, ns, s, set_condition, terminating, uid};
use krab_runtime::{ContainerInfo, Runtime, is_managed};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use tokio::time::Instant;
const MAX_BACKOFF: u64 = 300;
struct CState {
spec: Value,
id: Option<String>,
info: Option<ContainerInfo>,
docker_restarts: u64,
restarts: u64,
started_at: Instant,
started: bool,
ready: bool,
ok: u32,
fails: [u32; 3],
next_probe: [Option<Instant>; 3],
backoff: u32,
next_start: Option<Instant>,
waiting: Option<(String, String)>,
done: bool,
last_term: Option<Value>,
}
impl CState {
fn new(spec: &Value) -> Self {
Self {
spec: spec.clone(),
id: None,
info: None,
docker_restarts: 0,
restarts: 0,
started_at: Instant::now(),
started: false,
ready: false,
ok: 0,
fails: [0; 3],
next_probe: [None; 3],
backoff: 0,
next_start: None,
waiting: None,
done: false,
last_term: None,
}
}
fn name(&self) -> &str {
s(&self.spec, "/name")
}
fn state(&self) -> &str {
self.info.as_ref().map(|i| i.state.as_str()).unwrap_or("")
}
fn reset_probes(&mut self) {
self.started_at = Instant::now();
self.started = false;
self.ready = false;
self.ok = 0;
self.fails = [0; 3];
self.next_probe = [None; 3];
}
fn schedule_backoff(&mut self) -> Duration {
let d = Duration::from_secs((10u64 << self.backoff.min(5)).min(MAX_BACKOFF));
self.next_start = Some(Instant::now() + d);
self.backoff += 1;
d
}
fn gate_open(&self) -> bool {
self.next_start.is_none_or(|t| Instant::now() >= t)
}
fn terminated(&self) -> Option<Value> {
let i = self.info.as_ref()?;
Some(json!({"terminated": {
"exitCode": i.exit_code,
"reason": if i.exit_code == 0 { "Completed" } else { "Error" },
"startedAt": real_time(&i.started_at),
"finishedAt": real_time(&i.finished_at),
"containerID": format!("docker://{}", i.id)
}}))
}
}
fn real_time(s: &str) -> Value {
if s.is_empty() || s.starts_with("0001-") {
Value::Null
} else {
json!(
s.split('.')
.next()
.map(|x| format!("{}Z", x.trim_end_matches('Z')))
.unwrap_or_default()
)
}
}
pub struct Worker<R> {
sh: Arc<Shared<R>>,
key: String,
uid: String,
pod: Value,
init: Vec<CState>,
main: Vec<CState>,
vols: Option<HashMap<String, VolSrc>>,
aliases: Option<Vec<String>>,
adopted: bool,
terminal: bool,
init_failed: bool,
}
impl<R: Runtime> Worker<R> {
pub fn new(sh: Arc<Shared<R>>, key: String, pod: Value) -> Self {
let list = |f: &str| -> Vec<CState> {
pod["spec"][f]
.as_array()
.into_iter()
.flatten()
.map(CState::new)
.collect()
};
let terminal = matches!(s(&pod, "/status/phase"), "Succeeded" | "Failed");
Self {
init: list("initContainers"),
main: list("containers"),
uid: uid(&pod).to_string(),
sh,
key,
pod,
vols: None,
aliases: None,
adopted: false,
terminal,
init_failed: false,
}
}
pub async fn run(mut self, notify: Arc<Notify>) {
loop {
match util::get(&self.sh.store, &self.key).filter(|p| uid(p) == self.uid) {
None => {
self.teardown(false).await;
return;
}
Some(p) if terminating(&p) => {
self.pod = p;
self.teardown(true).await;
return;
}
Some(p) => {
self.pod = p;
self.sync().await;
}
}
tokio::select! {
_ = notify.notified() => {}
_ = tokio::time::sleep(self.sh.cfg.sync_period) => {}
}
}
}
fn event(&self, reason: &str, msg: &str, warn: bool) {
self.sh
.rec
.event(&self.sh.store, &self.pod, reason, msg, warn);
}
fn policy(&self) -> &str {
match s(&self.pod, "/spec/restartPolicy") {
"" => "Always",
p => p,
}
}
fn pod_ip(&self) -> String {
self.main
.first()
.and_then(|c| c.info.as_ref())
.map(|i| i.ip.clone())
.unwrap_or_default()
}
fn host_ip(&self) -> String {
util::get(&self.sh.store, &format!("nodes/{}", self.sh.cfg.node_name))
.and_then(|n| {
n["status"]["addresses"].as_array()?.iter().find_map(|a| {
(a["type"] == "InternalIP")
.then(|| a["address"].as_str().map(str::to_string))?
})
})
.unwrap_or_default()
}
fn desired_aliases(&self) -> Vec<String> {
let namespace = ns(&self.pod);
let mut out = Vec::new();
for (_, ep) in util::list(&self.sh.store, &format!("endpoints/{namespace}/")) {
let hit = ep["subsets"].as_array().into_iter().flatten().any(|sub| {
sub["addresses"]
.as_array()
.into_iter()
.flatten()
.any(|a| s(a, "/targetRef/uid") == self.uid)
});
if hit {
out.push(name(&ep).to_string());
out.push(format!("{}.{namespace}.svc.cluster.local", name(&ep)));
}
}
out.sort();
out
}
fn slot(&mut self, init: bool, i: usize) -> &mut CState {
if init {
&mut self.init[i]
} else {
&mut self.main[i]
}
}
async fn adopt(&mut self) {
let Ok(list) = self.sh.rt.list().await else {
return;
};
for c in list.into_iter().filter(is_managed) {
if c.labels.get("krab.io/uid") != Some(&self.uid) {
continue;
}
let cname = c
.labels
.get("krab.io/container")
.cloned()
.unwrap_or_default();
let init = c.labels.contains_key("krab.io/init");
let slots = if init { &mut self.init } else { &mut self.main };
if let Some(slot) = slots.iter_mut().find(|x| x.name() == cname) {
slot.id = Some(c.id.clone());
slot.info = Some(c);
}
}
}
async fn sync(&mut self) {
if self.terminal {
return;
}
if !self.adopted {
self.adopt().await;
self.adopted = true;
}
let sh = self.sh.clone();
{
let mut net = sh.net.lock().await;
if !*net {
match sh.rt.ensure_network(&sh.cfg.network).await {
Ok(()) => *net = true,
Err(e) => {
drop(net);
self.event(
"NetworkNotReady",
&format!("network {}: {e}", sh.cfg.network),
true,
);
self.write_status();
return;
}
}
}
}
if self.vols.is_none() {
match prepare_volumes(
&sh.store,
&self.pod,
&sh.cfg.volume_root,
&sh.cfg.allow_host_paths,
) {
Ok(v) => self.vols = Some(v),
Err(e) => {
self.event(
"FailedMount",
&format!("MountVolume.SetUp failed: {e}"),
true,
);
self.write_status();
return;
}
}
}
for i in 0..self.init.len() {
if self.init[i].done {
continue;
}
self.step_init(i).await;
if !self.init[i].done {
self.write_status();
return;
}
}
for i in 0..self.main.len() {
self.step_main(i).await;
}
self.sync_aliases().await;
self.write_status();
}
async fn refresh(&mut self, init: bool, i: usize) {
let rt = self.sh.rt.clone();
let c = self.slot(init, i);
let Some(id) = c.id.clone() else { return };
let mut info = ContainerInfo {
id: id.clone(),
..Default::default()
};
match rt.inspect(&mut info).await {
Ok(()) => {
info.id = id;
if info.restart_count > c.docker_restarts {
c.docker_restarts = info.restart_count;
c.reset_probes();
}
c.info = Some(info);
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
c.id = None;
c.info = None;
c.restarts += 1;
}
Err(_) => {}
}
}
async fn pull(&mut self, init: bool, i: usize, image: &str) -> bool {
self.event("Pulling", &format!("Pulling image \"{image}\""), false);
match self.sh.rt.pull_image(image).await {
Ok(()) => {
self.event(
"Pulled",
&format!("Successfully pulled image \"{image}\""),
false,
);
true
}
Err(e) => {
self.event(
"Failed",
&format!("Failed to pull image \"{image}\": {e}"),
true,
);
self.event("Failed", "Error: ErrImagePull", true);
let c = self.slot(init, i);
c.waiting = Some(("ErrImagePull".into(), e.to_string()));
c.schedule_backoff();
false
}
}
}
fn fail_create(&mut self, init: bool, i: usize, reason: &str, msg: String) {
self.event("Failed", &format!("Error: {msg}"), true);
let c = self.slot(init, i);
c.waiting = Some((reason.into(), msg));
c.schedule_backoff();
}
async fn create(&mut self, init: bool, i: usize) {
let sh = self.sh.clone();
let rt = &sh.rt;
let cjson = self.slot(init, i).spec.clone();
if let Some((reason, _)) = self.slot(init, i).waiting.clone()
&& reason == "ErrImagePull"
{
let image = s(&cjson, "/image").to_string();
self.event(
"BackOff",
&format!("Back-off pulling image \"{image}\""),
false,
);
}
let aliases = if init || i > 0 {
Vec::new()
} else {
self.desired_aliases()
};
let (pod_ip, host_ip) = (self.pod_ip(), self.host_ip());
let ctx = Ctx {
store: &sh.store,
pod: &self.pod,
node: &sh.cfg.node_name,
pod_ip: &pod_ip,
host_ip: &host_ip,
};
let Some(vols) = self.vols.as_ref() else {
return;
};
let spec = match container_spec(&ctx, &cjson, init, vols, &sh.cfg.network, aliases.clone())
{
Ok(s) => s,
Err(e) => return self.fail_create(init, i, "CreateContainerConfigError", e),
};
let image = spec.image.clone();
let policy = cjson["imagePullPolicy"]
.as_str()
.unwrap_or_else(|| default_pull_policy(&image))
.to_string();
if policy == "Always" && !self.pull(init, i, &image).await {
return;
}
let mut res = rt.create_container(&spec).await;
if let Err(e) = &res
&& e.kind() == io::ErrorKind::AlreadyExists
{
let mut info = ContainerInfo {
id: spec.name.clone(),
..Default::default()
};
if rt.inspect(&mut info).await.is_ok() && is_managed(&info) {
if info.labels.get("krab.io/uid") == Some(&self.uid) {
let c = self.slot(init, i);
c.id = Some(info.id.clone());
c.info = Some(info);
return;
}
let _ = rt.remove(&info.id, true).await;
}
res = rt.create_container(&spec).await;
}
match &res {
Err(e) if e.kind() == io::ErrorKind::NotFound && policy == "Never" => {
let msg =
format!("Container image \"{image}\" is not present with pull policy of Never");
return self.fail_create(init, i, "ErrImageNeverPull", msg);
}
Err(e) if e.kind() == io::ErrorKind::NotFound && policy == "IfNotPresent" => {
if !self.pull(init, i, &image).await {
return;
}
res = rt.create_container(&spec).await;
}
Ok(_) if policy == "IfNotPresent" => {
self.event(
"Pulled",
&format!("Container image \"{image}\" already present on machine"),
false,
);
}
_ => {}
}
let id = match res {
Ok(id) => id,
Err(e) => return self.fail_create(init, i, "CreateContainerError", e.to_string()),
};
let cname = s(&cjson, "/name").to_string();
self.event("Created", &format!("Created container: {cname}"), false);
{
let c = self.slot(init, i);
c.id = Some(id.clone());
c.waiting = None;
c.reset_probes();
}
match rt.start(&id).await {
Ok(()) => {
self.event("Started", &format!("Started container {cname}"), false);
let c = self.slot(init, i);
c.next_start = None;
if !init && i == 0 {
self.aliases = Some(aliases);
}
}
Err(e) => {
self.event(
"Failed",
&format!("Error: failed to start container {cname}: {e}"),
true,
);
let c = self.slot(init, i);
c.waiting = Some(("RunContainerError".into(), e.to_string()));
c.schedule_backoff();
}
}
self.refresh(init, i).await;
}
async fn restart_exited(&mut self, init: bool, i: usize) {
let rt = self.sh.rt.clone();
let cname = self.slot(init, i).name().to_string();
let pod_ref = format!("{}_{}", name(&self.pod), ns(&self.pod));
let c = self.slot(init, i);
if c.next_start.is_none() {
c.last_term = c.terminated();
let d = c.schedule_backoff();
let msg = format!(
"Back-off {}s restarting failed container={cname} pod={pod_ref}",
d.as_secs()
);
self.event("BackOff", &msg, true);
return;
}
if !c.gate_open() {
return;
}
let Some(id) = c.id.clone() else { return };
c.next_start = None;
c.restarts += 1;
c.reset_probes();
if rt.start(&id).await.is_ok() {
self.event("Started", &format!("Started container {cname}"), false);
}
self.refresh(init, i).await;
}
async fn step_init(&mut self, i: usize) {
if self.init[i].id.is_none() {
if self.init[i].gate_open() {
self.create(true, i).await;
}
return;
}
self.refresh(true, i).await;
let c = &mut self.init[i];
if !matches!(c.state(), "exited" | "dead") {
return;
}
let code = c.info.as_ref().map(|x| x.exit_code).unwrap_or(-1);
if code == 0 {
c.done = true;
c.backoff = 0;
return;
}
if self.policy() == "Never" {
self.init_failed = true;
return;
}
self.restart_exited(true, i).await;
}
async fn step_main(&mut self, i: usize) {
if self.main[i].id.is_none() {
if self.main[i].gate_open() {
self.create(false, i).await;
}
return;
}
self.refresh(false, i).await;
let state = self.main[i].state().to_string();
match state.as_str() {
"running" => self.probe_all(i).await,
"created" => {
let id = self.main[i].id.clone().unwrap_or_default();
let _ = self.sh.rt.start(&id).await;
}
"exited" | "dead" => {
let c = &mut self.main[i];
c.ready = false;
let code = c.info.as_ref().map(|x| x.exit_code).unwrap_or(-1);
let restart = match self.policy() {
"Never" => false,
"OnFailure" => code != 0,
_ => true,
};
if restart {
self.restart_exited(false, i).await;
}
}
_ => self.main[i].ready = false,
}
}
async fn probe_once(&mut self, i: usize, kind: Kind) -> Option<Result<(), String>> {
let c = &self.main[i];
let p = c.spec[kind.field()].clone();
if !p.is_object() {
return None;
}
let prm = probe::params(&p);
let now = Instant::now();
let due = match c.next_probe[kind as usize] {
None => c.started_at + Duration::from_secs(prm.initial_delay),
Some(t) => t,
};
if now < due {
return None;
}
let id = c.id.clone().unwrap_or_default();
let spec = c.spec.clone();
let ip = self.pod_ip();
let res = probe::run(&*self.sh.rt, &id, &spec, &p, &ip).await;
self.main[i].next_probe[kind as usize] =
Some(Instant::now() + Duration::from_secs(prm.period));
Some(res)
}
async fn kill_and_restart(&mut self, i: usize, why: &str) {
let name = self.main[i].name().to_string();
self.event(
"Killing",
&format!("Container {name} {why}, will be restarted"),
false,
);
let grace = self.pod["spec"]["terminationGracePeriodSeconds"]
.as_u64()
.unwrap_or(30)
.min(30);
let id = self.main[i].id.clone().unwrap_or_default();
let rt = self.sh.rt.clone();
let _ = rt.stop(&id, grace).await;
self.refresh(false, i).await;
let c = &mut self.main[i];
c.last_term = c.terminated();
c.restarts += 1;
c.reset_probes();
if rt.start(&id).await.is_ok() {
self.event("Started", &format!("Started container {name}"), false);
}
self.refresh(false, i).await;
}
async fn probe_all(&mut self, i: usize) {
let spec = self.main[i].spec.clone();
let has = |k: Kind| spec[k.field()].is_object();
if has(Kind::Startup) && !self.main[i].started {
self.main[i].ready = false;
match self.probe_once(i, Kind::Startup).await {
Some(Ok(())) => self.main[i].started = true,
Some(Err(e)) => {
self.event("Unhealthy", &format!("Startup probe failed: {e}"), true);
let thr = probe::params(&self.main[i].spec[Kind::Startup.field()]).failure;
self.main[i].fails[0] += 1;
if self.main[i].fails[0] >= thr {
self.kill_and_restart(i, "failed startup probe").await;
}
return;
}
None => return,
}
}
self.main[i].started = true;
if let Some(r) = self.probe_once(i, Kind::Liveness).await {
match r {
Ok(()) => self.main[i].fails[1] = 0,
Err(e) => {
self.event("Unhealthy", &format!("Liveness probe failed: {e}"), true);
let thr = probe::params(&self.main[i].spec[Kind::Liveness.field()]).failure;
self.main[i].fails[1] += 1;
if self.main[i].fails[1] >= thr {
return self.kill_and_restart(i, "failed liveness probe").await;
}
}
}
}
if !has(Kind::Readiness) {
self.main[i].ready = true;
return;
}
if let Some(r) = self.probe_once(i, Kind::Readiness).await {
let prm = probe::params(&self.main[i].spec[Kind::Readiness.field()]);
match r {
Ok(()) => {
let c = &mut self.main[i];
c.fails[2] = 0;
c.ok += 1;
if c.ok >= prm.success {
c.ready = true;
}
}
Err(e) => {
self.event("Unhealthy", &format!("Readiness probe failed: {e}"), true);
let c = &mut self.main[i];
c.ok = 0;
c.fails[2] += 1;
if c.fails[2] >= prm.failure {
c.ready = false;
}
}
}
}
}
async fn sync_aliases(&mut self) {
let Some(c) = self.main.first() else { return };
let Some(id) = c.id.clone().filter(|_| c.state() == "running") else {
return;
};
let want = self.desired_aliases();
if self.aliases.as_ref() == Some(&want) {
return;
}
let rt = self.sh.rt.clone();
let net = self.sh.cfg.network.clone();
let _ = rt.disconnect_network(&id, &net).await;
if rt.connect_network(&id, &net, &want).await.is_ok() {
self.aliases = Some(want);
}
self.refresh(false, 0).await;
}
fn container_status(c: &CState) -> Value {
let running = c.state() == "running";
let state = match (c.id.as_ref(), c.state()) {
(None, _) => {
let (r, m) = c
.waiting
.clone()
.unwrap_or(("ContainerCreating".into(), String::new()));
let mut w = json!({"reason": r});
if !m.is_empty() {
w["message"] = json!(m);
}
json!({"waiting": w})
}
(_, "running") => {
json!({"running": {"startedAt": real_time(c.info.as_ref().map(|i| i.started_at.as_str()).unwrap_or(""))}})
}
(_, "restarting") => json!({"waiting": {"reason": "CrashLoopBackOff"}}),
(_, "exited" | "dead") if c.next_start.is_some() => {
json!({"waiting": {"reason": "CrashLoopBackOff"}})
}
(_, "exited" | "dead") => c.terminated().unwrap_or(json!({"waiting": {}})),
_ => json!({"waiting": {"reason": "ContainerCreating"}}),
};
let info = c.info.as_ref();
let mut st = json!({
"name": c.name(),
"image": s(&c.spec, "/image"),
"imageID": info.map(|i| i.image_id.as_str()).unwrap_or(""),
"ready": c.ready && running,
"started": running && c.started,
"restartCount": c.restarts + c.docker_restarts,
"state": state,
"lastState": c.last_term.clone().unwrap_or(json!({}))
});
if let Some(id) = &c.id {
st["containerID"] = json!(format!("docker://{id}"));
}
st
}
fn write_status(&mut self) {
let init_done = self.init.iter().all(|c| c.done);
let all_started = self.main.iter().all(|c| c.id.is_some());
let term: Vec<i64> = self
.main
.iter()
.filter(|c| matches!(c.state(), "exited" | "dead") && c.next_start.is_none())
.map(|c| c.info.as_ref().map(|i| i.exit_code).unwrap_or(-1))
.collect();
let all_term = all_started && !self.main.is_empty() && term.len() == self.main.len();
let all_ok = term.iter().all(|c| *c == 0);
let phase = if self.init_failed {
"Failed"
} else if !init_done || !all_started {
"Pending"
} else if all_term && self.policy() == "Never" {
if all_ok { "Succeeded" } else { "Failed" }
} else if all_term && self.policy() == "OnFailure" && all_ok {
"Succeeded"
} else {
"Running"
};
let unready: Vec<&str> = self
.main
.iter()
.filter(|c| !(c.ready && c.state() == "running"))
.map(|c| c.name())
.collect();
let ready = unready.is_empty() && phase == "Running";
let msg = if ready {
String::new()
} else {
format!("containers with unready status: [{}]", unready.join(" "))
};
let statuses: Vec<Value> = self.main.iter().map(Self::container_status).collect();
let init_statuses: Vec<Value> = self
.init
.iter()
.map(|c| {
let mut v = Self::container_status(c);
v["ready"] = json!(c.done);
v
})
.collect();
let pod_ip = self.pod_ip();
let host_ip = self.host_ip();
let uid = self.uid.clone();
let updated = util::update(&self.sh.store, &self.key, |p| {
if util::uid(p) != uid {
return false;
}
let before = p["status"].clone();
if !p["status"].is_object() {
p["status"] = json!({});
}
let st = &mut p["status"];
st["phase"] = json!(phase);
if !host_ip.is_empty() {
st["hostIP"] = json!(host_ip);
st["hostIPs"] = json!([{"ip": host_ip}]);
}
if pod_ip.is_empty() {
if let Some(o) = st.as_object_mut() {
o.remove("podIP");
o.remove("podIPs");
}
} else {
st["podIP"] = json!(pod_ip);
st["podIPs"] = json!([{"ip": pod_ip}]);
}
if st["startTime"].is_null() {
st["startTime"] = json!(util::now_rfc());
}
st["containerStatuses"] = json!(statuses);
if !init_statuses.is_empty() {
st["initContainerStatuses"] = json!(init_statuses);
}
set_condition(p, "PodScheduled", true, "", "");
if init_done {
set_condition(p, "Initialized", true, "", "");
} else {
set_condition(
p,
"Initialized",
false,
"ContainersNotInitialized",
"containers with incomplete status",
);
}
let reason = if ready { "" } else { "ContainersNotReady" };
set_condition(p, "ContainersReady", ready, reason, &msg);
set_condition(p, "Ready", ready, reason, &msg);
p["status"] != before
});
if updated.is_some() || matches!(phase, "Succeeded" | "Failed") {
self.terminal = matches!(phase, "Succeeded" | "Failed");
}
}
async fn teardown(&mut self, finalize: bool) {
let rt = self.sh.rt.clone();
let grace = self.pod["metadata"]["deletionGracePeriodSeconds"]
.as_u64()
.or_else(|| self.pod["spec"]["terminationGracePeriodSeconds"].as_u64())
.unwrap_or(30)
.min(30);
let mut ids: Vec<(String, String)> = self
.main
.iter()
.chain(self.init.iter())
.filter_map(|c| Some((c.id.clone()?, c.name().to_string())))
.collect();
if let Ok(list) = rt.list().await {
for c in list.into_iter().filter(is_managed) {
if c.labels.get("krab.io/uid") == Some(&self.uid)
&& !ids.iter().any(|(id, _)| *id == c.id)
{
let n = c
.labels
.get("krab.io/container")
.cloned()
.unwrap_or_default();
ids.push((c.id, n));
}
}
}
for (id, cname) in ids {
self.event("Killing", &format!("Stopping container {cname}"), false);
let _ = rt.stop(&id, grace).await;
let _ = rt.remove(&id, true).await;
}
for v in self.vols.take().unwrap_or_default().into_values() {
if let VolSrc::Named(n) = v {
let _ = rt.remove_volume(&n).await;
}
}
let _ = std::fs::remove_dir_all(self.sh.cfg.volume_root.join(&self.uid));
if finalize
&& util::get(&self.sh.store, &self.key)
.is_some_and(|p| uid(&p) == self.uid && terminating(&p))
{
util::delete(&self.sh.store, &self.key);
}
}
}