- Logs: every unit's as they come (the last 500 first, 5000 kept), one unit's on its own, following or held; terminal colours stripped; a virtual list, so thousands of lines cost nothing. The follow starts when the page is first opened and reconnects by itself. - Linux (development, tests): the service's children get SIGKILL when it dies (PR_SET_PDEATHSIG), as the Job Object does on Windows; a killed service no longer leaves sing-box running (the e2e test leaked one per run). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
442 lines
15 KiB
Rust
442 lines
15 KiB
Rust
//! The supervisor: what systemd does for upstream. Each unit is one program, started,
|
|
//! watched, restarted with backoff when it dies, its output kept in a ring and a log file.
|
|
//! On Windows every child joins a Job Object that kills it with the service.
|
|
|
|
use std::collections::{BTreeMap, VecDeque};
|
|
use std::io::Write;
|
|
use std::path::PathBuf;
|
|
use std::process::Stdio;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|
|
|
use serde::Serialize;
|
|
use tokio::io::{AsyncBufReadExt, BufReader};
|
|
use tokio::process::Command;
|
|
use tokio::sync::{broadcast, watch};
|
|
|
|
/// How to run a unit. Two specs that compare equal need no restart.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct UnitSpec {
|
|
pub name: String,
|
|
pub program: PathBuf,
|
|
pub args: Vec<String>,
|
|
pub env: Vec<(String, String)>,
|
|
pub cwd: Option<PathBuf>,
|
|
/// Changes when a file the unit reads changes (its rendered config): a restart.
|
|
pub generation: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum UnitState {
|
|
Inactive,
|
|
Activating,
|
|
Active,
|
|
Deactivating,
|
|
Failed,
|
|
}
|
|
|
|
impl UnitState {
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::Inactive => "inactive",
|
|
Self::Activating => "activating",
|
|
Self::Active => "active",
|
|
Self::Deactivating => "deactivating",
|
|
Self::Failed => "failed",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct LogLine {
|
|
pub unit: String,
|
|
/// Unix time, milliseconds.
|
|
pub at: u64,
|
|
pub line: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct UnitStatus {
|
|
pub name: String,
|
|
pub state: UnitState,
|
|
pub pid: Option<u32>,
|
|
pub restarts: u32,
|
|
/// Why it failed last.
|
|
pub result: Option<String>,
|
|
pub since: Option<u64>,
|
|
}
|
|
|
|
const RING: usize = 2000;
|
|
/// A unit that fails this many times within `START_LIMIT_INTERVAL` stays failed.
|
|
const START_LIMIT: usize = 5;
|
|
const START_LIMIT_INTERVAL: Duration = Duration::from_secs(60);
|
|
/// A unit whose log file outgrows this starts a new one, keeping one old.
|
|
const LOG_FILE_MAX: u64 = 5 * 1024 * 1024;
|
|
|
|
struct Shared {
|
|
state: UnitState,
|
|
pid: Option<u32>,
|
|
restarts: u32,
|
|
result: Option<String>,
|
|
since: Option<u64>,
|
|
}
|
|
|
|
struct Unit {
|
|
spec: UnitSpec,
|
|
shared: Arc<Mutex<Shared>>,
|
|
stop: watch::Sender<bool>,
|
|
task: tokio::task::JoinHandle<()>,
|
|
}
|
|
|
|
pub struct Supervisor {
|
|
units: BTreeMap<String, Unit>,
|
|
logs: Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
|
|
log_dir: PathBuf,
|
|
feed: broadcast::Sender<LogLine>,
|
|
#[cfg(windows)]
|
|
job: Option<crate::job::Job>,
|
|
}
|
|
|
|
fn now_ms() -> u64 {
|
|
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
|
|
}
|
|
|
|
impl Supervisor {
|
|
pub fn new(log_dir: PathBuf) -> Self {
|
|
let (feed, _) = broadcast::channel(1024);
|
|
Self {
|
|
units: BTreeMap::new(),
|
|
logs: Arc::new(Mutex::new(BTreeMap::new())),
|
|
log_dir,
|
|
feed,
|
|
#[cfg(windows)]
|
|
job: crate::job::Job::new().map_err(|e| tracing::warn!("no job object: {e}")).ok(),
|
|
}
|
|
}
|
|
|
|
pub fn subscribe(&self) -> broadcast::Receiver<LogLine> {
|
|
self.feed.subscribe()
|
|
}
|
|
|
|
/// The last `n` log lines of `unit`, or of every unit by time.
|
|
pub fn tail(&self, unit: Option<&str>, n: usize) -> Vec<LogLine> {
|
|
let logs = self.logs.lock().unwrap();
|
|
let mut lines: Vec<LogLine> = match unit {
|
|
Some(u) => logs.get(u).map(|r| r.iter().cloned().collect()).unwrap_or_default(),
|
|
None => logs.values().flatten().cloned().collect(),
|
|
};
|
|
lines.sort_by_key(|l| l.at);
|
|
let skip = lines.len().saturating_sub(n);
|
|
lines.split_off(skip)
|
|
}
|
|
|
|
/// A line of the service's own about a unit, in that unit's log.
|
|
pub fn note(&self, unit: &str, line: impl Into<String>) {
|
|
push_log(&self.logs, &self.feed, &self.log_dir, unit, line.into());
|
|
}
|
|
|
|
pub fn status(&self) -> Vec<UnitStatus> {
|
|
self.units
|
|
.iter()
|
|
.map(|(name, u)| {
|
|
let s = u.shared.lock().unwrap();
|
|
UnitStatus { name: name.clone(), state: s.state, pid: s.pid, restarts: s.restarts, result: s.result.clone(), since: s.since }
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
pub fn state_of(&self, name: &str) -> UnitState {
|
|
self.units.get(name).map_or(UnitState::Inactive, |u| u.shared.lock().unwrap().state)
|
|
}
|
|
|
|
/// Runs `spec`, restarting the unit if it runs another spec, leaving it be if it runs this one.
|
|
pub fn ensure(&mut self, spec: UnitSpec) {
|
|
if let Some(u) = self.units.get(&spec.name) {
|
|
let alive = !u.task.is_finished();
|
|
if alive && u.spec == spec && u.shared.lock().unwrap().state != UnitState::Failed {
|
|
return;
|
|
}
|
|
}
|
|
self.start(spec);
|
|
}
|
|
|
|
/// Starts `spec`, stopping what ran under its name first.
|
|
pub fn start(&mut self, spec: UnitSpec) {
|
|
let name = spec.name.clone();
|
|
self.stop_now(&name);
|
|
let shared = Arc::new(Mutex::new(Shared { state: UnitState::Activating, pid: None, restarts: 0, result: None, since: Some(now_ms()) }));
|
|
let (stop_tx, stop_rx) = watch::channel(false);
|
|
let ctx = RunCtx {
|
|
spec: spec.clone(),
|
|
shared: shared.clone(),
|
|
logs: self.logs.clone(),
|
|
feed: self.feed.clone(),
|
|
log_dir: self.log_dir.clone(),
|
|
#[cfg(windows)]
|
|
job: self.job.as_ref().map(|j| j.handle()),
|
|
};
|
|
let task = tokio::spawn(run(ctx, stop_rx));
|
|
self.units.insert(name, Unit { spec, shared, stop: stop_tx, task });
|
|
}
|
|
|
|
/// Restarts a unit with the spec it has.
|
|
pub fn restart(&mut self, name: &str) -> bool {
|
|
match self.units.get(name).map(|u| u.spec.clone()) {
|
|
Some(spec) => {
|
|
self.start(spec);
|
|
true
|
|
}
|
|
None => false,
|
|
}
|
|
}
|
|
|
|
fn stop_now(&mut self, name: &str) {
|
|
if let Some(u) = self.units.remove(name) {
|
|
let _ = u.stop.send(true);
|
|
// The task kills the child as it sees the flag; it is not waited for here, but
|
|
// the next start of the unit waits for nothing either: a listener still held for a
|
|
// moment shows as one restart.
|
|
let shared = u.shared.clone();
|
|
tokio::spawn(async move {
|
|
let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await;
|
|
shared.lock().unwrap().state = UnitState::Inactive;
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Stops a unit and waits for its process to be gone.
|
|
pub async fn stop(&mut self, name: &str) {
|
|
if let Some(u) = self.units.remove(name) {
|
|
let _ = u.stop.send(true);
|
|
let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await;
|
|
}
|
|
}
|
|
|
|
pub fn names(&self) -> Vec<String> {
|
|
self.units.keys().cloned().collect()
|
|
}
|
|
|
|
pub async fn stop_all(&mut self) {
|
|
for name in self.names() {
|
|
self.stop(&name).await;
|
|
}
|
|
}
|
|
}
|
|
|
|
struct RunCtx {
|
|
spec: UnitSpec,
|
|
shared: Arc<Mutex<Shared>>,
|
|
logs: Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
|
|
feed: broadcast::Sender<LogLine>,
|
|
log_dir: PathBuf,
|
|
#[cfg(windows)]
|
|
job: Option<isize>,
|
|
}
|
|
|
|
fn push_log(
|
|
logs: &Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
|
|
feed: &broadcast::Sender<LogLine>,
|
|
log_dir: &std::path::Path,
|
|
unit: &str,
|
|
line: String,
|
|
) {
|
|
let entry = LogLine { unit: unit.to_owned(), at: now_ms(), line };
|
|
{
|
|
let mut logs = logs.lock().unwrap();
|
|
let ring = logs.entry(unit.to_owned()).or_default();
|
|
if ring.len() >= RING {
|
|
ring.pop_front();
|
|
}
|
|
ring.push_back(entry.clone());
|
|
}
|
|
let path = log_dir.join(format!("{unit}.log"));
|
|
if std::fs::metadata(&path).is_ok_and(|m| m.len() > LOG_FILE_MAX) {
|
|
let _ = std::fs::rename(&path, log_dir.join(format!("{unit}.log.1")));
|
|
}
|
|
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
|
|
let _ = writeln!(f, "{} {}", entry.at, entry.line);
|
|
}
|
|
let _ = feed.send(entry);
|
|
}
|
|
|
|
async fn run(ctx: RunCtx, mut stop: watch::Receiver<bool>) {
|
|
let mut failures: VecDeque<Instant> = VecDeque::new();
|
|
let mut backoff = Duration::from_millis(500);
|
|
let log = |line: String| push_log(&ctx.logs, &ctx.feed, &ctx.log_dir, &ctx.spec.name, line);
|
|
loop {
|
|
let mut cmd = Command::new(&ctx.spec.program);
|
|
cmd.args(&ctx.spec.args)
|
|
.envs(ctx.spec.env.iter().map(|(k, v)| (k, v)))
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped())
|
|
.kill_on_drop(true);
|
|
if let Some(cwd) = &ctx.spec.cwd {
|
|
cmd.current_dir(cwd);
|
|
}
|
|
#[cfg(windows)]
|
|
{
|
|
// No console window for the children.
|
|
cmd.creation_flags(0x0800_0000);
|
|
}
|
|
// On Linux (development, tests) the children end with the service, as the Job Object
|
|
// ends them on Windows, even when the service is killed outright. The signal comes when
|
|
// the spawning thread ends: a runtime worker, which lives as long as the service.
|
|
#[cfg(target_os = "linux")]
|
|
unsafe {
|
|
cmd.pre_exec(|| {
|
|
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
|
|
return Err(std::io::Error::last_os_error());
|
|
}
|
|
Ok(())
|
|
});
|
|
}
|
|
let mut child = match cmd.spawn() {
|
|
Ok(c) => c,
|
|
Err(e) => {
|
|
let why = format!("cannot start {}: {e}", ctx.spec.program.display());
|
|
log(format!("proxy-suite: {why}"));
|
|
let mut s = ctx.shared.lock().unwrap();
|
|
s.state = UnitState::Failed;
|
|
s.result = Some(why);
|
|
return;
|
|
}
|
|
};
|
|
#[cfg(windows)]
|
|
if let (Some(job), Some(handle)) = (ctx.job, child.raw_handle()) {
|
|
crate::job::assign(job, handle as isize);
|
|
}
|
|
{
|
|
let mut s = ctx.shared.lock().unwrap();
|
|
s.pid = child.id();
|
|
s.state = UnitState::Activating;
|
|
s.since = Some(now_ms());
|
|
}
|
|
log(format!("proxy-suite: started {} (pid {})", ctx.spec.program.display(), child.id().unwrap_or(0)));
|
|
for pipe in [child.stdout.take().map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Send + Unpin>), child.stderr.take().map(|p| Box::new(p) as _)].into_iter().flatten() {
|
|
let logs = ctx.logs.clone();
|
|
let feed = ctx.feed.clone();
|
|
let dir = ctx.log_dir.clone();
|
|
let unit = ctx.spec.name.clone();
|
|
tokio::spawn(async move {
|
|
let mut lines = BufReader::new(pipe).lines();
|
|
while let Ok(Some(line)) = lines.next_line().await {
|
|
push_log(&logs, &feed, &dir, &unit, line);
|
|
}
|
|
});
|
|
}
|
|
// Up once it has lived a moment: none of the backends tells when it is ready.
|
|
let started = Instant::now();
|
|
let status = loop {
|
|
tokio::select! {
|
|
status = child.wait() => break Some(status),
|
|
_ = tokio::time::sleep(Duration::from_millis(700)), if ctx.shared.lock().unwrap().state == UnitState::Activating => {
|
|
ctx.shared.lock().unwrap().state = UnitState::Active;
|
|
}
|
|
_ = stop.changed() => {
|
|
if *stop.borrow() {
|
|
ctx.shared.lock().unwrap().state = UnitState::Deactivating;
|
|
let _ = child.start_kill();
|
|
let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;
|
|
let mut s = ctx.shared.lock().unwrap();
|
|
s.state = UnitState::Inactive;
|
|
s.pid = None;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
let why = match status {
|
|
Some(Ok(s)) => format!("exited ({s})"),
|
|
Some(Err(e)) => format!("lost ({e})"),
|
|
None => "stopped".into(),
|
|
};
|
|
log(format!("proxy-suite: {} {why}", ctx.spec.name));
|
|
let now = Instant::now();
|
|
failures.push_back(now);
|
|
while failures.front().is_some_and(|t| now - *t > START_LIMIT_INTERVAL) {
|
|
failures.pop_front();
|
|
}
|
|
{
|
|
let mut s = ctx.shared.lock().unwrap();
|
|
s.pid = None;
|
|
s.result = Some(why.clone());
|
|
if failures.len() >= START_LIMIT {
|
|
s.state = UnitState::Failed;
|
|
drop(s);
|
|
log(format!("proxy-suite: {} failed {START_LIMIT} times in a minute; not restarting it", ctx.spec.name));
|
|
return;
|
|
}
|
|
s.state = UnitState::Activating;
|
|
s.restarts += 1;
|
|
}
|
|
// A run that lasted a while starts the backoff over.
|
|
if started.elapsed() > Duration::from_secs(30) {
|
|
backoff = Duration::from_millis(500);
|
|
}
|
|
tokio::select! {
|
|
_ = tokio::time::sleep(backoff) => {}
|
|
_ = stop.changed() => {
|
|
if *stop.borrow() {
|
|
ctx.shared.lock().unwrap().state = UnitState::Inactive;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
backoff = (backoff * 2).min(Duration::from_secs(30));
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn spec(name: &str, program: &str, args: &[&str]) -> UnitSpec {
|
|
UnitSpec {
|
|
name: name.into(),
|
|
program: program.into(),
|
|
args: args.iter().map(|s| s.to_string()).collect(),
|
|
env: Vec::new(),
|
|
cwd: None,
|
|
generation: "1".into(),
|
|
}
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn a_unit_runs_logs_and_stops() {
|
|
let dir = std::env::temp_dir().join(format!("ps-units-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let mut sup = Supervisor::new(dir.clone());
|
|
sup.start(spec("echo", "sh", &["-c", "echo hello; sleep 30"]));
|
|
tokio::time::sleep(Duration::from_millis(1200)).await;
|
|
assert_eq!(sup.state_of("echo"), UnitState::Active);
|
|
assert!(sup.tail(Some("echo"), 10).iter().any(|l| l.line == "hello"));
|
|
sup.stop("echo").await;
|
|
assert_eq!(sup.state_of("echo"), UnitState::Inactive);
|
|
assert!(std::fs::read_to_string(dir.join("echo.log")).unwrap().contains("hello"));
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn a_dying_unit_is_restarted_then_given_up_on() {
|
|
let dir = std::env::temp_dir().join(format!("ps-units-die-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let mut sup = Supervisor::new(dir);
|
|
sup.start(spec("dies", "sh", &["-c", "exit 3"]));
|
|
tokio::time::sleep(Duration::from_secs(10)).await;
|
|
let st = sup.status();
|
|
assert_eq!(st[0].state, UnitState::Failed);
|
|
assert!(st[0].restarts >= 3, "{st:?}");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_missing_program_fails_at_once() {
|
|
let mut sup = Supervisor::new(std::env::temp_dir());
|
|
sup.start(spec("missing", "/nonexistent/program", &[]));
|
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
|
assert_eq!(sup.state_of("missing"), UnitState::Failed);
|
|
}
|
|
}
|