`leleka run` restarted a crashed engine twice after a fixed 5 s and then ended the service; a hung engine, a growing log and a client waiting on a dead engine had no answer. All of it is now in the supervisor and in what `leleka up` writes: * Restart with backoff (config.rs RestartPolicy backoff_initial_s 5 / backoff_max_s 300, max_engine_restarts 6 in a row, reset after 600 s of ready): recover_engine() waits 5, 10, 20 ... s, counts a restart that fails (load refused, port taken) as an attempt and retries it instead of ending the service; only after the last attempt does the supervisor exit 1 and let systemd start everything afresh. * Hang detector (watchdog.rs, pure and tested; HealthPolicy in leleka.json: interval 10 s, fail 120 s, max_request 3900 s): every 10 s the supervisor reads GET /metrics of the API (the control plane's own view; the engine's telemetry is not used, the API refreshes it only between requests). API unreachable 120 s: restart the API. Worker not ready 120 s (the API lost the engine): SIGKILL and restart the engine. A request active longer than 3900 s (generation_timeout 3600 + 300): the same. A stopped (SIGSTOP) or deadlocked engine ends this way. * Requests get an error, not a hang: strata.json now carries runtime.stall_timeout_s 600 (no engine event for 10 min during a request cancels it with an error to the client) and generation_timeout_s 3600 (RequestLimits in leleka.json). * Bounded logs (logs.rs): every 10 s the supervisor copy-truncates any STATE/logs/*.log past 16 MiB, keeps 3 generations (children keep their O_APPEND descriptors, nothing is told); <= 16 x 4 x 6 files; one 16 MiB copy per rotation. tail_of reads only the last 256 KiB. * Status file: started_unix, restarts_total, last_restart_unix/reason, health, log_bytes; rewritten every 30 s as a heartbeat. * units.rs (and scripts/ops/leleka.service, a test pins the file to the generator for the server layout): StartLimitIntervalSec=0 with RestartSteps/RestartMaxDelaySec (30 s growing to 10 min), LimitCORE=0 (a 100 GB core dump must not hit the root NVMe), LimitNOFILE, TasksMax, OOMScoreAdjust=-500 (system scope), journal rate limit, RequiresMountsFor, TimeoutStopSec 180, and ConditionPathExists=!STATE/lab-mode so the unit stays down while the GPU belongs to the lab queue. * Tests (fake runtime, no GPU): a reported hang kills and replaces the engine; restarts back off, a start that fails twice and then works is just a slower restart, three failures in a row end the service with a message; an oversize log is rotated while the service runs; the existing lifecycle tests (SIGKILL of the engine, SIGTERM drain) still pass. 134 unit tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
244 lines
8.3 KiB
Rust
244 lines
8.3 KiB
Rust
//! Bounded service logs.
|
|
//!
|
|
//! The children (engine, gateway, API) write straight into `STATE/logs/NAME.log`, opened by the supervisor in append
|
|
//! mode and handed over as their standard output and error. Nothing in the children rotates them, so over weeks a
|
|
//! chatty engine would fill the disk. The supervisor therefore checks the directory every few seconds and *copy-truncates*
|
|
//! a file that passed its limit: the last `limit` bytes go to `NAME.log.1` (older generations shift to `.2`, `.3`, ...,
|
|
//! the oldest is deleted) and the live file is truncated in place. A writer with `O_APPEND` continues at the new end of
|
|
//! file, so no child has to be told; the only loss is the few lines written between the copy and the truncate.
|
|
//!
|
|
//! The write volume is small by construction (one copy of at most `limit` bytes per rotation, and the engine is quiet
|
|
//! unless a trace switch is on), which matters on a root NVMe that stalls under long writes. The total on disk is
|
|
//! bounded by `files * (keep + 1) * limit`.
|
|
use std::{
|
|
fs::File,
|
|
io::{self, Read, Seek, SeekFrom, Write},
|
|
path::{Path, PathBuf},
|
|
};
|
|
|
|
/// Per-file size that triggers a rotation.
|
|
pub const DEFAULT_LIMIT_BYTES: u64 = 16 << 20;
|
|
/// Rotated generations kept per log.
|
|
pub const DEFAULT_KEEP: usize = 3;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct Policy {
|
|
pub limit: u64,
|
|
pub keep: usize,
|
|
}
|
|
|
|
impl Default for Policy {
|
|
fn default() -> Self {
|
|
Policy {
|
|
limit: DEFAULT_LIMIT_BYTES,
|
|
keep: DEFAULT_KEEP,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn generation(path: &Path, n: usize) -> PathBuf {
|
|
let mut name = path.as_os_str().to_owned();
|
|
name.push(format!(".{n}"));
|
|
PathBuf::from(name)
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
fn private_create(path: &Path) -> io::Result<File> {
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create(true)
|
|
.truncate(true)
|
|
.mode(0o600)
|
|
.open(path)
|
|
}
|
|
|
|
#[cfg(not(unix))]
|
|
fn private_create(path: &Path) -> io::Result<File> {
|
|
std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create(true)
|
|
.truncate(true)
|
|
.open(path)
|
|
}
|
|
|
|
/// Rotate `path` if it is larger than the policy limit. `Ok(true)` when it was rotated.
|
|
pub fn rotate_if_needed(path: &Path, policy: Policy) -> io::Result<bool> {
|
|
let live = match std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.open(path)
|
|
{
|
|
Ok(file) => file,
|
|
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
|
|
Err(error) => return Err(error),
|
|
};
|
|
let len = live.metadata()?.len();
|
|
if len <= policy.limit {
|
|
return Ok(false);
|
|
}
|
|
// Shift the older generations (the oldest falls off the end).
|
|
if policy.keep > 0 {
|
|
let _ = std::fs::remove_file(generation(path, policy.keep));
|
|
for n in (1..policy.keep).rev() {
|
|
let from = generation(path, n);
|
|
if from.exists() {
|
|
std::fs::rename(&from, generation(path, n + 1))?;
|
|
}
|
|
}
|
|
// The newest `limit` bytes of the live file, snapped to the start of a line (at most `limit` bytes in memory).
|
|
let start = len - policy.limit;
|
|
let mut window = Vec::with_capacity(policy.limit as usize);
|
|
let mut live_read = live.try_clone()?;
|
|
live_read.seek(SeekFrom::Start(start))?;
|
|
live_read.take(policy.limit).read_to_end(&mut window)?;
|
|
let skip = if start > 0 {
|
|
window.iter().position(|&b| b == b'\n').map_or(0, |i| i + 1)
|
|
} else {
|
|
0
|
|
};
|
|
let mut copy = private_create(&generation(path, 1))?;
|
|
copy.write_all(&window[skip..])?;
|
|
copy.flush()?;
|
|
} else {
|
|
let _ = std::fs::remove_file(generation(path, 1));
|
|
}
|
|
// Truncate in place; appenders continue at offset 0 of the same inode.
|
|
live.set_len(0)?;
|
|
Ok(true)
|
|
}
|
|
|
|
/// Apply the policy to every `*.log` in `dir`. Returns the paths that were rotated.
|
|
pub fn enforce(dir: &Path, policy: Policy) -> Vec<(PathBuf, io::Result<bool>)> {
|
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
|
return Vec::new();
|
|
};
|
|
let mut results = Vec::new();
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if path.extension().is_some_and(|e| e == "log") && path.is_file() {
|
|
let outcome = rotate_if_needed(&path, policy);
|
|
if !matches!(outcome, Ok(false)) {
|
|
results.push((path, outcome));
|
|
}
|
|
}
|
|
}
|
|
results
|
|
}
|
|
|
|
/// Total bytes in `dir` (non-recursive), for the status report.
|
|
pub fn total_bytes(dir: &Path) -> u64 {
|
|
std::fs::read_dir(dir)
|
|
.map(|entries| {
|
|
entries
|
|
.flatten()
|
|
.filter_map(|e| e.metadata().ok())
|
|
.filter(|m| m.is_file())
|
|
.map(|m| m.len())
|
|
.sum()
|
|
})
|
|
.unwrap_or(0)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::io::Write;
|
|
|
|
fn dir(name: &str) -> PathBuf {
|
|
let d = std::env::temp_dir().join(format!("leleka-logs-{name}-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&d);
|
|
std::fs::create_dir_all(&d).unwrap();
|
|
d
|
|
}
|
|
|
|
fn append(path: &Path) -> File {
|
|
std::fs::OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(path)
|
|
.unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn a_small_log_is_left_alone() {
|
|
let d = dir("small");
|
|
let p = d.join("engine.log");
|
|
append(&p).write_all(b"hello\n").unwrap();
|
|
assert!(
|
|
!rotate_if_needed(
|
|
&p,
|
|
Policy {
|
|
limit: 100,
|
|
keep: 2
|
|
}
|
|
)
|
|
.unwrap()
|
|
);
|
|
assert_eq!(std::fs::read(&p).unwrap(), b"hello\n");
|
|
assert!(!rotate_if_needed(&d.join("none.log"), Policy::default()).unwrap());
|
|
std::fs::remove_dir_all(d).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn a_big_log_is_copy_truncated_and_the_appender_keeps_working() {
|
|
let d = dir("big");
|
|
let p = d.join("engine.log");
|
|
let mut writer = append(&p);
|
|
let policy = Policy {
|
|
limit: 10_000,
|
|
keep: 2,
|
|
};
|
|
let mut total = 0;
|
|
for i in 0..2000 {
|
|
let line = format!("line {i:05} xxxxxxxxxxxxxxxxxxxxxxxx\n");
|
|
writer.write_all(line.as_bytes()).unwrap();
|
|
total += line.len();
|
|
if i % 100 == 99 {
|
|
let _ = rotate_if_needed(&p, policy).unwrap();
|
|
assert!(std::fs::metadata(&p).unwrap().len() <= policy.limit + 2_000);
|
|
}
|
|
}
|
|
assert!(total > 50_000);
|
|
// Generations exist, are bounded, hold whole lines, and the newest generation ends before the live file starts.
|
|
let first = std::fs::read_to_string(generation(&p, 1)).unwrap();
|
|
assert!(first.len() as u64 <= policy.limit);
|
|
assert!(first.lines().all(|l| l.starts_with("line ")), "{first:?}");
|
|
assert!(generation(&p, 2).exists());
|
|
assert!(!generation(&p, 3).exists());
|
|
let live = std::fs::read_to_string(&p).unwrap();
|
|
let last_of_first: u32 = first.lines().last().unwrap()[5..10].parse().unwrap();
|
|
if let Some(first_live) = live.lines().next() {
|
|
let n: u32 = first_live[5..10].parse().unwrap();
|
|
assert!(n > last_of_first, "{n} {last_of_first}");
|
|
}
|
|
// The very last line is in the live file or the newest generation.
|
|
assert!(live.contains("line 01999") || first.contains("line 01999"));
|
|
std::fs::remove_dir_all(d).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn enforce_handles_every_log_in_the_directory_and_keep_zero_drops_history() {
|
|
let d = dir("enforce");
|
|
for name in ["a.log", "b.log"] {
|
|
append(&d.join(name)).write_all(&vec![b'x'; 5000]).unwrap();
|
|
}
|
|
append(&d.join("note.txt"))
|
|
.write_all(&vec![b'x'; 5000])
|
|
.unwrap();
|
|
let rotated = enforce(
|
|
&d,
|
|
Policy {
|
|
limit: 1000,
|
|
keep: 0,
|
|
},
|
|
);
|
|
assert_eq!(rotated.len(), 2);
|
|
assert_eq!(std::fs::metadata(d.join("a.log")).unwrap().len(), 0);
|
|
assert!(!d.join("a.log.1").exists());
|
|
assert_eq!(std::fs::metadata(d.join("note.txt")).unwrap().len(), 5000);
|
|
assert!(total_bytes(&d) >= 5000);
|
|
std::fs::remove_dir_all(d).unwrap();
|
|
}
|
|
}
|