| 1 |
#![allow(clippy::expect_used)] |
| 2 |
#![allow(clippy::unwrap_used)] |
| 3 |
#![allow(clippy::match_wild_err_arm)] |
| 4 |
#![allow(clippy::uninlined_format_args)] |
| 5 |
#![allow(clippy::useless_vec)] |
| 6 |
#![allow(clippy::needless_pass_by_value)] |
| 7 |
#![allow(clippy::needless_continue)] |
| 8 |
#![allow(clippy::doc_markdown)] |
| 9 |
#![allow(clippy::indexing_slicing)] |
| 10 |
#![allow(clippy::panic)] |
| 11 |
#![allow(clippy::unnecessary_wraps)] |
| 12 |
#![allow(clippy::explicit_iter_loop)] |
| 13 |
#![allow(clippy::ignored_unit_patterns)] |
| 14 |
#![allow(clippy::for_kv_map)] |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
use std::{ |
| 28 |
collections::HashMap, |
| 29 |
process::{Command, exit}, |
| 30 |
sync::{ |
| 31 |
Arc, |
| 32 |
atomic::{AtomicBool, Ordering}, |
| 33 |
}, |
| 34 |
thread, |
| 35 |
time::{Duration, Instant}, |
| 36 |
}; |
| 37 |
|
| 38 |
use fork::{Fork, fork, waitpid}; |
| 39 |
|
| 40 |
#[derive(Debug, Clone)] |
| 41 |
struct ProcessInfo { |
| 42 |
name: String, |
| 43 |
pid: libc::pid_t, |
| 44 |
started_at: Instant, |
| 45 |
restarts: u32, |
| 46 |
max_restarts: u32, |
| 47 |
} |
| 48 |
|
| 49 |
struct Supervisor { |
| 50 |
processes: HashMap<Fork, ProcessInfo>, |
| 51 |
shutdown: Arc<AtomicBool>, |
| 52 |
} |
| 53 |
|
| 54 |
impl Supervisor { |
| 55 |
fn new() -> Self { |
| 56 |
Self { |
| 57 |
processes: HashMap::new(), |
| 58 |
shutdown: Arc::new(AtomicBool::new(false)), |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
fn spawn(&mut self, name: String, command: Vec<String>) -> std::io::Result<Fork> { |
| 64 |
match fork()? { |
| 65 |
result @ Fork::Parent(pid) => { |
| 66 |
println!("✅ Spawned '{}' with PID: {}", name, pid); |
| 67 |
|
| 68 |
|
| 69 |
self.processes.insert( |
| 70 |
result, |
| 71 |
ProcessInfo { |
| 72 |
name: name.clone(), |
| 73 |
pid, |
| 74 |
started_at: Instant::now(), |
| 75 |
restarts: 0, |
| 76 |
max_restarts: 3, |
| 77 |
}, |
| 78 |
); |
| 79 |
|
| 80 |
Ok(result) |
| 81 |
} |
| 82 |
Fork::Child => { |
| 83 |
|
| 84 |
let program = &command[0]; |
| 85 |
let args = &command[1..]; |
| 86 |
|
| 87 |
Command::new(program) |
| 88 |
.args(args) |
| 89 |
.status() |
| 90 |
.expect("Failed to execute command"); |
| 91 |
|
| 92 |
exit(0); |
| 93 |
} |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
|
| 98 |
fn handle_exit(&mut self, fork_result: Fork) { |
| 99 |
if let Some(info) = self.processes.remove(&fork_result) { |
| 100 |
let uptime = info.started_at.elapsed(); |
| 101 |
let name = info.name.clone(); |
| 102 |
let restarts = info.restarts; |
| 103 |
let max_restarts = info.max_restarts; |
| 104 |
|
| 105 |
println!( |
| 106 |
"\n💀 Process '{}' (PID: {}) exited after {:.2}s", |
| 107 |
name, |
| 108 |
info.pid, |
| 109 |
uptime.as_secs_f64() |
| 110 |
); |
| 111 |
|
| 112 |
|
| 113 |
if restarts < max_restarts && !self.shutdown.load(Ordering::Relaxed) { |
| 114 |
println!( |
| 115 |
"🔄 Restarting '{}' (restart {}/{})", |
| 116 |
name, |
| 117 |
restarts + 1, |
| 118 |
max_restarts |
| 119 |
); |
| 120 |
|
| 121 |
if let Err(e) = self.restart(info) { |
| 122 |
eprintln!("❌ Failed to restart '{}': {}", name, e); |
| 123 |
} |
| 124 |
} else if restarts >= max_restarts { |
| 125 |
println!( |
| 126 |
"⚠️ Process '{}' reached max restarts, not restarting", |
| 127 |
name |
| 128 |
); |
| 129 |
} |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
|
| 134 |
fn restart(&mut self, mut info: ProcessInfo) -> std::io::Result<()> { |
| 135 |
let name = info.name.clone(); |
| 136 |
info.restarts += 1; |
| 137 |
info.started_at = Instant::now(); |
| 138 |
|
| 139 |
|
| 140 |
let command = vec!["sleep".to_string(), "2".to_string()]; |
| 141 |
|
| 142 |
match fork()? { |
| 143 |
result @ Fork::Parent(pid) => { |
| 144 |
info.pid = pid; |
| 145 |
self.processes.insert(result, info); |
| 146 |
Ok(()) |
| 147 |
} |
| 148 |
Fork::Child => { |
| 149 |
Command::new(&command[0]) |
| 150 |
.args(&command[1..]) |
| 151 |
.status() |
| 152 |
.unwrap_or_else(|e| panic!("Failed to execute {}: {}", name, e)); |
| 153 |
exit(0); |
| 154 |
} |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
|
| 159 |
fn wait_for_exit(&mut self) -> std::io::Result<()> { |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
for (fork_result, _info) in self.processes.clone().iter() { |
| 164 |
if let Some(pid) = fork_result.child_pid() { |
| 165 |
|
| 166 |
match waitpid(pid) { |
| 167 |
Ok(_) => { |
| 168 |
self.handle_exit(*fork_result); |
| 169 |
return Ok(()); |
| 170 |
} |
| 171 |
Err(_) => { |
| 172 |
|
| 173 |
continue; |
| 174 |
} |
| 175 |
} |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
|
| 180 |
thread::sleep(Duration::from_millis(100)); |
| 181 |
Ok(()) |
| 182 |
} |
| 183 |
|
| 184 |
|
| 185 |
fn stats(&self) -> String { |
| 186 |
let total = self.processes.len(); |
| 187 |
let total_restarts: u32 = self.processes.values().map(|p| p.restarts).sum(); |
| 188 |
|
| 189 |
format!( |
| 190 |
"📊 Supervisor Stats: {} processes, {} total restarts", |
| 191 |
total, total_restarts |
| 192 |
) |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
fn list(&self) { |
| 197 |
println!("\n📋 Supervised Processes:"); |
| 198 |
println!("┌─────────────────┬──────────┬──────────┬──────────┐"); |
| 199 |
println!("│ Name │ PID │ Uptime │ Restarts │"); |
| 200 |
println!("├─────────────────┼──────────┼──────────┼──────────┤"); |
| 201 |
|
| 202 |
for (_fork, info) in &self.processes { |
| 203 |
let uptime = info.started_at.elapsed().as_secs(); |
| 204 |
println!( |
| 205 |
"│ {:15} │ {:8} │ {:6}s │ {:8} │", |
| 206 |
info.name, info.pid, uptime, info.restarts |
| 207 |
); |
| 208 |
} |
| 209 |
println!("└─────────────────┴──────────┴──────────┴──────────┘\n"); |
| 210 |
} |
| 211 |
|
| 212 |
|
| 213 |
fn shutdown(&mut self) { |
| 214 |
println!("\n🛑 Shutting down supervisor..."); |
| 215 |
self.shutdown.store(true, Ordering::Relaxed); |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
for (fork_result, info) in &self.processes { |
| 221 |
println!(" Stopping '{}' (PID: {})", info.name, info.pid); |
| 222 |
if let Some(pid) = fork_result.child_pid() { |
| 223 |
|
| 224 |
let _ = waitpid(pid); |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
self.processes.clear(); |
| 229 |
println!("✅ All processes stopped"); |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
fn main() { |
| 234 |
println!("🚀 Advanced Process Supervisor\n"); |
| 235 |
|
| 236 |
let mut supervisor = Supervisor::new(); |
| 237 |
|
| 238 |
|
| 239 |
println!("Starting workers...\n"); |
| 240 |
|
| 241 |
for i in 1..=3 { |
| 242 |
let name = format!("worker-{}", i); |
| 243 |
let command = vec!["sleep".to_string(), format!("{}", i * 2)]; |
| 244 |
|
| 245 |
match supervisor.spawn(name, command) { |
| 246 |
Ok(_) => {} |
| 247 |
Err(e) => eprintln!("Failed to spawn worker: {}", e), |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
supervisor.list(); |
| 252 |
|
| 253 |
|
| 254 |
println!("📡 Supervisor running. Waiting for process events...\n"); |
| 255 |
|
| 256 |
for _ in 0..10 { |
| 257 |
if supervisor.processes.is_empty() { |
| 258 |
println!("✅ All processes completed"); |
| 259 |
break; |
| 260 |
} |
| 261 |
|
| 262 |
|
| 263 |
if let Err(e) = supervisor.wait_for_exit() { |
| 264 |
eprintln!("Error waiting for child: {}", e); |
| 265 |
break; |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
println!("\n{}\n", supervisor.stats()); |
| 270 |
} |
| 271 |
|
| 272 |
supervisor.shutdown(); |
| 273 |
} |