ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
//! System Service Monitoring and Control
//!
//! This module provides cross-platform system service monitoring capabilities
//! including service status, management, and auto-start configuration.
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::services::{ServiceMonitor, ServiceStatus};
//!
//! let monitor = ServiceMonitor::new().unwrap();
//!
//! // List all services
//! for service in monitor.services() {
//!     println!("{}: {:?}", service.name, service.status);
//! }
//!
//! // Check specific service
//! if let Some(status) = monitor.get_service("sshd") {
//!     println!("SSH: {:?}", status.status);
//! }
//! ```

use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Instant;

/// Service status states
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ServiceStatus {
    /// Service is running
    Running,
    /// Service is stopped
    Stopped,
    /// Service is starting
    Starting,
    /// Service is stopping
    Stopping,
    /// Service has failed
    Failed,
    /// Service status is unknown
    Unknown,
    /// Service is not found
    NotFound,
    /// Service ran to completion and is held active with no process left
    /// running: systemd's `active (exited)`, a oneshot unit with
    /// `RemainAfterExit`. Neither running nor stopped.
    Exited,
}

impl std::fmt::Display for ServiceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceStatus::Running => write!(f, "running"),
            ServiceStatus::Stopped => write!(f, "stopped"),
            ServiceStatus::Starting => write!(f, "starting"),
            ServiceStatus::Stopping => write!(f, "stopping"),
            ServiceStatus::Failed => write!(f, "failed"),
            ServiceStatus::Unknown => write!(f, "unknown"),
            ServiceStatus::NotFound => write!(f, "not-found"),
            ServiceStatus::Exited => write!(f, "exited"),
        }
    }
}

/// Service type classification
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ServiceType {
    /// Simple foreground service
    Simple,
    /// Forking daemon
    Forking,
    /// Oneshot service
    Oneshot,
    /// D-Bus activated service
    Dbus,
    /// Notify service
    Notify,
    /// Idle service
    Idle,
    /// Windows service
    Win32,
    /// Unknown type
    Unknown,
}

/// Service startup type
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StartupType {
    /// Automatically start on boot
    Automatic,
    /// Manual start required
    Manual,
    /// Disabled
    Disabled,
    /// Start on demand
    OnDemand,
    /// Unknown
    Unknown,
}

impl std::fmt::Display for StartupType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StartupType::Automatic => write!(f, "automatic"),
            StartupType::Manual => write!(f, "manual"),
            StartupType::Disabled => write!(f, "disabled"),
            StartupType::OnDemand => write!(f, "on-demand"),
            StartupType::Unknown => write!(f, "unknown"),
        }
    }
}

/// Detailed information about a system service
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceInfo {
    /// Service name
    pub name: String,
    /// Display name / description
    pub display_name: Option<String>,
    /// Current status
    pub status: ServiceStatus,
    /// Service type
    pub service_type: ServiceType,
    /// Startup type
    pub startup_type: StartupType,
    /// Process ID (if running)
    pub pid: Option<u32>,
    /// Memory usage (bytes)
    pub memory_bytes: Option<u64>,
    /// CPU time (seconds)
    pub cpu_time_secs: Option<f64>,
    /// Main process exit code
    pub exit_code: Option<i32>,
    /// Unit file path (Linux)
    pub unit_file: Option<String>,
    /// Service dependencies
    pub dependencies: Vec<String>,
    /// Services that depend on this
    pub dependents: Vec<String>,
    /// Is service enabled at boot. `None` where the boot-time state was not
    /// read (for example `systemctl show` failed). Not `false`: that would
    /// claim the service is disabled.
    pub enabled: Option<bool>,
    /// Load state (systemd)
    pub load_state: Option<String>,
    /// Sub-state (systemd)
    pub sub_state: Option<String>,
    /// Last error message
    pub error_message: Option<String>,
    /// Start time
    pub start_time: Option<String>,
}

impl ServiceInfo {
    /// Create a new ServiceInfo
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            display_name: None,
            status: ServiceStatus::Unknown,
            service_type: ServiceType::Unknown,
            startup_type: StartupType::Unknown,
            pid: None,
            memory_bytes: None,
            cpu_time_secs: None,
            exit_code: None,
            unit_file: None,
            dependencies: Vec::new(),
            dependents: Vec::new(),
            enabled: None,
            load_state: None,
            sub_state: None,
            error_message: None,
            start_time: None,
        }
    }

    /// Check if service is active
    pub fn is_active(&self) -> bool {
        self.status == ServiceStatus::Running
    }

    /// Check if service is failed
    pub fn is_failed(&self) -> bool {
        self.status == ServiceStatus::Failed
    }
}

/// System service monitor
pub struct ServiceMonitor {
    /// Discovered services
    services: Vec<ServiceInfo>,
    /// Service map by name
    service_map: HashMap<String, usize>,
    /// Last update time
    last_update: Instant,
    /// Filter for specific services
    filter: Option<Vec<String>>,
}

impl ServiceMonitor {
    /// Create a new service monitor
    pub fn new() -> Result<Self> {
        let mut monitor = Self {
            services: Vec::new(),
            service_map: HashMap::new(),
            last_update: Instant::now(),
            filter: None,
        };

        monitor.discover()?;
        Ok(monitor)
    }

    /// Create a monitor for specific services
    pub fn with_filter(service_names: Vec<String>) -> Result<Self> {
        // Stored names carry no `.service` suffix, so a filter given as
        // `sshd.service` would match nothing.
        let service_names = service_names
            .into_iter()
            .map(|n| normalise_service_name(&n).to_string())
            .collect();
        let mut monitor = Self {
            services: Vec::new(),
            service_map: HashMap::new(),
            last_update: Instant::now(),
            filter: Some(service_names),
        };

        monitor.discover()?;
        Ok(monitor)
    }

    /// Refresh service information
    pub fn refresh(&mut self) -> Result<()> {
        self.services.clear();
        self.service_map.clear();
        self.discover()?;
        self.last_update = Instant::now();
        Ok(())
    }

    /// Get all services
    pub fn services(&self) -> &[ServiceInfo] {
        &self.services
    }

    /// Get service by name
    pub fn get_service(&self, name: &str) -> Option<&ServiceInfo> {
        self.service_map
            .get(normalise_service_name(name))
            .and_then(|&idx| self.services.get(idx))
    }

    /// Get running services
    pub fn running_services(&self) -> Vec<&ServiceInfo> {
        self.services
            .iter()
            .filter(|s| s.status == ServiceStatus::Running)
            .collect()
    }

    /// Get failed services
    pub fn failed_services(&self) -> Vec<&ServiceInfo> {
        self.services
            .iter()
            .filter(|s| s.status == ServiceStatus::Failed)
            .collect()
    }

    /// Check if a service is active. `None` when this monitor holds no
    /// service of that name, which is not the same as inactive.
    pub fn is_active(&self, name: &str) -> Option<bool> {
        self.get_service(name).map(|s| s.is_active())
    }

    /// Start a service
    pub fn start(&self, name: &str) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_start_service(name)
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_start_service(name)
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let _ = name;
            Err(IronError::UnsupportedPlatform(
                "Service control not supported".to_string(),
            ))
        }
    }

    /// Stop a service
    pub fn stop(&self, name: &str) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_stop_service(name)
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_stop_service(name)
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let _ = name;
            Err(IronError::UnsupportedPlatform(
                "Service control not supported".to_string(),
            ))
        }
    }

    /// Restart a service
    pub fn restart(&self, name: &str) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_restart_service(name)
        }

        #[cfg(target_os = "windows")]
        {
            // Windows: stop then start
            self.windows_stop_service(name)?;
            std::thread::sleep(std::time::Duration::from_millis(500));
            self.windows_start_service(name)
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let _ = name;
            Err(IronError::UnsupportedPlatform(
                "Service control not supported".to_string(),
            ))
        }
    }

    /// Enable service at boot
    pub fn enable(&self, name: &str) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_enable_service(name)
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_set_startup(name, StartupType::Automatic)
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let _ = name;
            Err(IronError::UnsupportedPlatform(
                "Service control not supported".to_string(),
            ))
        }
    }

    /// Disable service at boot
    pub fn disable(&self, name: &str) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_disable_service(name)
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_set_startup(name, StartupType::Manual)
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let _ = name;
            Err(IronError::UnsupportedPlatform(
                "Service control not supported".to_string(),
            ))
        }
    }

    // Platform discovery
    fn discover(&mut self) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            self.linux_discover()
        }

        #[cfg(target_os = "windows")]
        {
            self.windows_discover()
        }

        #[cfg(target_os = "macos")]
        {
            self.macos_discover()
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
        {
            Ok(())
        }
    }

    // ==================== Linux Implementation ====================

    #[cfg(target_os = "linux")]
    fn linux_discover(&mut self) -> Result<()> {
        use std::process::Command;

        // Use systemctl to list services
        let output = Command::new("systemctl")
            .args([
                "list-units",
                "--type=service",
                "--all",
                "--no-pager",
                "--no-legend",
            ])
            .output();

        // A failed `systemctl` is an error, not an empty machine. Returning
        // `Ok` with no services made every lookup report NotFound.
        let output = output.map_err(|e| IronError::HardwareError(format!("systemctl: {e}")))?;
        if !output.status.success() {
            return Err(IronError::HardwareError(
                "systemctl list-units --type=service failed".to_string(),
            ));
        }
        if let Ok(stdout) = String::from_utf8(output.stdout) {
            for line in stdout.lines() {
                if let Some(service) = self.linux_parse_service_line(line) {
                    // Apply filter if set
                    if let Some(ref filter) = self.filter {
                        if !filter.iter().any(|f| service.name.contains(f)) {
                            continue;
                        }
                    }

                    let idx = self.services.len();
                    self.service_map.insert(service.name.clone(), idx);
                    self.services.push(service);
                }
            }
        }

        // Get detailed info for each service.
        //
        // Iterating `&mut self.services` while calling `&self` method borrows self
        // both ways at once. Move the vector out for the duration and put it back:
        // `linux_get_service_details` does not read `self.services`, so nothing
        // observes it missing.
        let mut services = std::mem::take(&mut self.services);
        for service in &mut services {
            self.linux_get_service_details(service);
        }
        self.services = services;

        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn linux_parse_service_line(&self, line: &str) -> Option<ServiceInfo> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 4 {
            return None;
        }

        let name = parts[0].trim_end_matches(".service").to_string();
        let load_state = parts[1].to_string();
        let active_state = parts[2].to_string();
        let sub_state = parts[3].to_string();

        let status = match active_state.as_str() {
            "active" => match sub_state.as_str() {
                "running" => ServiceStatus::Running,
                // `active (exited)` was reported stopped, which a unit systemd
                // holds active is not.
                "exited" => ServiceStatus::Exited,
                "waiting" => ServiceStatus::Starting,
                // A sub-state not listed here used to read as running.
                _ => ServiceStatus::Unknown,
            },
            "inactive" => ServiceStatus::Stopped,
            "failed" => ServiceStatus::Failed,
            "activating" => ServiceStatus::Starting,
            "deactivating" => ServiceStatus::Stopping,
            _ => ServiceStatus::Unknown,
        };

        let mut service = ServiceInfo::new(&name);
        service.status = status;
        service.load_state = Some(load_state);
        service.sub_state = Some(sub_state);

        // Get description from remaining parts
        if parts.len() > 4 {
            service.display_name = Some(parts[4..].join(" "));
        }

        Some(service)
    }

    #[cfg(target_os = "linux")]
    fn linux_get_service_details(&self, service: &mut ServiceInfo) {
        use std::process::Command;

        // Get detailed service info
        let output = Command::new("systemctl")
            .args(["show", &format!("{}.service", service.name)])
            .output();

        if let Ok(output) = output {
            if let Ok(stdout) = String::from_utf8(output.stdout) {
                for line in stdout.lines() {
                    if let Some((key, value)) = line.split_once('=') {
                        match key {
                            "MainPID" => {
                                if let Ok(pid) = value.parse::<u32>() {
                                    if pid > 0 {
                                        service.pid = Some(pid);
                                    }
                                }
                            }
                            "MemoryCurrent" => {
                                if let Ok(mem) = value.parse::<u64>() {
                                    if mem < u64::MAX {
                                        service.memory_bytes = Some(mem);
                                    }
                                }
                            }
                            // When the unit last entered the active state, which is
                            // its start. `ExecMainExitTimestamp` is when it exited,
                            // and was stored here as the start time.
                            "ActiveEnterTimestamp" => {
                                if !value.is_empty() {
                                    service.start_time = Some(value.to_string());
                                }
                            }
                            "Type" => {
                                service.service_type = match value {
                                    "simple" => ServiceType::Simple,
                                    "forking" => ServiceType::Forking,
                                    "oneshot" => ServiceType::Oneshot,
                                    "dbus" => ServiceType::Dbus,
                                    "notify" => ServiceType::Notify,
                                    "idle" => ServiceType::Idle,
                                    _ => ServiceType::Unknown,
                                };
                            }
                            "UnitFileState" => {
                                // Empty for units with no unit file (transient or
                                // generated). That is no answer, not "disabled".
                                if !value.is_empty() {
                                    service.enabled = Some(value == "enabled");
                                }
                                service.startup_type = match value {
                                    "enabled" => StartupType::Automatic,
                                    "disabled" => StartupType::Disabled,
                                    "static" => StartupType::Manual,
                                    "masked" => StartupType::Disabled,
                                    _ => StartupType::Unknown,
                                };
                            }
                            "FragmentPath" => {
                                if !value.is_empty() {
                                    service.unit_file = Some(value.to_string());
                                }
                            }
                            "Requires" | "Wants" => {
                                for dep in value.split_whitespace() {
                                    let dep_name = dep.trim_end_matches(".service");
                                    if !dep_name.is_empty() {
                                        service.dependencies.push(dep_name.to_string());
                                    }
                                }
                            }
                            "RequiredBy" | "WantedBy" => {
                                for dep in value.split_whitespace() {
                                    let dep_name = dep.trim_end_matches(".service");
                                    if !dep_name.is_empty() {
                                        service.dependents.push(dep_name.to_string());
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_start_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("systemctl")
            .args(["start", &format!("{}.service", name)])
            .status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to start service '{}' (check permissions)",
                name
            ))),
            Err(e) => Err(IronError::System(format!(
                "Failed to execute systemctl: {}",
                e
            ))),
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_stop_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("systemctl")
            .args(["stop", &format!("{}.service", name)])
            .status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to stop service '{}' (check permissions)",
                name
            ))),
            Err(e) => Err(IronError::System(format!(
                "Failed to execute systemctl: {}",
                e
            ))),
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_restart_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("systemctl")
            .args(["restart", &format!("{}.service", name)])
            .status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to restart service '{}' (check permissions)",
                name
            ))),
            Err(e) => Err(IronError::System(format!(
                "Failed to execute systemctl: {}",
                e
            ))),
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_enable_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("systemctl")
            .args(["enable", &format!("{}.service", name)])
            .status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to enable service '{}' (check permissions)",
                name
            ))),
            Err(e) => Err(IronError::System(format!(
                "Failed to execute systemctl: {}",
                e
            ))),
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_disable_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("systemctl")
            .args(["disable", &format!("{}.service", name)])
            .status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to disable service '{}' (check permissions)",
                name
            ))),
            Err(e) => Err(IronError::System(format!(
                "Failed to execute systemctl: {}",
                e
            ))),
        }
    }

    // ==================== Windows Implementation ====================

    #[cfg(target_os = "windows")]
    fn windows_discover(&mut self) -> Result<()> {
        use std::process::Command;

        // Use PowerShell to get services. A failed query is an error, not an
        // empty machine: `Ok` with no services made every lookup report NotFound.
        let output = Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Get-Service | Select-Object Name, DisplayName, Status, StartType | ConvertTo-Json",
            ])
            .output()
            .map_err(|e| IronError::HardwareError(format!("powershell: {e}")))?;
        if !output.status.success() {
            return Err(IronError::HardwareError("Get-Service failed".to_string()));
        }
        let stdout = String::from_utf8(output.stdout)
            .map_err(|e| IronError::HardwareError(format!("Get-Service output: {e}")))?;
        self.windows_parse_services(&stdout)
    }

    #[cfg(target_os = "windows")]
    fn windows_parse_services(&mut self, json_str: &str) -> Result<()> {
        // Parse PowerShell JSON output
        #[derive(serde::Deserialize)]
        struct PsService {
            #[serde(rename = "Name")]
            name: Option<String>,
            #[serde(rename = "DisplayName")]
            display_name: Option<String>,
            #[serde(rename = "Status")]
            status: Option<i32>,
            #[serde(rename = "StartType")]
            start_type: Option<i32>,
        }

        // Get-Service always returns an array here. Output that does not parse
        // is an error, not a machine with no services.
        let services: Vec<PsService> = serde_json::from_str(json_str).map_err(|e| {
            IronError::HardwareError(format!("Get-Service JSON did not parse: {e}"))
        })?;
        for ps_svc in services {
            if let Some(name) = ps_svc.name {
                // Apply filter if set
                if let Some(ref filter) = self.filter {
                    if !filter.iter().any(|f| name.contains(f)) {
                        continue;
                    }
                }

                let mut service = ServiceInfo::new(&name);
                service.display_name = ps_svc.display_name;
                service.service_type = ServiceType::Win32;

                // Status: 1=Stopped, 2=StartPending, 3=StopPending, 4=Running
                service.status = match ps_svc.status {
                    Some(1) => ServiceStatus::Stopped,
                    Some(2) => ServiceStatus::Starting,
                    Some(3) => ServiceStatus::Stopping,
                    Some(4) => ServiceStatus::Running,
                    _ => ServiceStatus::Unknown,
                };

                // StartType: 0=Boot, 1=System, 2=Automatic, 3=Manual, 4=Disabled
                service.startup_type = match ps_svc.start_type {
                    Some(0) | Some(1) | Some(2) => StartupType::Automatic,
                    Some(3) => StartupType::Manual,
                    Some(4) => StartupType::Disabled,
                    _ => StartupType::Unknown,
                };

                // Unknown start type stays `None`, not `false`.
                service.enabled = ps_svc.start_type.map(|t| matches!(t, 0..=2));

                let idx = self.services.len();
                self.service_map.insert(name, idx);
                self.services.push(service);
            }
        }
        Ok(())
    }

    #[cfg(target_os = "windows")]
    fn windows_start_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("sc").args(["start", name]).status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to start service '{}' (run as Administrator)",
                name
            ))),
            Err(e) => Err(IronError::System(format!("Failed to execute sc: {}", e))),
        }
    }

    #[cfg(target_os = "windows")]
    fn windows_stop_service(&self, name: &str) -> Result<()> {
        use std::process::Command;

        let status = Command::new("sc").args(["stop", name]).status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to stop service '{}' (run as Administrator)",
                name
            ))),
            Err(e) => Err(IronError::System(format!("Failed to execute sc: {}", e))),
        }
    }

    #[cfg(target_os = "windows")]
    fn windows_set_startup(&self, name: &str, startup: StartupType) -> Result<()> {
        use std::process::Command;

        let start_type = match startup {
            StartupType::Automatic => "auto",
            StartupType::Manual => "demand",
            StartupType::Disabled => "disabled",
            _ => "demand",
        };

        let status = Command::new("sc")
            .args(["config", name, "start=", start_type])
            .status();

        match status {
            Ok(s) if s.success() => Ok(()),
            Ok(_) => Err(IronError::System(format!(
                "Failed to configure service '{}' (run as Administrator)",
                name
            ))),
            Err(e) => Err(IronError::System(format!("Failed to execute sc: {}", e))),
        }
    }

    // ==================== macOS Implementation ====================

    #[cfg(target_os = "macos")]
    fn macos_discover(&mut self) -> Result<()> {
        use std::process::Command;

        // Use launchctl to list services. A failed listing is an error, not an
        // empty machine, for the same reason as on Linux and Windows.
        let output = Command::new("launchctl")
            .args(["list"])
            .output()
            .map_err(|e| IronError::HardwareError(format!("launchctl: {e}")))?;
        if !output.status.success() {
            return Err(IronError::HardwareError(
                "launchctl list failed".to_string(),
            ));
        }
        let stdout = String::from_utf8(output.stdout)
            .map_err(|e| IronError::HardwareError(format!("launchctl output: {e}")))?;
        for line in stdout.lines().skip(1) {
            // Skip header
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 3 {
                let name = parts[2].to_string();

                // Apply filter if set
                if let Some(ref filter) = self.filter {
                    if !filter.iter().any(|f| name.contains(f)) {
                        continue;
                    }
                }

                let mut service = ServiceInfo::new(&name);

                // PID column
                if let Ok(pid) = parts[0].parse::<u32>() {
                    service.pid = Some(pid);
                    service.status = ServiceStatus::Running;
                } else if parts[0] == "-" {
                    service.status = ServiceStatus::Stopped;
                }

                // Exit code column
                if let Ok(code) = parts[1].parse::<i32>() {
                    service.exit_code = Some(code);
                    if code != 0 && service.status == ServiceStatus::Stopped {
                        service.status = ServiceStatus::Failed;
                    }
                }

                let idx = self.services.len();
                self.service_map.insert(name, idx);
                self.services.push(service);
            }
        }

        Ok(())
    }
}

/// Service summary for quick overview
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceSummary {
    /// Total services
    pub total: usize,
    /// Running services
    pub running: usize,
    /// Stopped services
    pub stopped: usize,
    /// Failed services
    pub failed: usize,
    /// Enabled at boot
    pub enabled: usize,
}

/// Get a quick summary of services
pub fn service_summary() -> Result<ServiceSummary> {
    let monitor = ServiceMonitor::new()?;
    let services = monitor.services();

    Ok(ServiceSummary {
        total: services.len(),
        running: services
            .iter()
            .filter(|s| s.status == ServiceStatus::Running)
            .count(),
        stopped: services
            .iter()
            .filter(|s| s.status == ServiceStatus::Stopped)
            .count(),
        failed: services
            .iter()
            .filter(|s| s.status == ServiceStatus::Failed)
            .count(),
        enabled: services.iter().filter(|s| s.enabled == Some(true)).count(),
    })
}

/// Check if a specific service is running. `None` when the service could not
/// be queried (the monitor could not be built, or the service is not known),
/// rather than `false`, which would say it is stopped.
pub fn is_service_running(name: &str) -> Option<bool> {
    ServiceMonitor::with_filter(vec![name.to_string()])
        .ok()
        .and_then(|monitor| monitor.is_active(name))
}

/// Strip the systemd `.service` suffix so `sshd` and `sshd.service` name the
/// same unit. Other platforms' names pass through unchanged.
fn normalise_service_name(name: &str) -> &str {
    name.strip_suffix(".service").unwrap_or(name)
}

/// Get status of specific services
pub fn get_services_status(names: Vec<&str>) -> Result<HashMap<String, ServiceStatus>> {
    let filter: Vec<String> = names.iter().map(|s| s.to_string()).collect();
    let monitor = ServiceMonitor::with_filter(filter)?;

    let mut statuses = HashMap::new();
    for name in names {
        let status = monitor
            .get_service(name)
            .map(|s| s.status.clone())
            .unwrap_or(ServiceStatus::NotFound);
        statuses.insert(name.to_string(), status);
    }

    Ok(statuses)
}

/// Common system services to monitor
pub fn common_services() -> Vec<&'static str> {
    #[cfg(target_os = "linux")]
    {
        vec![
            "sshd",
            "docker",
            "nginx",
            "apache2",
            "postgresql",
            "mysql",
            "redis",
            "mongodb",
            "NetworkManager",
            "bluetooth",
            "cups",
            "cron",
            "rsyslog",
            "ufw",
        ]
    }

    #[cfg(target_os = "windows")]
    {
        vec![
            "wuauserv",          // Windows Update
            "BITS",              // Background Intelligent Transfer
            "Spooler",           // Print Spooler
            "WinDefend",         // Windows Defender
            "Dhcp",              // DHCP Client
            "Dnscache",          // DNS Client
            "EventLog",          // Windows Event Log
            "W32Time",           // Windows Time
            "AudioSrv",          // Windows Audio
            "LanmanServer",      // Server (file sharing)
            "LanmanWorkstation", // Workstation
            "MpsSvc",            // Windows Firewall
        ]
    }

    #[cfg(target_os = "macos")]
    {
        vec![
            "com.apple.dock",
            "com.apple.Finder",
            "com.apple.loginwindow",
            "com.apple.WindowServer",
            "com.apple.SystemUIServer",
            "com.apple.wifi.WiFiAgent",
            "com.apple.bluetoothd",
        ]
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        vec![]
    }
}

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

    #[test]
    fn test_service_info_new_defaults() {
        let info = ServiceInfo::new("sshd");
        assert_eq!(info.name, "sshd");
        assert_eq!(info.status, ServiceStatus::Unknown);
        assert_eq!(info.enabled, None);
        assert!(info.dependencies.is_empty());
        assert!(info.dependents.is_empty());
        assert!(info.pid.is_none());
    }

    #[test]
    fn test_service_info_is_active() {
        let mut info = ServiceInfo::new("test");
        assert!(!info.is_active());
        info.status = ServiceStatus::Running;
        assert!(info.is_active());
        info.status = ServiceStatus::Stopped;
        assert!(!info.is_active());
    }

    #[test]
    fn test_service_info_is_failed() {
        let mut info = ServiceInfo::new("test");
        assert!(!info.is_failed());
        info.status = ServiceStatus::Failed;
        assert!(info.is_failed());
    }

    #[test]
    fn test_service_status_display() {
        assert_eq!(ServiceStatus::Running.to_string(), "running");
        assert_eq!(ServiceStatus::Stopped.to_string(), "stopped");
        assert_eq!(ServiceStatus::Starting.to_string(), "starting");
        assert_eq!(ServiceStatus::Stopping.to_string(), "stopping");
        assert_eq!(ServiceStatus::Failed.to_string(), "failed");
        assert_eq!(ServiceStatus::Unknown.to_string(), "unknown");
        assert_eq!(ServiceStatus::NotFound.to_string(), "not-found");
    }

    #[test]
    fn test_startup_type_display() {
        assert_eq!(StartupType::Automatic.to_string(), "automatic");
        assert_eq!(StartupType::Manual.to_string(), "manual");
        assert_eq!(StartupType::Disabled.to_string(), "disabled");
        assert_eq!(StartupType::OnDemand.to_string(), "on-demand");
        assert_eq!(StartupType::Unknown.to_string(), "unknown");
    }

    #[test]
    fn test_service_info_serde_roundtrip() {
        let info = ServiceInfo::new("nginx");
        let json = serde_json::to_string(&info).unwrap();
        let parsed: ServiceInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "nginx");
        assert_eq!(parsed.status, ServiceStatus::Unknown);
    }

    #[test]
    fn test_normalise_service_name_strips_systemd_suffix() {
        assert_eq!(normalise_service_name("sshd.service"), "sshd");
        assert_eq!(normalise_service_name("sshd"), "sshd");
        assert_eq!(normalise_service_name("com.apple.dock"), "com.apple.dock");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_systemd_exited_is_neither_running_nor_stopped() {
        let monitor = ServiceMonitor {
            services: Vec::new(),
            service_map: HashMap::new(),
            last_update: Instant::now(),
            filter: None,
        };
        // Captured `systemctl list-units --type=service --no-legend` lines.
        let exited = monitor
            .linux_parse_service_line(concat!(
                "systemd-remount-fs.service loaded active exited ",
                "Remount Root and Kernel File Systems"
            ))
            .unwrap();
        assert_eq!(exited.status, ServiceStatus::Exited);
        let odd = monitor
            .linux_parse_service_line("foo.service loaded active reloading Foo")
            .unwrap();
        assert_eq!(odd.status, ServiceStatus::Unknown);
    }
}