diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bff1415..530ce9d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ and listed with their assets on the uses a skipped container's address is an error in the profile's check. A lane on a node does not create what its profile skips. A file with `skip` wants `requires = "0.21.0"`. +- **A service's `stop` command** (ADR-0059, #245): `[services.] + stop = "docker rm -f api{lane_suffix}-{port}"` ends what `run` started + outside its process tree, a container of a `docker run` service. It + runs whenever an instance ends (a stop, a replacement, a failed start, + one that ended by itself), before the graceful signal, with the + instance's placeholders, at most 30 s; after a crash the next start runs + the ones recorded. `docs/stack-file.md` describes a container as a + service (`--init`, `--rm`, a name per instance). A file with `stop` says + `requires = "0.21.0"`. ## [0.20.0] - 2026-10-23 diff --git a/crates/devstack-config/src/lib.rs b/crates/devstack-config/src/lib.rs index 1f7536bd..c1269705 100644 --- a/crates/devstack-config/src/lib.rs +++ b/crates/devstack-config/src/lib.rs @@ -51,6 +51,10 @@ pub const ANNOUNCED_SINCE: &str = "0.20.0"; /// file that sets it wants `requires` at least this. pub const SKIP_SINCE: &str = "0.21.0"; +/// The first devstack that knows `[services.] stop` (ADR-0059): a +/// file that sets it wants `requires` at least this. +pub const STOP_SINCE: &str = "0.21.0"; + /// `"1.2.3"`, `"v1.2"`, `"1"` as numbers; `None` when malformed. A /// pre-release or build suffix (`1.2.3-rc1`, `1.2.3+abc`) is ignored here; /// [`version_order`] takes it into account. diff --git a/crates/devstack-config/src/model.rs b/crates/devstack-config/src/model.rs index 231ce15c..422b9959 100644 --- a/crates/devstack-config/src/model.rs +++ b/crates/devstack-config/src/model.rs @@ -131,6 +131,8 @@ pub struct ServiceProfile { pub build: Option, pub output: Option, pub run: Option, + /// What ends what `run` started outside its process tree (ADR-0059). + pub stop: Option, pub spa: Option, pub cwd: Option, pub health: Option, @@ -256,6 +258,7 @@ impl Stack { // gives itself is set below. if k == Kind::Static { svc.run = String::new(); + svc.stop = None; } if k != Kind::Devserver { svc.rebuild = None; @@ -288,6 +291,9 @@ impl Stack { if let Some(r) = &o.run { svc.run = r.clone(); } + if o.stop.is_some() { + svc.stop = o.stop.clone(); + } if o.spa.is_some() { svc.spa = o.spa; } @@ -838,6 +844,12 @@ pub struct Service { /// serves the artifact itself). #[serde(default)] pub run: String, + /// Command run whenever an instance ends, before the graceful signal + /// (ADR-0059): for what `run` started outside its process tree, a + /// container (`docker rm -f api{lane_suffix}-{port}`). The instance's + /// placeholders, as `run`; at most 30 s; a failure does not hold up the + /// stop. + pub stop: Option, /// `kind = "static"`: answer paths without a file extension with /// `index.html` (client-side routes of a single-page app). Default `true`. pub spa: Option, diff --git a/crates/devstack-config/src/validate.rs b/crates/devstack-config/src/validate.rs index 030d7aa9..3f99c36a 100644 --- a/crates/devstack-config/src/validate.rs +++ b/crates/devstack-config/src/validate.rs @@ -602,6 +602,19 @@ pub fn validate(stack: &Stack) -> Vec { "missing `run`: the command that starts the service", ); } + if let Some(stop) = &svc.stop { + if svc.kind == Kind::Static { + c.err( + format!("{p}.stop"), + "kind `static` has no `stop`: devstack serves the built files itself, nothing runs", + ); + } else if stop.trim().is_empty() { + c.err( + format!("{p}.stop"), + "is empty: leave it out, or give the command that ends what `run` started (ADR-0059)", + ); + } + } if svc.spa.is_some() && svc.kind != Kind::Static { c.err(format!("{p}.spa"), "`spa` belongs to `kind = \"static\"`"); } @@ -797,6 +810,9 @@ pub fn validate(stack: &Stack) -> Vec { artifact: svc.build.is_some(), }; c.text(&format!("{p}.run"), &svc.run, scope); + if let Some(stop) = &svc.stop { + c.text(&format!("{p}.stop"), stop, scope); + } for (k, field) in [("build", &svc.build), ("output", &svc.output)] { if let Some(v) = field { c.text(&format!("{p}.{k}"), v, Scope::Build); @@ -995,8 +1011,9 @@ pub fn validate(stack: &Stack) -> Vec { const FIRST_LANES: u32 = 3; /// What a valid stack file may want changed (`devstack check` prints them): -/// `[stack] reviewed` without the `requires` that keeps an older devstack -/// from failing on it; two services whose ports differ by one of the first +/// a newer key (`[stack] reviewed`, `announced_ports`, a service's `stop`) +/// without the `requires` that keeps an older devstack from failing on it; +/// two services whose ports differ by one of the first /// few multiples of `[lanes] port_step`, so that one of the first lanes /// would run one of them on the other's port. The daemon skips such lane /// numbers, so lane 1 is not on `port + port_step` as the file suggests. @@ -1058,6 +1075,37 @@ pub fn warnings(stack: &Stack) -> Vec { }); } } + let stop = crate::version_order(crate::STOP_SINCE); + if stack + .stack + .requires + .as_deref() + .is_none_or(|r| crate::version_order(r) < stop) + { + let in_profiles = stack.profiles.iter().flat_map(|(p, profile)| { + profile + .services + .iter() + .filter(|(_, o)| o.stop.is_some()) + .map(move |(n, _)| format!("profiles.{p}.services.{n}.stop")) + }); + let paths: Vec = stack + .services + .iter() + .filter(|(_, svc)| svc.stop.is_some()) + .map(|(n, _)| format!("services.{n}.stop")) + .chain(in_profiles) + .collect(); + for path in paths { + out.push(Issue { + path, + message: format!( + "a devstack before {v} does not know this key and fails on it with \"unknown field\": `requires = \"{v}\"` makes it ask to be updated instead", + v = crate::STOP_SINCE + ), + }); + } + } if step == 0 { return out; } diff --git a/crates/devstack-config/tests/profiles.rs b/crates/devstack-config/tests/profiles.rs index 1b7a4258..2969b309 100644 --- a/crates/devstack-config/tests/profiles.rs +++ b/crates/devstack-config/tests/profiles.rs @@ -294,3 +294,28 @@ fn skip_wants_requires_at_its_first_devstack() { s.stack.requires = Some(SKIP_SINCE.into()); assert!(warnings(&s).iter().all(|i| i.path != "profiles.lite.skip")); } + +#[test] +fn a_profile_sets_a_services_stop_and_a_static_one_drops_it() { + let s = load( + r#" +[services.ocr] +run = "docker run --rm --init --name ocr{lane_suffix}-{port} -p {port}:8000 ocr:dev" +stop = "docker rm -f ocr{lane_suffix}-{port}" +port = 5100 + +[profiles.acceptance.services.mailer] +stop = "mailer --stop" + +[profiles.acceptance.services.ocr] +kind = "static" +build = "npm run build" +output = "dist" +"#, + ) + .unwrap(); + let a = s.with_profile("acceptance").unwrap(); + assert_eq!(a.services["mailer"].stop.as_deref(), Some("mailer --stop")); + assert_eq!(a.services["ocr"].stop, None); + assert!(s.services["mailer"].stop.is_none()); +} diff --git a/crates/devstack-config/tests/stack_files.rs b/crates/devstack-config/tests/stack_files.rs index f6863fa3..f757bbc0 100644 --- a/crates/devstack-config/tests/stack_files.rs +++ b/crates/devstack-config/tests/stack_files.rs @@ -1025,3 +1025,40 @@ services: assert!(!all.contains("DEVSTACK_PORT_X"), "{all}"); assert_eq!(w.len(), 3, "each once: {all}"); } + +#[test] +fn a_services_stop_takes_the_placeholders_of_its_run() { + use devstack_config::{STOP_SINCE, validate::warnings}; + let text = MINIMAL.replace( + "port = 5000\n", + "port = 5000\nstop = \"docker rm -f api{lane_suffix}-{port}\"\n", + ); + let mut s = from_str(&text, Path::new("t")).unwrap(); + assert_eq!( + s.services["api"].stop.as_deref(), + Some("docker rm -f api{lane_suffix}-{port}") + ); + let w = warnings(&s); + assert!( + w.iter() + .any(|i| i.path == "services.api.stop" && i.message.contains(STOP_SINCE)), + "{w:?}" + ); + s.stack.requires = Some(STOP_SINCE.into()); + assert!(warnings(&s).is_empty()); + + // An unknown placeholder, an empty command and a static service's stop. + let all = invalid(&MINIMAL.replace("port = 5000\n", "port = 5000\nstop = \"rm {nope}\"\n")) + .join("\n"); + assert!(all.contains("services.api.stop"), "{all}"); + let all = invalid(&MINIMAL.replace("port = 5000\n", "port = 5000\nstop = \" \"\n")).join("\n"); + assert!(all.contains("services.api.stop: is empty"), "{all}"); + let all = invalid(&format!( + "{MINIMAL}[services.site]\nkind = \"static\"\nbuild = \"npm run build\"\noutput = \"dist\"\nport = 4300\nstop = \"true\"\n" + )) + .join("\n"); + assert!( + all.contains("services.site.stop: kind `static` has no `stop`"), + "{all}" + ); +} diff --git a/crates/devstack-daemon/src/state.rs b/crates/devstack-daemon/src/state.rs index daae07ef..297505c6 100644 --- a/crates/devstack-daemon/src/state.rs +++ b/crates/devstack-daemon/src/state.rs @@ -354,12 +354,28 @@ pub struct Persisted { /// Process trees to clean up after a crash (Linux; ADR-0016). #[serde(default)] pub records: Vec, + /// The `stop` command of every running instance that has one + /// (ADR-0059), expanded: what the next start runs after a crash. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub stops: Vec, /// Service -> the candidate a promotion gate holds (ADR-0013), so the /// gate outlives a daemon restart. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub held: BTreeMap, } +/// An instance's expanded `stop` command (ADR-0059) as `state.json` keeps +/// it, without the instance's environment (it can hold secrets). +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct StopRecord { + /// The instance's cleanup record (`@`). + pub record: String, + pub command: String, + pub cwd: PathBuf, + /// The instance's log, which its output goes to. + pub log: PathBuf, +} + /// A held candidate as `state.json` keeps it. #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct HeldRecord { diff --git a/crates/devstack-daemon/src/supervisor/lifecycle.rs b/crates/devstack-daemon/src/supervisor/lifecycle.rs index 098b4417..66606f7d 100644 --- a/crates/devstack-daemon/src/supervisor/lifecycle.rs +++ b/crates/devstack-daemon/src/supervisor/lifecycle.rs @@ -1,11 +1,11 @@ //! The slot lifecycle: start, stop, monitor. use super::{ - Instance, JOB_TIMEOUT, KEEP_BUILD_LOGS, KEEP_RUN_LOGS, STOPPED, Supervisor, free_port, + Instance, JOB_TIMEOUT, KEEP_BUILD_LOGS, KEEP_RUN_LOGS, STOPPED, StopCmd, Supervisor, free_port, on_this_platform, port_in_use, tail, }; use crate::proxy::{Proxy, Upstream, Waiting}; -use crate::state::{EventBody, Status, now_ms}; +use crate::state::{EventBody, Status, StopRecord, now_ms}; use devstack_config::model::{Kind, Service}; use devstack_env::Context; use devstack_proc::Spec; @@ -24,6 +24,80 @@ pub(super) const SETTLE: Duration = Duration::from_millis(500); pub(super) const STABLE: Duration = Duration::from_secs(300); const MAX_EXITS: u32 = 5; +/// How long a service's `stop` command may run (ADR-0059). +pub(super) const STOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(30); + +/// Run an instance's `stop` command (ADR-0059) to its end, at most +/// [`STOP_COMMAND_TIMEOUT`], its output appended to the instance's `log`. +/// A failure is said there and as a diagnostic; it never holds up the stop. +#[allow(clippy::too_many_arguments)] +pub(super) fn run_stop( + lane: &str, + service: &str, + record: &str, + command: &str, + cwd: &Path, + env: &BTreeMap, + log: &Path, + opts: &devstack_proc::Options, +) { + use std::io::Write; + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(log) + .ok(); + let outcome = (|| -> Result<(), String> { + let out = file + .as_mut() + .ok_or_else(|| format!("cannot open {}", log.display()))?; + let _ = writeln!(out, "\n[devstack] stop: {command}"); + let spec = Spec { + name: format!("{record}-stop"), + command: command.to_string(), + cwd: cwd.to_path_buf(), + env: env.clone(), + log: out.try_clone().map_err(|e| e.to_string())?, + }; + let (mut tree, _) = devstack_proc::spawn(spec, opts).map_err(|e| e.to_string())?; + let t0 = Instant::now(); + loop { + if let Some(code) = tree.try_exit_code() { + // What it left of its own tree goes with it. + tree.kill(); + return match code { + 0 => Ok(()), + c => Err(format!( + "exited with code {}", + crate::state::exit_code_text(c) + )), + }; + } + if t0.elapsed() >= STOP_COMMAND_TIMEOUT { + tree.kill(); + return Err(format!( + "still ran after {} s, and was ended", + STOP_COMMAND_TIMEOUT.as_secs() + )); + } + std::thread::sleep(Duration::from_millis(50)); + } + })(); + if let Err(e) = outcome { + if let Some(out) = file.as_mut() { + let _ = writeln!(out, "[devstack] stop failed: {e}"); + } + crate::diag::warn( + "service_stop_failed", + serde_json::json!({ + "lane": lane, + "service": service, + "error": e, + }), + ); + } +} + impl Supervisor { /// Infra, then every autostart service for this platform, in order; a /// service that fails holds back only what comes `after` it. @@ -196,6 +270,8 @@ impl Supervisor { } s.watch.clear(); s.promote = None; + // `stop` ends what `run` starts (ADR-0059). + s.stop = None; s } _ => svc.clone(), @@ -596,8 +672,7 @@ impl Supervisor { let ready = match self.wait_instance(svc, &mut inst, &cancel) { Ok(s) => s, Err(e) => { - inst.tree.kill(); - self.forget_record(&inst.record); + self.end(&mut inst, None); refuse(&e); return Err(e); } @@ -609,8 +684,7 @@ impl Supervisor { if (proxy.is_some() || fronted) && let Some(e) = self.main_ports_elsewhere(name, svc) { - inst.tree.kill(); - self.forget_record(&inst.record); + self.end(&mut inst, None); return Err(e); } if fronted && let Some(p) = inst.port { @@ -633,7 +707,9 @@ impl Supervisor { self.release_held(name, None); } if svc.kind == Kind::Job { - self.forget_record(&inst.record); + // Done: its `stop` all the same (ADR-0059), for a container its + // process left. + self.end(&mut inst, None); self.set_status(name, ready); return Ok(()); } @@ -674,6 +750,16 @@ impl Supervisor { let lookup = |k: &str| ctx.var(k); let command = devstack_config::interpolate::expand(&svc.run, &ctx, &lookup) .map_err(|e| format!("run: {e}"))?; + // Expanded now, so it addresses this instance (its port, its lane) + // whenever it ends (ADR-0059). + let stop = svc + .stop + .as_ref() + .map(|s| { + devstack_config::interpolate::expand(s, &ctx, &lookup) + .map_err(|e| format!("stop: {e}")) + }) + .transpose()?; for d in &svc.ensure_dirs { let dir = devstack_config::interpolate::expand(d, &ctx, &lookup) .map_err(|e| format!("ensure_dirs: {e}"))?; @@ -705,6 +791,11 @@ impl Supervisor { let dir = log.parent().unwrap(); crate::diag::prune(dir, "run-", KEEP_RUN_LOGS); crate::diag::prune(dir, "build-", KEEP_BUILD_LOGS); + let stop = stop.map(|command| StopCmd { + command, + cwd: cwd.clone(), + env: env_map.clone(), + }); let spec = Spec { name: record.clone(), command, @@ -717,6 +808,15 @@ impl Supervisor { let mut p = self.persisted.lock().unwrap(); p.records.retain(|r| r.name != record); p.records.push(rec); + p.stops.retain(|s| s.record != record); + if let Some(s) = &stop { + p.stops.push(StopRecord { + record: record.clone(), + command: s.command.clone(), + cwd: s.cwd.clone(), + log: log.clone(), + }); + } p.save(&self.state_dir); } Ok(Instance { @@ -726,15 +826,43 @@ impl Supervisor { log, record, started: Instant::now(), + stop, }) } pub(super) fn forget_record(&self, record: &str) { let mut p = self.persisted.lock().unwrap(); p.records.retain(|r| r.name != record); + p.stops.retain(|s| s.record != record); p.save(&self.state_dir); } + /// End an instance, the one way every end goes: its `stop` command first + /// (ADR-0059), then the graceful signal and a kill after `graceful` + /// (ADR-0009), or a kill at once (`None`); then its records go. + pub(super) fn end(&self, inst: &mut Instance, graceful: Option) { + if let Some(s) = &inst.stop { + let service = inst.record.split('@').next().unwrap_or(&inst.record); + run_stop( + &self.lane, + service, + &inst.record, + &s.command, + &s.cwd, + &s.env, + &inst.log, + &self.proc_opts, + ); + } + match graceful { + Some(t) => { + inst.tree.stop(t); + } + None => inst.tree.kill(), + } + self.forget_record(&inst.record); + } + fn context( &self, svc: &Service, @@ -917,8 +1045,7 @@ impl Supervisor { ran = i.started.elapsed(); let left = i.tree.pids().len(); build = i.build_id.clone(); - i.tree.kill(); - me.forget_record(&i.record); + me.end(&mut i, None); crate::diag::warn( "service_exited", serde_json::json!({ @@ -1019,8 +1146,7 @@ impl Supervisor { self.set_front(name, crate::tcpfwd::FrontState::Refuse); } if let Some(mut i) = inst { - i.tree.stop(Duration::from_secs(20)); - self.forget_record(&i.record); + self.end(&mut i, Some(Duration::from_secs(20))); } self.set_status(name, Status::Stopped); Ok(()) diff --git a/crates/devstack-daemon/src/supervisor/mod.rs b/crates/devstack-daemon/src/supervisor/mod.rs index 64d937d5..28af8deb 100644 --- a/crates/devstack-daemon/src/supervisor/mod.rs +++ b/crates/devstack-daemon/src/supervisor/mod.rs @@ -44,6 +44,16 @@ struct Instance { record: String, /// When it was spawned: how long it ran, when it exits by itself. started: Instant, + /// Its `stop` command, expanded when it started (ADR-0059). + stop: Option, +} + +/// An instance's `stop` command (ADR-0059): what ends what its `run` +/// started outside its tree, with the instance's directory and environment. +struct StopCmd { + command: String, + cwd: PathBuf, + env: BTreeMap, } pub(crate) struct Slot { @@ -419,6 +429,26 @@ impl Supervisor { let persisted = Persisted::load(&state_dir); // ADR-0016: kill what a crashed previous instance left (Linux; a no-op on Windows). devstack_proc::cleanup(&persisted.records); + // ADR-0059: and end what its `stop` commands were for (a container + // its process started), with devstack's own environment. + std::thread::scope(|scope| { + for s in &persisted.stops { + let (lane, opts) = (&lane, &proc_opts); + scope.spawn(move || { + let service = s.record.split('@').next().unwrap_or(&s.record); + lifecycle::run_stop( + lane, + service, + &s.record, + &s.command, + &s.cwd, + &BTreeMap::new(), + &s.log, + opts, + ); + }); + } + }); // A held candidate stays held across a daemon restart (ADR-0013). let held = persisted .held @@ -456,6 +486,7 @@ impl Supervisor { persisted: Mutex::new(Persisted { main: persisted.main, records: Vec::new(), + stops: Vec::new(), held: persisted.held, }), seq: AtomicU64::new(0), diff --git a/crates/devstack-daemon/src/supervisor/replace.rs b/crates/devstack-daemon/src/supervisor/replace.rs index e5f7e189..1d23bd4d 100644 --- a/crates/devstack-daemon/src/supervisor/replace.rs +++ b/crates/devstack-daemon/src/supervisor/replace.rs @@ -212,15 +212,13 @@ The running instance was left as it was." Err(e) => return fail(e), }; if let Err(e) = self.wait_instance(svc, &mut candidate, &cancel) { - candidate.tree.kill(); - self.forget_record(&candidate.record); + self.end(&mut candidate, None); return fail(e); } // A lane took the main ports meanwhile (`promote --lane`): the // proxy forwards there now, and stays so. if let Some(e) = self.main_ports_elsewhere(name, svc) { - candidate.tree.kill(); - self.forget_record(&candidate.record); + self.end(&mut candidate, None); return fail(e); } @@ -241,8 +239,7 @@ The running instance was left as it was." Err(e) => return self.running_without_workers(name, svc, e), }; if let Err(e) = self.wait_instance(svc, &mut fin, &cancel) { - fin.tree.kill(); - self.forget_record(&fin.record); + self.end(&mut fin, None); return self.running_without_workers(name, svc, e); } let without_workers = self.switch_to(name, &proxy, fin); @@ -294,8 +291,7 @@ The running instance was left as it was." if let Some(port) = old.port { proxy.drain(port, Duration::from_secs(5)); } - old.tree.stop(Duration::from_secs(10)); - self.forget_record(&old.record); + self.end(&mut old, Some(Duration::from_secs(10))); } } diff --git a/crates/devstack/tests/daemon_lifecycle.rs b/crates/devstack/tests/daemon_lifecycle.rs index 772b81e2..fb939a76 100644 --- a/crates/devstack/tests/daemon_lifecycle.rs +++ b/crates/devstack/tests/daemon_lifecycle.rs @@ -1556,6 +1556,66 @@ run = "{brief}" s.ok(&["down"]); } +/// A service's `stop` (ADR-0059) runs when devstack stops an instance, with +/// that instance's port, into its log; after the daemon died, the next start +/// runs the one it recorded. +#[test] +fn a_services_stop_ends_what_its_run_started() { + if !enabled("DEVSTACK_INTEGRATION") { + eprintln!("skipped: set DEVSTACK_INTEGRATION=1"); + return; + } + let s = Stack::new(false); + let stopped = s.dir.path().join("stopped.txt"); + // No digit before `>>`: `sh` would read it as a file descriptor. + let stop = format!("echo stopped-{{port}} >> \"{}\"", stopped.display()); + std::fs::write( + s.file(), + format!( + r#"version = 1 +[stack] +name = "stops" +[services.box] +run = "{run}" +stop = '{stop}' +port = {port} +"#, + run = runs_for(300), + port = s.port, + ), + ) + .unwrap(); + let stops = || std::fs::read_to_string(&stopped).unwrap_or_default(); + let instance_port = || s.service_view("box")["instance_port"].as_u64().unwrap_or(0); + + s.ok(&["up"]); + let first = instance_port(); + assert!(first != 0, "{}", s.diag()); + s.ok(&["stop", "box"]); + assert!( + stops().contains(&format!("stopped-{first}")), + "the stop of {first}: {}\n{}", + stops(), + s.diag() + ); + let log = s.ok(&["logs", "box"]); + assert!(log.contains("[devstack] stop: echo stopped-"), "{log}"); + + // The daemon dies hard: the next start runs the recorded stop. + s.ok(&["start", "box"]); + let second = instance_port(); + assert!(second != 0 && second != first, "{}", s.diag()); + kill_hard(s.daemon_pid()); + s.ok(&["up"]); + assert!( + stops().contains(&format!("stopped-{second}")), + "the stop {second} recorded: {}\n{}", + stops(), + s.diag() + ); + s.ok(&["down"]); +} + /// A command that runs for about `s` seconds. fn runs_for(s: u32) -> String { if cfg!(windows) { diff --git a/docs/adr/0009-the-daemon-owns-every-process-tree.md b/docs/adr/0009-the-daemon-owns-every-process-tree.md index 42db8be8..47324c58 100644 --- a/docs/adr/0009-the-daemon-owns-every-process-tree.md +++ b/docs/adr/0009-the-daemon-owns-every-process-tree.md @@ -3,7 +3,7 @@ - **Status:** Accepted (2026-10-14) - **Date:** 2026-10-14 - **Deciders:** project owner -- **Related:** [ADR-0005](0005-rust-for-daemon-and-cli.md), plan phase 0 spike (a) +- **Related:** [ADR-0005](0005-rust-for-daemon-and-cli.md), plan phase 0 spike (a), [ADR-0059](0059-a-services-stop-command-ends-what-its-run-started.md) (a service's `stop` command ends what its process started outside the tree, a container say) ## Context diff --git a/docs/adr/0059-a-services-stop-command-ends-what-its-run-started.md b/docs/adr/0059-a-services-stop-command-ends-what-its-run-started.md new file mode 100644 index 00000000..9b9922da --- /dev/null +++ b/docs/adr/0059-a-services-stop-command-ends-what-its-run-started.md @@ -0,0 +1,123 @@ +# ADR-0059: A service's `stop` command ends what its `run` started outside its process tree + +- **Status:** Accepted (2026-10-23) +- **Date:** 2026-10-23 +- **Deciders:** project owner +- **Related:** [#245](https://github.com/nuetzliches/devstack/issues/245), [ADR-0009](0009-the-daemon-owns-every-process-tree.md), [ADR-0016](0016-a-daemon-restart-is-a-clean-restart.md), [ADR-0004](0004-infrastructure-is-delegated-to-compose.md), [ADR-0041](0041-a-profile-says-how-a-lane-runs-for-a-purpose.md) + +## Context + +A service developed in the repository whose runtime needs Linux tools (an +API with OCR libraries, say) cannot run natively on a Windows machine. It +can run as a service with `build = "docker build -t img ..."` and `run = +"docker run --rm -p {port}:8000 img"`, and so get `watch`, candidates and a +lane's own `{port}`, which a Compose container does not get. + +ADR-0009 owns the `docker` CLI's process tree, not the container: that +lives in Docker's VM. Measured with devstack 0.20.0 on Windows 11 and +Docker Desktop (#245): + +- the graceful stop reaches the container: `CTRL_BREAK` to the service's + process group, which the `docker run` CLI forwards to the container as + `SIGINT` (`--sig-proxy`, the default). With `docker run --rm --init alpine + sleep 300` the stop took 0 s and the container was gone, for `devstack + stop` and `devstack down` alike; +- without `--init`, `sleep` is the container's PID 1, which has no default + action for `SIGINT` and ignores it. devstack waited the 20 s, killed the + CLI, and the container kept running. + +So a container whose process handles the signal ends with its service +today. What still leaves one behind is everything that ends the CLI +without the container: a process that ignores the signal (the kill after +the timeout), the CLI killed or crashed on its own, a start that failed its +health check, and a daemon that died (its job object kills the CLI, ADR-0009, +and nothing tells the container). The container left running holds memory +and CPU, and its published port: the next instance on the same port fails +with "port is already allocated", a failed start although the code is fine. +`docker rm -f` before `docker run` in `run` is no way out: with a fixed name +it removes the main instance while a candidate starts. + +## Decision + +1. **`[services.] stop`** is a command line devstack runs whenever an + instance of the service ends: a stop, a restart, a `down`, the old + instance a candidate replaced, a start or candidate that failed or was + cancelled, and an instance that ended on its own (its root exited, a + job included). It runs **before** the graceful signal, so a process that + ignores the signal does not cost the timeout, and the command decides how + politely (`docker stop -t 10 ...` or `docker rm -f ...`). +2. **It addresses the instance that ends.** It is expanded when the + instance starts, with the instance's placeholders, the same as `run`: + `{port}` (the instance's own port, internal behind the proxy), + `{artifact}`, `{repo}`, `{lane}`, `{lane_suffix}`, `{is_main}`, + `{service.…}`, `{compose.…}` and `${VAR}`. It runs in the instance's + working directory with its environment. A container named + `api{lane_suffix}-{port}` in `run` is that name in `stop`, for the main + instance, a candidate and every lane. +3. **It is bounded and never blocks the stop.** It may run 30 s; its output + goes into the instance's log. A non-zero exit or the timeout is written + there and reported as a diagnostic; the stop goes on as ADR-0009 says: + graceful signal, wait, kill. +4. **A daemon that died still runs it.** The expanded command, its working + directory and the instance's log are recorded with the instance's + cleanup record in `state.json` (ADR-0016). The next start of that tree's + supervisor (the daemon's start for the main tree, the lane's start for a + lane) runs every recorded `stop` before anything starts, then forgets + them. It runs with devstack's own environment, not the service's: the + service's environment can hold secrets and is not written to disk. +5. **A profile may set it** (`[profiles..services.] stop`), + like `run`. `kind = "static"` has no process and no `stop`; a profile + that makes a service static drops it. In hot-reload mode the service runs + its `hot_reload` command instead of `run`, and `stop` does not apply. +6. **Format.** `stop` is new and optional; files without it are unchanged + (ADR-0023). A file that uses it says `requires = "0.21.0"`, and `devstack + check` warns when it does not. + +## Alternatives considered + +- **Documentation only (`--init`, a process that handles `SIGINT`).** It is + documented as well, and is enough for a clean stop. It does not cover a + CLI killed on its own, a failed start, the kill after the timeout or a + dead daemon, which are exactly the cases that leave a port taken. +- **Run `stop` only after the graceful signal timed out.** A process that + ignores the signal would cost every stop and every replacement 20 s, and + the case of a CLI that already ended would not be covered. +- **devstack recognises `docker run`** and adds `--cidfile` or a label to + remove the container itself. It rewrites the user's command line, knows + one tool only, and makes devstack a container runtime beside Compose + (ADR-0004). +- **A Compose service with a build that `watch` rebuilds.** That is the + "image" variant ADR-0041 left for later: no candidate, no promotion, a + different decision. + +## Consequences + +- Every end of an instance of a service with `stop` runs one more program, + a `docker` call of about a second, also where the container is gone + already (a `docker rm -f` of no container fails harmlessly, and says so in + the log). +- After a daemon crash the `stop` runs without the service's environment: + a `stop` that needs a variable only the service gets (not `PATH`, + `DOCKER_HOST`) fails then, and says so in the log of the instance. +- A lane that is not started again after a crash keeps what its instances + left until it is (`devstack lane prune` does not run `stop`). + +## Enforced by + +- `crates/devstack-config`: `Service::stop` and `ServiceProfile::stop` + (`model.rs`, the profile merge), the checks and the `requires` warning + (`validate.rs`, `STOP_SINCE`); `docs/stack-file.md`. +- `crates/devstack-daemon`: the expanded `stop` with each instance + (`supervisor/lifecycle.rs`: `launch`; one place ends an instance, `end`), + every site that ended an instance with `tree.stop`/`tree.kill` going + through it (`lifecycle.rs`, `replace.rs`), the record in `state.json` + (`state.rs`: `Persisted::stops`) and the run at a supervisor's start + (`supervisor/mod.rs`). +- `skills/` (the stack-file skill) and `crates/devstack-skills`. + +## What this ADR does not say + +- That devstack runs containers as services. A `docker run` service is a + native process that happens to start one; Compose stays the infra plane + (ADR-0004), and a lane on a node, which has no Docker, cannot run it. +- That `stop` replaces the graceful signal. Both happen, in that order. diff --git a/docs/adr/README.md b/docs/adr/README.md index d9b6c22d..684d06d8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -57,7 +57,7 @@ stay. | [0006](0006-dashboard-vue-same-origin.md) | The dashboard is a Vue 3 SPA served same-origin by the daemon | Accepted; who serves it replaced by ADR-0021 (the hub) | | [0007](0007-one-http-api-is-the-control-surface.md) | One HTTP API is the control surface; CLI, MCP and dashboard are its clients | Accepted | | [0008](0008-background-workers-run-only-in-the-active-slot.md) | Background workers run only in the active slot | Accepted | -| [0009](0009-the-daemon-owns-every-process-tree.md) | The daemon owns every process tree it starts | Accepted | +| [0009](0009-the-daemon-owns-every-process-tree.md) | The daemon owns every process tree it starts | Accepted; what a service starts outside its tree is ended by its `stop` command, ADR-0059 | | [0010](0010-promotion-mechanism.md) | Promotion mechanism: restart on the fixed port or switch a reverse proxy | Accepted (option B, the reverse proxy; measured) | | [0011](0011-platform-windows-native-first.md) | Windows-native first; WSL is decided by measurement | Accepted; macOS added as a preview by ADR-0054 | | [0012](0012-shared-infrastructure-between-lanes.md) | Which infrastructure may be shared between lanes | Decided by ADR-0030 | @@ -107,3 +107,4 @@ stay. | [0056](0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md) | A lane on a node relays its UDP ports, a tunnel per client, a datagram per frame | Accepted | | [0057](0057-a-port-a-container-announces-moves-inside-it-too.md) | A port a container announces moves inside the container too, and Compose is told its number | Accepted | | [0058](0058-a-profile-can-leave-out-containers-and-services.md) | A profile can leave out containers, whole Compose groups and services | Accepted | +| [0059](0059-a-services-stop-command-ends-what-its-run-started.md) | A service's `stop` command ends what its `run` started outside its process tree | Accepted | diff --git a/docs/stack-file.md b/docs/stack-file.md index 495beae2..781b8311 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -451,6 +451,49 @@ server reloads itself). | `ensure_dirs = ["{repo}/data/files"]` | created before start | | `prepare = { run = "npm ci", inputs = ["web/package-lock.json"] }` | installs what a copy of the source lacks (see below) | | `timeout = "10m"` | `kind = "job"` only: how long it may run before it counts as failed and is stopped; default 30 minutes. `devstack stop ` ends it at once | +| `stop = "docker rm -f api{lane_suffix}-{port}"` | ends what `run` started outside its process tree, a container ([ADR-0059](adr/0059-a-services-stop-command-ends-what-its-run-started.md), below); not for `kind = "static"` | + +### A container as a service (`docker run`) + +A service whose runtime needs Linux tools can run as a container and still +get `watch`, candidates and a lane's own port, which a Compose container +does not: + +```toml +[services.ocr] +build = "docker build -t ocr:dev ocr" +run = "docker run --rm --init --name ocr{lane_suffix}-{port} -p {port}:8000 ocr:dev" +stop = "docker rm -f ocr{lane_suffix}-{port}" +port = 5100 +health = { http = "/health", timeout = "60s" } +watch = ["ocr/**"] +``` + +devstack owns the `docker` CLI's process tree, not the container, which +runs in Docker's VM ([ADR-0009](adr/0009-the-daemon-owns-every-process-tree.md)): + +- **The graceful stop reaches the container** through the CLI, which + passes it on: `CTRL_BREAK` on Windows arrives there as `SIGINT`, + `SIGTERM` elsewhere as `SIGTERM`. The process in the container must end + on it: a container's PID 1 ignores a signal it has no handler for, so + use `--init` or an entrypoint that handles both. Otherwise the CLI is + killed after 20 s and the container keeps running. +- **`--rm`** removes the container once it ended. +- **A name with `{lane_suffix}-{port}`** (`{port}` is the instance's own, + internal behind the proxy) keeps a candidate apart from the main instance + and a lane from the main tree. A fixed name, or a `docker rm -f` before + `docker run` in `run`, would remove the main instance while a candidate + starts. +- **`stop`** runs whenever an instance ends (a stop, a restart, the old + instance a candidate replaced, a start that failed, one that ended on its + own), before the graceful signal, with that instance's placeholders, at + most 30 s; its output and a failure go into the instance's log, and the + stop goes on regardless. After the daemon died, its next start runs the + `stop` of every instance it had (with devstack's environment, not the + service's). It covers what the signal does not: a process that ignores + it, a CLI that ended by itself. In hot-reload mode it does not apply. + +A file with `stop` should say `requires = "0.21.0"` in `[stack]`. ### `prepare`: what a copy of the source lacks @@ -716,8 +759,8 @@ devstack lane start --profile acceptance --run # from the main tree `{is_main}`), `autostart`, `skip` (below), `command` (one of `[commands]`), `need` (as `[lanes.need]`, each part the larger of the two; a lane with the profile is measured on its own, its runs are the profile's), and - per service `kind`, `build`, `output`, `run`, `spa`, `cwd`, `health` and - `env`. A service it does not name runs as the file says. Its `env` is + per service `kind`, `build`, `output`, `run`, `stop`, `spa`, `cwd`, + `health` and `env`. A service it does not name runs as the file says. Its `env` is added to every service's, a service's own `env` in the profile on top. `watch`, `port` and the other keys stay as the file says. - **`skip`** ([ADR-0058](adr/0058-a-profile-can-leave-out-containers-and-services.md)) @@ -737,7 +780,7 @@ devstack lane start --profile acceptance --run # from the main tree container is not created, so it cannot be started there later in that run. A file with `skip` should say `requires = "0.21.0"` in `[stack]`. - **Another `kind` drops what only the old one takes:** a dev server made - `static` loses its `run` (unless the profile gives one), `rebuild` and + `static` loses its `run` and `stop` (unless the profile gives them), `rebuild` and `restart_on`; a `devserver` or `tool` loses `build` and `output`; `spa` stays with `static` only, `hot_reload` with `service`, `timeout` with `job`; a `job` or `tool` loses `health` and `proxy`. What the profile sets diff --git a/skills/devstack-config/SKILL.md b/skills/devstack-config/SKILL.md index a16a18a3..eaf8918e 100644 --- a/skills/devstack-config/SKILL.md +++ b/skills/devstack-config/SKILL.md @@ -122,6 +122,15 @@ without a stack file starts from `devstack init` (a draft with TODOs). the files' port as default (`${DEVSTACK_PORT_MEDIA_7881:-7881}`); keep `ports` literal. Without the key, a lane's server announces the main tree's port. Add `requires = "0.20.0"` to `[stack]`. +- **A container as a service** (`run = "docker run ..."`, for what needs + Linux tools but should get `watch` and candidates) needs three things: a + process in it that ends on `SIGINT` and `SIGTERM` (`docker run --init`, + or an entrypoint that handles them: devstack's graceful stop reaches the + container through the CLI), `--rm`, and a name with + `{lane_suffix}-{port}` so a candidate and the main instance do not + collide. Add `stop = "docker rm -f "`: devstack runs it + whenever an instance ends, also after a crash, so no container is left + holding the port. Add `requires = "0.21.0"` to `[stack]`. - **Paths** are relative to the repository root; use `{repo}` where a process needs an absolute one. Generated directories (`bin`, `obj`, `node_modules`, `target`, `.git`, `.devstack`) never count as changes. Compose files, env