aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-supervisor / src / supervisor.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Process supervision with typed, generation-scoped readiness (issue #534). |
| 17 | //! |
| 18 | //! Readiness contract: |
| 19 | //! - Every successful spawn increments the service's `generation` and puts it in |
| 20 | //! [`ServiceState::Spawned`]. A spawned child is never [`ServiceState::Ready`] until a |
| 21 | //! probe taken for that same pid and generation succeeds. |
| 22 | //! - With `health_url`: `Ready` only after an HTTP GET to that URL returns a 2xx status |
| 23 | //! while the pid is alive. A non-2xx status, a connection error or a timeout gives |
| 24 | //! [`ServiceState::Unhealthy`]. |
| 25 | //! - Without `health_url`: `Ready` once the liveness check finds the pid alive in `/proc`. |
| 26 | //! This is liveness, not readiness: it says the process exists, not that it serves. |
| 27 | //! - Probes run with the state mutex released. Each result carries the (pid, generation) |
| 28 | //! it was taken for and is discarded when the service has since restarted or stopped, |
| 29 | //! so a slow answer for an old child can never mark its replacement ready. |
| 30 | |
| 31 | use std::collections::HashMap; |
| 32 | use std::future::Future; |
| 33 | use std::sync::Arc; |
| 34 | use std::time::{Duration, Instant}; |
| 35 | use tokio::sync::{broadcast, Mutex, Notify}; |
| 36 | use tokio::task::JoinSet; |
| 37 | use tokio::time::{interval, sleep, MissedTickBehavior}; |
| 38 | use tracing::{error, info, warn}; |
| 39 | |
| 40 | use crate::config::{ServiceConfig, SupervisorConfig}; |
| 41 | use crate::proc_telemetry::get_process_stats; |
| 42 | |
| 43 | pub fn compute_restart_delay(restart_count: u32, base_secs: u64, max_secs: u64) -> Duration { |
| 44 | let factor = 2u64.saturating_pow(restart_count.saturating_sub(1)); |
| 45 | let secs = std::cmp::min(base_secs.saturating_mul(factor), max_secs); |
| 46 | Duration::from_secs(secs) |
| 47 | } |
| 48 | |
| 49 | /// Lifecycle state of one managed service. |
| 50 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 51 | pub enum ServiceState { |
| 52 | /// Not running and not scheduled to run (initial state, shutdown, or `restart = "no"`). |
| 53 | Stopped, |
| 54 | /// Child spawned; no probe has been dispatched for this generation yet. |
| 55 | Spawned, |
| 56 | /// First probe for this generation is in flight; not ready. |
| 57 | Probing, |
| 58 | /// Readiness condition met for the current generation (see module docs). |
| 59 | Ready, |
| 60 | /// Last probe failed, the child exited and awaits restart, or the spawn failed. |
| 61 | Unhealthy, |
| 62 | } |
| 63 | |
| 64 | impl ServiceState { |
| 65 | pub fn is_ready(self) -> bool { |
| 66 | self == ServiceState::Ready |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone)] |
| 71 | pub struct ManagedServiceState { |
| 72 | pub name: String, |
| 73 | pub config: ServiceConfig, |
| 74 | pub pid: Option<u32>, |
| 75 | /// Incremented on every successful spawn; 0 means never spawned. |
| 76 | pub generation: u64, |
| 77 | pub state: ServiceState, |
| 78 | pub restart_count: u32, |
| 79 | pub uptime_secs: u64, |
| 80 | pub rss_mb: f64, |
| 81 | pub spawned_at: Option<Instant>, |
| 82 | } |
| 83 | |
| 84 | /// Tunables. `Default` keeps the previous fixed values: 3 s probe tick, 1500 ms HTTP |
| 85 | /// timeout, restart backoff base 2 s capped at 60 s, 5 s retry after a failed spawn. |
| 86 | #[derive(Debug, Clone)] |
| 87 | pub struct SupervisorOptions { |
| 88 | pub probe_interval: Duration, |
| 89 | pub probe_timeout: Duration, |
| 90 | pub restart_base_secs: u64, |
| 91 | pub restart_max_secs: u64, |
| 92 | pub spawn_retry_delay: Duration, |
| 93 | /// How long shutdown waits for supervise tasks to kill and reap their children. |
| 94 | pub shutdown_grace: Duration, |
| 95 | } |
| 96 | |
| 97 | impl Default for SupervisorOptions { |
| 98 | fn default() -> Self { |
| 99 | Self { |
| 100 | probe_interval: Duration::from_secs(3), |
| 101 | probe_timeout: Duration::from_millis(1500), |
| 102 | restart_base_secs: 2, |
| 103 | restart_max_secs: 60, |
| 104 | spawn_retry_delay: Duration::from_secs(5), |
| 105 | shutdown_grace: Duration::from_secs(5), |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// What a probe was taken for, captured under the mutex before the lock is dropped. |
| 111 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 112 | pub struct ProbeTicket { |
| 113 | pub name: String, |
| 114 | pub pid: u32, |
| 115 | pub generation: u64, |
| 116 | pub health_url: Option<String>, |
| 117 | } |
| 118 | |
| 119 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 120 | pub enum ProbeOutcome { |
| 121 | /// Pid alive and, when a health_url is configured, it answered 2xx. |
| 122 | Healthy, |
| 123 | /// health_url answered with this non-2xx status. |
| 124 | HttpFailure(u16), |
| 125 | /// health_url could not be reached (connect error, timeout, protocol error). |
| 126 | HttpError(String), |
| 127 | /// The pid is no longer alive. |
| 128 | ProcessGone, |
| 129 | } |
| 130 | |
| 131 | #[derive(Debug, Clone)] |
| 132 | pub struct ProbeReport { |
| 133 | pub ticket: ProbeTicket, |
| 134 | pub outcome: ProbeOutcome, |
| 135 | pub rss_bytes: u64, |
| 136 | } |
| 137 | |
| 138 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 139 | pub enum ApplyResult { |
| 140 | Applied { |
| 141 | from: ServiceState, |
| 142 | to: ServiceState, |
| 143 | }, |
| 144 | /// The service restarted or stopped since the ticket was taken; result discarded. |
| 145 | Stale, |
| 146 | UnknownService, |
| 147 | } |
| 148 | |
| 149 | /// Records a successful spawn and returns the new generation. |
| 150 | pub fn record_spawn( |
| 151 | states: &mut HashMap<String, ManagedServiceState>, |
| 152 | name: &str, |
| 153 | pid: Option<u32>, |
| 154 | ) -> u64 { |
| 155 | match states.get_mut(name) { |
| 156 | Some(st) => { |
| 157 | st.generation += 1; |
| 158 | st.pid = pid; |
| 159 | st.state = ServiceState::Spawned; |
| 160 | st.spawned_at = Some(Instant::now()); |
| 161 | st.uptime_secs = 0; |
| 162 | st.rss_mb = 0.0; |
| 163 | st.generation |
| 164 | } |
| 165 | None => 0, |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// Records that the child of `generation` is gone. `next` is `Unhealthy` while a restart |
| 170 | /// is pending, `Stopped` for shutdown or `restart = "no"`. Returns the restart count. |
| 171 | pub fn record_exit( |
| 172 | states: &mut HashMap<String, ManagedServiceState>, |
| 173 | name: &str, |
| 174 | generation: u64, |
| 175 | next: ServiceState, |
| 176 | count_restart: bool, |
| 177 | ) -> u32 { |
| 178 | match states.get_mut(name) { |
| 179 | Some(st) if st.generation == generation => { |
| 180 | st.pid = None; |
| 181 | st.state = next; |
| 182 | st.spawned_at = None; |
| 183 | if count_restart { |
| 184 | st.restart_count += 1; |
| 185 | } |
| 186 | st.restart_count |
| 187 | } |
| 188 | Some(st) => st.restart_count, |
| 189 | None => 0, |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /// Takes probe tickets for every running service and moves `Spawned` to `Probing`. |
| 194 | /// Call with the lock held; it does no I/O. |
| 195 | pub fn begin_probe_round(states: &mut HashMap<String, ManagedServiceState>) -> Vec<ProbeTicket> { |
| 196 | let mut tickets = Vec::new(); |
| 197 | for st in states.values_mut() { |
| 198 | let Some(pid) = st.pid else { continue }; |
| 199 | if st.state == ServiceState::Stopped { |
| 200 | continue; |
| 201 | } |
| 202 | if st.state == ServiceState::Spawned { |
| 203 | st.state = ServiceState::Probing; |
| 204 | } |
| 205 | tickets.push(ProbeTicket { |
| 206 | name: st.name.clone(), |
| 207 | pid, |
| 208 | generation: st.generation, |
| 209 | health_url: st.config.health_url.clone(), |
| 210 | }); |
| 211 | } |
| 212 | tickets |
| 213 | } |
| 214 | |
| 215 | /// Applies one probe result if, and only if, it still describes the current child. |
| 216 | /// Call with the lock held; it does no I/O. |
| 217 | pub fn apply_probe_report( |
| 218 | states: &mut HashMap<String, ManagedServiceState>, |
| 219 | report: &ProbeReport, |
| 220 | ) -> ApplyResult { |
| 221 | let Some(st) = states.get_mut(&report.ticket.name) else { |
| 222 | return ApplyResult::UnknownService; |
| 223 | }; |
| 224 | if st.pid != Some(report.ticket.pid) |
| 225 | || st.generation != report.ticket.generation |
| 226 | || st.state == ServiceState::Stopped |
| 227 | { |
| 228 | return ApplyResult::Stale; |
| 229 | } |
| 230 | let from = st.state; |
| 231 | let to = match report.outcome { |
| 232 | ProbeOutcome::Healthy => ServiceState::Ready, |
| 233 | ProbeOutcome::HttpFailure(_) | ProbeOutcome::HttpError(_) | ProbeOutcome::ProcessGone => { |
| 234 | ServiceState::Unhealthy |
| 235 | } |
| 236 | }; |
| 237 | st.state = to; |
| 238 | if report.outcome != ProbeOutcome::ProcessGone { |
| 239 | st.rss_mb = report.rss_bytes as f64 / (1024.0 * 1024.0); |
| 240 | } |
| 241 | st.uptime_secs = st.spawned_at.map(|t| t.elapsed().as_secs()).unwrap_or(0); |
| 242 | ApplyResult::Applied { from, to } |
| 243 | } |
| 244 | |
| 245 | /// Runs one probe with no lock held. The HTTP request is bounded by the client timeout. |
| 246 | pub async fn probe_one(client: aien_localhttp::Client, ticket: ProbeTicket) -> ProbeReport { |
| 247 | let stats = get_process_stats(ticket.pid); |
| 248 | let outcome = if !stats.is_alive { |
| 249 | ProbeOutcome::ProcessGone |
| 250 | } else { |
| 251 | match ticket.health_url.as_deref() { |
| 252 | None => ProbeOutcome::Healthy, |
| 253 | Some(url) => match client.get(url).send().await { |
| 254 | Ok(res) if res.status().is_success() => ProbeOutcome::Healthy, |
| 255 | Ok(res) => ProbeOutcome::HttpFailure(res.status().as_u16()), |
| 256 | Err(e) => ProbeOutcome::HttpError(e.to_string()), |
| 257 | }, |
| 258 | } |
| 259 | }; |
| 260 | ProbeReport { |
| 261 | ticket, |
| 262 | outcome, |
| 263 | rss_bytes: stats.rss_bytes, |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | type StateMap = Arc<Mutex<HashMap<String, ManagedServiceState>>>; |
| 268 | |
| 269 | pub struct Supervisor { |
| 270 | config: SupervisorConfig, |
| 271 | options: SupervisorOptions, |
| 272 | states: StateMap, |
| 273 | } |
| 274 | |
| 275 | impl Supervisor { |
| 276 | pub fn new(config: SupervisorConfig) -> Self { |
| 277 | Self::with_options(config, SupervisorOptions::default()) |
| 278 | } |
| 279 | |
| 280 | pub fn with_options(config: SupervisorConfig, options: SupervisorOptions) -> Self { |
| 281 | let mut states = HashMap::new(); |
| 282 | for (name, s_cfg) in &config.services { |
| 283 | states.insert( |
| 284 | name.clone(), |
| 285 | ManagedServiceState { |
| 286 | name: name.clone(), |
| 287 | config: s_cfg.clone(), |
| 288 | pid: None, |
| 289 | generation: 0, |
| 290 | state: ServiceState::Stopped, |
| 291 | restart_count: 0, |
| 292 | uptime_secs: 0, |
| 293 | rss_mb: 0.0, |
| 294 | spawned_at: None, |
| 295 | }, |
| 296 | ); |
| 297 | } |
| 298 | Self { |
| 299 | config, |
| 300 | options, |
| 301 | states: Arc::new(Mutex::new(states)), |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// Copy of the in-process state. There is no IPC: only the process running the |
| 306 | /// daemon can see this. |
| 307 | pub async fn snapshot(&self) -> HashMap<String, ManagedServiceState> { |
| 308 | self.states.lock().await.clone() |
| 309 | } |
| 310 | |
| 311 | /// Runs until Ctrl-C. |
| 312 | pub async fn run_daemon(&self) -> Result<(), Box<dyn std::error::Error>> { |
| 313 | self.run_until(async { |
| 314 | let _ = tokio::signal::ctrl_c().await; |
| 315 | info!("Received termination signal. Shutting down all managed services gracefully..."); |
| 316 | }) |
| 317 | .await?; |
| 318 | Ok(()) |
| 319 | } |
| 320 | |
| 321 | /// Runs until `shutdown` completes, then kills and reaps every child. |
| 322 | /// |
| 323 | /// Refuses to start, before spawning anything, when a `health_url` is not a |
| 324 | /// plain `http://` URL (an `https://` URL fails with |
| 325 | /// [`aien_localhttp::Error::HttpsRefused`]). |
| 326 | pub async fn run_until<F>(&self, shutdown: F) -> Result<(), aien_localhttp::Error> |
| 327 | where |
| 328 | F: Future<Output = ()>, |
| 329 | { |
| 330 | self.config.validate_health_urls()?; |
| 331 | info!( |
| 332 | "Starting SparkOS Sovereign Supervisor with {} service(s)...", |
| 333 | self.config.services.len() |
| 334 | ); |
| 335 | let client = aien_localhttp::Client::builder() |
| 336 | .timeout(self.options.probe_timeout) |
| 337 | .connect_timeout(self.options.probe_timeout) |
| 338 | .build(); |
| 339 | |
| 340 | let (shutdown_tx, _) = broadcast::channel::<()>(1); |
| 341 | let kick = Arc::new(Notify::new()); |
| 342 | let mut supervisors = JoinSet::new(); |
| 343 | for (name, s_cfg) in self.config.services.clone() { |
| 344 | supervisors.spawn(Self::supervise_loop( |
| 345 | name, |
| 346 | s_cfg, |
| 347 | self.states.clone(), |
| 348 | shutdown_tx.subscribe(), |
| 349 | kick.clone(), |
| 350 | self.options.clone(), |
| 351 | )); |
| 352 | } |
| 353 | |
| 354 | tokio::pin!(shutdown); |
| 355 | let mut tick = interval(self.options.probe_interval); |
| 356 | tick.set_missed_tick_behavior(MissedTickBehavior::Delay); |
| 357 | |
| 358 | loop { |
| 359 | tokio::select! { |
| 360 | biased; |
| 361 | _ = &mut shutdown => break, |
| 362 | _ = tick.tick() => {} |
| 363 | _ = kick.notified() => {} |
| 364 | } |
| 365 | |
| 366 | let tickets = { |
| 367 | let mut map = self.states.lock().await; |
| 368 | begin_probe_round(&mut map) |
| 369 | }; |
| 370 | let mut probes = JoinSet::new(); |
| 371 | for ticket in tickets { |
| 372 | probes.spawn(probe_one(client.clone(), ticket)); |
| 373 | } |
| 374 | let stop = loop { |
| 375 | tokio::select! { |
| 376 | biased; |
| 377 | _ = &mut shutdown => { |
| 378 | probes.abort_all(); |
| 379 | break true; |
| 380 | } |
| 381 | joined = probes.join_next() => match joined { |
| 382 | None => break false, |
| 383 | Some(Ok(report)) => { |
| 384 | let applied = { |
| 385 | let mut map = self.states.lock().await; |
| 386 | apply_probe_report(&mut map, &report) |
| 387 | }; |
| 388 | log_apply(&report, applied); |
| 389 | } |
| 390 | Some(Err(e)) => warn!("Health probe task failed: {}", e), |
| 391 | } |
| 392 | } |
| 393 | }; |
| 394 | if stop { |
| 395 | break; |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | let _ = shutdown_tx.send(()); |
| 400 | let deadline = tokio::time::Instant::now() + self.options.shutdown_grace; |
| 401 | while !supervisors.is_empty() { |
| 402 | match tokio::time::timeout_at(deadline, supervisors.join_next()).await { |
| 403 | Ok(Some(Err(e))) => warn!("Supervise task failed: {}", e), |
| 404 | Ok(_) => {} |
| 405 | Err(_) => { |
| 406 | warn!( |
| 407 | "{} supervise task(s) did not stop within {:?}; aborting them", |
| 408 | supervisors.len(), |
| 409 | self.options.shutdown_grace |
| 410 | ); |
| 411 | supervisors.abort_all(); |
| 412 | break; |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | info!("SparkOS Sovereign Supervisor halted cleanly."); |
| 418 | Ok(()) |
| 419 | } |
| 420 | |
| 421 | async fn supervise_loop( |
| 422 | name: String, |
| 423 | config: ServiceConfig, |
| 424 | states: StateMap, |
| 425 | mut shutdown_rx: broadcast::Receiver<()>, |
| 426 | kick: Arc<Notify>, |
| 427 | options: SupervisorOptions, |
| 428 | ) { |
| 429 | loop { |
| 430 | let command_path = if let Some(stripped) = config.command.strip_prefix("~/") { |
| 431 | let home = std::env::var("HOME") |
| 432 | .or_else(|_| std::env::var("USERPROFILE")) |
| 433 | .unwrap_or_else(|_| ".".to_string()); |
| 434 | format!("{}/{}", home, stripped) |
| 435 | } else { |
| 436 | config.command.clone() |
| 437 | }; |
| 438 | info!( |
| 439 | "[{}] Spawning process: {} {:?}...", |
| 440 | name, command_path, config.args |
| 441 | ); |
| 442 | let mut cmd = tokio::process::Command::new(&command_path); |
| 443 | cmd.args(&config.args); |
| 444 | for (k, v) in &config.env { |
| 445 | cmd.env(k, v); |
| 446 | } |
| 447 | |
| 448 | match cmd.spawn() { |
| 449 | Ok(mut child) => { |
| 450 | let pid = child.id(); |
| 451 | let generation = { |
| 452 | let mut map = states.lock().await; |
| 453 | record_spawn(&mut map, &name, pid) |
| 454 | }; |
| 455 | kick.notify_one(); |
| 456 | info!( |
| 457 | "[{}] Running with PID {:?} (generation {}); not ready until probed", |
| 458 | name, pid, generation |
| 459 | ); |
| 460 | |
| 461 | tokio::select! { |
| 462 | _ = shutdown_rx.recv() => { |
| 463 | info!("[{}] Terminating child PID {:?} for supervisor shutdown...", name, pid); |
| 464 | let _ = child.kill().await; |
| 465 | let _ = child.wait().await; |
| 466 | let mut map = states.lock().await; |
| 467 | record_exit(&mut map, &name, generation, ServiceState::Stopped, false); |
| 468 | return; |
| 469 | } |
| 470 | status_res = child.wait() => { |
| 471 | match status_res { |
| 472 | Ok(status) => { |
| 473 | warn!("[{}] Process exited with status: {}", name, status); |
| 474 | } |
| 475 | Err(e) => { |
| 476 | error!("[{}] Process error: {}", name, e); |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | let next = if config.restart == "no" { |
| 483 | ServiceState::Stopped |
| 484 | } else { |
| 485 | ServiceState::Unhealthy |
| 486 | }; |
| 487 | let st_restarts = { |
| 488 | let mut map = states.lock().await; |
| 489 | record_exit(&mut map, &name, generation, next, true) |
| 490 | }; |
| 491 | |
| 492 | if config.restart == "no" { |
| 493 | info!("[{}] Configured restart is no. Halting supervision.", name); |
| 494 | break; |
| 495 | } |
| 496 | |
| 497 | let delay = compute_restart_delay( |
| 498 | st_restarts, |
| 499 | options.restart_base_secs, |
| 500 | options.restart_max_secs, |
| 501 | ); |
| 502 | info!( |
| 503 | "[{}] Restarting in {}s (restart #{})...", |
| 504 | name, |
| 505 | delay.as_secs(), |
| 506 | st_restarts |
| 507 | ); |
| 508 | tokio::select! { |
| 509 | _ = shutdown_rx.recv() => { |
| 510 | mark_stopped(&states, &name).await; |
| 511 | return; |
| 512 | } |
| 513 | _ = sleep(delay) => {} |
| 514 | } |
| 515 | } |
| 516 | Err(e) => { |
| 517 | error!( |
| 518 | "[{}] Failed to spawn: {}. Retrying in {:?}...", |
| 519 | name, e, options.spawn_retry_delay |
| 520 | ); |
| 521 | { |
| 522 | let mut map = states.lock().await; |
| 523 | if let Some(st) = map.get_mut(&name) { |
| 524 | st.state = ServiceState::Unhealthy; |
| 525 | } |
| 526 | } |
| 527 | tokio::select! { |
| 528 | _ = shutdown_rx.recv() => { |
| 529 | mark_stopped(&states, &name).await; |
| 530 | return; |
| 531 | } |
| 532 | _ = sleep(options.spawn_retry_delay) => {} |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | /// Used only when no child is running (restart backoff or spawn retry). |
| 541 | async fn mark_stopped(states: &StateMap, name: &str) { |
| 542 | let mut map = states.lock().await; |
| 543 | if let Some(st) = map.get_mut(name) { |
| 544 | st.pid = None; |
| 545 | st.state = ServiceState::Stopped; |
| 546 | st.spawned_at = None; |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | fn log_apply(report: &ProbeReport, applied: ApplyResult) { |
| 551 | let t = &report.ticket; |
| 552 | match applied { |
| 553 | ApplyResult::Applied { from, to } if from != to => match to { |
| 554 | ServiceState::Ready => info!( |
| 555 | "[{}] {:?} -> Ready (pid {}, generation {})", |
| 556 | t.name, from, t.pid, t.generation |
| 557 | ), |
| 558 | _ => warn!( |
| 559 | "[{}] {:?} -> {:?} (pid {}, generation {}): {:?}", |
| 560 | t.name, from, to, t.pid, t.generation, report.outcome |
| 561 | ), |
| 562 | }, |
| 563 | ApplyResult::Applied { .. } => {} |
| 564 | ApplyResult::Stale => info!( |
| 565 | "[{}] Discarded stale probe result for pid {} generation {}", |
| 566 | t.name, t.pid, t.generation |
| 567 | ), |
| 568 | ApplyResult::UnknownService => warn!("[{}] Probe result for unknown service", t.name), |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | #[cfg(test)] |
| 573 | mod tests { |
| 574 | use super::*; |
| 575 | |
| 576 | fn svc(name: &str, health_url: Option<&str>) -> HashMap<String, ManagedServiceState> { |
| 577 | let mut config = SupervisorConfig { |
| 578 | services: HashMap::new(), |
| 579 | }; |
| 580 | config.services.insert( |
| 581 | name.to_string(), |
| 582 | ServiceConfig { |
| 583 | command: "sleep".into(), |
| 584 | args: vec!["30".into()], |
| 585 | env: HashMap::new(), |
| 586 | restart: "always".into(), |
| 587 | health_url: health_url.map(String::from), |
| 588 | }, |
| 589 | ); |
| 590 | Supervisor::new(config).states.try_lock().unwrap().clone() |
| 591 | } |
| 592 | |
| 593 | fn report(ticket: &ProbeTicket, outcome: ProbeOutcome) -> ProbeReport { |
| 594 | ProbeReport { |
| 595 | ticket: ticket.clone(), |
| 596 | outcome, |
| 597 | rss_bytes: 4096, |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | #[test] |
| 602 | fn test_compute_restart_delay_backoff() { |
| 603 | assert_eq!(compute_restart_delay(1, 2, 60), Duration::from_secs(2)); |
| 604 | assert_eq!(compute_restart_delay(2, 2, 60), Duration::from_secs(4)); |
| 605 | assert_eq!(compute_restart_delay(3, 2, 60), Duration::from_secs(8)); |
| 606 | assert_eq!(compute_restart_delay(4, 2, 60), Duration::from_secs(16)); |
| 607 | assert_eq!(compute_restart_delay(5, 2, 60), Duration::from_secs(32)); |
| 608 | assert_eq!(compute_restart_delay(6, 2, 60), Duration::from_secs(60)); // capped at max |
| 609 | } |
| 610 | |
| 611 | #[test] |
| 612 | fn default_options_keep_previous_fixed_values() { |
| 613 | let o = SupervisorOptions::default(); |
| 614 | assert_eq!(o.probe_interval, Duration::from_secs(3)); |
| 615 | assert_eq!(o.probe_timeout, Duration::from_millis(1500)); |
| 616 | assert_eq!((o.restart_base_secs, o.restart_max_secs), (2, 60)); |
| 617 | assert_eq!(o.spawn_retry_delay, Duration::from_secs(5)); |
| 618 | } |
| 619 | |
| 620 | #[test] |
| 621 | fn new_service_starts_stopped_generation_zero() { |
| 622 | let m = svc("a", None); |
| 623 | assert_eq!(m["a"].state, ServiceState::Stopped); |
| 624 | assert_eq!(m["a"].generation, 0); |
| 625 | } |
| 626 | |
| 627 | #[test] |
| 628 | fn spawn_is_not_ready_and_probing_is_not_ready() { |
| 629 | let mut m = svc("a", None); |
| 630 | assert_eq!(record_spawn(&mut m, "a", Some(100)), 1); |
| 631 | assert_eq!(m["a"].state, ServiceState::Spawned); |
| 632 | assert!(!m["a"].state.is_ready()); |
| 633 | let tickets = begin_probe_round(&mut m); |
| 634 | assert_eq!(tickets.len(), 1); |
| 635 | assert_eq!(m["a"].state, ServiceState::Probing); |
| 636 | assert!(!m["a"].state.is_ready()); |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn healthy_report_makes_ready_failures_make_unhealthy() { |
| 641 | let mut m = svc("a", Some("http://127.0.0.1:1/health")); |
| 642 | record_spawn(&mut m, "a", Some(100)); |
| 643 | let t = begin_probe_round(&mut m).remove(0); |
| 644 | assert_eq!( |
| 645 | apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), |
| 646 | ApplyResult::Applied { |
| 647 | from: ServiceState::Probing, |
| 648 | to: ServiceState::Ready |
| 649 | } |
| 650 | ); |
| 651 | for bad in [ |
| 652 | ProbeOutcome::HttpFailure(500), |
| 653 | ProbeOutcome::HttpError("refused".into()), |
| 654 | ProbeOutcome::ProcessGone, |
| 655 | ] { |
| 656 | assert_eq!( |
| 657 | apply_probe_report(&mut m, &report(&t, bad)), |
| 658 | ApplyResult::Applied { |
| 659 | from: ServiceState::Ready, |
| 660 | to: ServiceState::Unhealthy |
| 661 | } |
| 662 | ); |
| 663 | apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)); |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn stale_generation_is_ignored_even_with_reused_pid() { |
| 669 | let mut m = svc("a", None); |
| 670 | record_spawn(&mut m, "a", Some(100)); |
| 671 | let old = begin_probe_round(&mut m).remove(0); |
| 672 | record_exit(&mut m, "a", 1, ServiceState::Unhealthy, true); |
| 673 | // Same pid again: only the generation tells the two children apart. |
| 674 | assert_eq!(record_spawn(&mut m, "a", Some(100)), 2); |
| 675 | assert_eq!( |
| 676 | apply_probe_report(&mut m, &report(&old, ProbeOutcome::Healthy)), |
| 677 | ApplyResult::Stale |
| 678 | ); |
| 679 | assert_eq!(m["a"].state, ServiceState::Spawned); |
| 680 | } |
| 681 | |
| 682 | #[test] |
| 683 | fn stale_pid_is_ignored() { |
| 684 | let mut m = svc("a", None); |
| 685 | record_spawn(&mut m, "a", Some(100)); |
| 686 | let mut t = begin_probe_round(&mut m).remove(0); |
| 687 | t.pid = 101; |
| 688 | assert_eq!( |
| 689 | apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), |
| 690 | ApplyResult::Stale |
| 691 | ); |
| 692 | assert_eq!(m["a"].state, ServiceState::Probing); |
| 693 | } |
| 694 | |
| 695 | #[test] |
| 696 | fn result_after_stop_is_ignored() { |
| 697 | let mut m = svc("a", None); |
| 698 | record_spawn(&mut m, "a", Some(100)); |
| 699 | let t = begin_probe_round(&mut m).remove(0); |
| 700 | record_exit(&mut m, "a", 1, ServiceState::Stopped, false); |
| 701 | assert_eq!( |
| 702 | apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), |
| 703 | ApplyResult::Stale |
| 704 | ); |
| 705 | assert_eq!(m["a"].state, ServiceState::Stopped); |
| 706 | assert!(begin_probe_round(&mut m).is_empty()); |
| 707 | } |
| 708 | |
| 709 | #[test] |
| 710 | fn unknown_service_is_reported() { |
| 711 | let mut m = svc("a", None); |
| 712 | let t = ProbeTicket { |
| 713 | name: "ghost".into(), |
| 714 | pid: 1, |
| 715 | generation: 1, |
| 716 | health_url: None, |
| 717 | }; |
| 718 | assert_eq!( |
| 719 | apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), |
| 720 | ApplyResult::UnknownService |
| 721 | ); |
| 722 | } |
| 723 | |
| 724 | #[test] |
| 725 | fn exit_for_old_generation_does_not_touch_new_child() { |
| 726 | let mut m = svc("a", None); |
| 727 | record_spawn(&mut m, "a", Some(100)); |
| 728 | record_spawn(&mut m, "a", Some(200)); |
| 729 | record_exit(&mut m, "a", 1, ServiceState::Unhealthy, true); |
| 730 | assert_eq!(m["a"].pid, Some(200)); |
| 731 | assert_eq!(m["a"].state, ServiceState::Spawned); |
| 732 | assert_eq!(m["a"].restart_count, 0); |
| 733 | } |
| 734 | } |