geist_supervisor 0.1.28

Generic OTA supervisor for field devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Service Manager
//!
//! Handles all systemctl operations for ROC Camera service management.
//! This module centralizes service control logic that was previously
//! scattered across multiple files.

use anyhow::{Context, Result};
use std::process::Command;
use std::time::Duration;
use tracing::{debug, error, info, warn};

// Constants for service management
const SERVICE_STOP_TIMEOUT_ATTEMPTS: u32 = 10; // 50 seconds for stop operations

/// Manages systemd service operations for ROC Camera
///
/// This service centralizes all systemctl operations and provides
/// robust error handling, retries, and test environment support.
#[derive(Debug, Clone)]
pub struct ServiceManager {
    service_name: String,
}

impl ServiceManager {
    pub fn new(service_name: String) -> Self {
        Self { service_name }
    }

    /// Check if service is currently running
    pub fn is_service_running(&self) -> bool {
        // In test environment, assume service is running
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);
        if is_test_env {
            return true;
        }

        // Always use sudo for systemctl commands to avoid polkit prompts
        match Command::new("sudo")
            .args(["systemctl", "is-active", &self.service_name])
            .output()
        {
            Ok(output) => {
                let status = String::from_utf8_lossy(&output.stdout).trim().to_string();
                debug!(
                    "Service status: {} - success: {}",
                    status,
                    output.status.success()
                );

                // Service can be "active", "inactive", "failed", etc.
                // We only consider it running if it's "active"
                status == "active"
            }
            Err(e) => {
                debug!("Systemctl failed: {}", e);
                false
            }
        }
    }

    /// Check service status without requiring sudo (for read-only operations)
    pub fn check_service_status_readonly(&self) -> String {
        // In test environment, return mock status
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);
        if is_test_env {
            return "running".to_string();
        }

        // Try without sudo first for read-only status check
        match Command::new("systemctl")
            .args(["is-active", &self.service_name])
            .output()
        {
            Ok(output) => {
                let status = String::from_utf8_lossy(&output.stdout).trim().to_string();
                debug!("Service status (no-sudo): {}", status);

                // Map systemctl status to our simplified status
                match status.as_str() {
                    "active" => "running".to_string(),
                    "inactive" => "stopped".to_string(),
                    "failed" => "failed".to_string(),
                    "activating" => "starting".to_string(),
                    "deactivating" => "stopping".to_string(),
                    _ => "unknown".to_string(),
                }
            }
            Err(e) => {
                debug!("Systemctl failed (no-sudo): {}", e);
                "unknown".to_string()
            }
        }
    }

    /// Stop the systemd service with timeout and disable restart during update
    pub fn stop_service(&self) -> Result<()> {
        info!("Stopping service: {}", self.service_name);

        // In test environment, skip actual systemctl commands
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);
        if is_test_env {
            info!("Test environment detected, skipping service stop");
            return Ok(());
        }

        // First, temporarily disable the service to prevent automatic restart
        info!("Temporarily disabling service to prevent restart during update");
        let disable_output = self.run_systemctl(&["disable", &self.service_name])?;
        if !disable_output.status.success() {
            warn!("Failed to disable service, continuing anyway");
        }

        // Try to stop the service
        let output = self.run_systemctl(&["stop", &self.service_name])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            // Don't fail if service was already stopped
            if stderr.contains("Unit") && stderr.contains("not loaded") {
                warn!(
                    "Service {} was not loaded (already stopped?)",
                    self.service_name
                );
                return Ok(());
            }

            anyhow::bail!(
                "Failed to stop service {}: STDERR: {} STDOUT: {}",
                self.service_name,
                stderr,
                stdout
            );
        }

        // Wait for service to actually stop
        for attempt in 1..=SERVICE_STOP_TIMEOUT_ATTEMPTS {
            let status_output = self.run_systemctl(&["is-active", &self.service_name])?;

            let status_string = String::from_utf8_lossy(&status_output.stdout);
            let status = status_string.trim();
            if status == "inactive" || status == "failed" {
                info!("Service stopped successfully after {} attempts", attempt);
                return Ok(());
            }

            debug!("Waiting for service to stop (attempt {})", attempt);
            std::thread::sleep(Duration::from_secs(1));
        }

        warn!("Service may not have stopped gracefully within timeout, proceeding anyway");
        Ok(())
    }

    /// Start the systemd service with verification and re-enable it
    pub fn start_service(&self) -> Result<()> {
        info!("Starting service: {}", self.service_name);

        // In test environment, skip actual systemctl commands
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);
        if is_test_env {
            info!("Test environment detected, skipping service start");
            return Ok(());
        }

        // Re-enable the service to restore automatic restart capability
        info!("Re-enabling service to restore automatic restart");
        let enable_output = self.run_systemctl(&["enable", &self.service_name])?;
        if !enable_output.status.success() {
            warn!("Failed to re-enable service, but continuing");
        }

        // Reload systemd daemon to pick up any changes
        if let Err(e) = self.run_systemctl(&["daemon-reload"]) {
            warn!("Failed to reload systemd daemon: {}", e);
        }

        let output = self.run_systemctl(&["start", &self.service_name])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            error!("Failed to issue start command for service: {}", stderr);

            // Get detailed status for debugging
            if let Ok(status_output) = self.run_systemctl(&["status", &self.service_name]) {
                let status_info = String::from_utf8_lossy(&status_output.stdout);
                error!("Service status after failed start:\n{}", status_info);
            }

            anyhow::bail!(
                "Failed to start service {}: STDERR: {} STDOUT: {}",
                self.service_name,
                stderr,
                stdout
            );
        }

        info!("Service start command issued, verifying startup...");
        Ok(())
    }

    /// Wait for service to become active with timeout
    pub fn wait_for_service_active(&self, timeout_secs: Option<u64>) -> Result<()> {
        let timeout = timeout_secs.unwrap_or(100); // Default 100 seconds
        let check_interval = 5; // Check every 5 seconds
        let max_attempts = timeout / check_interval;

        // In test environment, skip waiting
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);
        if is_test_env {
            info!("Test environment detected, skipping service wait");
            return Ok(());
        }

        // Reset any failed state before starting verification
        info!("Resetting any previous failed state before verification...");
        if let Err(e) = Command::new("sudo")
            .args(["systemctl", "reset-failed", &self.service_name])
            .output()
        {
            warn!("Failed to reset failed state (this is usually fine): {}", e);
        }

        // Give service initial time to start
        std::thread::sleep(std::time::Duration::from_secs(3));

        info!(
            "Waiting for service to become active (max {} seconds)...",
            timeout
        );

        for attempt in 1..=max_attempts {
            std::thread::sleep(std::time::Duration::from_secs(check_interval));

            if self.is_service_running() {
                info!(
                    "✅ Service is active (attempt {}/{})",
                    attempt, max_attempts
                );
                return Ok(());
            }

            info!(
                "⏳ Service not active yet (attempt {}/{}) - checking status...",
                attempt, max_attempts
            );

            // Check service status for failure detection
            if let Ok(status_output) = Command::new("sudo")
                .args([
                    "systemctl",
                    "status",
                    &self.service_name,
                    "--no-pager",
                    "-l",
                ])
                .output()
            {
                let status = String::from_utf8_lossy(&status_output.stdout);

                // Check for recent failures (not pre-existing ones)
                if status.contains("failed") || status.contains("Failed") {
                    // Check if this is a recent failure
                    let is_recent_failure = if let Ok(log_output) = Command::new("journalctl")
                        .args([
                            "-u",
                            &self.service_name,
                            "-n",
                            "5",
                            "--no-pager",
                            "--since=5 minutes ago",
                        ])
                        .output()
                    {
                        let recent_logs = String::from_utf8_lossy(&log_output.stdout);
                        recent_logs.contains("Starting")
                            || recent_logs.contains("Started")
                            || recent_logs.contains("Stopping")
                    } else {
                        false
                    };

                    if is_recent_failure {
                        error!(
                            "❌ Service has failed state detected on attempt {} (recent failure)",
                            attempt
                        );
                        error!("Service status:\n{}", status);

                        // Get recent logs for context
                        if let Ok(log_output) = Command::new("journalctl")
                            .args(["-u", &self.service_name, "-n", "15", "--no-pager"])
                            .output()
                        {
                            let logs = String::from_utf8_lossy(&log_output.stdout);
                            error!("Recent service logs:\n{}", logs);
                        }

                        anyhow::bail!("Service failed to start - recent failure detected");
                    } else {
                        warn!(
                            "⚠️ Service shows failed state from before update (attempt {}) - continuing to wait",
                            attempt
                        );
                        continue;
                    }
                }

                // Log brief status for progress tracking
                if let Some(active_line) = status
                    .lines()
                    .find(|line| line.trim().starts_with("Active:"))
                {
                    info!("Status: {}", active_line.trim());
                }
            } else {
                warn!("Could not check service status on attempt {}", attempt);
            }
        }

        anyhow::bail!("Service failed to become active within {} seconds", timeout);
    }

    /// Get detailed service status
    pub fn get_service_status(&self) -> Result<String> {
        let output = self.run_systemctl(&["status", &self.service_name, "--no-pager", "-l"])?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Get service logs
    pub fn get_service_logs(&self, lines: u32) -> Result<String> {
        let output = Command::new("journalctl")
            .args([
                "-u",
                &self.service_name,
                "-n",
                &lines.to_string(),
                "--no-pager",
            ])
            .output()
            .context("Failed to get service logs")?;

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Restart the service
    pub fn restart_service(&self) -> Result<()> {
        info!("Restarting service: {}", self.service_name);

        // In test environment, skip actual operations
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);
        if is_test_env {
            info!("Test environment detected, skipping service restart");
            return Ok(());
        }

        let output = self.run_systemctl(&["restart", &self.service_name])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!(
                "Failed to restart service {}: {}",
                self.service_name,
                stderr
            );
        }

        info!("Service restart command issued successfully");
        Ok(())
    }

    /// Check if systemd service exists and is controllable
    pub fn check_service_exists(&self) -> Result<()> {
        let output = self.run_systemctl(&["is-active", &self.service_name])?;

        let status = String::from_utf8_lossy(&output.stdout).trim().to_string();
        debug!("Service {} status: {}", self.service_name, status);

        // We can work with active, inactive, or failed states
        // But not with unknown/not-found
        if status == "unknown" {
            anyhow::bail!("Service {} not found", self.service_name);
        }

        Ok(())
    }

    /// Enable the service to start on boot
    pub fn enable_service(&self) -> Result<()> {
        info!("Enabling service: {}", self.service_name);

        let output = self.run_systemctl(&["enable", &self.service_name])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to enable service {}: {}", self.service_name, stderr);
        }

        info!("Service enabled successfully");
        Ok(())
    }

    /// Disable the service from starting on boot
    pub fn disable_service(&self) -> Result<()> {
        info!("Disabling service: {}", self.service_name);

        let output = self.run_systemctl(&["disable", &self.service_name])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!(
                "Failed to disable service {}: {}",
                self.service_name,
                stderr
            );
        }

        info!("Service disabled successfully");
        Ok(())
    }

    /// Reload systemd daemon
    pub fn reload_daemon(&self) -> Result<()> {
        debug!("Reloading systemd daemon");
        let output = self.run_systemctl(&["daemon-reload"])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            warn!("Failed to reload systemd daemon: {}", stderr);
        }

        Ok(())
    }

    /// Run systemctl command with sudo
    fn run_systemctl(&self, args: &[&str]) -> Result<std::process::Output> {
        // Skip systemd control on non-Linux systems or in test environment
        let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok() || cfg!(test);

        if cfg!(target_os = "macos") || cfg!(target_os = "windows") || is_test_env {
            debug!(
                "Skipping systemctl command in development/test environment: systemctl {}",
                args.join(" ")
            );
            // Return a mock successful output for development/test
            #[cfg(unix)]
            let status = std::os::unix::process::ExitStatusExt::from_raw(0);
            #[cfg(not(unix))]
            let status = std::process::ExitStatus::from(std::process::ExitCode::SUCCESS);

            return Ok(std::process::Output {
                status,
                stdout: b"active\n".to_vec(),
                stderr: Vec::new(),
            });
        }

        // Check if we're already running as root
        #[cfg(unix)]
        let is_root = unsafe { libc::geteuid() == 0 };
        #[cfg(not(unix))]
        let is_root = false;

        let mut command = if is_root {
            // If we're already root, run systemctl directly
            let mut cmd = Command::new("systemctl");
            cmd.args(args);
            cmd
        } else {
            // If we're not root, use sudo
            let mut cmd = Command::new("sudo");
            cmd.arg("systemctl");
            cmd.args(args);
            cmd
        };

        command
            .output()
            .context(format!("Failed to run systemctl {}", args.join(" ")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_service_manager_creation() {
        let manager = ServiceManager::new("test_service".to_string());
        assert_eq!(manager.service_name, "test_service");
    }

    #[test]
    fn test_is_service_running_test_env() {
        // In test environment, should always return true
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());
        assert!(manager.is_service_running());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_stop_service_test_env() {
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());
        let result = manager.stop_service();
        assert!(result.is_ok());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_start_service_test_env() {
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());
        let result = manager.start_service();
        assert!(result.is_ok());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_wait_for_service_active_test_env() {
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());
        let result = manager.wait_for_service_active(Some(1));
        assert!(result.is_ok());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_restart_service_test_env() {
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());
        let result = manager.restart_service();
        assert!(result.is_ok());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_enable_disable_service_test_env() {
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());

        let enable_result = manager.enable_service();
        assert!(enable_result.is_ok());

        let disable_result = manager.disable_service();
        assert!(disable_result.is_ok());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_reload_daemon_test_env() {
        std::env::set_var("GEIST_APP_BINARY_PATH_TEST", "1");

        let manager = ServiceManager::new("test_service".to_string());
        let result = manager.reload_daemon();
        assert!(result.is_ok());

        std::env::remove_var("GEIST_APP_BINARY_PATH_TEST");
    }

    #[test]
    fn test_service_manager_debug() {
        let manager = ServiceManager::new("test_service".to_string());
        let debug_str = format!("{:?}", manager);
        assert!(debug_str.contains("test_service"));
    }

    #[test]
    fn test_service_manager_clone() {
        let manager = ServiceManager::new("test_service".to_string());
        let cloned = manager.clone();
        assert_eq!(manager.service_name, cloned.service_name);
    }
}