hyprstream_service/service/spawner/
systemd.rs1use std::process::Stdio;
20
21use tokio::process::Command;
22use uuid::Uuid;
23
24use super::{ProcessConfig, ProcessKind, ProcessReadiness, SpawnedProcess, SpawnerBackend};
25use hyprstream_rpc::error::{Result, RpcError};
26
27pub struct SystemdBackend {
32 user_mode: bool,
34
35 slice: String,
37}
38
39impl SystemdBackend {
40 pub fn new() -> Self {
44 let user_mode = !nix::unistd::geteuid().is_root();
45
46 Self {
47 user_mode,
48 slice: "hyprstream-workers.slice".to_owned(),
49 }
50 }
51
52 pub fn with_user_mode(user_mode: bool) -> Self {
54 Self {
55 user_mode,
56 slice: "hyprstream-workers.slice".to_owned(),
57 }
58 }
59
60 pub fn with_slice(mut self, slice: impl Into<String>) -> Self {
62 self.slice = slice.into();
63 self
64 }
65
66 pub fn is_available() -> bool {
68 let under_systemd = std::path::Path::new("/run/systemd/system").exists()
70 || std::env::var("NOTIFY_SOCKET").is_ok();
71
72 if !under_systemd {
73 return false;
74 }
75
76 which::which("systemd-run").is_ok()
78 }
79
80 fn generate_unit_name(&self, name: &str) -> String {
82 let short_uuid = &Uuid::new_v4().to_string()[..8];
83 format!("hyprstream-{name}-{short_uuid}.service")
84 }
85
86 fn build_command(&self, config: &ProcessConfig, unit_name: &str) -> Command {
88 let mut cmd = Command::new("systemd-run");
89
90 if self.user_mode {
92 cmd.arg("--user");
93 }
94
95 cmd.arg("--unit").arg(unit_name);
97 cmd.arg("--description")
98 .arg(format!("Hyprstream worker: {}", config.name));
99
100 cmd.arg("--slice").arg(&self.slice);
102
103 cmd.arg("--property=CollectMode=inactive-or-failed");
105
106 cmd.arg("--property=Type=exec");
108
109 if let Some(ref limit) = config.memory_limit {
111 cmd.arg(format!("--property=MemoryMax={limit}"));
112 }
113
114 if let Some(quota) = config.cpu_quota {
116 cmd.arg(format!("--property=CPUQuota={quota}%"));
117 }
118
119 if config.restart_on_failure {
121 cmd.arg("--property=Restart=on-failure");
122 cmd.arg("--property=RestartSec=1");
123 }
124
125 if let Some(ref dir) = config.working_dir {
127 cmd.arg(format!("--property=WorkingDirectory={}", dir.display()));
128 }
129
130 for (key, value) in &config.env {
132 cmd.arg("--setenv").arg(format!("{key}={value}"));
133 }
134
135 for (key, value) in &config.unit_properties {
137 cmd.arg(format!("--property={key}={value}"));
138 }
139
140 cmd.arg("--").arg(&config.executable);
142 cmd.args(&config.args);
143
144 cmd
145 }
146}
147
148impl Default for SystemdBackend {
149 fn default() -> Self {
150 Self::new()
151 }
152}
153
154#[async_trait::async_trait]
155impl SpawnerBackend for SystemdBackend {
156 async fn spawn(&self, config: ProcessConfig) -> Result<SpawnedProcess> {
157 if config.readiness != ProcessReadiness::Immediate {
161 return Err(RpcError::InvalidOperation(
162 "notification readiness is only supported by the standalone spawner".to_owned(),
163 ));
164 }
165 let unit_name = self.generate_unit_name(&config.name);
166
167 tracing::debug!(
168 name = %config.name,
169 unit = %unit_name,
170 user_mode = %self.user_mode,
171 "Spawning daemon via systemd-run"
172 );
173
174 let mut cmd = self.build_command(&config, &unit_name);
176
177 cmd.stdout(Stdio::piped());
179 cmd.stderr(Stdio::piped());
180
181 let output = cmd.output().await.map_err(|e| {
182 RpcError::SpawnFailed(format!(
183 "failed to run systemd-run for {}: {}",
184 config.name, e
185 ))
186 })?;
187
188 if !output.status.success() {
189 let stderr = String::from_utf8_lossy(&output.stderr);
190 return Err(RpcError::SpawnFailed(format!(
191 "systemd-run failed for {}: {}",
192 config.name, stderr
193 )));
194 }
195
196 tracing::info!(
197 name = %config.name,
198 unit = %unit_name,
199 "Daemon spawned as systemd transient unit"
200 );
201
202 Ok(SpawnedProcess::new(
203 unit_name.clone(),
204 ProcessKind::SystemdUnit(unit_name),
205 ))
206 }
207
208 async fn stop(&self, process: &SpawnedProcess) -> Result<()> {
209 let unit_name = match &process.kind {
210 ProcessKind::SystemdUnit(name) => name,
211 ProcessKind::Direct(_) => {
212 return Err(RpcError::InvalidOperation(
213 "SystemdBackend cannot stop direct processes".to_owned(),
214 ));
215 }
216 };
217
218 tracing::debug!(
219 unit = %unit_name,
220 "Stopping systemd unit"
221 );
222
223 let mut cmd = Command::new("systemctl");
225
226 if self.user_mode {
227 cmd.arg("--user");
228 }
229
230 cmd.arg("stop").arg(unit_name);
231
232 let output = cmd.output().await.map_err(|e| {
233 RpcError::StopFailed(format!("failed to run systemctl stop for {unit_name}: {e}"))
234 })?;
235
236 if !output.status.success() {
237 let stderr = String::from_utf8_lossy(&output.stderr);
238 if !stderr.contains("not loaded") && !stderr.contains("not found") {
240 tracing::warn!(
241 unit = %unit_name,
242 error = %stderr,
243 "systemctl stop returned error"
244 );
245 }
246 }
247
248 tracing::info!(
249 unit = %unit_name,
250 "Systemd unit stopped"
251 );
252
253 Ok(())
254 }
255
256 async fn is_running(&self, process: &SpawnedProcess) -> Result<bool> {
257 let unit_name = match &process.kind {
258 ProcessKind::SystemdUnit(name) => name,
259 ProcessKind::Direct(_) => {
260 return Err(RpcError::InvalidOperation(
261 "SystemdBackend cannot check direct processes".to_owned(),
262 ));
263 }
264 };
265
266 let mut cmd = Command::new("systemctl");
268
269 if self.user_mode {
270 cmd.arg("--user");
271 }
272
273 cmd.arg("is-active").arg("--quiet").arg(unit_name);
274
275 let status = cmd.status().await.map_err(|e| {
276 RpcError::Other(format!(
277 "failed to run systemctl is-active for {unit_name}: {e}"
278 ))
279 })?;
280
281 Ok(status.success())
283 }
284
285 fn backend_type(&self) -> &'static str {
286 "systemd"
287 }
288}
289
290#[cfg(test)]
291#[allow(clippy::print_stdout)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn test_is_available() {
297 let available = SystemdBackend::is_available();
299 println!("Systemd available: {available}");
300 }
301
302 #[test]
303 fn test_generate_unit_name() {
304 let backend = SystemdBackend::new();
305 let name = backend.generate_unit_name("nydusd");
306
307 assert!(name.starts_with("hyprstream-nydusd-"));
308 assert!(name.ends_with(".service"));
309 }
310
311 #[test]
312 fn test_user_mode_detection() {
313 let backend = SystemdBackend::new();
314 let expected_user_mode = !nix::unistd::geteuid().is_root();
315 assert_eq!(backend.user_mode, expected_user_mode);
316 }
317
318 #[test]
319 fn test_build_command() {
320 let backend = SystemdBackend::with_user_mode(true);
321
322 let config = ProcessConfig::new("test", "/usr/bin/test")
323 .args(["--foo", "bar"])
324 .working_dir("/tmp")
325 .env("KEY", "VALUE")
326 .memory_limit("1G")
327 .cpu_quota(200);
328
329 let cmd = backend.build_command(&config, "test-unit.service");
330
331 drop(cmd);
333 }
334
335 #[tokio::test]
336 #[ignore = "requires systemd"]
337 async fn test_spawn_and_stop() -> hyprstream_rpc::Result<()> {
338 if !SystemdBackend::is_available() {
339 println!("Systemd not available, skipping test");
340 return Ok(());
341 }
342
343 let backend = SystemdBackend::new();
344
345 let config = ProcessConfig::new("test-sleep", "sleep").args(["60"]);
346
347 let process = backend.spawn(config).await?;
348
349 assert!(process.is_systemd());
350 assert!(process.unit_name().is_some());
351
352 let running = backend.is_running(&process).await?;
354 assert!(running);
355
356 backend.stop(&process).await?;
358
359 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
361
362 let running = backend.is_running(&process).await?;
364 assert!(!running);
365 Ok(())
366 }
367}