Skip to main content

hyprstream_core/cli/
daemon.rs

1//! Daemonization support for running hyprstream in the background
2//!
3//! Provides helper functions for detaching the process from the terminal
4//! and running as a background daemon.
5//!
6//! # Usage
7//!
8//! ```ignore
9//! use hyprstream::cli::daemon::maybe_daemonize;
10//!
11//! // In server startup, before creating tokio runtime:
12//! maybe_daemonize(detach, working_dir, pid_file)?;
13//! ```
14
15use anyhow::{Context, Result};
16use std::path::PathBuf;
17use tracing::info;
18
19/// Default PID file location
20///
21/// Delegates to hyprstream_workers::paths for consistent path resolution.
22fn default_pid_file() -> PathBuf {
23    hyprstream_workers::paths::pid_file()
24}
25
26/// Daemonize the process if requested
27///
28/// This function should be called early in main(), before creating the tokio runtime.
29/// It uses the `daemonize` crate to properly fork and detach from the terminal.
30///
31/// # Arguments
32///
33/// * `detach` - Whether to detach from the terminal
34/// * `working_dir` - Optional working directory to change to after daemonizing
35/// * `pid_file` - Optional PID file path (defaults to runtime-appropriate location)
36///
37/// # Returns
38///
39/// Returns `Ok(())` if daemonization succeeded or was not requested.
40/// Returns `Err` if daemonization failed.
41///
42/// # Example
43///
44/// ```ignore
45/// // Call before creating tokio runtime
46/// maybe_daemonize(cmd.detach, cmd.server.working_dir.clone(), cmd.server.pid_file.clone())?;
47///
48/// // Now create runtime and start server
49/// let rt = tokio::runtime::Runtime::new()?;
50/// rt.block_on(async { /* server code */ });
51/// ```
52pub fn maybe_daemonize(
53    detach: bool,
54    working_dir: Option<String>,
55    pid_file: Option<String>,
56) -> Result<()> {
57    if !detach {
58        return Ok(());
59    }
60
61    #[cfg(unix)]
62    {
63        use daemonize::Daemonize;
64
65        let pid_path = pid_file.map(PathBuf::from).unwrap_or_else(default_pid_file);
66
67        // Ensure runtime directory exists with correct permissions
68        hyprstream_workers::paths::ensure_runtime_dir()
69            .with_context(|| "Failed to create runtime directory")?;
70
71        let mut daemon = Daemonize::new().pid_file(&pid_path).chown_pid_file(true);
72
73        // Set working directory if specified
74        if let Some(ref dir) = working_dir {
75            let path = PathBuf::from(dir);
76            if !path.exists() {
77                std::fs::create_dir_all(&path)
78                    .with_context(|| format!("Failed to create working directory: {dir}"))?;
79            }
80            daemon = daemon.working_directory(path);
81        }
82
83        info!("Daemonizing with PID file: {}", pid_path.display());
84
85        daemon
86            .start()
87            .with_context(|| format!("Failed to daemonize (PID file: {})", pid_path.display()))?;
88
89        info!("Successfully daemonized");
90        Ok(())
91    }
92
93    #[cfg(not(unix))]
94    {
95        anyhow::bail!(
96            "Daemonization is only supported on Unix systems. Use a service manager on Windows."
97        );
98    }
99}
100
101/// Check if a PID file exists and the process is still running
102///
103/// # Arguments
104///
105/// * `pid_file` - Optional PID file path (defaults to runtime-appropriate location)
106///
107/// # Returns
108///
109/// `Some(pid)` if the process is running, `None` if not running or PID file doesn't exist.
110pub fn check_running(pid_file: Option<String>) -> Option<u32> {
111    let pid_path = pid_file.map(PathBuf::from).unwrap_or_else(default_pid_file);
112
113    let pid_str = std::fs::read_to_string(&pid_path).ok()?;
114    let pid: u32 = pid_str.trim().parse().ok()?;
115
116    #[cfg(unix)]
117    {
118        // Check if process exists by sending signal 0 (null signal)
119        use nix::sys::signal::kill;
120        use nix::unistd::Pid;
121
122        // Using None sends signal 0, which checks process existence without side effects
123        if kill(Pid::from_raw(pid as i32), None).is_ok() {
124            return Some(pid);
125        }
126    }
127
128    #[cfg(not(unix))]
129    {
130        // On non-Unix, just check if PID file exists
131        return Some(pid);
132    }
133
134    None
135}
136
137/// Stop a running daemon by sending SIGTERM
138///
139/// # Arguments
140///
141/// * `pid_file` - Optional PID file path (defaults to runtime-appropriate location)
142///
143/// # Returns
144///
145/// `Ok(())` if the daemon was stopped or wasn't running.
146/// `Err` if stopping failed.
147pub fn stop_daemon(pid_file: Option<String>) -> Result<()> {
148    let pid_path = pid_file.map(PathBuf::from).unwrap_or_else(default_pid_file);
149
150    let pid_str = std::fs::read_to_string(&pid_path)
151        .with_context(|| format!("No PID file found at: {}", pid_path.display()))?;
152
153    let pid: u32 = pid_str
154        .trim()
155        .parse()
156        .with_context(|| format!("Invalid PID in file: {pid_str}"))?;
157
158    #[cfg(unix)]
159    {
160        use nix::sys::signal::{kill, Signal};
161        use nix::unistd::Pid;
162
163        info!("Sending SIGTERM to process {}", pid);
164        kill(Pid::from_raw(pid as i32), Signal::SIGTERM)
165            .with_context(|| format!("Failed to send SIGTERM to PID {pid}"))?;
166
167        // Remove PID file
168        let _ = std::fs::remove_file(&pid_path);
169
170        info!("Daemon stopped (PID {})", pid);
171        Ok(())
172    }
173
174    #[cfg(not(unix))]
175    {
176        anyhow::bail!("Stopping daemons is only supported on Unix systems");
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn test_default_pid_file() {
186        let pid_file = default_pid_file();
187        assert!(pid_file.to_string_lossy().contains("hyprstream"));
188    }
189
190    #[test]
191    fn test_check_running_no_file() {
192        // Should return None if PID file doesn't exist
193        let result = check_running(Some("/nonexistent/path/hyprstream.pid".to_owned()));
194        assert!(result.is_none());
195    }
196
197    #[test]
198    fn test_maybe_daemonize_disabled() {
199        // Should succeed when detach is false
200        let result = maybe_daemonize(false, None, None);
201        assert!(result.is_ok());
202    }
203}