Files
leleka/crates/deploy/src/supervisor.rs
T

189 lines
5.6 KiB
Rust

//! `leleka run`: the foreground supervisor that systemd (or a terminal) starts.
//!
//! Order: seal the archive (once) -> gateway -> engine -> wait for the engine port -> typed `load-mtp` through
//! `leleka-cli` -> wait for `model_ready` -> public API -> wait for `/ready` -> supervise. An engine that dies is
//! restarted with the same sealed descriptor (no second 55 GB copy) and loaded again, up to a bound; the API
//! process stays up and reports not-ready meanwhile. SIGTERM/SIGINT drain the API first, then stop the gateway
//! and the engine (both handle SIGINT only), and escalate to SIGKILL after the grace period.
use crate::{
config::{GATEWAY_TOKEN_ENV, KarArg, RUNTIME_TOKEN_ENV, RunConfig},
facts::parse_env_file,
http,
layout::Paths,
logs,
profile::{ARCHIVE_BYTES, KarSource, MemfdExtents, PinSource, archive_sha256, extents_sha256},
reconfigure, sealed, watchdog,
};
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
use serde::Serialize;
use std::{
collections::BTreeMap,
fs::File,
io::Write,
net::SocketAddr,
path::{Path, PathBuf},
process::Stdio,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::{
process::{Child, Command},
sync::watch,
time::{sleep, timeout},
};
const LOG_ROTATE_BYTES: u64 = 64 << 20;
/// Set by `--hidden` (the Windows logon task): the children get no console window.
pub static HIDDEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[derive(Clone, Debug)]
pub struct Options {
pub config: PathBuf,
/// A sealed archive descriptor inherited from a holder process (tests, operator tooling). The supervisor
/// reopens it and does not copy the archive itself.
pub kar_fd: Option<u32>,
}
#[derive(Debug)]
pub struct Failure {
pub code: i32,
pub message: String,
}
fn fail<T>(code: i32, message: impl Into<String>) -> Result<T, Flow> {
Err(Flow::Fatal(Failure {
code,
message: message.into(),
}))
}
#[derive(Debug)]
enum Flow {
/// A stop signal arrived while waiting.
Stopped,
Fatal(Failure),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
Starting,
Sealing,
StartingGateway,
StartingEngine,
Loading,
StartingApi,
Ready,
EngineRestarting,
Draining,
Stopped,
Failed,
}
#[derive(Serialize)]
struct StatusDoc<'a> {
schema_version: u32,
phase: Phase,
ready: bool,
message: &'a str,
updated_unix: u64,
supervisor_pid: u32,
engine_pid: Option<u32>,
gateway_pid: Option<u32>,
api_pid: Option<u32>,
engine_restarts: u32,
endpoint: &'a str,
model: &'a str,
model_digest: &'a str,
profile: &'a str,
kar_source: &'a str,
memfd_extents: &'a str,
/// When this supervisor started (service uptime = now - this).
started_unix: u64,
/// Engine restarts since the service started (crashes, hangs, failed restarts), whatever the in-a-row counter says.
restarts_total: u32,
last_restart_unix: Option<u64>,
last_restart_reason: Option<&'a str>,
/// The hang detector's last judgement ("healthy", or what looks wrong).
health: &'a str,
/// Bytes in the log directory (rotation keeps it bounded).
log_bytes: u64,
}
struct Log {
file: std::sync::Mutex<File>,
}
/// `runtime.proto` `OperationResult.State`.
const OPERATION_FAILED: i64 = 3;
const OPERATION_INDETERMINATE: i64 = 4;
struct Supervisor {
config: RunConfig,
paths: Paths,
env: BTreeMap<String, String>,
api_key: String,
log: Log,
status_path: PathBuf,
shutdown: watch::Receiver<bool>,
archive: Option<File>,
/// Identity of the file the sealed archive was copied from (device, inode, size, mtime, ctime), when stable.
source_identity: Option<FileIdentity>,
/// The sealed archive is known to match its pinned digest (stamp of its source file, or a previous engine of
/// this supervisor verified this very memfd): the engine is told not to hash it again.
archive_attested: bool,
/// `memfd_extents: ple_only`: the pinned SHA-256 of the archive's extents. The memfd holds only those bytes (or all of them, when it
/// came from a holder) and the engine verifies it against this digest instead of the archive's SHA-256; no stamp or attestation
/// of the whole archive applies to it.
archive_sparse_pin: Option<[u8; 32]>,
stamps: VerifyStamps,
api_addr: SocketAddr,
engine_addr: SocketAddr,
daemon_addr: SocketAddr,
engine_restarts: u32,
pids: [Option<u32>; 3],
phase: Phase,
message: String,
beats: u32,
started_unix: u64,
restarts_total: u32,
last_restart: Option<(u64, String)>,
health_note: String,
}
/// The file `leleka down` creates on Windows (there is no signal to send to a supervisor in another console).
pub const STOP_REQUEST_FILE: &str = "stop.request";
#[cfg(test)]
mod tests;
mod api;
mod archive;
mod children;
mod cli_output;
mod engine;
mod live_reconfigure;
mod load;
mod logfile;
mod signals;
mod sparse;
mod startup;
mod status;
mod supervise;
pub use children::own_group;
pub use cli_output::{
parse_operation, parse_operation_state, parse_runtime_status, tail_of, valid_token,
};
pub use logfile::{format_utc, rotate_log, write_private};
use logfile::{open_log, private_append, unix_now};
#[cfg(target_os = "linux")]
use signals::interrupt;
#[cfg(windows)]
use signals::interrupt;
#[cfg(not(any(target_os = "linux", windows)))]
use signals::interrupt;
use signals::spawn_signal_task;
#[cfg(windows)]
use startup::leleka_libc_shim_dll_dirs_env;
pub use startup::run;