crates/run/supervisor/tests/supervisor.rs 12.7 KiB 375 lines Raw
1 //! The supervisor against shell plugins: accept, timeout, kill, and backoff.2 3 use std::fs::{self, File};4 use std::io::Write;5 use std::os::unix::fs::PermissionsExt;6 use std::os::unix::net::UnixStream;7 use std::path::{Path, PathBuf};8 use std::process::{self, Command as ProcessCommand, ExitStatus};9 use std::sync::Mutex;10 use std::sync::atomic::{AtomicU64, Ordering};11 use std::time::{Duration, Instant};12 13 use inf3r_supervisor::{Backoff, Child, Command, Failure, SpawnError, sweep_stale};14 15 const SCRIPT_MODE: u32 = 0o700;16 const WAIT: Duration = Duration::from_secs(5);17 const GRACE: Duration = Duration::from_secs(1);18 const SHORT_GRACE: Duration = Duration::from_millis(10);19 const SHORT_WAIT: Duration = Duration::from_millis(100);20 const POLL: Duration = Duration::from_millis(5);21 const TOOK: Duration = Duration::from_millis(100);22 const MAX: Duration = Duration::from_secs(1);23 24 const CONNECT: &str = r#"exec python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM); s.connect(sys.argv[1]); s.close()' "$2""#;25 /// Connects, then waits for the other end to close. `SIGTERM` is ignored, so26 /// only a real shutdown or the kill can end it.27 const DRAIN: &str = r#"exec python3 -c 'import signal,socket,sys; signal.signal(signal.SIGTERM, signal.SIG_IGN); s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM); s.connect(sys.argv[1]); s.recv(1); sys.exit(0)' "$2""#;28 const SLEEP: &str = "exec sleep 30";29 /// Sleeps through `SIGTERM`, so only `SIGKILL` ends it. It writes a marker30 /// after it has installed the handler, so a test never races the interpreter.31 const STUBBORN: &str = r#"exec python3 -c 'import pathlib,signal,sys,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); pathlib.Path(sys.argv[1]).write_text("ready"); time.sleep(30)' "$0.ready""#;32 /// Writes the socket path that the supervisor passed in argv, then sleeps.33 const ANNOUNCE: &str = r#"printf '%s' "$2" > "$0.peer"; exec sleep 30"#;34 const EXIT: &str = "exit 7";35 /// Writes one environment value that the supervisor passed, then sleeps.36 const ENV: &str = r#"printf '%s' "$INF3R_BUNDLE_DIR" > "$0.env"; exec sleep 30"#;37 const SIGTERM: i32 = 15;38 39 /// Serialises the write of a script and the fork that runs one. A fork copies40 /// every open descriptor, so a concurrent write would make the exec fail with41 /// `ETXTBSY`.42 static SPAWN: Mutex<()> = Mutex::new(());43 44 /// A plugin as a shell script. The shebang makes `/bin/sh` the binary.45 struct Script {46     path: PathBuf,47 }48 49 impl Script {50     fn new(body: &str) -> Script {51         static NEXT: AtomicU64 = AtomicU64::new(0);52         let serial = NEXT.fetch_add(1, Ordering::Relaxed);53         let path =54             std::env::temp_dir().join(format!("inf3r-supervisor-{}-{serial}.sh", process::id()));55 56         let mut file = File::create(&path).expect("create the plugin script");57         writeln!(file, "#!/bin/sh").expect("write the shebang");58         writeln!(file, "{body}").expect("write the body");59         let mut permissions = file.metadata().expect("script metadata").permissions();60         permissions.set_mode(SCRIPT_MODE);61         fs::set_permissions(&path, permissions).expect("make the script executable");62         drop(file);63 64         Script { path }65     }66 67     fn path(&self) -> &Path {68         &self.path69     }70 }71 72 impl Drop for Script {73     fn drop(&mut self) {74         let _ = fs::remove_file(&self.path);75         let _ = fs::remove_file(format!("{}.ready", self.path.display()));76         let _ = fs::remove_file(format!("{}.peer", self.path.display()));77         let _ = fs::remove_file(format!("{}.env", self.path.display()));78     }79 }80 81 fn socket_root() -> PathBuf {82     let root = Path::new("/tmp").join(format!("inf3r-sup-{}", process::id()));83     fs::create_dir_all(&root).expect("the socket root");84     root85 }86 87 fn spawn(body: &str) -> (Script, Child) {88     spawn_with_env(body, Vec::new())89 }90 91 fn spawn_with_env(body: &str, env: Vec<(String, String)>) -> (Script, Child) {92     let _guard = SPAWN.lock().expect("the test lock");93     let script = Script::new(body);94     let command = Command {95         program: script.path().to_path_buf(),96         args: Vec::new(),97         env,98     };99     let child = Child::spawn_in(command, &socket_root()).expect("spawn");100     (script, child)101 }102 103 fn wait_for_text(path: &Path) -> String {104     let deadline = Instant::now() + WAIT;105     loop {106         if let Ok(text) = fs::read_to_string(path)107             && !text.is_empty()108         {109             return text;110         }111         assert!(112             Instant::now() < deadline,113             "{} never appeared",114             path.display()115         );116         std::thread::sleep(POLL);117     }118 }119 120 fn exit_status(line: &str) -> ExitStatus {121     // A fork copies every descriptor that another thread holds open for122     // writing, and an exec of a file with such a descriptor fails with123     // ETXTBSY. Every spawn in this process takes the same lock.124     let _guard = SPAWN.lock().expect("the test lock");125     ProcessCommand::new("/bin/sh")126         .args(["-c", line])127         .status()128         .expect("the shell runs")129 }130 131 #[test]132 fn a_plugin_connects_and_stops_with_code_zero() {133     let (_script, mut child) = spawn(CONNECT);134 135     let stream = child.accept(WAIT).expect("accept");136     drop(stream);137     assert!(child.pid() > 0);138 139     let deadline = Instant::now() + WAIT;140     while child.alive() {141         assert!(Instant::now() < deadline, "the plugin did not exit");142         std::thread::sleep(POLL);143     }144 145     let stop = child.stop(GRACE).expect("stop");146     assert_eq!(stop.code, Some(0));147     assert!(!stop.killed);148     assert!(!child.alive());149 }150 151 #[test]152 fn a_plugin_that_ignores_sigterm_needs_the_kill() {153     let (script, mut child) = spawn(STUBBORN);154     let ready = PathBuf::from(format!("{}.ready", script.path().display()));155     wait_for_text(&ready);156 157     let stop = child.stop(SHORT_GRACE).expect("stop");158     assert!(stop.killed);159     assert!(stop.signal.is_some());160     assert_eq!(stop.code, None);161     assert!(!child.alive());162 }163 164 #[test]165 fn sigterm_ends_a_plugin_without_the_kill() {166     let (_script, mut child) = spawn(SLEEP);167 168     let stop = child.stop(GRACE).expect("stop");169     assert!(!stop.killed);170     assert_eq!(stop.signal, Some(SIGTERM));171     assert_eq!(stop.code, None);172     assert!(!child.alive());173 }174 175 #[test]176 fn a_stop_closes_the_socket_that_the_caller_holds() {177     let (_script, mut child) = spawn(DRAIN);178     let stream = child.accept(WAIT).expect("accept");179 180     let stop = child.stop(GRACE).expect("stop");181     assert!(!stop.killed);182     assert_eq!(stop.code, Some(0));183     drop(stream);184     assert!(!child.alive());185 }186 187 #[test]188 fn a_path_that_was_not_published_cannot_take_the_plugin_socket() {189     let (script, mut child) = spawn(ANNOUNCE);190     let peer_file = PathBuf::from(format!("{}.peer", script.path().display()));191     let path = PathBuf::from(wait_for_text(&peer_file));192     let wrong = path.with_extension("not-the-token");193     assert!(194         UnixStream::connect(&wrong).is_err(),195         "the wrong path connected"196     );197 198     let error = child199         .accept(SHORT_WAIT)200         .expect_err("the plugin never connected");201     assert_eq!(error, SpawnError::Timeout, "{error:?}");202     let _ = fs::remove_file(peer_file);203 }204 205 #[test]206 fn a_stopped_child_removes_its_private_directory() {207     let (_script, mut child) = spawn(ANNOUNCE);208     let path = child.socket_path().expect("the listener").to_path_buf();209     let directory = path.parent().expect("the instance directory").to_path_buf();210     assert!(directory.is_dir(), "{} is missing", directory.display());211     assert_eq!(212         fs::metadata(&directory)213             .expect("directory mode")214             .permissions()215             .mode()216             & 0o777,217         0o700218     );219     assert_eq!(220         fs::metadata(&path)221             .expect("socket mode")222             .permissions()223             .mode()224             & 0o777,225         0o666226     );227 228     let _ = child.accept(SHORT_WAIT);229     let _ = child.stop(GRACE).expect("stop");230     assert!(231         !directory.exists(),232         "{} survived the stop",233         directory.display()234     );235 }236 237 #[test]238 fn a_restart_uses_a_fresh_path_and_never_reuses_the_old_directory() {239     let (script, mut first) = spawn(ANNOUNCE);240     let first_path = first.socket_path().expect("the listener").to_path_buf();241     let first_dir = first_path242         .parent()243         .expect("the instance directory")244         .to_path_buf();245     let _ = first.stop(GRACE).expect("stop");246     assert!(!first_dir.exists());247 248     let (_script, mut second) = spawn(ANNOUNCE);249     let second_path = second.socket_path().expect("the listener").to_path_buf();250     assert_ne!(first_path, second_path);251     assert!(second_path.exists());252     let _ = second.stop(GRACE).expect("stop");253     let _ = fs::remove_file(format!("{}.peer", script.path().display()));254 }255 256 #[test]257 fn a_dropped_child_is_reaped() {258     let (_script, child) = spawn(STUBBORN);259     let pid = child.pid();260     drop(child);261 262     let path = format!("/proc/{pid}");263     let deadline = Instant::now() + WAIT;264     while Path::new(&path).exists() {265         assert!(Instant::now() < deadline, "the child {pid} is still alive");266         std::thread::sleep(POLL);267     }268 }269 270 #[test]271 fn a_plugin_that_exits_before_connecting_is_connect() {272     let (_script, mut child) = spawn(EXIT);273 274     let error = child.accept(WAIT).expect_err("the child never connects");275     match error {276         SpawnError::Connect(status) => assert_eq!(status.code(), Some(7)),277         other => panic!("expected Connect, got {other:?}"),278     }279 }280 281 #[test]282 fn backoff_doubles_from_zero_and_success_clears_it() {283     let mut backoff = Backoff::default();284 285     assert_eq!(backoff.wait(TOOK, MAX), Duration::ZERO);286     assert_eq!(backoff.wait(TOOK, MAX), TOOK);287     assert_eq!(backoff.wait(TOOK, MAX), Duration::from_millis(200));288     assert_eq!(backoff.failures(), 3);289 290     backoff.success();291     assert_eq!(backoff.failures(), 0);292     assert!(!backoff.unloadable());293     assert_eq!(backoff.wait(TOOK, MAX), Duration::ZERO);294 }295 296 #[test]297 fn permanent_marks_the_peer_unloadable() {298     let mut backoff = Backoff::default();299 300     backoff.permanent();301     assert!(backoff.unloadable());302     assert_eq!(backoff.failures(), 1);303     assert!(backoff.wait(TOOK, MAX) <= MAX);304 305     backoff.success();306     assert!(!backoff.unloadable());307 }308 309 #[test]310 fn from_exit_maps_a_signal_to_killed_and_every_code_to_crashed() {311     assert_eq!(312         Failure::from_exit(exit_status("kill -TERM $$")),313         Failure::Killed314     );315     assert_eq!(Failure::from_exit(exit_status("exit 0")), Failure::Crashed);316     assert_eq!(Failure::from_exit(exit_status("exit 7")), Failure::Crashed);317 318     assert!(Failure::Version.is_permanent());319     assert!(Failure::Frame.is_permanent());320     assert!(Failure::Stream.is_permanent());321     assert!(Failure::Size.is_permanent());322     assert!(Failure::Dependency.is_permanent());323     assert!(!Failure::Crashed.is_permanent());324     assert!(!Failure::Killed.is_permanent());325     assert!(!Failure::Timeout.is_permanent());326 }327 328 #[test]329 fn a_plugin_gets_the_environment_that_the_supervisor_names() {330     let (script, mut child) = spawn_with_env(331         ENV,332         vec![(333             "INF3R_BUNDLE_DIR".to_string(),334             "/tmp/one-bundle".to_string(),335         )],336     );337     let path = PathBuf::from(format!("{}.env", script.path().display()));338     assert_eq!(wait_for_text(&path), "/tmp/one-bundle");339     let stop = child.stop(GRACE).expect("stop");340     assert_eq!(stop.signal, Some(SIGTERM));341     assert!(!child.alive());342 }343 344 #[test]345 fn a_sweep_removes_only_directories_without_a_live_owner() {346     let root = Path::new("/tmp").join(format!("inf3r-sweep-{}", process::id()));347     let _ = fs::remove_dir_all(&root);348     fs::create_dir_all(&root).expect("the run root");349     let stale = root.join("0123456789abcdef0123456789abcdef");350     fs::create_dir(&stale).expect("the stale directory");351     fs::write(stale.join("lock"), b"").expect("the stale lock");352     let live = root.join("fedcba9876543210fedcba9876543210");353     fs::create_dir(&live).expect("the live directory");354     fs::write(live.join("lock"), b"").expect("the live lock");355     let held = File::open(live.join("lock")).expect("open the live lock");356     rustix::fs::flock(&held, rustix::fs::FlockOperation::LockExclusive).expect("lock");357 358     assert_eq!(sweep_stale(&root).expect("sweep"), 1);359     assert!(!stale.exists());360     assert!(live.exists());361     drop(held);362     // A test thread may have forked while the lock file was open; the child363     // holds the descriptor until exec closes it. Retry past that window.364     let started = std::time::Instant::now();365     let mut removed = 0;366     while removed == 0 && started.elapsed() < std::time::Duration::from_secs(2) {367         removed = sweep_stale(&root).expect("sweep");368         if removed == 0 {369             std::thread::sleep(std::time::Duration::from_millis(5));370         }371     }372     assert_eq!(removed, 1);373     assert!(!live.exists());374     let _ = fs::remove_dir_all(root);375 }