interplane.Get Omega
Read in your language

aien-sovereign-core

Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core / crates / spark-supervisor / src / supervisor.rs

209 lines · 7921 bytes Raw Blame History
1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::Duration;
4use tokio::sync::{broadcast, Mutex};
5use tokio::time::sleep;
6use tracing::{error, info, warn};
7
8use crate::config::{ServiceConfig, SupervisorConfig};
9use crate::proc_telemetry::get_process_stats;
10
11#[derive(Debug, Clone)]
12pub struct ManagedServiceState {
13 pub name: String,
14 pub config: ServiceConfig,
15 pub pid: Option<u32>,
16 pub restart_count: u32,
17 pub is_healthy: bool,
18 pub uptime_secs: u64,
19 pub rss_mb: f64,
20}
21
22pub struct Supervisor {
23 config: SupervisorConfig,
24 states: Arc<Mutex<HashMap<String, ManagedServiceState>>>,
25}
26
27impl Supervisor {
28 pub fn new(config: SupervisorConfig) -> Self {
29 let mut states = HashMap::new();
30 for (name, s_cfg) in &config.services {
31 states.insert(
32 name.clone(),
33 ManagedServiceState {
34 name: name.clone(),
35 config: s_cfg.clone(),
36 pid: None,
37 restart_count: 0,
38 is_healthy: false,
39 uptime_secs: 0,
40 rss_mb: 0.0,
41 },
42 );
43 }
44 Self {
45 config,
46 states: Arc::new(Mutex::new(states)),
47 }
48 }
49
50 pub async fn run_daemon(&self) -> Result<(), Box<dyn std::error::Error>> {
51 info!("Starting SparkOS Sovereign Supervisor with {} service(s)...", self.config.services.len());
52
53 let (shutdown_tx, _) = broadcast::channel::<()>(1);
54
55 for (name, s_cfg) in self.config.services.clone() {
56 let states = self.states.clone();
57 let mut shutdown_rx = shutdown_tx.subscribe();
58 tokio::spawn(async move {
59 Self::supervise_loop(name, s_cfg, states, &mut shutdown_rx).await;
60 });
61 }
62
63 let states = self.states.clone();
64 let http_client = reqwest::Client::builder()
65 .timeout(Duration::from_millis(1500))
66 .build()
67 .unwrap_or_default();
68
69 let mut shutdown_rx = shutdown_tx.subscribe();
70
71 loop {
72 tokio::select! {
73 _ = tokio::signal::ctrl_c() => {
74 info!("Received termination signal. Shutting down all managed services gracefully...");
75 let _ = shutdown_tx.send(());
76 // Allow child processes brief grace period to terminate
77 sleep(Duration::from_millis(1000)).await;
78 break;
79 }
80 _ = shutdown_rx.recv() => {
81 break;
82 }
83 _ = sleep(Duration::from_secs(3)) => {
84 let mut map = states.lock().await;
85 for (_name, state) in map.iter_mut() {
86 if let Some(pid) = state.pid {
87 let p_stats = get_process_stats(pid);
88 if p_stats.is_alive {
89 state.rss_mb = p_stats.rss_bytes as f64 / (1024.0 * 1024.0);
90 state.uptime_secs += 3;
91 } else {
92 state.is_healthy = false;
93 }
94
95 if let Some(ref h_url) = state.config.health_url {
96 if let Ok(res) = http_client.get(h_url).send().await {
97 state.is_healthy = res.status().is_success();
98 } else {
99 state.is_healthy = false;
100 }
101 } else {
102 state.is_healthy = p_stats.is_alive;
103 }
104 }
105 }
106 }
107 }
108 }
109
110 info!("SparkOS Sovereign Supervisor halted cleanly.");
111 Ok(())
112 }
113
114 async fn supervise_loop(
115 name: String,
116 config: ServiceConfig,
117 states: Arc<Mutex<HashMap<String, ManagedServiceState>>>,
118 shutdown_rx: &mut broadcast::Receiver<()>,
119 ) {
120 loop {
121 info!("[{}] Spawning process: {} {:?}...", name, config.command, config.args);
122 let mut cmd = tokio::process::Command::new(&config.command);
123 cmd.args(&config.args);
124 for (k, v) in &config.env {
125 cmd.env(k, v);
126 }
127
128 match cmd.spawn() {
129 Ok(mut child) => {
130 let pid = child.id();
131 {
132 let mut map = states.lock().await;
133 if let Some(st) = map.get_mut(&name) {
134 st.pid = pid;
135 st.uptime_secs = 0;
136 st.is_healthy = true;
137 }
138 }
139 info!("[{}] Running with PID {:?}", name, pid);
140
141 tokio::select! {
142 _ = shutdown_rx.recv() => {
143 info!("[{}] Terminating child PID {:?} for supervisor shutdown...", name, pid);
144 let _ = child.kill().await;
145 let _ = child.wait().await;
146 let mut map = states.lock().await;
147 if let Some(st) = map.get_mut(&name) {
148 st.pid = None;
149 st.is_healthy = false;
150 }
151 return;
152 }
153 status_res = child.wait() => {
154 match status_res {
155 Ok(status) => {
156 warn!("[{}] Process exited with status: {}", name, status);
157 }
158 Err(e) => {
159 error!("[{}] Process error: {}", name, e);
160 }
161 }
162 }
163 }
164
165 {
166 let mut map = states.lock().await;
167 if let Some(st) = map.get_mut(&name) {
168 st.pid = None;
169 st.is_healthy = false;
170 st.restart_count += 1;
171 }
172 }
173
174 if config.restart == "no" {
175 info!("[{}] Configured restart is no. Halting supervision.", name);
176 break;
177 }
178
179 info!("[{}] Restarting in 2 seconds...", name);
180 sleep(Duration::from_secs(2)).await;
181 }
182 Err(e) => {
183 error!("[{}] Failed to spawn: {}. Retrying in 5 seconds...", name, e);
184 sleep(Duration::from_secs(5)).await;
185 }
186 }
187 }
188 }
189
190 pub async fn print_status(&self) {
191 let map = self.states.lock().await;
192 println!("");
193 println!("=== SparkOS Sovereign Supervisor Services ===");
194 println!("{:<18} {:<10} {:<10} {:<12} {:<10} {:<10}", "SERVICE", "STATUS", "PID", "MEMORY", "RESTARTS", "HEALTH");
195 println!("{}", "-".repeat(74));
196
197 for (name, st) in map.iter() {
198 let pid_str = st.pid.map(|p| p.to_string()).unwrap_or_else(|| "-".into());
199 let status_str = if st.pid.is_some() { "RUNNING" } else { "STOPPED" };
200 let mem_str = format!("{:.1} MB", st.rss_mb);
201 let health_str = if st.is_healthy { "OK" } else { "UNHEALTHY" };
202
203 println!("{:<18} {:<10} {:<10} {:<12} {:<10} {:<10}",
204 name, status_str, pid_str, mem_str, st.restart_count, health_str);
205 }
206 println!("{}", "-".repeat(74));
207 println!("");
208 }
209}