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

259 lines
8.6 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);
}
if policy.keep > 0 {
shift_generations(path, policy.keep)?;
copy_newest(&live, path, len, policy.limit)?;
} 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)
}
/// Shift the older generations (the oldest falls off the end).
fn shift_generations(path: &Path, keep: usize) -> io::Result<()> {
let _ = std::fs::remove_file(generation(path, keep));
for n in (1..keep).rev() {
let from = generation(path, n);
if from.exists() {
std::fs::rename(&from, generation(path, n + 1))?;
}
}
Ok(())
}
/// The newest `limit` bytes of the live file, snapped to the start of a line (at most `limit` bytes in memory), as
/// generation 1.
fn copy_newest(live: &File, path: &Path, len: u64, limit: u64) -> io::Result<()> {
let start = len - limit;
let mut window = Vec::with_capacity(limit as usize);
let mut live_read = live.try_clone()?;
live_read.seek(SeekFrom::Start(start))?;
live_read.take(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()
}
/// 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);
check_generations_hold_whole_lines_in_order(&p, policy);
std::fs::remove_dir_all(d).unwrap();
}
fn check_generations_hold_whole_lines_in_order(p: &Path, policy: Policy) {
// 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"));
}
#[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();
}
}