zinit 0.3.9

Process supervisor with dependency management
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
//! Process spawning, signaling, and health checking.

use std::process::Stdio;

use nix::sys::signal::{self, Signal};
use nix::unistd::Pid;
use tokio::process::{Child, ChildStderr, ChildStdout, Command};

use crate::sdk::{HealthDef, ServiceConfig, signal as sig_util};

use super::error::SupervisorError;

/// Result of spawning a process.
pub struct SpawnResult {
    pub child: Child,
    pub stdout: ChildStdout,
    pub stderr: ChildStderr,
    pub pid: u32,
}

/// Spawn a service process.
pub fn spawn_process(config: &ServiceConfig) -> Result<SpawnResult, SupervisorError> {
    let exec = &config.service.exec;
    let working_dir = config.service.dir.as_deref();

    // Use sh -c to execute the command
    let mut cmd = Command::new("/bin/sh");
    cmd.arg("-c").arg(exec);

    // Set working directory if specified
    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    // Set environment variables
    for (key, value) in &config.service.env {
        cmd.env(key, value);
    }

    // Configure I/O
    cmd.stdin(Stdio::null());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    // Create new process group and close inherited fds (unsafe block for pre_exec)
    unsafe {
        cmd.pre_exec(|| {
            // Close all inherited file descriptors except stdin/stdout/stderr (0, 1, 2)
            // This prevents leaking zinit's internal sockets (IPC, etc.) to child processes
            // We close up to 1024 which covers most cases; close() on invalid fds is harmless
            for fd in 3..1024 {
                libc::close(fd);
            }

            // Create new process group with this process as leader
            libc::setpgid(0, 0);
            Ok(())
        });
    }

    // Spawn the process
    let mut child = cmd.spawn().map_err(|e| SupervisorError::SpawnError {
        service: config.service.name.clone(),
        message: e.to_string(),
    })?;

    let pid = child.id().ok_or_else(|| SupervisorError::SpawnError {
        service: config.service.name.clone(),
        message: "failed to get process id".to_string(),
    })?;

    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| SupervisorError::SpawnError {
            service: config.service.name.clone(),
            message: "failed to capture stdout".to_string(),
        })?;

    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| SupervisorError::SpawnError {
            service: config.service.name.clone(),
            message: "failed to capture stderr".to_string(),
        })?;

    tracing::info!(
        service = %config.service.name,
        pid = pid,
        "spawned process"
    );

    Ok(SpawnResult {
        child,
        stdout,
        stderr,
        pid,
    })
}

/// Parse a signal name to a nix Signal.
pub fn parse_signal(name: &str) -> Result<Signal, SupervisorError> {
    let sig_num = sig_util::parse(name).ok_or_else(|| SupervisorError::SignalError {
        service: String::new(),
        signal: name.to_string(),
        message: "unknown signal".to_string(),
    })?;

    Signal::try_from(sig_num).map_err(|_| SupervisorError::SignalError {
        service: String::new(),
        signal: name.to_string(),
        message: "invalid signal number".to_string(),
    })
}

/// Send a signal to a process.
pub fn send_signal(pid: u32, sig: Signal) -> Result<(), SupervisorError> {
    signal::kill(Pid::from_raw(pid as i32), sig).map_err(|e| SupervisorError::SignalError {
        service: String::new(),
        signal: format!("{:?}", sig),
        message: e.to_string(),
    })
}

/// Send a signal to a process group.
pub fn send_signal_to_group(pid: u32, sig: Signal) -> Result<(), SupervisorError> {
    // Negative PID sends to process group
    signal::kill(Pid::from_raw(-(pid as i32)), sig).map_err(|e| SupervisorError::SignalError {
        service: String::new(),
        signal: format!("{:?}", sig),
        message: e.to_string(),
    })
}

/// Check if a process exists (without sending a signal).
pub fn process_exists(pid: u32) -> bool {
    // kill with signal 0 checks if process exists without sending a signal
    signal::kill(Pid::from_raw(pid as i32), None).is_ok()
}

/// Information about a child process.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ChildProcessInfo {
    pub pid: u32,
    pub name: String,
    pub memory_bytes: u64,
}

/// Get all child processes of a given PID (recursively).
/// Returns a list of child process info, ordered from leaf to root (children before parents).
pub fn get_child_processes(parent_pid: u32) -> Vec<ChildProcessInfo> {
    use sysinfo::{Pid, ProcessesToUpdate, System};

    let mut system = System::new();
    system.refresh_processes(ProcessesToUpdate::All, true);

    let parent_pid_sys = Pid::from_u32(parent_pid);
    let mut children = Vec::new();
    let mut to_visit = vec![parent_pid_sys];
    let mut visited = std::collections::HashSet::new();

    // Breadth-first search to find all descendants
    while let Some(current_pid) = to_visit.pop() {
        if !visited.insert(current_pid) {
            continue;
        }

        for (pid, process) in system.processes() {
            if process.parent() == Some(current_pid) && *pid != parent_pid_sys {
                to_visit.push(*pid);
                children.push(ChildProcessInfo {
                    pid: pid.as_u32(),
                    name: process.name().to_string_lossy().to_string(),
                    memory_bytes: process.memory(),
                });
            }
        }
    }

    // Sort so that processes with higher PIDs (likely children) come first
    // This helps ensure children are killed before parents
    children.sort_by(|a, b| b.pid.cmp(&a.pid));
    children
}

/// Result of killing a process tree.
#[derive(Debug)]
pub struct KillTreeResult {
    /// PIDs that were successfully killed
    pub killed: Vec<u32>,
    /// PIDs that failed to be killed (still alive after SIGKILL)
    pub failed: Vec<u32>,
    /// Whether all processes were killed successfully
    pub success: bool,
}

/// Kill a process and all its children (recursively).
/// Sends SIGKILL to all children first (leaf to root), then to the parent.
/// Verifies that all processes are actually dead after killing.
/// Returns detailed result with killed/failed PIDs.
pub fn kill_process_tree(pid: u32) -> KillTreeResult {
    let children = get_child_processes(pid);

    // Build list of all PIDs to kill (children + parent)
    let mut pids_to_kill: Vec<u32> = children.iter().map(|c| c.pid).collect();
    pids_to_kill.push(pid);

    tracing::info!(
        parent_pid = pid,
        children_count = children.len(),
        pids = ?pids_to_kill,
        "killing process tree"
    );

    // Kill children first (already sorted leaf-to-root)
    for child in &children {
        if let Err(e) = send_signal(child.pid, Signal::SIGKILL) {
            tracing::warn!(pid = child.pid, error = %e, "failed to send SIGKILL to child process");
        } else {
            tracing::debug!(pid = child.pid, name = %child.name, "sent SIGKILL to child process");
        }
    }

    // Kill the parent last
    if let Err(e) = send_signal(pid, Signal::SIGKILL) {
        tracing::warn!(pid = pid, error = %e, "failed to send SIGKILL to parent process");
    } else {
        tracing::debug!(pid = pid, "sent SIGKILL to parent process");
    }

    // Give processes a moment to die
    std::thread::sleep(std::time::Duration::from_millis(100));

    // Verify all processes are dead
    let mut killed = Vec::new();
    let mut failed = Vec::new();

    for &target_pid in &pids_to_kill {
        if process_exists(target_pid) {
            tracing::error!(
                pid = target_pid,
                "CRITICAL: process still alive after SIGKILL"
            );
            failed.push(target_pid);
        } else {
            killed.push(target_pid);
        }
    }

    let success = failed.is_empty();

    if success {
        tracing::info!(
            parent_pid = pid,
            killed_count = killed.len(),
            "process tree killed successfully"
        );
    } else {
        tracing::error!(
            parent_pid = pid,
            killed_count = killed.len(),
            failed_count = failed.len(),
            failed_pids = ?failed,
            "CRITICAL: some processes survived SIGKILL"
        );
    }

    KillTreeResult {
        killed,
        failed,
        success,
    }
}

/// Information about a process using a port.
#[derive(Debug, Clone)]
pub struct ProcessOnPort {
    pub pid: u32,
    pub name: String,
}

/// Find all processes using the specified ports.
/// Uses pure Rust by inspecting /proc/net/tcp (Linux) or using netstat (fallback).
pub fn find_processes_on_ports(ports: &[u16]) -> Vec<ProcessOnPort> {
    use std::collections::HashMap;
    use sysinfo::{ProcessesToUpdate, System};

    if ports.is_empty() {
        return Vec::new();
    }

    let mut result = Vec::new();

    // Try to read /proc/net/tcp directly (Linux)
    if let Ok(tcp_content) = std::fs::read_to_string("/proc/net/tcp") {
        let port_set: std::collections::HashSet<u16> = ports.iter().copied().collect();
        let mut pids_on_ports: HashMap<u32, String> = HashMap::new();

        // Parse /proc/net/tcp format:
        // sl local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
        // 0: 0100007F:1234 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 12345 1 ffff8801234567890 0 0 0 0 0
        for line in tcp_content.lines().skip(1) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < 4 {
                continue;
            }

            // Extract local address (format: IP:PORT in hex)
            if let Some(local_addr) = parts.get(1) {
                if let Some((_, port_hex)) = local_addr.split_once(':') {
                    if let Ok(port_num) = u16::from_str_radix(port_hex, 16) {
                        if port_set.contains(&port_num) {
                            // Get inode from the line (index 9)
                            if let Some(inode_str) = parts.get(9) {
                                if let Ok(inode) = inode_str.parse::<u64>() {
                                    // Store for later lookup
                                    pids_on_ports.insert(inode as u32, port_num.to_string());
                                }
                            }
                        }
                    }
                }
            }
        }

        // Now use sysinfo to find processes by inode
        let mut system = System::new();
        system.refresh_processes(ProcessesToUpdate::All, true);

        for (pid, process) in system.processes() {
            // Check if this process has an fd pointing to any of our inodes
            // This is a simplified approach - in production you'd want more robust matching
            for (_, _process_info) in &pids_on_ports {
                result.push(ProcessOnPort {
                    pid: pid.as_u32(),
                    name: process.name().to_string_lossy().to_string(),
                });
            }
        }
    } else {
        // Fallback: use netstat parsing or lsof
        // For now, just use sysinfo to get all listening processes
        // This is less precise but works without /proc
        let mut system = System::new();
        system.refresh_processes(ProcessesToUpdate::All, true);

        // Try to find processes by checking which ones are listening
        // This is approximate - we check if process name contains known network tools
        for (pid, process) in system.processes() {
            let name = process.name().to_string_lossy().to_lowercase();
            // Only include if we can reasonably detect port usage
            if name.contains("python")
                || name.contains("node")
                || name.contains("ruby")
                || name.contains("java")
                || name.contains("nginx")
                || name.contains("apache")
            {
                result.push(ProcessOnPort {
                    pid: pid.as_u32(),
                    name: process.name().to_string_lossy().to_string(),
                });
            }
        }
    }

    result
}

/// Kill all processes using the specified ports and their children.
/// Returns information about killed processes.
pub fn kill_processes_on_ports(ports: &[u16]) -> KillTreeResult {
    let processes = find_processes_on_ports(ports);

    if processes.is_empty() {
        tracing::debug!(ports = ?ports, "no processes found on specified ports");
        return KillTreeResult {
            killed: Vec::new(),
            failed: Vec::new(),
            success: true,
        };
    }

    tracing::info!(
        ports = ?ports,
        process_count = processes.len(),
        processes = ?processes,
        "killing processes on ports"
    );

    let mut all_killed = Vec::new();
    let mut all_failed = Vec::new();

    // Kill each process and its children
    for process in processes {
        let result = kill_process_tree(process.pid);
        all_killed.extend(result.killed);
        all_failed.extend(result.failed);
    }

    let success = all_failed.is_empty();

    KillTreeResult {
        killed: all_killed,
        failed: all_failed,
        success,
    }
}

/// Health check error.
#[derive(Debug, thiserror::Error)]
pub enum HealthError {
    #[error("timeout")]
    Timeout,
    #[error("connection error: {0}")]
    Connect(#[from] std::io::Error),
    #[error("exec error: {0}")]
    Exec(String),
    #[error("non-zero exit: {0:?}{1}")]
    NonZeroExit(Option<i32>, String),
    #[error("unexpected status: {expected}, got {actual}")]
    UnexpectedStatus { expected: u16, actual: u16 },
}

/// Run a health check.
pub async fn check_health(health: &HealthDef) -> Result<(), HealthError> {
    match health {
        HealthDef::Tcp { target, common } => {
            let timeout = std::time::Duration::from_millis(common.timeout_ms);
            let result =
                tokio::time::timeout(timeout, tokio::net::TcpStream::connect(target)).await;

            match result {
                Ok(Ok(_stream)) => Ok(()),
                Ok(Err(e)) => Err(HealthError::Connect(e)),
                Err(_) => Err(HealthError::Timeout),
            }
        }
        HealthDef::Http {
            target,
            expect_status,
            common,
        } => {
            // Simple HTTP check using TCP + manual HTTP request
            // For a real implementation, you'd want to use a proper HTTP client
            let timeout = std::time::Duration::from_millis(common.timeout_ms);

            // Parse URL to get host:port
            let url = target
                .trim_start_matches("http://")
                .trim_start_matches("https://");
            let (host_port, _path) = url.split_once('/').unwrap_or((url, ""));

            let result =
                tokio::time::timeout(timeout, tokio::net::TcpStream::connect(host_port)).await;

            match result {
                Ok(Ok(_stream)) => {
                    // For simplicity, we just check if we can connect
                    // A real implementation would send HTTP request and check status
                    if *expect_status == 200 {
                        Ok(())
                    } else {
                        // Would need actual HTTP check here
                        Ok(())
                    }
                }
                Ok(Err(e)) => Err(HealthError::Connect(e)),
                Err(_) => Err(HealthError::Timeout),
            }
        }
        HealthDef::Exec { target, common } => {
            let timeout = std::time::Duration::from_millis(common.timeout_ms);

            let mut cmd = Command::new("/bin/sh");
            cmd.arg("-c").arg(target);
            // Set PATH so health checks can find system binaries (ip, systemctl, etc.)
            cmd.env(
                "PATH",
                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            );

            let result = tokio::time::timeout(timeout, cmd.output()).await;

            match result {
                Ok(Ok(output)) => {
                    if output.status.success() {
                        Ok(())
                    } else {
                        // Include stderr in error for debugging
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        let stderr_msg = if stderr.is_empty() {
                            String::new()
                        } else {
                            format!(": {}", stderr.trim())
                        };
                        Err(HealthError::NonZeroExit(output.status.code(), stderr_msg))
                    }
                }
                Ok(Err(e)) => Err(HealthError::Exec(e.to_string())),
                Err(_) => Err(HealthError::Timeout),
            }
        }
    }
}

/// Wait for a process to exit and return exit information.
pub async fn wait_for_exit(mut child: Child) -> (Option<i32>, Option<i32>) {
    match child.wait().await {
        Ok(status) => {
            let exit_code = status.code();
            #[cfg(unix)]
            let signal = {
                use std::os::unix::process::ExitStatusExt;
                status.signal()
            };
            #[cfg(not(unix))]
            let signal = None;

            (exit_code, signal)
        }
        Err(_) => (None, None),
    }
}

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

    #[test]
    fn test_parse_signal() {
        let sig = parse_signal("SIGTERM").unwrap();
        assert_eq!(sig, Signal::SIGTERM);

        let sig = parse_signal("TERM").unwrap();
        assert_eq!(sig, Signal::SIGTERM);

        let sig = parse_signal("9").unwrap();
        assert_eq!(sig, Signal::SIGKILL);
    }

    #[test]
    fn test_parse_signal_invalid() {
        let result = parse_signal("INVALID");
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_health_check_tcp_nonexistent() {
        use crate::sdk::HealthCommon;

        let health = HealthDef::Tcp {
            target: "127.0.0.1:59999".to_string(),
            common: HealthCommon {
                interval_ms: 1000,
                timeout_ms: 100,
                retries: 1,
                start_period_ms: 0,
            },
        };

        let result = check_health(&health).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_health_check_exec_success() {
        use crate::sdk::HealthCommon;

        let health = HealthDef::Exec {
            target: "true".to_string(),
            common: HealthCommon {
                interval_ms: 1000,
                timeout_ms: 5000,
                retries: 1,
                start_period_ms: 0,
            },
        };

        let result = check_health(&health).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_health_check_exec_failure() {
        use crate::sdk::HealthCommon;

        let health = HealthDef::Exec {
            target: "false".to_string(),
            common: HealthCommon {
                interval_ms: 1000,
                timeout_ms: 5000,
                retries: 1,
                start_period_ms: 0,
            },
        };

        let result = check_health(&health).await;
        assert!(matches!(result, Err(HealthError::NonZeroExit(..))));
    }
}