Skip to main content

ironmonitor/
services.rs

1//! System Service Monitoring and Control
2//!
3//! This module provides cross-platform system service monitoring capabilities
4//! including service status, management, and auto-start configuration.
5//!
6//! # Example
7//!
8//! ```no_run
9//! use ironmonitor::services::{ServiceMonitor, ServiceStatus};
10//!
11//! let monitor = ServiceMonitor::new().unwrap();
12//!
13//! // List all services
14//! for service in monitor.services() {
15//!     println!("{}: {:?}", service.name, service.status);
16//! }
17//!
18//! // Check specific service
19//! if let Some(status) = monitor.get_service("sshd") {
20//!     println!("SSH: {:?}", status.status);
21//! }
22//! ```
23
24use crate::error::{IronError, Result};
25use serde::{Deserialize, Serialize};
26use std::collections::HashMap;
27use std::time::Instant;
28
29/// Service status states
30#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub enum ServiceStatus {
32    /// Service is running
33    Running,
34    /// Service is stopped
35    Stopped,
36    /// Service is starting
37    Starting,
38    /// Service is stopping
39    Stopping,
40    /// Service has failed
41    Failed,
42    /// Service status is unknown
43    Unknown,
44    /// Service is not found
45    NotFound,
46    /// Service ran to completion and is held active with no process left
47    /// running: systemd's `active (exited)`, a oneshot unit with
48    /// `RemainAfterExit`. Neither running nor stopped.
49    Exited,
50}
51
52impl std::fmt::Display for ServiceStatus {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        match self {
55            ServiceStatus::Running => write!(f, "running"),
56            ServiceStatus::Stopped => write!(f, "stopped"),
57            ServiceStatus::Starting => write!(f, "starting"),
58            ServiceStatus::Stopping => write!(f, "stopping"),
59            ServiceStatus::Failed => write!(f, "failed"),
60            ServiceStatus::Unknown => write!(f, "unknown"),
61            ServiceStatus::NotFound => write!(f, "not-found"),
62            ServiceStatus::Exited => write!(f, "exited"),
63        }
64    }
65}
66
67/// Service type classification
68#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
69pub enum ServiceType {
70    /// Simple foreground service
71    Simple,
72    /// Forking daemon
73    Forking,
74    /// Oneshot service
75    Oneshot,
76    /// D-Bus activated service
77    Dbus,
78    /// Notify service
79    Notify,
80    /// Idle service
81    Idle,
82    /// Windows service
83    Win32,
84    /// Unknown type
85    Unknown,
86}
87
88/// Service startup type
89#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
90pub enum StartupType {
91    /// Automatically start on boot
92    Automatic,
93    /// Manual start required
94    Manual,
95    /// Disabled
96    Disabled,
97    /// Start on demand
98    OnDemand,
99    /// Unknown
100    Unknown,
101}
102
103impl std::fmt::Display for StartupType {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        match self {
106            StartupType::Automatic => write!(f, "automatic"),
107            StartupType::Manual => write!(f, "manual"),
108            StartupType::Disabled => write!(f, "disabled"),
109            StartupType::OnDemand => write!(f, "on-demand"),
110            StartupType::Unknown => write!(f, "unknown"),
111        }
112    }
113}
114
115/// Detailed information about a system service
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct ServiceInfo {
118    /// Service name
119    pub name: String,
120    /// Display name / description
121    pub display_name: Option<String>,
122    /// Current status
123    pub status: ServiceStatus,
124    /// Service type
125    pub service_type: ServiceType,
126    /// Startup type
127    pub startup_type: StartupType,
128    /// Process ID (if running)
129    pub pid: Option<u32>,
130    /// Memory usage (bytes)
131    pub memory_bytes: Option<u64>,
132    /// CPU time (seconds)
133    pub cpu_time_secs: Option<f64>,
134    /// Main process exit code
135    pub exit_code: Option<i32>,
136    /// Unit file path (Linux)
137    pub unit_file: Option<String>,
138    /// Service dependencies
139    pub dependencies: Vec<String>,
140    /// Services that depend on this
141    pub dependents: Vec<String>,
142    /// Is service enabled at boot. `None` where the boot-time state was not
143    /// read (for example `systemctl show` failed). Not `false`: that would
144    /// claim the service is disabled.
145    pub enabled: Option<bool>,
146    /// Load state (systemd)
147    pub load_state: Option<String>,
148    /// Sub-state (systemd)
149    pub sub_state: Option<String>,
150    /// Last error message
151    pub error_message: Option<String>,
152    /// Start time
153    pub start_time: Option<String>,
154}
155
156impl ServiceInfo {
157    /// Create a new ServiceInfo
158    pub fn new(name: impl Into<String>) -> Self {
159        Self {
160            name: name.into(),
161            display_name: None,
162            status: ServiceStatus::Unknown,
163            service_type: ServiceType::Unknown,
164            startup_type: StartupType::Unknown,
165            pid: None,
166            memory_bytes: None,
167            cpu_time_secs: None,
168            exit_code: None,
169            unit_file: None,
170            dependencies: Vec::new(),
171            dependents: Vec::new(),
172            enabled: None,
173            load_state: None,
174            sub_state: None,
175            error_message: None,
176            start_time: None,
177        }
178    }
179
180    /// Check if service is active
181    pub fn is_active(&self) -> bool {
182        self.status == ServiceStatus::Running
183    }
184
185    /// Check if service is failed
186    pub fn is_failed(&self) -> bool {
187        self.status == ServiceStatus::Failed
188    }
189}
190
191/// System service monitor
192pub struct ServiceMonitor {
193    /// Discovered services
194    services: Vec<ServiceInfo>,
195    /// Service map by name
196    service_map: HashMap<String, usize>,
197    /// Last update time
198    last_update: Instant,
199    /// Filter for specific services
200    filter: Option<Vec<String>>,
201}
202
203impl ServiceMonitor {
204    /// Create a new service monitor
205    pub fn new() -> Result<Self> {
206        let mut monitor = Self {
207            services: Vec::new(),
208            service_map: HashMap::new(),
209            last_update: Instant::now(),
210            filter: None,
211        };
212
213        monitor.discover()?;
214        Ok(monitor)
215    }
216
217    /// Create a monitor for specific services
218    pub fn with_filter(service_names: Vec<String>) -> Result<Self> {
219        // Stored names carry no `.service` suffix, so a filter given as
220        // `sshd.service` would match nothing.
221        let service_names = service_names
222            .into_iter()
223            .map(|n| normalise_service_name(&n).to_string())
224            .collect();
225        let mut monitor = Self {
226            services: Vec::new(),
227            service_map: HashMap::new(),
228            last_update: Instant::now(),
229            filter: Some(service_names),
230        };
231
232        monitor.discover()?;
233        Ok(monitor)
234    }
235
236    /// Refresh service information
237    pub fn refresh(&mut self) -> Result<()> {
238        self.services.clear();
239        self.service_map.clear();
240        self.discover()?;
241        self.last_update = Instant::now();
242        Ok(())
243    }
244
245    /// Get all services
246    pub fn services(&self) -> &[ServiceInfo] {
247        &self.services
248    }
249
250    /// Get service by name
251    pub fn get_service(&self, name: &str) -> Option<&ServiceInfo> {
252        self.service_map
253            .get(normalise_service_name(name))
254            .and_then(|&idx| self.services.get(idx))
255    }
256
257    /// Get running services
258    pub fn running_services(&self) -> Vec<&ServiceInfo> {
259        self.services
260            .iter()
261            .filter(|s| s.status == ServiceStatus::Running)
262            .collect()
263    }
264
265    /// Get failed services
266    pub fn failed_services(&self) -> Vec<&ServiceInfo> {
267        self.services
268            .iter()
269            .filter(|s| s.status == ServiceStatus::Failed)
270            .collect()
271    }
272
273    /// Check if a service is active. `None` when this monitor holds no
274    /// service of that name, which is not the same as inactive.
275    pub fn is_active(&self, name: &str) -> Option<bool> {
276        self.get_service(name).map(|s| s.is_active())
277    }
278
279    /// Start a service
280    pub fn start(&self, name: &str) -> Result<()> {
281        #[cfg(target_os = "linux")]
282        {
283            self.linux_start_service(name)
284        }
285
286        #[cfg(target_os = "windows")]
287        {
288            self.windows_start_service(name)
289        }
290
291        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
292        {
293            let _ = name;
294            Err(IronError::UnsupportedPlatform(
295                "Service control not supported".to_string(),
296            ))
297        }
298    }
299
300    /// Stop a service
301    pub fn stop(&self, name: &str) -> Result<()> {
302        #[cfg(target_os = "linux")]
303        {
304            self.linux_stop_service(name)
305        }
306
307        #[cfg(target_os = "windows")]
308        {
309            self.windows_stop_service(name)
310        }
311
312        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
313        {
314            let _ = name;
315            Err(IronError::UnsupportedPlatform(
316                "Service control not supported".to_string(),
317            ))
318        }
319    }
320
321    /// Restart a service
322    pub fn restart(&self, name: &str) -> Result<()> {
323        #[cfg(target_os = "linux")]
324        {
325            self.linux_restart_service(name)
326        }
327
328        #[cfg(target_os = "windows")]
329        {
330            // Windows: stop then start
331            self.windows_stop_service(name)?;
332            std::thread::sleep(std::time::Duration::from_millis(500));
333            self.windows_start_service(name)
334        }
335
336        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
337        {
338            let _ = name;
339            Err(IronError::UnsupportedPlatform(
340                "Service control not supported".to_string(),
341            ))
342        }
343    }
344
345    /// Enable service at boot
346    pub fn enable(&self, name: &str) -> Result<()> {
347        #[cfg(target_os = "linux")]
348        {
349            self.linux_enable_service(name)
350        }
351
352        #[cfg(target_os = "windows")]
353        {
354            self.windows_set_startup(name, StartupType::Automatic)
355        }
356
357        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
358        {
359            let _ = name;
360            Err(IronError::UnsupportedPlatform(
361                "Service control not supported".to_string(),
362            ))
363        }
364    }
365
366    /// Disable service at boot
367    pub fn disable(&self, name: &str) -> Result<()> {
368        #[cfg(target_os = "linux")]
369        {
370            self.linux_disable_service(name)
371        }
372
373        #[cfg(target_os = "windows")]
374        {
375            self.windows_set_startup(name, StartupType::Manual)
376        }
377
378        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
379        {
380            let _ = name;
381            Err(IronError::UnsupportedPlatform(
382                "Service control not supported".to_string(),
383            ))
384        }
385    }
386
387    // Platform discovery
388    fn discover(&mut self) -> Result<()> {
389        #[cfg(target_os = "linux")]
390        {
391            self.linux_discover()
392        }
393
394        #[cfg(target_os = "windows")]
395        {
396            self.windows_discover()
397        }
398
399        #[cfg(target_os = "macos")]
400        {
401            self.macos_discover()
402        }
403
404        #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
405        {
406            Ok(())
407        }
408    }
409
410    // ==================== Linux Implementation ====================
411
412    #[cfg(target_os = "linux")]
413    fn linux_discover(&mut self) -> Result<()> {
414        use std::process::Command;
415
416        // Use systemctl to list services
417        let output = Command::new("systemctl")
418            .args([
419                "list-units",
420                "--type=service",
421                "--all",
422                "--no-pager",
423                "--no-legend",
424            ])
425            .output();
426
427        // A failed `systemctl` is an error, not an empty machine. Returning
428        // `Ok` with no services made every lookup report NotFound.
429        let output = output.map_err(|e| IronError::HardwareError(format!("systemctl: {e}")))?;
430        if !output.status.success() {
431            return Err(IronError::HardwareError(
432                "systemctl list-units --type=service failed".to_string(),
433            ));
434        }
435        if let Ok(stdout) = String::from_utf8(output.stdout) {
436            for line in stdout.lines() {
437                if let Some(service) = self.linux_parse_service_line(line) {
438                    // Apply filter if set
439                    if let Some(ref filter) = self.filter {
440                        if !filter.iter().any(|f| service.name.contains(f)) {
441                            continue;
442                        }
443                    }
444
445                    let idx = self.services.len();
446                    self.service_map.insert(service.name.clone(), idx);
447                    self.services.push(service);
448                }
449            }
450        }
451
452        // Get detailed info for each service.
453        //
454        // Iterating `&mut self.services` while calling `&self` method borrows self
455        // both ways at once. Move the vector out for the duration and put it back:
456        // `linux_get_service_details` does not read `self.services`, so nothing
457        // observes it missing.
458        let mut services = std::mem::take(&mut self.services);
459        for service in &mut services {
460            self.linux_get_service_details(service);
461        }
462        self.services = services;
463
464        Ok(())
465    }
466
467    #[cfg(target_os = "linux")]
468    fn linux_parse_service_line(&self, line: &str) -> Option<ServiceInfo> {
469        let parts: Vec<&str> = line.split_whitespace().collect();
470        if parts.len() < 4 {
471            return None;
472        }
473
474        let name = parts[0].trim_end_matches(".service").to_string();
475        let load_state = parts[1].to_string();
476        let active_state = parts[2].to_string();
477        let sub_state = parts[3].to_string();
478
479        let status = match active_state.as_str() {
480            "active" => match sub_state.as_str() {
481                "running" => ServiceStatus::Running,
482                // `active (exited)` was reported stopped, which a unit systemd
483                // holds active is not.
484                "exited" => ServiceStatus::Exited,
485                "waiting" => ServiceStatus::Starting,
486                // A sub-state not listed here used to read as running.
487                _ => ServiceStatus::Unknown,
488            },
489            "inactive" => ServiceStatus::Stopped,
490            "failed" => ServiceStatus::Failed,
491            "activating" => ServiceStatus::Starting,
492            "deactivating" => ServiceStatus::Stopping,
493            _ => ServiceStatus::Unknown,
494        };
495
496        let mut service = ServiceInfo::new(&name);
497        service.status = status;
498        service.load_state = Some(load_state);
499        service.sub_state = Some(sub_state);
500
501        // Get description from remaining parts
502        if parts.len() > 4 {
503            service.display_name = Some(parts[4..].join(" "));
504        }
505
506        Some(service)
507    }
508
509    #[cfg(target_os = "linux")]
510    fn linux_get_service_details(&self, service: &mut ServiceInfo) {
511        use std::process::Command;
512
513        // Get detailed service info
514        let output = Command::new("systemctl")
515            .args(["show", &format!("{}.service", service.name)])
516            .output();
517
518        if let Ok(output) = output {
519            if let Ok(stdout) = String::from_utf8(output.stdout) {
520                for line in stdout.lines() {
521                    if let Some((key, value)) = line.split_once('=') {
522                        match key {
523                            "MainPID" => {
524                                if let Ok(pid) = value.parse::<u32>() {
525                                    if pid > 0 {
526                                        service.pid = Some(pid);
527                                    }
528                                }
529                            }
530                            "MemoryCurrent" => {
531                                if let Ok(mem) = value.parse::<u64>() {
532                                    if mem < u64::MAX {
533                                        service.memory_bytes = Some(mem);
534                                    }
535                                }
536                            }
537                            // When the unit last entered the active state, which is
538                            // its start. `ExecMainExitTimestamp` is when it exited,
539                            // and was stored here as the start time.
540                            "ActiveEnterTimestamp" => {
541                                if !value.is_empty() {
542                                    service.start_time = Some(value.to_string());
543                                }
544                            }
545                            "Type" => {
546                                service.service_type = match value {
547                                    "simple" => ServiceType::Simple,
548                                    "forking" => ServiceType::Forking,
549                                    "oneshot" => ServiceType::Oneshot,
550                                    "dbus" => ServiceType::Dbus,
551                                    "notify" => ServiceType::Notify,
552                                    "idle" => ServiceType::Idle,
553                                    _ => ServiceType::Unknown,
554                                };
555                            }
556                            "UnitFileState" => {
557                                // Empty for units with no unit file (transient or
558                                // generated). That is no answer, not "disabled".
559                                if !value.is_empty() {
560                                    service.enabled = Some(value == "enabled");
561                                }
562                                service.startup_type = match value {
563                                    "enabled" => StartupType::Automatic,
564                                    "disabled" => StartupType::Disabled,
565                                    "static" => StartupType::Manual,
566                                    "masked" => StartupType::Disabled,
567                                    _ => StartupType::Unknown,
568                                };
569                            }
570                            "FragmentPath" => {
571                                if !value.is_empty() {
572                                    service.unit_file = Some(value.to_string());
573                                }
574                            }
575                            "Requires" | "Wants" => {
576                                for dep in value.split_whitespace() {
577                                    let dep_name = dep.trim_end_matches(".service");
578                                    if !dep_name.is_empty() {
579                                        service.dependencies.push(dep_name.to_string());
580                                    }
581                                }
582                            }
583                            "RequiredBy" | "WantedBy" => {
584                                for dep in value.split_whitespace() {
585                                    let dep_name = dep.trim_end_matches(".service");
586                                    if !dep_name.is_empty() {
587                                        service.dependents.push(dep_name.to_string());
588                                    }
589                                }
590                            }
591                            _ => {}
592                        }
593                    }
594                }
595            }
596        }
597    }
598
599    #[cfg(target_os = "linux")]
600    fn linux_start_service(&self, name: &str) -> Result<()> {
601        use std::process::Command;
602
603        let status = Command::new("systemctl")
604            .args(["start", &format!("{}.service", name)])
605            .status();
606
607        match status {
608            Ok(s) if s.success() => Ok(()),
609            Ok(_) => Err(IronError::System(format!(
610                "Failed to start service '{}' (check permissions)",
611                name
612            ))),
613            Err(e) => Err(IronError::System(format!(
614                "Failed to execute systemctl: {}",
615                e
616            ))),
617        }
618    }
619
620    #[cfg(target_os = "linux")]
621    fn linux_stop_service(&self, name: &str) -> Result<()> {
622        use std::process::Command;
623
624        let status = Command::new("systemctl")
625            .args(["stop", &format!("{}.service", name)])
626            .status();
627
628        match status {
629            Ok(s) if s.success() => Ok(()),
630            Ok(_) => Err(IronError::System(format!(
631                "Failed to stop service '{}' (check permissions)",
632                name
633            ))),
634            Err(e) => Err(IronError::System(format!(
635                "Failed to execute systemctl: {}",
636                e
637            ))),
638        }
639    }
640
641    #[cfg(target_os = "linux")]
642    fn linux_restart_service(&self, name: &str) -> Result<()> {
643        use std::process::Command;
644
645        let status = Command::new("systemctl")
646            .args(["restart", &format!("{}.service", name)])
647            .status();
648
649        match status {
650            Ok(s) if s.success() => Ok(()),
651            Ok(_) => Err(IronError::System(format!(
652                "Failed to restart service '{}' (check permissions)",
653                name
654            ))),
655            Err(e) => Err(IronError::System(format!(
656                "Failed to execute systemctl: {}",
657                e
658            ))),
659        }
660    }
661
662    #[cfg(target_os = "linux")]
663    fn linux_enable_service(&self, name: &str) -> Result<()> {
664        use std::process::Command;
665
666        let status = Command::new("systemctl")
667            .args(["enable", &format!("{}.service", name)])
668            .status();
669
670        match status {
671            Ok(s) if s.success() => Ok(()),
672            Ok(_) => Err(IronError::System(format!(
673                "Failed to enable service '{}' (check permissions)",
674                name
675            ))),
676            Err(e) => Err(IronError::System(format!(
677                "Failed to execute systemctl: {}",
678                e
679            ))),
680        }
681    }
682
683    #[cfg(target_os = "linux")]
684    fn linux_disable_service(&self, name: &str) -> Result<()> {
685        use std::process::Command;
686
687        let status = Command::new("systemctl")
688            .args(["disable", &format!("{}.service", name)])
689            .status();
690
691        match status {
692            Ok(s) if s.success() => Ok(()),
693            Ok(_) => Err(IronError::System(format!(
694                "Failed to disable service '{}' (check permissions)",
695                name
696            ))),
697            Err(e) => Err(IronError::System(format!(
698                "Failed to execute systemctl: {}",
699                e
700            ))),
701        }
702    }
703
704    // ==================== Windows Implementation ====================
705
706    #[cfg(target_os = "windows")]
707    fn windows_discover(&mut self) -> Result<()> {
708        use std::process::Command;
709
710        // Use PowerShell to get services. A failed query is an error, not an
711        // empty machine: `Ok` with no services made every lookup report NotFound.
712        let output = Command::new("powershell")
713            .args([
714                "-NoProfile",
715                "-Command",
716                "Get-Service | Select-Object Name, DisplayName, Status, StartType | ConvertTo-Json",
717            ])
718            .output()
719            .map_err(|e| IronError::HardwareError(format!("powershell: {e}")))?;
720        if !output.status.success() {
721            return Err(IronError::HardwareError("Get-Service failed".to_string()));
722        }
723        let stdout = String::from_utf8(output.stdout)
724            .map_err(|e| IronError::HardwareError(format!("Get-Service output: {e}")))?;
725        self.windows_parse_services(&stdout)
726    }
727
728    #[cfg(target_os = "windows")]
729    fn windows_parse_services(&mut self, json_str: &str) -> Result<()> {
730        // Parse PowerShell JSON output
731        #[derive(serde::Deserialize)]
732        struct PsService {
733            #[serde(rename = "Name")]
734            name: Option<String>,
735            #[serde(rename = "DisplayName")]
736            display_name: Option<String>,
737            #[serde(rename = "Status")]
738            status: Option<i32>,
739            #[serde(rename = "StartType")]
740            start_type: Option<i32>,
741        }
742
743        // Get-Service always returns an array here. Output that does not parse
744        // is an error, not a machine with no services.
745        let services: Vec<PsService> = serde_json::from_str(json_str).map_err(|e| {
746            IronError::HardwareError(format!("Get-Service JSON did not parse: {e}"))
747        })?;
748        for ps_svc in services {
749            if let Some(name) = ps_svc.name {
750                // Apply filter if set
751                if let Some(ref filter) = self.filter {
752                    if !filter.iter().any(|f| name.contains(f)) {
753                        continue;
754                    }
755                }
756
757                let mut service = ServiceInfo::new(&name);
758                service.display_name = ps_svc.display_name;
759                service.service_type = ServiceType::Win32;
760
761                // Status: 1=Stopped, 2=StartPending, 3=StopPending, 4=Running
762                service.status = match ps_svc.status {
763                    Some(1) => ServiceStatus::Stopped,
764                    Some(2) => ServiceStatus::Starting,
765                    Some(3) => ServiceStatus::Stopping,
766                    Some(4) => ServiceStatus::Running,
767                    _ => ServiceStatus::Unknown,
768                };
769
770                // StartType: 0=Boot, 1=System, 2=Automatic, 3=Manual, 4=Disabled
771                service.startup_type = match ps_svc.start_type {
772                    Some(0) | Some(1) | Some(2) => StartupType::Automatic,
773                    Some(3) => StartupType::Manual,
774                    Some(4) => StartupType::Disabled,
775                    _ => StartupType::Unknown,
776                };
777
778                // Unknown start type stays `None`, not `false`.
779                service.enabled = ps_svc.start_type.map(|t| matches!(t, 0..=2));
780
781                let idx = self.services.len();
782                self.service_map.insert(name, idx);
783                self.services.push(service);
784            }
785        }
786        Ok(())
787    }
788
789    #[cfg(target_os = "windows")]
790    fn windows_start_service(&self, name: &str) -> Result<()> {
791        use std::process::Command;
792
793        let status = Command::new("sc").args(["start", name]).status();
794
795        match status {
796            Ok(s) if s.success() => Ok(()),
797            Ok(_) => Err(IronError::System(format!(
798                "Failed to start service '{}' (run as Administrator)",
799                name
800            ))),
801            Err(e) => Err(IronError::System(format!("Failed to execute sc: {}", e))),
802        }
803    }
804
805    #[cfg(target_os = "windows")]
806    fn windows_stop_service(&self, name: &str) -> Result<()> {
807        use std::process::Command;
808
809        let status = Command::new("sc").args(["stop", name]).status();
810
811        match status {
812            Ok(s) if s.success() => Ok(()),
813            Ok(_) => Err(IronError::System(format!(
814                "Failed to stop service '{}' (run as Administrator)",
815                name
816            ))),
817            Err(e) => Err(IronError::System(format!("Failed to execute sc: {}", e))),
818        }
819    }
820
821    #[cfg(target_os = "windows")]
822    fn windows_set_startup(&self, name: &str, startup: StartupType) -> Result<()> {
823        use std::process::Command;
824
825        let start_type = match startup {
826            StartupType::Automatic => "auto",
827            StartupType::Manual => "demand",
828            StartupType::Disabled => "disabled",
829            _ => "demand",
830        };
831
832        let status = Command::new("sc")
833            .args(["config", name, "start=", start_type])
834            .status();
835
836        match status {
837            Ok(s) if s.success() => Ok(()),
838            Ok(_) => Err(IronError::System(format!(
839                "Failed to configure service '{}' (run as Administrator)",
840                name
841            ))),
842            Err(e) => Err(IronError::System(format!("Failed to execute sc: {}", e))),
843        }
844    }
845
846    // ==================== macOS Implementation ====================
847
848    #[cfg(target_os = "macos")]
849    fn macos_discover(&mut self) -> Result<()> {
850        use std::process::Command;
851
852        // Use launchctl to list services. A failed listing is an error, not an
853        // empty machine, for the same reason as on Linux and Windows.
854        let output = Command::new("launchctl")
855            .args(["list"])
856            .output()
857            .map_err(|e| IronError::HardwareError(format!("launchctl: {e}")))?;
858        if !output.status.success() {
859            return Err(IronError::HardwareError(
860                "launchctl list failed".to_string(),
861            ));
862        }
863        let stdout = String::from_utf8(output.stdout)
864            .map_err(|e| IronError::HardwareError(format!("launchctl output: {e}")))?;
865        for line in stdout.lines().skip(1) {
866            // Skip header
867            let parts: Vec<&str> = line.split_whitespace().collect();
868            if parts.len() >= 3 {
869                let name = parts[2].to_string();
870
871                // Apply filter if set
872                if let Some(ref filter) = self.filter {
873                    if !filter.iter().any(|f| name.contains(f)) {
874                        continue;
875                    }
876                }
877
878                let mut service = ServiceInfo::new(&name);
879
880                // PID column
881                if let Ok(pid) = parts[0].parse::<u32>() {
882                    service.pid = Some(pid);
883                    service.status = ServiceStatus::Running;
884                } else if parts[0] == "-" {
885                    service.status = ServiceStatus::Stopped;
886                }
887
888                // Exit code column
889                if let Ok(code) = parts[1].parse::<i32>() {
890                    service.exit_code = Some(code);
891                    if code != 0 && service.status == ServiceStatus::Stopped {
892                        service.status = ServiceStatus::Failed;
893                    }
894                }
895
896                let idx = self.services.len();
897                self.service_map.insert(name, idx);
898                self.services.push(service);
899            }
900        }
901
902        Ok(())
903    }
904}
905
906/// Service summary for quick overview
907#[derive(Debug, Clone, Serialize, Deserialize)]
908pub struct ServiceSummary {
909    /// Total services
910    pub total: usize,
911    /// Running services
912    pub running: usize,
913    /// Stopped services
914    pub stopped: usize,
915    /// Failed services
916    pub failed: usize,
917    /// Enabled at boot
918    pub enabled: usize,
919}
920
921/// Get a quick summary of services
922pub fn service_summary() -> Result<ServiceSummary> {
923    let monitor = ServiceMonitor::new()?;
924    let services = monitor.services();
925
926    Ok(ServiceSummary {
927        total: services.len(),
928        running: services
929            .iter()
930            .filter(|s| s.status == ServiceStatus::Running)
931            .count(),
932        stopped: services
933            .iter()
934            .filter(|s| s.status == ServiceStatus::Stopped)
935            .count(),
936        failed: services
937            .iter()
938            .filter(|s| s.status == ServiceStatus::Failed)
939            .count(),
940        enabled: services.iter().filter(|s| s.enabled == Some(true)).count(),
941    })
942}
943
944/// Check if a specific service is running. `None` when the service could not
945/// be queried (the monitor could not be built, or the service is not known),
946/// rather than `false`, which would say it is stopped.
947pub fn is_service_running(name: &str) -> Option<bool> {
948    ServiceMonitor::with_filter(vec![name.to_string()])
949        .ok()
950        .and_then(|monitor| monitor.is_active(name))
951}
952
953/// Strip the systemd `.service` suffix so `sshd` and `sshd.service` name the
954/// same unit. Other platforms' names pass through unchanged.
955fn normalise_service_name(name: &str) -> &str {
956    name.strip_suffix(".service").unwrap_or(name)
957}
958
959/// Get status of specific services
960pub fn get_services_status(names: Vec<&str>) -> Result<HashMap<String, ServiceStatus>> {
961    let filter: Vec<String> = names.iter().map(|s| s.to_string()).collect();
962    let monitor = ServiceMonitor::with_filter(filter)?;
963
964    let mut statuses = HashMap::new();
965    for name in names {
966        let status = monitor
967            .get_service(name)
968            .map(|s| s.status.clone())
969            .unwrap_or(ServiceStatus::NotFound);
970        statuses.insert(name.to_string(), status);
971    }
972
973    Ok(statuses)
974}
975
976/// Common system services to monitor
977pub fn common_services() -> Vec<&'static str> {
978    #[cfg(target_os = "linux")]
979    {
980        vec![
981            "sshd",
982            "docker",
983            "nginx",
984            "apache2",
985            "postgresql",
986            "mysql",
987            "redis",
988            "mongodb",
989            "NetworkManager",
990            "bluetooth",
991            "cups",
992            "cron",
993            "rsyslog",
994            "ufw",
995        ]
996    }
997
998    #[cfg(target_os = "windows")]
999    {
1000        vec![
1001            "wuauserv",          // Windows Update
1002            "BITS",              // Background Intelligent Transfer
1003            "Spooler",           // Print Spooler
1004            "WinDefend",         // Windows Defender
1005            "Dhcp",              // DHCP Client
1006            "Dnscache",          // DNS Client
1007            "EventLog",          // Windows Event Log
1008            "W32Time",           // Windows Time
1009            "AudioSrv",          // Windows Audio
1010            "LanmanServer",      // Server (file sharing)
1011            "LanmanWorkstation", // Workstation
1012            "MpsSvc",            // Windows Firewall
1013        ]
1014    }
1015
1016    #[cfg(target_os = "macos")]
1017    {
1018        vec![
1019            "com.apple.dock",
1020            "com.apple.Finder",
1021            "com.apple.loginwindow",
1022            "com.apple.WindowServer",
1023            "com.apple.SystemUIServer",
1024            "com.apple.wifi.WiFiAgent",
1025            "com.apple.bluetoothd",
1026        ]
1027    }
1028
1029    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
1030    {
1031        vec![]
1032    }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use super::*;
1038
1039    #[test]
1040    fn test_service_info_new_defaults() {
1041        let info = ServiceInfo::new("sshd");
1042        assert_eq!(info.name, "sshd");
1043        assert_eq!(info.status, ServiceStatus::Unknown);
1044        assert_eq!(info.enabled, None);
1045        assert!(info.dependencies.is_empty());
1046        assert!(info.dependents.is_empty());
1047        assert!(info.pid.is_none());
1048    }
1049
1050    #[test]
1051    fn test_service_info_is_active() {
1052        let mut info = ServiceInfo::new("test");
1053        assert!(!info.is_active());
1054        info.status = ServiceStatus::Running;
1055        assert!(info.is_active());
1056        info.status = ServiceStatus::Stopped;
1057        assert!(!info.is_active());
1058    }
1059
1060    #[test]
1061    fn test_service_info_is_failed() {
1062        let mut info = ServiceInfo::new("test");
1063        assert!(!info.is_failed());
1064        info.status = ServiceStatus::Failed;
1065        assert!(info.is_failed());
1066    }
1067
1068    #[test]
1069    fn test_service_status_display() {
1070        assert_eq!(ServiceStatus::Running.to_string(), "running");
1071        assert_eq!(ServiceStatus::Stopped.to_string(), "stopped");
1072        assert_eq!(ServiceStatus::Starting.to_string(), "starting");
1073        assert_eq!(ServiceStatus::Stopping.to_string(), "stopping");
1074        assert_eq!(ServiceStatus::Failed.to_string(), "failed");
1075        assert_eq!(ServiceStatus::Unknown.to_string(), "unknown");
1076        assert_eq!(ServiceStatus::NotFound.to_string(), "not-found");
1077    }
1078
1079    #[test]
1080    fn test_startup_type_display() {
1081        assert_eq!(StartupType::Automatic.to_string(), "automatic");
1082        assert_eq!(StartupType::Manual.to_string(), "manual");
1083        assert_eq!(StartupType::Disabled.to_string(), "disabled");
1084        assert_eq!(StartupType::OnDemand.to_string(), "on-demand");
1085        assert_eq!(StartupType::Unknown.to_string(), "unknown");
1086    }
1087
1088    #[test]
1089    fn test_service_info_serde_roundtrip() {
1090        let info = ServiceInfo::new("nginx");
1091        let json = serde_json::to_string(&info).unwrap();
1092        let parsed: ServiceInfo = serde_json::from_str(&json).unwrap();
1093        assert_eq!(parsed.name, "nginx");
1094        assert_eq!(parsed.status, ServiceStatus::Unknown);
1095    }
1096
1097    #[test]
1098    fn test_normalise_service_name_strips_systemd_suffix() {
1099        assert_eq!(normalise_service_name("sshd.service"), "sshd");
1100        assert_eq!(normalise_service_name("sshd"), "sshd");
1101        assert_eq!(normalise_service_name("com.apple.dock"), "com.apple.dock");
1102    }
1103
1104    #[cfg(target_os = "linux")]
1105    #[test]
1106    fn test_systemd_exited_is_neither_running_nor_stopped() {
1107        let monitor = ServiceMonitor {
1108            services: Vec::new(),
1109            service_map: HashMap::new(),
1110            last_update: Instant::now(),
1111            filter: None,
1112        };
1113        // Captured `systemctl list-units --type=service --no-legend` lines.
1114        let exited = monitor
1115            .linux_parse_service_line(concat!(
1116                "systemd-remount-fs.service loaded active exited ",
1117                "Remount Root and Kernel File Systems"
1118            ))
1119            .unwrap();
1120        assert_eq!(exited.status, ServiceStatus::Exited);
1121        let odd = monitor
1122            .linux_parse_service_line("foo.service loaded active reloading Foo")
1123            .unwrap();
1124        assert_eq!(odd.status, ServiceStatus::Unknown);
1125    }
1126}