1 //! inf3r-supervisor — start a plugin, accept its connection, and classify its2 //! failure.3 //!4 //! A plugin is a process or a container. The supervisor is the part of the5 //! core that starts that peer and notices when it dies, without owning a socket6 //! of the wire protocol. The socket path is the whole start ABI: the supervisor7 //! creates a private directory, binds a filesystem socket there, passes the8 //! path as `--socket`, and accepts one connection. The path is random, and the9 //! kernel reports the peer uid on accept; that uid must be this process's uid10 //! (protocol section 10). The private directory, not a host pid, is what lets a11 //! container peer connect.12 //!13 //! No descriptor is passed to the child. A descriptor needs `pre_exec` or an14 //! `fd` operation and both cross into FFI; the tree denies `unsafe`. A path15 //! reaches the child through argv, which std can do safely. Descriptors sent16 //! later over the socket are ordinary Wire 2 grants.17 //!18 //! Failure memory follows spec section 14 rule 11: a transient failure waits19 //! for as long as it took, a success clears the memory, and a permanent failure20 //! makes the peer unloadable. The classes come from the wire code or the exit21 //! status (core.md section 7).22 23 use std::fmt;24 use std::fs::{self, File, OpenOptions};25 use std::io::Read;26 use std::net::Shutdown;27 use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};28 use std::os::unix::net::{UnixListener, UnixStream};29 use std::os::unix::process::ExitStatusExt;30 use std::path::{Path, PathBuf};31 use std::process::{Child as Process, ExitStatus};32 use std::sync::{Mutex, MutexGuard};33 use std::time::{Duration, Instant};34 35 use nix::sys::socket::getsockopt;36 use nix::sys::socket::sockopt::PeerCredentials;37 use rustix::fs::{FlockOperation, flock};38 use rustix::io::Errno;39 use rustix::process::{Pid, Signal, geteuid, kill_process};40 41 use inf3r_container::{ContainerSpec, Mount};42 43 /// The flag that carries the filesystem socket path to the plugin.44 const SOCKET_ARG: &str = "--socket";45 46 /// The environment variable that selects the private socket root.47 pub const RUN_DIR_ENV: &str = "INF3R_RUN_DIR";48 49 /// The default private socket root. The control creates one instance50 /// directory below it for every plugin.51 const DEFAULT_RUN_DIR: &str = "/run/inf3r";52 53 /// Bytes of randomness in one name. Sixteen bytes make 128 bits, so a process54 /// that was not told the path cannot guess it.55 const NAME_BYTES: usize = 16;56 57 /// The mode of the one directory that an engine can see.58 const DIRECTORY_MODE: u32 = 0o700;59 60 /// The mode of the socket file. The directory is the access boundary; the file61 /// itself must be connectable by the container-root uid that rootless Docker62 /// maps to this process.63 const SOCKET_MODE: u32 = 0o666;64 65 /// The file whose advisory lock says that an instance is still owned.66 const LOCK_FILE: &str = "lock";67 68 /// The suffix of the one socket in an instance directory.69 const SOCKET_SUFFIX: &str = ".sock";70 71 /// One hexadecimal digit is one nibble.72 const NIBBLE_BITS: u32 = 4;73 74 /// The low nibble of a byte.75 const LOW_NIBBLE: u8 = 0x0f;76 77 /// The alphabet of a lowercase hexadecimal name.78 const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";79 80 /// Where the kernel gives unpredictable bytes.81 const URANDOM: &str = "/dev/urandom";82 83 /// How often to look at a child or a listener while a deadline runs. Five84 /// milliseconds is short against every deadline in the tree and still leaves85 /// the caller's thread idle between looks.86 const POLL: Duration = Duration::from_millis(5);87 88 /// Each later failure doubles the previous wait.89 const GROWTH: u32 = 2;90 91 /// How a plugin is started: its binary and its own arguments.92 pub struct Command {93 /// The plugin binary.94 pub program: PathBuf,95 /// Arguments that follow the socket pair.96 pub args: Vec<String>,97 /// Environment that the plugin needs to find its bundle.98 pub env: Vec<(String, String)>,99 }100 101 /// One private socket directory and its listening socket.102 ///103 /// The directory is mode 0700 and the socket is mode 0666. The directory is the104 /// access boundary: it is the only path that is mounted into one engine105 /// container, so a sibling cannot reach the socket even though the file itself106 /// is connectable by the rootless-mapped container root.107 pub struct Listener {108 directory: PathBuf,109 host_directory: PathBuf,110 path: PathBuf,111 listener: UnixListener,112 _lock: File,113 }114 115 impl Listener {116 /// Creates a fresh instance directory below `run_dir` and binds one socket.117 ///118 /// The control path and the Docker daemon's source path are the same. A119 /// control container that mounts a host runtime directory at a different120 /// path uses [`Listener::bind_with_host`].121 pub fn bind(run_dir: &Path) -> Result<Listener, SpawnError> {122 Listener::bind_with_host(run_dir, run_dir)123 }124 125 /// Creates a fresh instance below two roots.126 ///127 /// `run_dir` is the path in the control; `host_dir` is the path that the128 /// Docker daemon sees. The instance name is shared, so a control container129 /// that mounts the host directory at `run_dir` can create the instance,130 /// and an engine can mount the same directory from the host path.131 pub fn bind_with_host(run_dir: &Path, host_dir: &Path) -> Result<Listener, SpawnError> {132 fs::DirBuilder::new()133 .recursive(true)134 .mode(DIRECTORY_MODE)135 .create(run_dir)136 .map_err(|why| SpawnError::Io(format!("{}: {why}", run_dir.display())))?;137 let _ = fs::set_permissions(run_dir, fs::Permissions::from_mode(DIRECTORY_MODE));138 139 for _ in 0..8 {140 let instance = name()?;141 let directory = run_dir.join(&instance);142 let host_directory = host_dir.join(&instance);143 match fs::DirBuilder::new()144 .mode(DIRECTORY_MODE)145 .create(&directory)146 {147 Ok(()) => {}148 Err(why) if why.kind() == std::io::ErrorKind::AlreadyExists => continue,149 Err(why) => {150 return Err(SpawnError::Io(format!("{}: {why}", directory.display())));151 }152 }153 return Listener::in_directory(directory, host_directory);154 }155 Err(SpawnError::Io(format!(156 "{}: no free instance directory",157 run_dir.display()158 )))159 }160 161 fn in_directory(directory: PathBuf, host_directory: PathBuf) -> Result<Listener, SpawnError> {162 let built = (|| {163 let lock_path = directory.join(LOCK_FILE);164 let lock = OpenOptions::new()165 .create_new(true)166 .write(true)167 .mode(0o600)168 .open(&lock_path)169 .map_err(|why| SpawnError::Io(format!("{}: {why}", lock_path.display())))?;170 flock(&lock, FlockOperation::LockExclusive)171 .map_err(|why| SpawnError::Io(format!("{}: {why}", lock_path.display())))?;172 173 let path = directory.join(format!("{}{SOCKET_SUFFIX}", name()?));174 let listener = UnixListener::bind(&path)175 .map_err(|why| SpawnError::Io(format!("{}: {why}", path.display())))?;176 fs::set_permissions(&path, fs::Permissions::from_mode(SOCKET_MODE))177 .map_err(|why| SpawnError::Io(format!("{}: {why}", path.display())))?;178 listener179 .set_nonblocking(true)180 .map_err(|why| SpawnError::Io(why.to_string()))?;181 Ok(Listener {182 directory: directory.clone(),183 host_directory,184 path,185 listener,186 _lock: lock,187 })188 })();189 if built.is_err() {190 let _ = fs::remove_dir_all(&directory);191 }192 built193 }194 195 /// The path that the plugin is told on argv.196 pub fn path(&self) -> &Path {197 &self.path198 }199 200 /// The one directory that a container is allowed to mount.201 pub fn directory(&self) -> &Path {202 &self.directory203 }204 205 /// Accepts one connection from this process's uid before `wait` runs out.206 pub fn accept(&self, wait: Duration, expected_uid: u32) -> Result<UnixStream, SpawnError> {207 self.accept_until(wait, expected_uid, || Ok(None))208 }209 210 fn accept_until<F>(211 &self,212 wait: Duration,213 expected_uid: u32,214 mut exited: F,215 ) -> Result<UnixStream, SpawnError>216 where217 F: FnMut() -> Result<Option<ExitStatus>, SpawnError>,218 {219 let mut rejected: Option<u32> = None;220 let deadline = Instant::now() + wait;221 loop {222 match self.listener.accept() {223 Ok((stream, _)) => {224 let peer = getsockopt(&stream, PeerCredentials)225 .map_err(|why| SpawnError::Io(format!("peer cred: {why:?}")))?;226 let uid = peer.uid();227 if uid != expected_uid {228 rejected = Some(uid);229 let _ = stream.shutdown(Shutdown::Both);230 continue;231 }232 stream233 .set_nonblocking(false)234 .map_err(|why| SpawnError::Io(format!("blocking: {why:?}")))?;235 return Ok(stream);236 }237 Err(why) if why.kind() == std::io::ErrorKind::WouldBlock => {238 if let Some(status) = exited()? {239 return Err(SpawnError::Connect(status));240 }241 let now = Instant::now();242 if now >= deadline {243 if let Some(uid) = rejected {244 return Err(SpawnError::Io(format!(245 "the socket peer uid {uid} is not the control uid"246 )));247 }248 return Err(SpawnError::Timeout);249 }250 std::thread::sleep(POLL.min(deadline - now));251 }252 Err(why) if why.kind() == std::io::ErrorKind::Interrupted => {}253 Err(why) => return Err(SpawnError::Io(format!("accept: {why:?}"))),254 }255 }256 }257 }258 259 impl Listener {260 /// Adds the one writable mount that an engine may receive.261 fn mount(&self, spec: &mut ContainerSpec) {262 spec.mounts.push(Mount {263 source: self.host_directory.clone(),264 target: self.directory.clone(),265 read_only: false,266 });267 }268 }269 270 impl Drop for Listener {271 /// Removing the instance directory removes the socket and its lock. The272 /// lock is held until this drop, so a sweep cannot remove a live peer.273 fn drop(&mut self) {274 let _ = fs::remove_dir_all(&self.directory);275 }276 }277 278 /// One running plugin.279 ///280 /// The listener and the accepted stream live here so that a restart cannot281 /// reuse the instance directory and a stop can close both before it waits for282 /// the process.283 pub struct Child {284 pid: u32,285 backend: Mutex<Backend>,286 listener: Option<Listener>,287 stream: Option<UnixStream>,288 start: Instant,289 ready: Option<Duration>,290 }291 292 /// The process handle that the supervisor watches.293 ///294 /// A process is the plugin itself. A container is the `docker run` CLI: when295 /// that process exits, the container has exited, and its status is the296 /// container's status. The container name is what stop and inspect use.297 enum Backend {298 Process(Process),299 Container { cli: Process, name: String },300 }301 302 impl Child {303 /// Starts the plugin and leaves it to connect, under the default run root.304 pub fn spawn(command: Command) -> Result<Child, SpawnError> {305 Child::spawn_in(command, &default_run_dir())306 }307 308 /// Starts the plugin under one explicit private socket root.309 ///310 /// The path is made fresh for every spawn. It exists only in this process311 /// and in the child's argv.312 pub fn spawn_in(command: Command, run_dir: &Path) -> Result<Child, SpawnError> {313 let listener =314 Listener::bind(run_dir).map_err(|why| SpawnError::Io(format!("listener: {why}")))?;315 let path = listener.path().to_string_lossy().into_owned();316 317 let start = Instant::now();318 let mut process = std::process::Command::new(&command.program);319 process.arg(SOCKET_ARG).arg(&path).args(&command.args);320 for (key, value) in &command.env {321 process.env(key, value);322 }323 let process = match process.spawn() {324 Ok(process) => process,325 Err(why) => return Err(SpawnError::Io(why.to_string())),326 };327 let pid = process.id();328 329 Ok(Child {330 pid,331 backend: Mutex::new(Backend::Process(process)),332 listener: Some(listener),333 stream: None,334 start,335 ready: None,336 })337 }338 339 /// Starts an engine as a sibling container.340 ///341 /// The listener's private directory is the only host path that the engine342 /// can write, and it is mounted at the same absolute path so the socket343 /// argument is identical inside and outside the container. The image's344 /// command receives `--socket <path>` after its own arguments.345 pub fn spawn_container_in(spec: ContainerSpec, run_dir: &Path) -> Result<Child, SpawnError> {346 Child::spawn_container_in_with(spec, run_dir, |_| Vec::new())347 }348 349 /// Starts a container whose socket root has a different host path.350 pub fn spawn_container_in_host(351 spec: ContainerSpec,352 run_dir: &Path,353 host_dir: &Path,354 ) -> Result<Child, SpawnError> {355 Child::spawn_container_in_host_with(spec, run_dir, host_dir, |_| Vec::new())356 }357 358 /// Starts a container and lets the caller add environment entries after359 /// the private directory exists. The closure is how a gate puts its trace360 /// file inside the one writable mount that the engine already has.361 pub fn spawn_container_in_with<F>(362 spec: ContainerSpec,363 run_dir: &Path,364 env: F,365 ) -> Result<Child, SpawnError>366 where367 F: FnOnce(&Path) -> Vec<(String, String)>,368 {369 Child::spawn_container_in_host_with(spec, run_dir, run_dir, env)370 }371 372 /// Starts a container with a separate host path for its private directory.373 ///374 /// The control passes its own `run_dir` path on argv; the engine mount375 /// source is `host_dir`. A control container that mounts a host runtime376 /// directory at a different path uses this form.377 pub fn spawn_container_in_host_with<F>(378 mut spec: ContainerSpec,379 run_dir: &Path,380 host_dir: &Path,381 env: F,382 ) -> Result<Child, SpawnError>383 where384 F: FnOnce(&Path) -> Vec<(String, String)>,385 {386 let listener = Listener::bind_with_host(run_dir, host_dir)387 .map_err(|why| SpawnError::Io(format!("listener: {why}")))?;388 let path = listener.path().to_string_lossy().into_owned();389 spec.env.extend(env(listener.directory()));390 listener.mount(&mut spec);391 let name = format!(392 "inf3r-{}",393 listener394 .directory()395 .file_name()396 .map(|name| name.to_string_lossy())397 .unwrap_or_default()398 );399 let extra = vec![SOCKET_ARG.to_string(), path];400 let start = Instant::now();401 let cli = spec402 .spawn(&name, &extra)403 .map_err(|why| SpawnError::Io(format!("docker spawn: {why:?}")))?;404 Ok(Child {405 pid: 0,406 backend: Mutex::new(Backend::Container { cli, name }),407 listener: Some(listener),408 stream: None,409 start,410 ready: None,411 })412 }413 414 /// The host process id, for a log line, a signal, or a memory probe.415 ///416 /// A container's pid lives in the host namespace; the control asks Docker417 /// for it. `None` means the container is not running or Docker did not418 /// answer.419 pub fn host_pid(&self) -> Option<u32> {420 let backend = self421 .backend422 .lock()423 .unwrap_or_else(|poison| poison.into_inner());424 match &*backend {425 Backend::Process(process) => Some(process.id()),426 Backend::Container { name, .. } => inf3r_container::host_pid(name),427 }428 }429 430 /// The host process id, or zero when the container is gone.431 pub fn pid(&self) -> u32 {432 self.host_pid().unwrap_or(self.pid)433 }434 435 /// The Docker logs of a container child, or an empty string in process436 /// mode. A start failure names the image's own words instead of only an437 /// exit status.438 pub fn logs(&self) -> String {439 self.container_name()440 .map(|name| inf3r_container::logs(&name))441 .unwrap_or_default()442 }443 444 /// The Docker name of a container child, for diagnostics or a label check.445 pub fn container_name(&self) -> Option<String> {446 let backend = self447 .backend448 .lock()449 .unwrap_or_else(|poison| poison.into_inner());450 match &*backend {451 Backend::Container { name, .. } => Some(name.clone()),452 Backend::Process(_) => None,453 }454 }455 456 /// The private directory that was mounted into a container child.457 pub fn directory(&self) -> Option<&Path> {458 self.listener.as_ref().map(Listener::directory)459 }460 461 /// The filesystem socket that this child was told to connect to.462 pub fn socket_path(&self) -> Option<&Path> {463 self.listener.as_ref().map(Listener::path)464 }465 466 /// The caller half of the accepted socket. Taken once; a second call is467 /// `None`.468 pub fn socket(&mut self) -> Option<UnixStream> {469 self.stream.take()470 }471 472 /// How long the start took, for the ready log line.473 pub fn started_in(&self) -> Duration {474 self.ready.unwrap_or_else(|| self.start.elapsed())475 }476 477 /// True while the process is alive. A child that has not been reaped is478 /// still alive, so this also reaps an exit.479 pub fn alive(&self) -> bool {480 let mut backend = self.lock();481 matches!(backend.try_wait(), Ok(None))482 }483 484 /// Accepts the child's one connection before `wait` runs out.485 ///486 /// The returned stream is a duplicate of the stored one. `socket` can take487 /// the stored stream later, and the caller can close its copy freely.488 ///489 /// A connection whose kernel uid is not this process's uid is closed and490 /// ignored. The listener stays open for the real peer, so one local491 /// impostor cannot make the start fail. The peer pid is deliberately not492 /// compared: a container peer has a pid in its own namespace, and the493 /// private path plus the uid is the credential (D28).494 pub fn accept(&mut self, wait: Duration) -> Result<UnixStream, SpawnError> {495 let Some(listener) = self.listener.as_ref() else {496 return Err(SpawnError::Io("the socket was accepted before".into()));497 };498 let expected_uid = geteuid().as_raw();499 let stream = listener.accept_until(wait, expected_uid, || self.exited())?;500 let core = stream501 .try_clone()502 .map_err(|why| SpawnError::Io(why.to_string()))?;503 self.stream = Some(stream);504 self.ready = Some(self.start.elapsed());505 Ok(core)506 }507 508 /// Asks the plugin to stop, then kills it after `grace`.509 ///510 /// Closing the listener first removes the instance directory, so a restart511 /// cannot find it. Shutting down the stream gives every copy, including the512 /// caller's, an EOF. The child then gets `SIGTERM` and the grace period to513 /// exit; a plugin that ignores both gets `SIGKILL` after the grace period.514 pub fn stop(&mut self, grace: Duration) -> Result<Stop, SpawnError> {515 self.listener.take();516 if let Some(stream) = self.stream.take() {517 let _ = stream.shutdown(Shutdown::Both);518 }519 520 let backend = self521 .backend522 .get_mut()523 .unwrap_or_else(|poison| poison.into_inner());524 let early = backend525 .try_wait()526 .map_err(|why| SpawnError::Io(why.to_string()))?;527 528 match backend {529 Backend::Process(process) => {530 if let Some(status) = early {531 return Ok(Stop::new(status, false));532 }533 terminate(self.pid)?;534 let deadline = Instant::now() + grace;535 loop {536 if let Some(status) = process537 .try_wait()538 .map_err(|why| SpawnError::Io(why.to_string()))?539 {540 return Ok(Stop::new(status, false));541 }542 let now = Instant::now();543 if now >= deadline {544 break;545 }546 std::thread::sleep(POLL.min(deadline - now));547 }548 if let Err(why) = process.kill() {549 if let Some(status) = process550 .try_wait()551 .map_err(|why| SpawnError::Io(why.to_string()))?552 {553 return Ok(Stop::new(status, false));554 }555 return Err(SpawnError::Io(why.to_string()));556 }557 let status = process558 .wait()559 .map_err(|why| SpawnError::Io(why.to_string()))?;560 Ok(Stop::new(status, true))561 }562 Backend::Container { cli, name } => {563 // The Docker CLI is only a handle. It can exit while the564 // daemon keeps the container alive, so the container stop path565 // must run even when `try_wait` already reaped the CLI.566 inf3r_container::stop(name, grace);567 let status = match early {568 Some(status) => status,569 None => {570 let deadline = Instant::now() + grace + Duration::from_secs(1);571 loop {572 if let Some(status) = cli573 .try_wait()574 .map_err(|why| SpawnError::Io(why.to_string()))?575 {576 return Ok(Stop::new(status, false));577 }578 let now = Instant::now();579 if now >= deadline {580 break;581 }582 std::thread::sleep(POLL.min(deadline - now));583 }584 let _ = cli.kill();585 cli.wait().map_err(|why| SpawnError::Io(why.to_string()))?586 }587 };588 Ok(Stop::new(status, false))589 }590 }591 }592 593 fn lock(&self) -> MutexGuard<'_, Backend> {594 self.backend595 .lock()596 .unwrap_or_else(|poison| poison.into_inner())597 }598 599 /// Reports an exit that already happened and reaps the process.600 ///601 /// A successful `try_wait` consumes the status, so a caller must record602 /// the failure now. A child that is still alive returns `None`.603 pub fn exited(&self) -> Result<Option<ExitStatus>, SpawnError> {604 let mut backend = self.lock();605 backend606 .try_wait()607 .map_err(|why| SpawnError::Io(why.to_string()))608 }609 }610 611 impl Backend {612 fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>> {613 match self {614 Backend::Process(process) => process.try_wait(),615 Backend::Container { cli, .. } => cli.try_wait(),616 }617 }618 }619 620 impl Drop for Child {621 /// A child that leaves scope without an explicit stop is still a process.622 ///623 /// The drop uses no grace: it closes the socket, sends `SIGTERM`, and then624 /// `SIGKILL` immediately. It must not make an early error or a panic hang625 /// for the normal shutdown grace, but it must not leak the process either.626 fn drop(&mut self) {627 let _ = self.stop(Duration::ZERO);628 }629 }630 631 /// How a stopped plugin ended.632 #[derive(Clone, Copy, PartialEq, Eq, Debug)]633 pub struct Stop {634 /// The exit code, when the process exited normally.635 pub code: Option<i32>,636 /// The signal, when the process was killed.637 pub signal: Option<i32>,638 /// True when the grace period ran out and the supervisor sent the kill.639 pub killed: bool,640 }641 642 impl Stop {643 fn new(status: ExitStatus, killed: bool) -> Stop {644 Stop {645 code: status.code(),646 signal: status.signal(),647 killed,648 }649 }650 }651 652 /// The supervisor's memory of one plugin's failures.653 ///654 /// The memory outlives a process. A plugin that fails to start twice must wait655 /// longer on the second try, and a permanent failure must survive every restart656 /// attempt until the operator clears it.657 #[derive(Clone, Default, Debug)]658 pub struct Backoff {659 failures: u32,660 next: Duration,661 unloadable: bool,662 }663 664 impl Backoff {665 /// Waits for as long as the failure took, then doubles each later wait up666 /// to `max`.667 ///668 /// The first failure waits zero. Its duration becomes the wait after the669 /// second failure, so a failure that took 100 ms delays the next start by670 /// 100 ms and the one after that by 200 ms.671 pub fn wait(&mut self, took: Duration, max: Duration) -> Duration {672 if self.failures == 0 {673 self.failures = 1;674 self.next = took.min(max);675 return Duration::ZERO;676 }677 let wait = self.next.min(max);678 self.failures = self.failures.saturating_add(1);679 self.next = wait.saturating_mul(GROWTH).min(max);680 wait681 }682 683 /// A success clears the state, including an unloadable mark.684 pub fn success(&mut self) {685 self.failures = 0;686 self.next = Duration::ZERO;687 self.unloadable = false;688 }689 690 /// A permanent failure marks the peer unloadable. It is never started again691 /// until the operator clears it.692 pub fn permanent(&mut self) {693 self.failures = self.failures.saturating_add(1);694 self.unloadable = true;695 }696 697 /// True when a permanent failure has marked the peer.698 pub fn unloadable(&self) -> bool {699 self.unloadable700 }701 702 /// Failures since the last success.703 pub fn failures(&self) -> u32 {704 self.failures705 }706 }707 708 /// The class of one failure, from the wire code or the exit status.709 #[derive(Clone, Copy, PartialEq, Eq, Debug)]710 pub enum Failure {711 /// The version ranges do not overlap.712 Version,713 /// A frame is malformed or out of order.714 Frame,715 /// A frame names a stream that is not open.716 Stream,717 /// A frame is larger than the wire allows.718 Size,719 /// A dependency could not be loaded.720 Dependency,721 /// The process ended without a signal.722 Crashed,723 /// The process ended because of a signal.724 Killed,725 /// No frame arrived inside the budget.726 Timeout,727 }728 729 impl Failure {730 /// True for the failures that the supervisor must not retry. Spec section731 /// 14 rule 11 calls these permanent; every other class is transient.732 pub fn is_permanent(self) -> bool {733 matches!(734 self,735 Failure::Version736 | Failure::Frame737 | Failure::Stream738 | Failure::Size739 | Failure::Dependency740 )741 }742 743 /// Reads a failure from an exit status.744 ///745 /// A signal is `Killed`. Every exit without a signal is `Crashed`, including746 /// code 0: the supervisor sees only the process, while the caller knows747 /// whether the job had already finished. The caller may turn code 0 into a748 /// success, but the exit status alone is not one.749 pub fn from_exit(status: ExitStatus) -> Failure {750 if status.signal().is_some() {751 Failure::Killed752 } else {753 Failure::Crashed754 }755 }756 }757 758 /// Why a spawn, an accept, or a stop failed.759 #[derive(Clone, PartialEq, Eq, Debug)]760 pub enum SpawnError {761 /// The kernel, the filesystem, or the process failed.762 Io(String),763 /// The child did not connect before the deadline.764 Timeout,765 /// The child exited before it connected. The status says how.766 Connect(ExitStatus),767 }768 769 impl fmt::Display for SpawnError {770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {771 match self {772 SpawnError::Io(why) => write!(f, "{why}"),773 SpawnError::Timeout => write!(f, "the plugin did not connect in time"),774 SpawnError::Connect(status) => {775 write!(f, "the plugin exited before it connected: {status}")776 }777 }778 }779 }780 781 impl std::error::Error for SpawnError {}782 783 /// Sends `SIGTERM` to the child. A process that has already exited is fine.784 fn terminate(pid: u32) -> Result<(), SpawnError> {785 let raw = i32::try_from(pid)786 .ok()787 .and_then(Pid::from_raw)788 .ok_or_else(|| SpawnError::Io(format!("the plugin pid {pid} is not valid")))?;789 match kill_process(raw, Signal::TERM) {790 Ok(()) | Err(Errno::SRCH) => Ok(()),791 Err(why) => Err(SpawnError::Io(why.to_string())),792 }793 }794 795 /// The private socket root: the operator's environment, or `/run/inf3r`.796 pub fn default_run_dir() -> PathBuf {797 std::env::var_os(RUN_DIR_ENV)798 .map(PathBuf::from)799 .unwrap_or_else(|| PathBuf::from(DEFAULT_RUN_DIR))800 }801 802 /// Removes instance directories whose owner is gone.803 ///804 /// A live owner holds an exclusive advisory lock on `<instance>/lock`; the lock805 /// is released by the kernel when the process dies, including a crash. A sweep806 /// therefore never removes a directory that a current control process owns.807 /// It only inspects names of the fixed 32-hex shape, so an operator's file in808 /// the run root is not touched. Returns how many stale directories were809 /// removed.810 pub fn sweep_stale(run_dir: &Path) -> Result<usize, SpawnError> {811 let entries = match fs::read_dir(run_dir) {812 Ok(entries) => entries,813 Err(why) if why.kind() == std::io::ErrorKind::NotFound => return Ok(0),814 Err(why) => {815 return Err(SpawnError::Io(format!("{}: {why}", run_dir.display())));816 }817 };818 let mut removed = 0;819 for entry in entries {820 let entry = match entry {821 Ok(entry) => entry,822 Err(_) => continue,823 };824 let Some(name) = entry.file_name().to_str().map(str::to_owned) else {825 continue;826 };827 if !is_instance_name(&name) || !entry.path().is_dir() {828 continue;829 }830 let lock_path = entry.path().join(LOCK_FILE);831 let lock = match OpenOptions::new().read(true).write(true).open(&lock_path) {832 Ok(lock) => lock,833 Err(_) => continue,834 };835 match flock(&lock, FlockOperation::NonBlockingLockExclusive) {836 Ok(()) => {837 drop(lock);838 if fs::remove_dir_all(entry.path()).is_ok() {839 removed += 1;840 }841 }842 Err(Errno::WOULDBLOCK) => {}843 Err(_) => {}844 }845 }846 Ok(removed)847 }848 849 fn is_instance_name(name: &str) -> bool {850 name.len() == NAME_BYTES * 2 && name.bytes().all(|byte| byte.is_ascii_hexdigit())851 }852 853 fn name() -> Result<String, SpawnError> {854 let mut bytes = [0u8; NAME_BYTES];855 File::open(URANDOM)856 .and_then(|mut file| file.read_exact(&mut bytes))857 .map_err(|why| SpawnError::Io(why.to_string()))?;858 859 let mut name = String::with_capacity(NAME_BYTES * 2);860 for byte in bytes {861 name.push(HEX_DIGITS[(byte >> NIBBLE_BITS) as usize] as char);862 name.push(HEX_DIGITS[(byte & LOW_NIBBLE) as usize] as char);863 }864 Ok(name)865 }