Skip to main content

waratah_notebook/
supervisor.rs

1//! jupyter-server sidecar lifecycle: spawn, readiness, restart, group kill.
2//!
3//! One sidecar per compute process, spawned in-process as a child in its
4//! own process group (`process_group(0)`). Kernels, however, run in their
5//! OWN sessions (`jupyter_client` launches them with
6//! `start_new_session=True`), so a group SIGKILL reaches only the sidecar;
7//! kernel cleanup is path-dependent:
8//!
9//! * graceful shutdown (signals, `SupervisorHandle::shutdown`) SIGTERMs the
10//!   sidecar first — its own handler shuts kernels down — then
11//!   group-SIGKILLs after [`SHUTDOWN_GRACE`];
12//! * hard kills (handle Drop, readiness timeout) sweep `/proc` for
13//!   processes carrying `JPY_PARENT_PID=<sidecar pid>` and SIGKILL them
14//!   ([`kill_orphaned_kernels`]).
15//!
16//! With both, `waratah stop` leaves no orphaned Python. If the sidecar
17//! dies on its own, it is restarted with capped exponential backoff and a
18//! freshly picked port; readiness (sidecar answered `GET /jupyter/api`
19//! with the token) is published on [`NotebookState`] so the proxy and
20//! capability endpoints follow along.
21
22use std::net::SocketAddr;
23use std::process::Stdio;
24use std::sync::Arc;
25use std::time::{Duration, Instant};
26
27use tokio::io::{AsyncBufReadExt, BufReader};
28use tokio::process::{Child, ChildStderr, ChildStdout, Command};
29use tokio::sync::watch;
30
31use crate::error::NotebookError;
32use crate::jupyter_config::{self, JupyterConfigSpec};
33use crate::options::NotebookOptions;
34use crate::state::NotebookState;
35use crate::{kernelspec, proxy, python_env};
36
37/// Poll interval while waiting for the sidecar to answer `GET /jupyter/api`.
38const READINESS_POLL: Duration = Duration::from_millis(200);
39/// Total readiness budget after each (re)start. Python startup is slow.
40const READINESS_TIMEOUT: Duration = Duration::from_secs(30);
41/// First restart backoff after a crash; doubles from here.
42const RESTART_BACKOFF_START: Duration = Duration::from_millis(500);
43/// Backoff ceiling between restart attempts.
44const RESTART_BACKOFF_MAX: Duration = Duration::from_secs(30);
45/// A run this stable resets the backoff curve.
46const STABLE_RUN: Duration = Duration::from_secs(60);
47
48/// How long the sidecar gets to shut its kernels down cleanly after
49/// SIGTERM before its process group is SIGKILLed. jupyter_client starts
50/// kernels with `start_new_session=True`, so kernels live in their OWN
51/// sessions and a group kill alone can never reach them — only the
52/// sidecar's SIGTERM cleanup (request kernel shutdowns, wait, kill) does.
53const SHUTDOWN_GRACE: Duration = Duration::from_secs(8);
54
55/// The generated config file name inside the runtime dir.
56const CONFIG_FILE: &str = "jupyter_server_config.py";
57
58/// Running sidecar supervisor.
59///
60/// [`SupervisorHandle::shutdown`] is the clean path (sidecar SIGTERM →
61/// kernel cleanup → group SIGKILL). Dropping the handle is the hard path
62/// mirroring `waratah_bin::SpawnedCluster`'s kill-on-drop: group SIGKILL
63/// for the sidecar, then the [`kill_orphaned_kernels`] sweep for its
64/// session-detached kernels.
65pub struct SupervisorHandle {
66    shutdown: watch::Sender<bool>,
67    join: Option<tokio::task::JoinHandle<()>>,
68    pgid: Arc<std::sync::Mutex<Option<u32>>>,
69}
70
71impl SupervisorHandle {
72    /// Fast-fail validation, then start the supervision task.
73    ///
74    /// Only cheap checks run inline (interpreter exists and is 3.11+); venv
75    /// provisioning and the first spawn happen in the background so engine
76    /// startup is not gated on slow Python work. Readiness is observable
77    /// through `state` (`GET /waratah/notebooks`, the cluster block, and
78    /// the proxy's 503s until then).
79    pub fn spawn(
80        options: NotebookOptions,
81        state: Arc<NotebookState>,
82    ) -> Result<Self, NotebookError> {
83        python_env::validate(&options)?;
84        let (shutdown, rx) = watch::channel(false);
85        let pgid = Arc::new(std::sync::Mutex::new(None));
86        let join = tokio::spawn(supervise(options, state, rx, pgid.clone()));
87        Ok(Self {
88            shutdown,
89            join: Some(join),
90            pgid,
91        })
92    }
93
94    /// Clean stop: signal the supervision loop, whose exit path SIGTERMs
95    /// the sidecar so it shuts its kernels down, then reaps.
96    pub async fn shutdown(mut self) {
97        let _ = self.shutdown.send(true);
98        if let Some(join) = self.join.take() {
99            let _ = join.await;
100        }
101    }
102}
103
104impl Drop for SupervisorHandle {
105    fn drop(&mut self) {
106        // Wake the loop; even if the runtime tears the task down before it
107        // runs, the synchronous kills here (and the loop's own copies) mean
108        // the sidecar and its kernels do not survive us.
109        let _ = self.shutdown.send(true);
110        if let Some(pgid) = *self.pgid.lock().expect("pgid lock") {
111            kill_process_group(pgid);
112            // The group kill cannot reach kernels (own sessions); sweep
113            // them via their parent-pid env before the pid can be recycled.
114            kill_orphaned_kernels(pgid);
115        }
116    }
117}
118
119async fn supervise(
120    options: NotebookOptions,
121    state: Arc<NotebookState>,
122    mut shutdown: watch::Receiver<bool>,
123    pgid_slot: Arc<std::sync::Mutex<Option<u32>>>,
124) {
125    let mut backoff = RESTART_BACKOFF_START;
126    // The live sidecar instance, kept across loop iterations so every exit
127    // path can shut it down through `graceful_shutdown` — kernels only die
128    // via the sidecar's own SIGTERM cleanup (see `SHUTDOWN_GRACE`).
129    let mut live: Option<(Child, u32)> = None;
130    loop {
131        if is_shutdown(&mut shutdown) {
132            break;
133        }
134
135        // Provisioning runs inside the loop: a transient pip failure (say,
136        // network) retries with the same backoff as a crashed sidecar.
137        let python = match python_env::ensure(&options).await {
138            Ok(python) => python,
139            Err(error) => {
140                eprintln!("notebooks: python environment unavailable: {error}");
141                state.set_ready(false);
142                if sleep_or_shutdown(&mut shutdown, backoff).await {
143                    break;
144                }
145                backoff = (backoff * 2).min(RESTART_BACKOFF_MAX);
146                continue;
147            }
148        };
149
150        // Engine-owned port allocation: probe a free port, hand it to the
151        // sidecar with port_retries = 0, and re-pick on every restart. A
152        // probe race surfaces as a fast sidecar exit and a normal restart.
153        let addr = match pick_addr(options.bind) {
154            Ok(addr) => addr,
155            Err(error) => {
156                eprintln!("notebooks: {error}");
157                state.set_ready(false);
158                if sleep_or_shutdown(&mut shutdown, backoff).await {
159                    break;
160                }
161                backoff = (backoff * 2).min(RESTART_BACKOFF_MAX);
162                continue;
163            }
164        };
165        if let Err(error) = write_runtime_files(&options, addr) {
166            // An unwritable runtime dir will not heal on retry.
167            eprintln!("notebooks: could not prepare sidecar runtime: {error}");
168            state.set_ready(false);
169            break;
170        }
171
172        let mut child = match spawn_sidecar(&options, &python) {
173            Ok(child) => child,
174            Err(error) => {
175                eprintln!("notebooks: {error}");
176                state.set_ready(false);
177                if sleep_or_shutdown(&mut shutdown, backoff).await {
178                    break;
179                }
180                backoff = (backoff * 2).min(RESTART_BACKOFF_MAX);
181                continue;
182            }
183        };
184        let Some(pid) = child.id() else {
185            break;
186        };
187        *pgid_slot.lock().expect("pgid lock") = Some(pid);
188        state.set_sidecar_addr(addr).await;
189        state.set_ready(false);
190        pump_output(child.stdout.take(), child.stderr.take());
191        live = Some((child, pid));
192
193        let started = Instant::now();
194        let mut timed_out = false;
195        let ready = loop {
196            if is_shutdown(&mut shutdown) {
197                break false;
198            }
199            match live.as_mut().expect("sidecar just spawned").0.try_wait() {
200                Ok(Some(status)) => {
201                    eprintln!("notebooks: sidecar exited during startup: {status}");
202                    break false;
203                }
204                Ok(None) => {}
205                Err(error) => {
206                    eprintln!("notebooks: could not poll sidecar: {error}");
207                    break false;
208                }
209            }
210            if proxy::probe_ready(addr, &options.token).await {
211                break true;
212            }
213            if started.elapsed() > READINESS_TIMEOUT {
214                eprintln!(
215                    "notebooks: sidecar did not answer on {addr} within {:?}; restarting",
216                    READINESS_TIMEOUT
217                );
218                timed_out = true;
219                break false;
220            }
221            if sleep_or_shutdown(&mut shutdown, READINESS_POLL).await {
222                break false;
223            }
224        };
225
226        if ready {
227            state.set_ready(true);
228            println!("notebook sidecar ready on {addr}");
229            let stable_since = Instant::now();
230            let exited = tokio::select! {
231                status = live.as_mut().expect("sidecar just spawned").0.wait() => {
232                    eprintln!("notebooks: sidecar exited: {status:?}");
233                    true
234                }
235                _ = shutdown_changed(&mut shutdown) => false,
236            };
237            if exited {
238                // The sidecar died on its own (crash, external kill): its
239                // kernels survive it in their own sessions and the
240                // replacement instance knows nothing about them — sweep
241                // them before restarting, or they leak forever.
242                kill_orphaned_kernels(pid);
243                live = None;
244            } else {
245                // Shutdown signalled with a live sidecar: leave `live` in
246                // place, the cleanup below shuts it down gracefully.
247                break;
248            }
249            if stable_since.elapsed() >= STABLE_RUN {
250                backoff = RESTART_BACKOFF_START;
251            }
252        } else if timed_out && let Some((mut child, pid)) = live.take() {
253            kill_process_group(pid);
254            let _ = child.wait().await;
255            // Not reachable by kernels before ready (the proxy 503s), but a
256            // half-up sidecar may have spawned extensions; sweep anyway.
257            kill_orphaned_kernels(pid);
258        }
259        // A non-timeout, non-ready exit (died during startup, or shutdown
260        // raced in) falls through: the shutdown check below breaks, the
261        // death path restarts with a fresh `live` next iteration.
262
263        state.set_ready(false);
264        if is_shutdown(&mut shutdown) {
265            break;
266        }
267        eprintln!("notebooks: restarting sidecar in {backoff:?}");
268        if sleep_or_shutdown(&mut shutdown, backoff).await {
269            break;
270        }
271        backoff = (backoff * 2).min(RESTART_BACKOFF_MAX);
272    }
273
274    state.set_ready(false);
275    if let Some((mut child, pid)) = live.take()
276        && child.try_wait().ok().flatten().is_none()
277    {
278        graceful_shutdown(&mut child, pid).await;
279    }
280
281    // Final backstop: anything left in the sidecar's process group dies.
282    if let Some(pgid) = *pgid_slot.lock().expect("pgid lock") {
283        kill_process_group(pgid);
284    }
285}
286
287/// SIGTERM the sidecar and give it [`SHUTDOWN_GRACE`] to shut its kernels
288/// down, then SIGKILL the process group. Kernels run in their own sessions
289/// (`jupyter_client` `start_new_session=True`); they die because
290/// jupyter-server's SIGTERM handler requests kernel shutdowns and waits,
291/// not because of our signals.
292async fn graceful_shutdown(child: &mut Child, pid: u32) {
293    // SAFETY: kill(2) with SIGTERM to the sidecar pid (its group leader).
294    unsafe {
295        libc::kill(pid as libc::pid_t, libc::SIGTERM);
296    }
297    if tokio::time::timeout(SHUTDOWN_GRACE, child.wait())
298        .await
299        .is_err()
300    {
301        // Sidecar ignored SIGTERM: hard-kill it, then sweep the kernels it
302        // could no longer shut down cleanly.
303        kill_process_group(pid);
304        let _ = child.wait().await;
305        kill_orphaned_kernels(pid);
306    }
307}
308
309/// SIGKILL the orphaned kernels of a hard-killed sidecar.
310///
311/// jupyter_client launches every kernel with `JPY_PARENT_PID=<sidecar pid>`
312/// in its environment, and kernels live in their own sessions — so they
313/// survive every signal we can aim at the sidecar's process group. Scan
314/// `/proc` for processes carrying that env value and kill them directly.
315/// Linux-only (as is the rest of this crate's process handling); elsewhere
316/// this is a no-op and kernels fall back to ipykernel's own parent poller.
317fn kill_orphaned_kernels(sidecar_pid: u32) {
318    let marker = format!("JPY_PARENT_PID={sidecar_pid}");
319    let entries = match std::fs::read_dir("/proc") {
320        Ok(entries) => entries,
321        Err(_) => return,
322    };
323    for entry in entries.flatten() {
324        let Ok(name) = entry.file_name().into_string() else {
325            continue;
326        };
327        let Ok(pid) = name.parse::<libc::pid_t>() else {
328            continue;
329        };
330        // The sidecar itself (and a zombie leftover of it) carries no env.
331        if pid as u32 == sidecar_pid {
332            continue;
333        }
334        let Ok(environ) = std::fs::read(format!("/proc/{pid}/environ")) else {
335            continue;
336        };
337        if environ
338            .split(|byte| *byte == 0)
339            .any(|entry| entry == marker.as_bytes())
340        {
341            // SAFETY: kill(2) SIGKILL to a pid we spawned (same user);
342            // ESRCH (already gone) is fine.
343            unsafe {
344                libc::kill(pid, libc::SIGKILL);
345            }
346        }
347    }
348}
349
350/// Write the generated config and per-repo kernelspecs into the runtime dir.
351fn write_runtime_files(options: &NotebookOptions, addr: SocketAddr) -> Result<(), NotebookError> {
352    std::fs::create_dir_all(&options.runtime_dir)?;
353    std::fs::create_dir_all(&options.dir)?;
354    let spec = JupyterConfigSpec {
355        port: addr.port(),
356        token: &options.token,
357        root_dir: &options.dir,
358        cull_idle_secs: options.cull_idle_secs,
359        allow_origin: &options.waratah_url(),
360    };
361    std::fs::write(
362        options.runtime_dir.join(CONFIG_FILE),
363        jupyter_config::render(&spec),
364    )?;
365    kernelspec::write_spec(&options.runtime_dir, &options.repo)?;
366    Ok(())
367}
368
369fn spawn_sidecar(
370    options: &NotebookOptions,
371    python: &std::path::Path,
372) -> Result<Child, NotebookError> {
373    let config_path = options.runtime_dir.join(CONFIG_FILE);
374    let mut command = Command::new(python);
375    command
376        .arg("-m")
377        .arg("jupyter_server")
378        .arg(format!("--config={}", config_path.display()))
379        // Kernels inherit these (jupyter_client launches with
380        // os.environ when no kernelspec env stanza says otherwise).
381        .env("WARATAH_URL", options.waratah_url())
382        .env("WARATAH_REPO", &options.repo)
383        // Makes {runtime_dir}/kernels/* discoverable as kernelspecs.
384        .env("JUPYTER_PATH", &options.runtime_dir)
385        // Kernel connection files and the cookie secret live with the
386        // cluster, not in ~/.local/share/jupyter (2.x has no config trait).
387        .env("JUPYTER_RUNTIME_DIR", &options.runtime_dir)
388        .stdout(Stdio::piped())
389        .stderr(Stdio::piped())
390        // Own process group: a group kill takes the sidecar without
391        // touching anything else in our tree. Kernels live in their own
392        // sessions and are handled separately (SHUTDOWN_GRACE /
393        // kill_orphaned_kernels).
394        .process_group(0);
395    command.spawn().map_err(|source| NotebookError::Spawn {
396        program: python.to_owned(),
397        source,
398    })
399}
400
401/// Prefix the sidecar's own output into the engine log (work-order
402/// requirement; this workspace logs with `eprintln!`, there is no
403/// tracing subscriber).
404fn pump_output(stdout: Option<ChildStdout>, stderr: Option<ChildStderr>) {
405    if let Some(stdout) = stdout {
406        tokio::spawn(pump(stdout));
407    }
408    if let Some(stderr) = stderr {
409        tokio::spawn(pump(stderr));
410    }
411}
412
413async fn pump<R>(reader: R)
414where
415    R: tokio::io::AsyncRead + Unpin,
416{
417    let mut lines = BufReader::new(reader).lines();
418    while let Ok(Some(line)) = lines.next_line().await {
419        eprintln!("jupyter: {line}");
420    }
421}
422
423/// SIGKILL a whole process group (sidecar + kernels). `pgid` is the child's
424/// pid because it was spawned with `process_group(0)`.
425fn kill_process_group(pgid: u32) {
426    // SAFETY: kill(2) on a negated pgid; ESRCH (already dead) is fine.
427    unsafe {
428        libc::kill(-(pgid as libc::pid_t), libc::SIGKILL);
429    }
430}
431
432/// Bind `:0`, read the assigned port, and drop the listener — the sidecar
433/// takes the port for real. Small TOCTOU race on a busy loopback, paid for
434/// with a fast sidecar exit and a normal restart. A failed probe is an
435/// error, not a `:0` address: the supervisor would otherwise poll port 0
436/// forever (guaranteed readiness timeout) instead of retrying with backoff.
437fn pick_addr(bind: SocketAddr) -> Result<SocketAddr, NotebookError> {
438    if bind.port() != 0 {
439        return Ok(bind);
440    }
441    let ip = if bind.ip().is_unspecified() {
442        std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
443    } else {
444        bind.ip()
445    };
446    std::net::TcpListener::bind(SocketAddr::new(ip, 0))
447        .and_then(|listener| listener.local_addr())
448        .map_err(|source| NotebookError::PortProbe { bind, source })
449}
450
451fn is_shutdown(shutdown: &mut watch::Receiver<bool>) -> bool {
452    *shutdown.borrow_and_update()
453}
454
455/// Resolves when the shutdown flag is set OR the sender is gone.
456async fn shutdown_changed(shutdown: &mut watch::Receiver<bool>) {
457    // borrow_and_update marks the current value seen; if it is already
458    // true there is no `changed()` edge left to wait for.
459    if is_shutdown(shutdown) {
460        return;
461    }
462    if shutdown.changed().await.is_err() {
463        return;
464    }
465    let _ = shutdown.borrow_and_update();
466}
467
468/// Sleep `duration`, cutting short on shutdown. Returns `true` when shut
469/// down (caller should stop), `false` when the sleep elapsed.
470async fn sleep_or_shutdown(shutdown: &mut watch::Receiver<bool>, duration: Duration) -> bool {
471    tokio::select! {
472        _ = tokio::time::sleep(duration) => is_shutdown(shutdown),
473        _ = shutdown_changed(shutdown) => true,
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    #[test]
482    fn picked_addrs_keep_the_requested_ip_and_nonzero_port() {
483        let picked = pick_addr("127.0.0.1:0".parse().unwrap()).unwrap();
484        assert_eq!(picked.ip().to_string(), "127.0.0.1");
485        assert_ne!(picked.port(), 0);
486
487        let fixed = pick_addr("127.0.0.1:9431".parse().unwrap()).unwrap();
488        assert_eq!(fixed.port(), 9431);
489
490        let unspecified = pick_addr("0.0.0.0:0".parse().unwrap()).unwrap();
491        assert_eq!(unspecified.ip().to_string(), "127.0.0.1");
492    }
493
494    #[test]
495    fn orphaned_kernel_sweep_kills_only_jpy_parent_pid_matches() {
496        use std::process::{Command, Stdio};
497        let spawn_sleeper = |envs: &[(&str, String)]| {
498            let mut command = Command::new("sleep");
499            command
500                .arg("30")
501                .stdout(Stdio::null())
502                .stderr(Stdio::null());
503            for (key, value) in envs {
504                command.env(key, value);
505            }
506            command.spawn().expect("sleep spawns")
507        };
508
509        let mut fake_sidecar = spawn_sleeper(&[]);
510        let sidecar_pid = fake_sidecar.id();
511        let mut fake_kernel = spawn_sleeper(&[("JPY_PARENT_PID", sidecar_pid.to_string())]);
512        let kernel_pid = fake_kernel.id();
513        // Unrelated process with a DIFFERENT parent pid must survive.
514        let mut bystander = spawn_sleeper(&[(
515            "JPY_PARENT_PID",
516            sidecar_pid.wrapping_add(100_000).to_string(),
517        )]);
518        let bystander_pid = bystander.id();
519
520        // Give /proc a moment to expose both fresh processes' environ.
521        std::thread::sleep(std::time::Duration::from_millis(100));
522        kill_orphaned_kernels(sidecar_pid);
523        std::thread::sleep(std::time::Duration::from_millis(100));
524
525        assert!(fake_kernel.try_wait().unwrap().is_some(), "kernel swept");
526        assert!(
527            bystander.try_wait().unwrap().is_none(),
528            "unrelated process must survive"
529        );
530        assert!(fake_sidecar.try_wait().unwrap().is_none());
531        let _ = fake_kernel.kill();
532        let _ = bystander.kill();
533        let _ = fake_sidecar.kill();
534        let _ = fake_kernel.wait();
535        let _ = bystander.wait();
536        let _ = fake_sidecar.wait();
537        let _ = kernel_pid;
538        let _ = bystander_pid;
539    }
540
541    #[test]
542    fn runtime_files_contain_config_and_kernelspec() {
543        let runtime = tempfile::tempdir().unwrap();
544        let books = tempfile::tempdir().unwrap();
545        let options = NotebookOptions {
546            dir: books.path().to_path_buf(),
547            runtime_dir: runtime.path().to_path_buf(),
548            venv_dir: runtime.path().join("venv"),
549            python: None,
550            bind: "127.0.0.1:0".parse().unwrap(),
551            token: "tok123".to_owned(),
552            cull_idle_secs: 120,
553            repo: "main".to_owned(),
554            engine_http: "127.0.0.1:8080".parse().unwrap(),
555        };
556        write_runtime_files(&options, "127.0.0.1:45678".parse().unwrap()).unwrap();
557        let config = std::fs::read_to_string(runtime.path().join(CONFIG_FILE)).unwrap();
558        assert!(config.contains("c.ServerApp.port = 45678"));
559        assert!(config.contains("c.IdentityProvider.token = \"tok123\""));
560        assert!(
561            runtime
562                .path()
563                .join("kernels")
564                .join("python3-main")
565                .join("kernel.json")
566                .is_file()
567        );
568    }
569}