hyprstream_core/cli/
daemon.rs1use anyhow::{Context, Result};
16use std::path::PathBuf;
17use tracing::info;
18
19fn default_pid_file() -> PathBuf {
23 hyprstream_workers::paths::pid_file()
24}
25
26pub 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 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 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
101pub 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 use nix::sys::signal::kill;
120 use nix::unistd::Pid;
121
122 if kill(Pid::from_raw(pid as i32), None).is_ok() {
124 return Some(pid);
125 }
126 }
127
128 #[cfg(not(unix))]
129 {
130 return Some(pid);
132 }
133
134 None
135}
136
137pub 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 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 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 let result = maybe_daemonize(false, None, None);
201 assert!(result.is_ok());
202 }
203}