waratah/daemon.rs
1//! Daemonization for `waratah start` (spawn-self detached).
2//!
3//! Default `waratah start` re-executes this same binary as a detached child
4//! carrying the original arguments plus the hidden `--daemon-ready <path>`
5//! marker, so the parent can return to the shell immediately and the cluster
6//! keeps running under `waratah stop`. `--foreground` (or `--query` /
7//! `--no-http`, which imply it) skips this module entirely.
8//!
9//! # Parent side ([`run_detached`])
10//!
11//! 1. Resolve the run layout (log dir) and mint a per-attempt status file
12//! name — `start-status-{pid}-{millis}.txt` — so two concurrent `waratah
13//! start` attempts never share a handshake file: a "still starting"
14//! attempt's late `ready` can never be attributed to another attempt,
15//! and no stale verdict can survive into a new attempt. The spawner
16//! removes the file on every exit.
17//! 2. Spawn `current_exe()` with the parent's own arguments plus
18//! `--daemon-ready`, fully detached: new process group (Unix) or
19//! `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` (Windows), stdin null,
20//! stdout → `output.txt`, stderr → `error.txt` (append). Storage children
21//! spawned later by the daemon inherit those fds, so their output lands
22//! in the same files with no per-child plumbing.
23//! 3. Poll the status file for one line — `ready` or `error: <message>` —
24//! up to [`READY_TIMEOUT`]. The child writes `ready` only once startup is
25//! complete and the HTTP socket is bound; a first boot with geo/temporal
26//! auto-rebuilds can sit in between for far longer than the timeout, so
27//! a timeout with a live child is reported as "still starting" (exit 0),
28//! not as a failure.
29//! 4. Ctrl+C / SIGTERM during the wait reaches only the foreground spawner
30//! (the daemon is in its own process group), so the spawner answers for
31//! the cluster: kill the starting group — SIGTERM, short grace, SIGKILL
32//! — clear the status file and the daemon's pidfile, and fail the
33//! invocation.
34//!
35//! # Child side ([`run_child`])
36//!
37//! Runs the normal `dev::start` path with three additions: the readiness
38//! status write (via [`DevOptions::ready_file`], reported by `run_session`
39//! right before the serve loop), the file-backed debug sink
40//! ([`DevOptions::debug_file`] → `debug.txt`, truncated each start), and a
41//! pidfile even for the memory backend (the working directory) so
42//! `waratah stop` without `--data-dir` can find the daemon.
43//!
44//! The daemon never changes its working directory: relative `--data-dir`
45//! paths and the memory backend's cwd pidfile/logs depend on it.
46
47use std::path::{Path, PathBuf};
48use std::process::Command;
49use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
50
51use crate::dev::{Backend, DevOptions};
52use crate::error::DevError;
53
54/// How long the spawner waits for the daemon child's `ready` line. Startup
55/// that outlives this (index auto-rebuilds on a first boot) is reported as
56/// "still starting" — the child keeps booting in the background.
57const READY_TIMEOUT: Duration = Duration::from_secs(30);
58
59/// How long a cancelled start's SIGTERM gets before the whole process
60/// group is SIGKILLed. Deliberately shorter than the daemon's own 5s HTTP
61/// drain: a cancelled start prefers returning the prompt over a fully
62/// drained teardown.
63const KILL_GRACE: Duration = Duration::from_secs(3);
64
65/// Per-attempt status file prefix in the log dir. The full name is
66/// `start-status-{spawner pid}-{unix millis}.txt`: two concurrent
67/// `waratah start` attempts always differ in pid, so they never share a
68/// handshake file.
69const STATUS_PREFIX: &str = "start-status-";
70
71/// Log file names inside the log dir.
72pub const OUTPUT_FILE: &str = "output.txt";
73pub const ERROR_FILE: &str = "error.txt";
74pub const DEBUG_FILE: &str = "debug.txt";
75
76/// Where the daemon writes its log files: `{data_dir}/logs` when a data dir
77/// is set, otherwise the working directory (memory backend).
78pub fn log_dir(data_dir: Option<&Path>) -> PathBuf {
79 match data_dir {
80 Some(dir) => dir.join("logs"),
81 None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
82 }
83}
84
85/// Mint this attempt's status path (see [`STATUS_PREFIX`]). No I/O.
86fn status_file(dir: &Path) -> PathBuf {
87 let millis = SystemTime::now()
88 .duration_since(UNIX_EPOCH)
89 .map(|d| d.as_millis())
90 .unwrap_or(0);
91 dir.join(format!(
92 "{STATUS_PREFIX}{}-{millis}.txt",
93 std::process::id()
94 ))
95}
96
97/// What the spawner needs to detach a cluster and report the result.
98pub struct DetachPlan {
99 /// Storage backend root (`--data-dir`); `None` = memory backend.
100 pub data_dir: Option<PathBuf>,
101 /// HTTP listen address the daemon was asked to bind (daemonized starts
102 /// always have HTTP: `--query` / `--no-http` imply foreground).
103 pub http: std::net::SocketAddr,
104 /// Whether `--debug` was given (debug.txt then joins the report).
105 pub debug: bool,
106}
107
108/// Spawn this binary as a detached daemon and report the outcome.
109///
110/// Every usage/validation error (bad `--config`, unusable `--http`, notebook
111/// misconfiguration) has already failed synchronously in the caller before
112/// this runs, so a failure reported here is a genuine startup failure of an
113/// otherwise well-formed invocation.
114pub async fn run_detached(plan: DetachPlan) -> Result<(), DevError> {
115 let exe = std::env::current_exe()?;
116 let dir = log_dir(plan.data_dir.as_deref());
117 std::fs::create_dir_all(&dir)?;
118 let output_path = dir.join(OUTPUT_FILE);
119 let error_path = dir.join(ERROR_FILE);
120 // Per-attempt handshake file: unique to this spawner, so no stale or
121 // concurrent attempt's verdict can be read here. The parent removes it
122 // on every exit below; if this process dies first, the unique name
123 // keeps the orphan from ever being mistaken for a live handshake.
124 let status_path = status_file(&dir);
125
126 let output = std::fs::OpenOptions::new()
127 .create(true)
128 .append(true)
129 .open(&output_path)?;
130 let error = std::fs::OpenOptions::new()
131 .create(true)
132 .append(true)
133 .open(&error_path)?;
134
135 let mut command = Command::new(&exe);
136 command
137 .args(std::env::args_os().skip(1))
138 .arg("--daemon-ready")
139 .arg(&status_path)
140 .stdin(std::process::Stdio::null())
141 .stdout(std::process::Stdio::from(output))
142 .stderr(std::process::Stdio::from(error));
143 detach(&mut command);
144 let mut child = command.spawn().map_err(|source| DevError::Spawn {
145 program: format!("{}", exe.display()),
146 source,
147 })?;
148 let pid = child.id();
149
150 // Verdict of the readiness wait.
151 enum Handshake {
152 /// The child wrote `ready`: startup complete, HTTP socket bound.
153 Ready,
154 /// The child wrote `error:`, or died before writing anything.
155 Failed(String),
156 /// [`READY_TIMEOUT`] elapsed with a live child (first-boot index
157 /// auto-rebuilds can outlive the wait): report and leave it
158 /// booting.
159 StillStarting,
160 }
161
162 // Exit check first in every pass: a child that dies leaves no status
163 // line behind in the panic/kill cases, and its stderr is in error.txt.
164 // The block is `Result<Handshake, DevError>` so the `?` propagates a
165 // `try_wait` failure; every loop exit is a `break Ok(..)`.
166 let handshake = async {
167 let deadline = Instant::now() + READY_TIMEOUT;
168 loop {
169 if let Some(status) = child.try_wait().map_err(DevError::from)? {
170 break Ok::<Handshake, DevError>(match read_status(&status_path) {
171 Some(line) if line.starts_with("error:") => {
172 Handshake::Failed(line["error:".len()..].trim().to_owned())
173 }
174 _ => Handshake::Failed(format!(
175 "daemon exited during startup ({status}); see {}",
176 error_path.display()
177 )),
178 });
179 }
180 match read_status(&status_path) {
181 Some(line) if line.starts_with("error:") => {
182 break Ok(Handshake::Failed(line["error:".len()..].trim().to_owned()));
183 }
184 Some(line) if line.starts_with("ready") => break Ok(Handshake::Ready),
185 _ => {}
186 }
187 if Instant::now() >= deadline {
188 break Ok(Handshake::StillStarting);
189 }
190 tokio::time::sleep(Duration::from_millis(100)).await;
191 }
192 };
193 tokio::select! {
194 handshake = handshake => match handshake? {
195 Handshake::Ready => {
196 let _ = std::fs::remove_file(&status_path);
197 print_daemonized(&plan, pid, &output_path, &error_path, &dir);
198 Ok(())
199 }
200 Handshake::Failed(message) => {
201 let _ = std::fs::remove_file(&status_path);
202 Err(DevError::Daemon(message))
203 }
204 Handshake::StillStarting => {
205 // Still booting (likely a first-boot index auto-rebuild):
206 // the daemon is alive and will serve when ready. Report
207 // where to watch instead of failing. The child is
208 // deliberately not waited: the daemon outlives this
209 // process.
210 let _ = std::fs::remove_file(&status_path);
211 println!(
212 "waratah cluster still starting (pid {pid}); follow {}",
213 output_path.display()
214 );
215 Ok(())
216 }
217 },
218 // The operator's Ctrl+C / SIGTERM reaches only this foreground
219 // process (the daemon is in its own process group), so the spawner
220 // must answer for the cluster: kill it and report the cancellation
221 // instead of silently leaving a half-booted cluster behind.
222 _ = wait_for_interrupt() => {
223 kill_starting_cluster(pid);
224 let _ = std::fs::remove_file(&status_path);
225 // A SIGKILL past the grace bypasses the daemon's own pidfile
226 // removal: clear it only if it still names the daemon we just
227 // killed — never a live cluster's file.
228 let pidfile = crate::dev::pidfile_path(plan.data_dir.as_deref());
229 crate::dev::remove_pidfile_if_names(&pidfile, pid as libc::pid_t);
230 Err(DevError::Daemon(format!(
231 "start cancelled by interrupt; killed the starting cluster (pid {pid})"
232 )))
233 }
234 }
235}
236
237/// The parent's success report: pid, URLs, log paths, stop hint.
238fn print_daemonized(
239 plan: &DetachPlan,
240 pid: u32,
241 output_path: &Path,
242 error_path: &Path,
243 dir: &Path,
244) {
245 println!("waratah cluster daemonized (pid {pid})");
246 println!(" console: http://{}/", plan.http);
247 println!(" RDF4J: http://{}/rdf4j/", plan.http);
248 println!(" health: http://{}/waratah/health", plan.http);
249 match plan.debug {
250 true => println!(
251 " logs: {}, {}, {}",
252 output_path.display(),
253 error_path.display(),
254 dir.join(DEBUG_FILE).display()
255 ),
256 false => println!(
257 " logs: {}, {}",
258 output_path.display(),
259 error_path.display()
260 ),
261 }
262 match &plan.data_dir {
263 Some(dir) => println!(" stop: waratah stop --data-dir {}", dir.display()),
264 None => println!(" stop: waratah stop"),
265 }
266}
267
268/// Resolve when the operator interrupts the start wait: SIGINT or SIGTERM
269/// on Unix, Ctrl+C on Windows.
270#[cfg(unix)]
271async fn wait_for_interrupt() {
272 use tokio::signal::unix::{SignalKind, signal};
273 let mut interrupt = signal(SignalKind::interrupt()).expect("install SIGINT handler");
274 let mut terminate = signal(SignalKind::terminate()).expect("install SIGTERM handler");
275 tokio::select! {
276 _ = interrupt.recv() => {}
277 _ = terminate.recv() => {}
278 }
279}
280
281#[cfg(windows)]
282async fn wait_for_interrupt() {
283 let _ = tokio::signal::ctrl_c().await;
284}
285
286/// Kill a cluster cancelled mid-startup. The signal reached only the
287/// foreground spawner: the daemon sits in its own process group (see
288/// [`detach`]), together with the storage children it already spawned, so
289/// the whole group must be killed from here — SIGTERM first (the daemon's
290/// own handler tears the children down and removes its pidfile), SIGKILL
291/// to the group past [`KILL_GRACE`].
292#[cfg(unix)]
293fn kill_starting_cluster(pid: u32) {
294 let pgid = pid as libc::pid_t;
295 // SAFETY: SIGTERM to the daemon's process group (pgid == pid — the
296 // child was spawned with `process_group(0)`); a negative pid targets
297 // the group.
298 unsafe { libc::kill(-pgid, libc::SIGTERM) };
299 let deadline = Instant::now() + KILL_GRACE;
300 while Instant::now() < deadline {
301 // SAFETY: signal 0 probes group existence without delivering.
302 if unsafe { libc::kill(-pgid, 0) } != 0 {
303 return;
304 }
305 std::thread::sleep(Duration::from_millis(50));
306 }
307 // SAFETY: SIGKILL to the same group after the SIGTERM grace expired.
308 unsafe { libc::kill(-pgid, libc::SIGKILL) };
309}
310
311#[cfg(windows)]
312fn kill_starting_cluster(_pid: u32) {
313 // No POSIX process groups: there is no tree kill without spawning
314 // `taskkill`, and the storage stack does not run on Windows yet —
315 // terminate what we can and accept that this platform is not a
316 // supported runtime for the storage side.
317}
318
319/// The daemon-child half: run the normal start path and funnel the outcome
320/// into the status file the spawner is polling.
321pub async fn run_child(status_path: PathBuf, mut options: DevOptions) -> Result<(), DevError> {
322 // Defense in depth: the parser-side rule (`--query` / `--no-http` imply
323 // foreground) makes this unreachable through the CLI; a daemon child
324 // must not trust its argv.
325 if options.query.is_some() || options.http.is_none() {
326 let message = "daemon child cannot serve --query or --no-http (they imply --foreground)";
327 write_status(&status_path, &format!("error: {message}"));
328 return Err(DevError::Daemon(message.to_owned()));
329 }
330 options.pidfile = true;
331 options.ready_file = Some(status_path.clone());
332 if options.debug {
333 options.debug_file = Some(
334 log_dir(match &options.backend {
335 Backend::RocksDb(dir) => Some(dir.as_path()),
336 Backend::Memory => None,
337 })
338 .join(DEBUG_FILE),
339 );
340 }
341 let result = crate::dev::start(options).await;
342 if let Err(error) = &result {
343 write_status(&status_path, &format!("error: {error}"));
344 }
345 result
346}
347
348/// Write the readiness line (called by `run_session` once startup is
349/// complete and the serve loop is about to begin).
350pub fn report_ready(status_path: &Path) {
351 write_status(status_path, "ready");
352}
353
354/// One-line status write. Newlines are flattened so the file always holds
355/// exactly one parseable line.
356fn write_status(status_path: &Path, line: &str) {
357 let flat = line.replace('\n', " ");
358 if let Err(error) = std::fs::write(status_path, format!("{flat}\n")) {
359 eprintln!("could not write {}: {error}", status_path.display());
360 }
361}
362
363/// First line of the status file, if it exists and is non-empty.
364fn read_status(status_path: &Path) -> Option<String> {
365 std::fs::read_to_string(status_path)
366 .ok()
367 .map(|text| text.lines().next().unwrap_or("").to_owned())
368 .filter(|line| !line.is_empty())
369}
370
371/// Make `command` survive the parent and the terminal.
372///
373/// Unix: the child gets its own process group, which takes it out of the
374/// terminal's foreground group. THAT is the isolation that matters: the tty
375/// delivers Ctrl+C (SIGINT) to the foreground group only, and a
376/// session-leader SIGHUP does not reach background groups. Redirecting
377/// stdin to null and stdout/stderr to files complements it — no terminal
378/// reads or writes (no SIGTTIN/SIGTTOU exposure), and the daemon's output
379/// lands in the run logs. (Full `setsid` — leaving the session and dropping
380/// the controlling terminal — needs unsafe `pre_exec`; nothing here touches
381/// the tty, so there is nothing it would add.)
382///
383/// Windows: `DETACHED_PROCESS` (no console) and `CREATE_NEW_PROCESS_GROUP`
384/// (own Ctrl+C group). The flag values are inlined from the CreateProcess
385/// documentation so the `windows` crate is not a dependency for two
386/// integers.
387fn detach(command: &mut Command) {
388 #[cfg(unix)]
389 {
390 use std::os::unix::process::CommandExt;
391 command.process_group(0);
392 }
393 #[cfg(windows)]
394 {
395 use std::os::windows::process::CommandExt;
396 const DETACHED_PROCESS: u32 = 0x0000_0008;
397 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
398 command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 /// The handshake file carries attempt identity: fixed prefix, this
407 /// spawner's pid, and a timestamp. Cross-attempt uniqueness comes from
408 /// the pid (one live process can never run two start attempts), so two
409 /// calls from THIS process may legitimately share a millisecond.
410 #[test]
411 fn status_file_names_carry_attempt_identity() {
412 let dir = Path::new("/arbitrary/log/dir");
413 let path = status_file(dir);
414 assert!(
415 path.starts_with(dir),
416 "the status file must live in the log dir"
417 );
418 let name = path.file_name().unwrap().to_str().unwrap();
419 assert!(
420 name.starts_with("start-status-") && name.ends_with(".txt"),
421 "unexpected status file name: {name}"
422 );
423 let body = name
424 .strip_prefix("start-status-")
425 .unwrap()
426 .strip_suffix(".txt")
427 .unwrap();
428 let (pid, millis) = body.split_once('-').unwrap_or_else(|| {
429 panic!("status file name must be start-status-<pid>-<millis>.txt: {name}")
430 });
431 assert_eq!(pid, std::process::id().to_string(), "spawner pid in name");
432 assert!(
433 millis.parse::<u128>().is_ok(),
434 "millis must be numeric: {name}"
435 );
436 }
437}