Skip to main content

hyprstream_service/service/spawner/
systemd.rs

1//! Systemd spawner using transient units.
2//!
3//! Spawns daemon processes as systemd transient units via `systemd-run`.
4//! Provides better resource isolation, automatic restart, and centralized logging.
5//!
6//! # Features
7//!
8//! - Spawns processes in `hyprstream-workers.slice` for resource isolation
9//! - Supports memory limits and CPU quotas
10//! - Automatic cleanup via `CollectMode=inactive-or-failed`
11//! - Works in both user and system mode
12//!
13//! # Unit Naming
14//!
15//! Units are named: `hyprstream-{name}-{uuid}.service`
16//!
17//! Example: `hyprstream-nydusd-abc123.service`
18
19use 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
27/// Systemd spawner backend using transient units.
28///
29/// Uses `systemd-run` to spawn processes as transient systemd units.
30/// Falls back to user mode (`--user`) if not running as root.
31pub struct SystemdBackend {
32    /// Whether to use user mode (--user flag).
33    user_mode: bool,
34
35    /// Slice for worker processes.
36    slice: String,
37}
38
39impl SystemdBackend {
40    /// Create a new systemd backend.
41    ///
42    /// Automatically detects whether to use user or system mode based on UID.
43    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    /// Create a backend with explicit mode selection.
53    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    /// Set the slice for spawned units.
61    pub fn with_slice(mut self, slice: impl Into<String>) -> Self {
62        self.slice = slice.into();
63        self
64    }
65
66    /// Check if systemd-run is available.
67    pub fn is_available() -> bool {
68        // Check if we're running under systemd
69        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        // Check if systemd-run is available
77        which::which("systemd-run").is_ok()
78    }
79
80    /// Generate a unique unit name.
81    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    /// Build systemd-run command.
87    fn build_command(&self, config: &ProcessConfig, unit_name: &str) -> Command {
88        let mut cmd = Command::new("systemd-run");
89
90        // User mode if not root
91        if self.user_mode {
92            cmd.arg("--user");
93        }
94
95        // Unit configuration
96        cmd.arg("--unit").arg(unit_name);
97        cmd.arg("--description")
98            .arg(format!("Hyprstream worker: {}", config.name));
99
100        // Slice for resource isolation
101        cmd.arg("--slice").arg(&self.slice);
102
103        // Automatic cleanup when stopped
104        cmd.arg("--property=CollectMode=inactive-or-failed");
105
106        // Service type
107        cmd.arg("--property=Type=exec");
108
109        // Memory limit
110        if let Some(ref limit) = config.memory_limit {
111            cmd.arg(format!("--property=MemoryMax={limit}"));
112        }
113
114        // CPU quota
115        if let Some(quota) = config.cpu_quota {
116            cmd.arg(format!("--property=CPUQuota={quota}%"));
117        }
118
119        // Restart on failure
120        if config.restart_on_failure {
121            cmd.arg("--property=Restart=on-failure");
122            cmd.arg("--property=RestartSec=1");
123        }
124
125        // Working directory
126        if let Some(ref dir) = config.working_dir {
127            cmd.arg(format!("--property=WorkingDirectory={}", dir.display()));
128        }
129
130        // Environment variables
131        for (key, value) in &config.env {
132            cmd.arg("--setenv").arg(format!("{key}={value}"));
133        }
134
135        // Custom unit properties
136        for (key, value) in &config.unit_properties {
137            cmd.arg(format!("--property={key}={value}"));
138        }
139
140        // The actual command to run
141        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        // Notification readiness is a standalone-supervision contract (#1585);
158        // transient systemd-run units are not the launcher's path and get no
159        // half-wired imitation of it.
160        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        // Build and run systemd-run command
175        let mut cmd = self.build_command(&config, &unit_name);
176
177        // Capture output for debugging
178        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        // Use systemctl stop
224        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            // Don't fail if unit doesn't exist (already stopped)
239            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        // Use systemctl is-active
267        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        // Exit code 0 = active, non-zero = inactive/failed
282        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        // This will depend on the test environment
298        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        // We can't easily inspect the Command, but at least verify it builds
332        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        // Check it's running
353        let running = backend.is_running(&process).await?;
354        assert!(running);
355
356        // Stop it
357        backend.stop(&process).await?;
358
359        // Give systemd a moment
360        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
361
362        // Check it's stopped
363        let running = backend.is_running(&process).await?;
364        assert!(!running);
365        Ok(())
366    }
367}