diff --git a/crates/kd/src/bin/kd.rs b/crates/kd/src/bin/kd.rs index 35f6ce5..41b8070 100644 --- a/crates/kd/src/bin/kd.rs +++ b/crates/kd/src/bin/kd.rs @@ -1,5 +1,6 @@ //! Command-line interface for `kd` (process supervision and signal coordination). +use std::os::unix::process::CommandExt; use std::process::{Command as StdCommand, ExitCode}; use anyhow::{Context, Result}; @@ -29,7 +30,7 @@ struct Cli { #[derive(Debug, Subcommand)] enum Command { - /// Demonstrate 2-phase graceful shutdown (Drain → Escalate → ForceKill) and emit JSON status. + /// Demonstrate 2-phase graceful shutdown (Drain -> Escalate -> ForceKill) and emit JSON status. Demo { /// Identifier for the demo workload run. #[arg(long, default_value = "default-demo")] @@ -59,6 +60,17 @@ enum Command { /// Inbound drain timeout in milliseconds upon receiving SIGTERM. #[arg(long, default_value = "10000")] drain_ms: u64, + + /// Escalation timeout in milliseconds before force killing. + #[arg(long, default_value = "5000")] + escalate_ms: u64, + + /// Optional command to execute as the primary supervised workload. + command: Option, + + /// Arguments passed to the primary command. + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + args: Vec, }, /// List all recognized POSIX signals and their integer numbers and categories. @@ -137,8 +149,10 @@ fn run_supervised( let _ = set_child_subreaper(true); let receiver = trap_default_termination().context("failed to trap termination signals")?; - let child = StdCommand::new(command) - .args(args) + let mut cmd = StdCommand::new(command); + cmd.args(args); + cmd.process_group(0); + let child = cmd .spawn() .with_context(|| format!("failed to spawn {command}"))?; @@ -160,21 +174,46 @@ fn run_supervised( Ok(ExitCode::from(exit_code as u8)) } -fn run_init(drain_ms: u64) -> Result { +fn run_init( + drain_ms: u64, + escalate_ms: u64, + command: Option, + args: &[String], +) -> Result { let _guard = TerminalGuard::init().context("failed to initialize terminal guard")?; let _ = set_child_subreaper(true); let receiver = trap_default_termination().context("failed to trap termination signals")?; let config = ShutdownConfig { drain_grace_period_ms: drain_ms, - escalate_timeout_ms: 5000, + escalate_timeout_ms: escalate_ms, force_kill_timeout_ms: 2000, default_exit_code: 0, double_sigint_fast_track: true, }; let mut coordinator = TeardownCoordinator::new(config); - tracing::info!("kd init container supervisor active (PID 1 mode)"); + + if let Some(ref cmd_name) = command { + let mut cmd = StdCommand::new(cmd_name); + cmd.args(args); + cmd.process_group(0); + let child = cmd + .spawn() + .with_context(|| format!("failed to spawn {cmd_name}"))?; + + let pid = ProcessId::new(child.id()); + let pgid = ProcessGroupId::new(child.id()); + coordinator.track_process(ProcessRecord::new(pid, pgid, cmd_name, true)); + + tracing::info!( + command = %cmd_name, + pid = %pid, + "kd init container supervisor active (PID 1 mode with primary workload)" + ); + } else { + tracing::info!("kd init container supervisor active (PID 1 orphan-reaper mode)"); + } let exit_code = coordinator.run_loop(&receiver); Ok(ExitCode::from(exit_code as u8)) @@ -199,7 +238,12 @@ fn main() -> Result { command, args, } => run_supervised(&command, &args, drain_ms, escalate_ms), - Command::Init { drain_ms } => run_init(drain_ms), + Command::Init { + drain_ms, + escalate_ms, + command, + args, + } => run_init(drain_ms, escalate_ms, command, &args), Command::Signals => { let signals = [ Signal::Hup, diff --git a/crates/kd/src/supervisor.rs b/crates/kd/src/supervisor.rs index a350940..35769b3 100644 --- a/crates/kd/src/supervisor.rs +++ b/crates/kd/src/supervisor.rs @@ -7,6 +7,7 @@ use std::fs; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::path::Path; +use std::time::Duration; use kd_domain::{ExitStatus, ProcessGroupId, ProcessId, Signal}; @@ -111,6 +112,58 @@ impl PidFd { )) } } + + /// Wait for process termination with an optional timeout using Linux `poll(2)`. + /// + /// On Linux >= 5.3, a process file descriptor becomes readable (`POLLIN`) + /// when the monitored process terminates. + /// + /// Returns `Ok(true)` if process exited, `Ok(false)` on timeout, or `Err(io::Error)` on failure. + /// + /// # Errors + /// Returns `io::Error` if `poll(2)` fails, or `ErrorKind::Unsupported` on platforms + /// without pidfd support. + pub fn wait_timeout(&self, timeout: Option) -> io::Result { + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + let timeout_ms = match timeout { + Some(dur) => dur.as_millis().min(libc::c_int::MAX as u128) as libc::c_int, + None => -1, + }; + + let mut pfd = libc::pollfd { + fd: self.fd.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }; + + // SAFETY: Calling poll on valid descriptor owned by Self. + #[allow(unsafe_code)] + let ret = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; + + if ret < 0 { + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + Ok(false) + } else { + Err(err) + } + } else if ret == 0 { + Ok(false) + } else { + Ok((pfd.revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR)) != 0) + } + } + + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let _ = timeout; + Err(io::Error::new( + io::ErrorKind::Unsupported, + "pidfd_wait is only supported on Linux", + )) + } + } } /// Send a signal to a process, preferring `pidfd_send_signal` and falling back to `kill(2)`. @@ -293,4 +346,24 @@ mod tests { assert_eq!(pidfd.pid().as_u32(), my_pid); } } + + #[test] + fn test_pidfd_wait_timeout_on_child() { + use std::process::Command; + + let mut child = Command::new("sleep") + .arg("0.05") + .spawn() + .expect("spawn sleep"); + let pid = ProcessId::new(child.id()); + + if let Ok(pidfd) = PidFd::open(pid) { + let exited = pidfd + .wait_timeout(Some(Duration::from_secs(1))) + .expect("poll wait"); + assert!(exited, "process should have exited within timeout"); + } + + let _ = child.wait(); + } } diff --git a/crates/kd/src/teardown.rs b/crates/kd/src/teardown.rs index 4e943df..4d069a1 100644 --- a/crates/kd/src/teardown.rs +++ b/crates/kd/src/teardown.rs @@ -10,8 +10,8 @@ use std::os::unix::net::UnixDatagram; use std::time::{Duration, Instant}; use kd_domain::{ - ChildState, ProcessGroupId, ProcessId, ProcessRecord, ShutdownAction, ShutdownConfig, - ShutdownPhase, ShutdownStateMachine, Signal, + ChildState, ExitStatus, ProcessGroupId, ProcessId, ProcessRecord, ShutdownAction, + ShutdownConfig, ShutdownPhase, ShutdownStateMachine, Signal, }; use crate::signal::SignalReceiver; @@ -92,13 +92,37 @@ impl TeardownCoordinator { self.execute_action(action); // 4. Check if all tracked processes have terminated + let all_dead = !self.tracked_processes.is_empty() + && self + .tracked_processes + .values() + .all(|p| p.state.is_terminated()); + if all_dead { + let action = self.state_machine.mark_all_reaped(); + self.execute_action(action); + } + } else if !self.tracked_processes.is_empty() { + // Check if tracked processes exited during normal running let all_dead = self .tracked_processes .values() .all(|p| p.state.is_terminated()); if all_dead { - let action = self.state_machine.mark_all_reaped(); - self.execute_action(action); + let exit_code = self + .tracked_processes + .values() + .filter_map(|p| match p.state { + ChildState::Terminated(ExitStatus::Success) => Some(0), + ChildState::Terminated(ExitStatus::Exited(code)) => Some(code), + ChildState::Terminated( + ExitStatus::Signaled(sig) | ExitStatus::CoreDumped(sig), + ) => Some(128 + sig.as_raw()), + _ => None, + }) + .next() + .unwrap_or(self.state_machine.config().default_exit_code); + + let _ = self.state_machine.force_terminate(exit_code); } } @@ -137,6 +161,20 @@ impl TeardownCoordinator { } => { tracing::info!(grace_period_ms, reason = %reason, "initiating graceful shutdown drain"); let _ = notify_systemd("STOPPING=1"); + + // Forward the graceful drain signal to all supervised processes + let drain_sig = match Signal::from_name(&reason) { + Ok(sig) if sig.can_catch() => sig, + _ => Signal::Term, + }; + for &pgid in &self.tracked_groups { + let _ = kill_process_group(pgid, drain_sig); + } + for record in self.tracked_processes.values() { + if record.state.is_running() { + let _ = send_signal_safe(record.pid, drain_sig); + } + } } ShutdownAction::EnterEscalate { timeout_ms } => { tracing::warn!( @@ -169,3 +207,58 @@ impl TeardownCoordinator { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_coordinator_normal_termination_exit_code() { + let config = ShutdownConfig { + drain_grace_period_ms: 1000, + escalate_timeout_ms: 500, + force_kill_timeout_ms: 200, + default_exit_code: 0, + double_sigint_fast_track: true, + }; + let mut coordinator = TeardownCoordinator::new(config); + let pid = ProcessId::new(99999); + let pgid = ProcessGroupId::new(99999); + let mut record = ProcessRecord::new(pid, pgid, "test-proc", true); + // Simulate child already terminated with exit code 42 + record.state = ChildState::Terminated(ExitStatus::Exited(42)); + coordinator.track_process(record); + + // First step should detect process termination and complete with code 42 + let exit_code = coordinator.step(None, Duration::from_millis(10)); + assert_eq!(exit_code, Some(42)); + assert_eq!( + *coordinator.phase(), + ShutdownPhase::Terminated { exit_code: 42 } + ); + } + + #[test] + fn test_coordinator_drain_signal_forwarding() { + let config = ShutdownConfig { + drain_grace_period_ms: 1000, + escalate_timeout_ms: 500, + force_kill_timeout_ms: 200, + default_exit_code: 0, + double_sigint_fast_track: true, + }; + let mut coordinator = TeardownCoordinator::new(config); + // Process with dummy PID + let pid = ProcessId::new(99998); + let pgid = ProcessGroupId::new(99998); + let record = ProcessRecord::new(pid, pgid, "test-drain-proc", true); + coordinator.track_process(record); + + // Action: EnterDrain with SIGINT + coordinator.execute_action(ShutdownAction::EnterDrain { + grace_period_ms: 1000, + reason: "Int".to_owned(), + }); + // Non-existent PID/PGID won't crash execute_action (idempotent / ESRCH handled) + } +} diff --git a/specs/0004-dependency-and-licence-policy.md b/specs/0004-dependency-and-licence-policy.md index 021e966..564311e 100644 --- a/specs/0004-dependency-and-licence-policy.md +++ b/specs/0004-dependency-and-licence-policy.md @@ -41,7 +41,7 @@ Todie / unsigned-gg. Contact: chris@todie.io. | `libc` | 0.2.190 | MIT OR Apache-2.0 | POSIX and Linux syscalls for pidfd, prctl, and termios. | Cargo.lock | | `serde` | 1.0.229 | MIT OR Apache-2.0 | Serialization and deserialization derive. | Cargo.lock | | `serde_json` | 1.0.151 | MIT OR Apache-2.0 | Structured JSON output for CLI and tests. | Cargo.lock | -| `sha2` | 0.10.9 | MIT OR Apache-2.0 | Cryptographic hash for contract pinning and xtask. | Cargo.lock | +| `sha2` | 0.11.0 | MIT OR Apache-2.0 | Cryptographic hash for contract pinning and xtask. | Cargo.lock | | `thiserror` | 2.0.21 | MIT OR Apache-2.0 | Typed domain error enums. | Cargo.lock | | `tracing` | 0.1.44 | MIT | Structured logging facade. | Cargo.lock | | `tracing-subscriber` | 0.3.23 | MIT | Log formatting and RUST_LOG filtering. | Cargo.lock |