use super::Shared;
use super::probe::{self, Kind};
use super::spec::{
Ctx, SPEC_HASH, VolSrc, container_spec, default_pull_policy, prepare_volumes, spec_hash,
};
use crate::util::{self, name, ns, s, set_condition, terminating, uid};
use krab_runtime::{ContainerInfo, LogOpts, Runtime, is_managed};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use tokio::time::Instant;
const MAX_BACKOFF: u64 = 300;
const HOOK_TIMEOUT: u64 = 30;
const VOLUME_SYNC: u64 = 15;
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>,
term_file: Option<PathBuf>,
log_message: Option<String>,
}
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,
term_file: None,
log_message: 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()?;
let mut t = json!({
"exitCode": i.exit_code,
"reason": if i.oom_killed { "OOMKilled" } else 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)
});
if let Some(m) = self
.term_file
.as_deref()
.and_then(read_term_message)
.or_else(|| self.log_message.clone())
{
t["message"] = json!(m);
}
Some(json!({"terminated": t}))
}
}
const TERM_MESSAGE_MAX: u64 = 4096;
const LOG_MESSAGE_MAX: usize = 2048;
async fn tail_logs<R: Runtime>(rt: &R, info: &ContainerInfo) -> Option<String> {
let opts = LogOpts {
tail: Some(80),
..Default::default()
};
let mut rx = rt.logs(info, &opts).await.ok()?;
let mut buf = Vec::new();
while let Some(b) = rx.recv().await {
buf.extend_from_slice(&b);
}
let from = buf.len().saturating_sub(LOG_MESSAGE_MAX);
let m = String::from_utf8_lossy(&buf[from..]).into_owned();
(!m.is_empty()).then_some(m)
}
fn read_term_message(p: &Path) -> Option<String> {
use std::io::Read;
let mut buf = Vec::new();
std::fs::File::open(p)
.ok()?
.take(TERM_MESSAGE_MAX)
.read_to_end(&mut buf)
.ok()?;
let m = String::from_utf8_lossy(&buf).into_owned();
(!m.is_empty()).then_some(m)
}
fn prepare_term_file(f: &Path) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
if let Some(d) = f.parent() {
std::fs::create_dir_all(d)?;
}
std::fs::write(f, b"")?;
std::fs::set_permissions(f, std::fs::Permissions::from_mode(0o666))
}
fn term_path(root: &Path, uid: &str, cname: &str) -> PathBuf {
root.join(uid).join("termlog").join(cname)
}
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,
vols_synced: Instant,
}
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");
let with_term = |mut v: Vec<CState>| {
for c in &mut v {
c.term_file = Some(term_path(&sh.cfg.volume_root, uid(&pod), c.name()));
}
v
};
Self {
init: with_term(list("initContainers")),
main: with_term(list("containers")),
uid: uid(&pod).to_string(),
sh,
key,
pod,
vols: None,
aliases: None,
adopted: false,
terminal,
init_failed: false,
vols_synced: Instant::now(),
}
}
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]
}
}
fn prev_restarts(&self, init: bool, cname: &str) -> u64 {
let f = if init {
"initContainerStatuses"
} else {
"containerStatuses"
};
self.pod["status"][f]
.as_array()
.into_iter()
.flatten()
.find(|x| x["name"] == cname)
.and_then(|x| x["restartCount"].as_u64())
.unwrap_or(0)
}
async fn adopt(&mut self) -> bool {
let Ok(list) = self.sh.rt.list().await else {
return false;
};
let mut ok = true;
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 prev = self.prev_restarts(init, &cname);
let slots = if init { &self.init } else { &self.main };
let Some(i) = slots.iter().position(|x| x.name() == cname) else {
continue;
};
if c.labels
.get(SPEC_HASH)
.is_some_and(|h| *h != spec_hash(&slots[i].spec))
{
let id = c.id.clone();
self.event(
"Killing",
&format!("Container {cname} definition changed, will be restarted"),
false,
);
let rt = self.sh.rt.clone();
let _ = rt.stop(&id, 10).await;
if let Err(e) = rt.remove(&id, true).await {
self.event(
"FailedKillPod",
&format!("error killing container {cname}: {e}"),
true,
);
ok = false;
continue;
}
self.slot(init, i).restarts = prev + 1;
continue;
}
let slot = self.slot(init, i);
slot.restarts = prev.saturating_sub(c.restart_count);
slot.docker_restarts = c.restart_count;
slot.id = Some(c.id.clone());
slot.info = Some(c);
}
ok
}
async fn deadline_exceeded(&mut self) -> bool {
let Some(limit) = self.pod["spec"]["activeDeadlineSeconds"].as_i64() else {
return false;
};
let started = util::parse_rfc3339(s(&self.pod, "/status/startTime"));
if started.is_none_or(|t| util::now_secs() - t <= limit) {
return false;
}
self.event(
"DeadlineExceeded",
"Pod was active on the node longer than the specified deadline",
true,
);
self.teardown(false).await;
let uid = self.uid.clone();
util::update(&self.sh.store, &self.key, |p| {
if util::uid(p) != uid {
return false;
}
p["status"]["phase"] = json!("Failed");
p["status"]["reason"] = json!("DeadlineExceeded");
p["status"]["message"] =
json!("Pod was active on the node longer than the specified deadline");
true
});
self.terminal = true;
true
}
async fn evicted(&mut self) -> bool {
let msg = s(&self.pod, "/metadata/annotations/krab.io~1evict").to_string();
if msg.is_empty() {
return false;
}
self.event("Evicted", &msg, true);
self.teardown(false).await;
let uid = self.uid.clone();
util::update(&self.sh.store, &self.key, |p| {
if util::uid(p) != uid {
return false;
}
p["status"]["phase"] = json!("Failed");
p["status"]["reason"] = json!("Evicted");
p["status"]["message"] = json!(msg);
true
});
self.terminal = true;
true
}
fn refresh_volumes(&mut self) {
if self.vols.is_none() || self.vols_synced.elapsed() < Duration::from_secs(VOLUME_SYNC) {
return;
}
self.vols_synced = Instant::now();
let has = self.pod["spec"]["volumes"].as_array().is_some_and(|v| {
v.iter()
.any(|x| x["configMap"].is_object() || x["secret"].is_object())
});
if has {
let sh = &self.sh;
let _ = prepare_volumes(
&sh.store,
&self.pod,
&sh.cfg.volume_root,
&sh.cfg.allow_host_paths,
);
}
}
async fn sync(&mut self) {
if self.terminal {
return;
}
self.refresh_volumes();
if self.evicted().await {
return;
}
if self.deadline_exceeded().await {
return;
}
if !self.adopted {
if !self.adopt().await {
return;
}
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();
}
let failed =
matches!(info.state.as_str(), "exited" | "dead") && info.exit_code != 0;
let fallback = failed
&& c.log_message.is_none()
&& s(&c.spec, "/terminationMessagePolicy") == "FallbackToLogsOnError"
&& c.term_file.as_deref().and_then(read_term_message).is_none();
if !failed {
c.log_message = None;
}
let snapshot = info.clone();
c.info = Some(info);
if fallback {
c.log_message = tail_logs(&*rt, &snapshot).await;
}
}
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 pins = sh
.cfg
.volume_root
.join(&self.uid)
.join("subpaths")
.join(s(&cjson, "/name"));
let ctx = Ctx {
store: &sh.store,
pod: &self.pod,
node: &sh.cfg.node_name,
pod_ip: &pod_ip,
host_ip: &host_ip,
subpaths: Some(&pins),
};
let Some(vols) = self.vols.as_ref() else {
return;
};
let mut 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 tpath = match s(&cjson, "/terminationMessagePath") {
"" => "/dev/termination-log",
p => p,
};
if tpath.starts_with('/')
&& !tpath.contains(':')
&& let Some(f) = self.slot(init, i).term_file.clone()
&& prepare_term_file(&f).is_ok()
{
spec.mounts.push(krab_runtime::Mount::Bind {
src: f.to_string_lossy().into_owned(),
dst: tpath.to_string(),
read_only: false,
});
}
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();
}
let mut started = false;
match rt.start(&id).await {
Ok(()) => {
started = true;
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;
if started && let Err(e) = self.run_hook(init, i, "postStart").await {
self.event(
"FailedPostStartHook",
&format!("PostStartHook failed: {e}"),
true,
);
let _ = rt.stop(&id, 2).await;
self.refresh(init, i).await;
}
}
async fn run_hook(&mut self, init: bool, i: usize, which: &str) -> Result<(), String> {
let c = self.slot(init, i);
let mut hook = c.spec["lifecycle"][which].clone();
if !hook.is_object() {
return Ok(());
}
hook["timeoutSeconds"] = json!(HOOK_TIMEOUT);
let (id, spec) = (c.id.clone().unwrap_or_default(), c.spec.clone());
let ip = self.pod_ip();
probe::run(&*self.sh.rt, &id, &spec, &hook, &ip).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(|c| {
let mut v = Self::container_status(c);
if !init_done
&& c.id.is_none()
&& v["state"]["waiting"]["reason"] == "ContainerCreating"
{
v["state"]["waiting"]["reason"] = json!("PodInitializing");
}
v
})
.collect();
let init_statuses: Vec<Value> = self
.init
.iter()
.enumerate()
.map(|(i, c)| {
let mut v = Self::container_status(c);
v["ready"] = json!(c.done);
if c.id.is_none()
&& v["state"]["waiting"]["reason"] == "ContainerCreating"
&& self.init[..i].iter().any(|p| !p.done)
{
v["state"]["waiting"]["reason"] = json!("PodInitializing");
}
v
})
.collect();
let incomplete = self
.init
.iter()
.filter(|c| !c.done)
.map(|c| c.name())
.collect::<Vec<_>>()
.join(" ");
let incomplete_msg = format!("containers with incomplete status: [{incomplete}]");
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",
&incomplete_msg,
);
}
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 {
if finalize {
let pos = self.main.iter().position(|c| c.name() == cname);
if let Some(i) = pos
&& self.main[i].spec["lifecycle"]["preStop"].is_object()
{
let budget = Duration::from_secs(grace.max(1));
if let Ok(Err(e)) =
tokio::time::timeout(budget, self.run_hook(false, i, "preStop")).await
{
self.event(
"FailedPreStopHook",
&format!("PreStopHook failed: {e}"),
true,
);
}
}
}
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 _ = krab_runtime::subpath::remove_dir_safely(&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);
}
}
}