Debian Codegraph @

examples/supervisor_advanced.rs

raw symbols SCIP
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 //! Advanced Process Supervisor with Signal Handling
17 //!
18 //! This example shows how to build a production-ready supervisor that:
19 //! - Uses Fork with Hash to track processes in a HashMap
20 //! - Gets notified when child processes exit (via SIGCHLD)
21 //! - Automatically restarts failed processes
22 //! - Tracks process metrics (uptime, restart count)
23 //! - Gracefully shuts down all children
24 //!
25 //! Run with: cargo run --example supervisor_advanced
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 /// Spawn a new supervised process
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 // Store using Fork as HashMap key!
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 // Child process - execute the command
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 /// Handle a process exit
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 // Auto-restart if under limit
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 /// Restart a process
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 // Simulate command (in real code, store original command)
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 /// Wait for any child to exit (blocking)
159 fn wait_for_exit(&mut self) -> std::io::Result<()> {
160 // In production, you'd use waitpid(-1, &mut status, 0) to wait for ANY child
161 // For this example, we'll iterate through known processes
162
163 for (fork_result, _info) in self.processes.clone().iter() {
164 if let Some(pid) = fork_result.child_pid() {
165 // Try to wait for this specific child (blocking)
166 match waitpid(pid) {
167 Ok(_) => {
168 self.handle_exit(*fork_result);
169 return Ok(());
170 }
171 Err(_) => {
172 // This child hasn't exited yet, continue
173 continue;
174 }
175 }
176 }
177 }
178
179 // No children exited yet
180 thread::sleep(Duration::from_millis(100));
181 Ok(())
182 }
183
184 /// Get supervisor statistics
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 /// List all supervised processes
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 /// Shutdown all supervised processes
213 fn shutdown(&mut self) {
214 println!("\n🛑 Shutting down supervisor...");
215 self.shutdown.store(true, Ordering::Relaxed);
216
217 // Send SIGTERM to all children (not shown - would use libc::kill)
218 // Then wait for them to exit gracefully
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 // In production: unsafe { libc::kill(pid, libc::SIGTERM) };
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 // Spawn multiple workers
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 // Supervisor main loop
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 // Wait for a child to exit
263 if let Err(e) = supervisor.wait_for_exit() {
264 eprintln!("Error waiting for child: {}", e);
265 break;
266 }
267
268 // Show stats periodically
269 println!("\n{}\n", supervisor.stats());
270 }
271
272 supervisor.shutdown();
273 }