Skip to main content

mecha10_cli/services/process/
control.rs

1//! Status, stop/restart, and cleanup operations for `ProcessService`
2
3use super::ProcessService;
4use anyhow::Result;
5use std::collections::HashMap;
6
7impl ProcessService {
8    /// Get status of all processes
9    ///
10    /// Returns a HashMap mapping process names to status strings
11    pub fn get_status(&mut self) -> HashMap<String, String> {
12        use mecha10_runtime::ProcessStatus;
13
14        self.manager
15            .status_all()
16            .into_iter()
17            .map(|(name, status)| {
18                let status_str = match status {
19                    ProcessStatus::Running => "running".to_string(),
20                    ProcessStatus::Exited(code) => format!("exited (code: {})", code),
21                    ProcessStatus::Error => "error".to_string(),
22                };
23                (name, status_str)
24            })
25            .collect()
26    }
27
28    /// Stop a specific process by name. Returns an error if the process is not found. Uses a
29    /// default 10-second timeout for graceful shutdown; use `stop_with_timeout` for a custom one.
30    pub fn stop(&mut self, name: &str) -> Result<()> {
31        self.manager.stop_graceful(name, std::time::Duration::from_secs(10))
32    }
33
34    /// Stop a process with timeout for graceful shutdown. Tries graceful shutdown (SIGTERM on
35    /// Unix), then force kills after the timeout.
36    pub fn stop_with_timeout(&mut self, name: &str, timeout: std::time::Duration) -> Result<()> {
37        self.manager.stop_graceful(name, timeout)
38    }
39
40    pub fn force_kill(&mut self, name: &str) -> Result<()> {
41        self.manager.force_kill(name)
42    }
43
44    /// Stop all processes gracefully in dependency order, delegating to the runtime's
45    /// ProcessManager.
46    pub fn cleanup(&mut self) {
47        self.manager.shutdown_all();
48    }
49
50    pub fn is_running(&mut self, name: &str) -> bool {
51        self.manager.is_running(name)
52    }
53
54    /// Restart a specific process: stops it if running and starts it again.
55    pub fn restart(&mut self, name: &str, binary_path: &str, args: &[&str]) -> Result<u32> {
56        if self.is_running(name) {
57            self.stop(name)?;
58            std::thread::sleep(std::time::Duration::from_millis(100));
59        }
60
61        self.spawn_node(name, binary_path, args)
62    }
63
64    /// Restart all processes. `nodes` is a list of (name, binary_path, args) tuples.
65    pub fn restart_all(&mut self, nodes: Vec<(&str, &str, Vec<&str>)>) -> Result<HashMap<String, u32>> {
66        self.cleanup();
67
68        std::thread::sleep(std::time::Duration::from_millis(500));
69
70        self.spawn_nodes(nodes)
71    }
72}