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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Integration tests for process name filtering and kill_others functionality
//!
//! These tests verify that:
//! 1. Process name conflicts are detected when external processes match the filter
//! 2. kill_others functionality properly terminates matching external processes
//! 3. kill_others also kills child processes of the external processes
//!
//! ## Running the tests
//!
//! The integration tests require a running zinit-server. Run them with:
//!
//! ```bash
//! # Build zinit first
//! cargo build --release
//!
//! # Run the ignored integration tests
//! cargo test --test process_filter_integration -- --ignored --nocapture
//! ```

use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::thread;
use std::time::Duration;

/// Get the path to the zinit binary (built from this project)
fn get_zinit_binary() -> PathBuf {
    let mut path = std::env::current_exe().unwrap();
    path.pop(); // Remove test binary name
    path.pop(); // Remove deps
    path.push("zinit");
    if !path.exists() {
        // Try release build
        path.pop();
        path.pop();
        path.push("release");
        path.push("zinit");
    }
    path
}

/// Check if a process with given PID exists
fn process_exists(pid: u32) -> bool {
    #[cfg(unix)]
    {
        use nix::sys::signal::{Signal, kill};
        use nix::unistd::Pid;
        kill(Pid::from_raw(pid as i32), Signal::SIGCONT).is_ok()
    }
    #[cfg(not(unix))]
    {
        false
    }
}

/// Start a test process with a specific name pattern
struct TestProcess {
    child: Child,
    pid: u32,
    name_hint: String,
}

impl TestProcess {
    /// Start a bash process with a unique identifier in its name
    /// Uses: bash -c 'exec -a UNIQUE_MARKER sleep 60' to give the process a unique name
    fn start_sleep(duration_secs: u64) -> Result<Self, String> {
        let duration_str = duration_secs.to_string();
        // Use combination of PID and random number to ensure uniqueness across parallel tests
        let marker = format!(
            "ZINIT_TEST_SLEEP_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .subsec_nanos()
        );

        // Use bash to create a process with a unique name via exec -a
        // This allows us to match only our test processes, not system sleep commands
        let script = format!("exec -a {} sleep {}", marker, duration_str);

        let child = Command::new("bash")
            .arg("-c")
            .arg(&script)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .map_err(|e| format!("Failed to start sleep process: {}", e))?;

        let pid = child.id();
        Ok(Self {
            child,
            pid,
            name_hint: marker,
        })
    }

    fn pid(&self) -> u32 {
        self.pid
    }

    fn name_hint(&self) -> &str {
        &self.name_hint
    }

    fn is_running(&self) -> bool {
        process_exists(self.pid)
    }
}

impl Drop for TestProcess {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// Start a zinit server on a unique socket
struct ZinitServer {
    child: Child,
    socket_path: PathBuf,
}

impl ZinitServer {
    fn start() -> Result<Self, String> {
        let socket_path = PathBuf::from(format!(
            "/tmp/zinit-proc-filter-test-{}.sock",
            std::process::id()
        ));
        let config_dir = PathBuf::from(format!(
            "/tmp/zinit-proc-filter-test-{}-cfg",
            std::process::id()
        ));

        // Clean up any existing socket
        let _ = std::fs::remove_file(&socket_path);
        let _ = std::fs::remove_dir_all(&config_dir);
        std::fs::create_dir_all(&config_dir)
            .map_err(|e| format!("Failed to create config dir: {}", e))?;

        let zinit_bin = get_zinit_binary();
        if !zinit_bin.exists() {
            return Err(format!(
                "Zinit binary not found at {:?}. Run 'cargo build' first.",
                zinit_bin
            ));
        }

        let child = Command::new(&zinit_bin)
            .arg("server")
            .arg("--socket")
            .arg(&socket_path)
            .arg("--config-dir")
            .arg(&config_dir)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| format!("Failed to start zinit server: {}", e))?;

        // Wait for socket to be created
        let start = std::time::Instant::now();
        while !socket_path.exists() {
            if start.elapsed().as_secs() > 5 {
                return Err("Timeout waiting for zinit server to start".to_string());
            }
            thread::sleep(Duration::from_millis(100));
        }

        // Give server a moment to be fully ready
        thread::sleep(Duration::from_millis(200));

        Ok(Self { child, socket_path })
    }

    fn socket_path(&self) -> &PathBuf {
        &self.socket_path
    }
}

impl Drop for ZinitServer {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
        let _ = std::fs::remove_file(&self.socket_path);
        let config_dir = PathBuf::from(format!(
            "/tmp/zinit-proc-filter-test-{}-cfg",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&config_dir);
    }
}

// ============================================================================
// Unit Tests (run without server)
// ============================================================================

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

    #[test]
    fn test_can_start_test_process() {
        let process = TestProcess::start_sleep(3).expect("Should start sleep process");
        assert!(process.is_running(), "Process should be running");
        assert!(
            process.name_hint().contains("ZINIT_TEST_SLEEP"),
            "Process should have unique test marker"
        );
    }

    #[test]
    fn test_find_processes_by_name_with_sleep() {
        let _process = match TestProcess::start_sleep(60) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Give the process a moment to start
        thread::sleep(Duration::from_millis(100));

        // Try to find processes matching "ZINIT_TEST_SLEEP"
        // This is the unique marker we use in start_sleep()
        let processes = zinit::server::graph::find_processes_by_name("ZINIT_TEST_SLEEP");
        assert!(
            !processes.is_empty(),
            "Should find at least one process matching 'ZINIT_TEST_SLEEP'"
        );
    }

    #[test]
    fn test_find_processes_case_insensitive() {
        let _process = match TestProcess::start_sleep(60) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        thread::sleep(Duration::from_millis(100));

        // Try different case variations of our unique marker
        let lower = zinit::server::graph::find_processes_by_name("zinit_test_sleep");
        let upper = zinit::server::graph::find_processes_by_name("ZINIT_TEST_SLEEP");
        let mixed = zinit::server::graph::find_processes_by_name("ZiNiT_tEsT_sLeEp");

        assert!(!lower.is_empty(), "Should find with lowercase");
        assert!(!upper.is_empty(), "Should find with uppercase");
        assert!(!mixed.is_empty(), "Should find with mixed case");

        // Case-insensitive matching should find results with all case variations
        // Note: Due to how process names work on different OSes, we can't guarantee
        // finding the exact same count across all variations, but we should find
        // at least one match with each case variation
        assert!(
            lower
                .iter()
                .any(|p| p.name.to_lowercase().contains("zinit_test_sleep")),
            "Should find matching process with lowercase"
        );
        assert!(
            upper
                .iter()
                .any(|p| p.name.to_lowercase().contains("zinit_test_sleep")),
            "Should find matching process with uppercase"
        );
        assert!(
            mixed
                .iter()
                .any(|p| p.name.to_lowercase().contains("zinit_test_sleep")),
            "Should find matching process with mixed case"
        );
    }

    #[test]
    fn test_find_processes_empty_filter() {
        let processes = zinit::server::graph::find_processes_by_name("");
        assert!(processes.is_empty(), "Empty filter should match nothing");
    }

    #[test]
    fn test_kill_process_tree_sleep() {
        let process = match TestProcess::start_sleep(60) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        let pid = process.pid();
        assert!(process_exists(pid), "Process should be running before drop");

        // Dropping the process should kill it via Drop impl
        drop(process);

        // Wait a moment for signal to take effect
        thread::sleep(Duration::from_millis(100));

        // Process should be gone (killed by Drop)
        // Note: On some systems, zombie processes may persist briefly
        // but the important thing is we can start a new process with same name
        let _new_process = match TestProcess::start_sleep(3) {
            Ok(p) => {
                assert!(p.is_running(), "Should be able to start a new process");
                p
            }
            Err(e) => {
                eprintln!("Could not start new process: {}", e);
                return;
            }
        };
    }
}

// ============================================================================
// Integration Tests (require zinit server)
// ============================================================================

#[cfg(test)]
mod integration_tests {
    use super::*;
    use zinit::ZinitHandle;
    use zinit::client::client::ServiceConfigBuilder;

    /// Create a ZinitHandle connected to a specific socket
    fn connect_to_server(socket_path: &PathBuf) -> Result<ZinitHandle, String> {
        use zinit::client::client::ZinitClient;

        let client = ZinitClient::unix(socket_path);
        ZinitHandle::with_client(client).map_err(|e| format!("Failed to connect to zinit: {}", e))
    }

    #[test]
    #[ignore = "Requires building zinit binary first (cargo build)"]
    fn test_process_filter_detects_conflict() {
        println!("\n=== Integration Test: process_filter detects conflict ===\n");

        // Start zinit server
        let server = match ZinitServer::start() {
            Ok(s) => {
                println!("Started zinit server on {:?}", s.socket_path());
                s
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Connect to the server
        let handle = match connect_to_server(server.socket_path()) {
            Ok(h) => {
                println!("Connected to zinit server");
                h
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Verify connection
        match handle.ping() {
            Ok(resp) => println!("Ping successful: version {}", resp.version),
            Err(e) => {
                eprintln!("Skipping test: ping failed: {}", e);
                return;
            }
        }

        // Start a test process
        let test_process = match TestProcess::start_sleep(60) {
            Ok(p) => {
                println!("Started test process: {} (PID: {})", p.name_hint(), p.pid());
                p
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        assert!(test_process.is_running(), "Test process should be running");

        // Create a service with process_filter (no kill_others)
        let service_name = format!("process-filter-test-{}", std::process::id());
        let config = ServiceConfigBuilder::new(&service_name)
            .exec("echo 'test service'")
            .process_filter("sleep") // Will match our test process
            .build();

        println!(
            "Creating service '{}' with process_filter='sleep' (no kill_others)",
            service_name
        );

        match handle.service_set(config) {
            Ok(_) => println!("Service created successfully"),
            Err(e) => {
                eprintln!("Failed to create service: {}", e);
                return;
            }
        }

        // Try to start the service
        println!("Starting service...");
        match handle.start(&service_name) {
            Ok(_) => println!("Start returned OK"),
            Err(e) => println!("Start returned error: {}", e),
        }

        // Wait a moment
        thread::sleep(Duration::from_millis(500));

        // Check service status - should be blocked due to process filter
        println!("Checking service status...");
        match handle.status(&service_name) {
            Ok(status) => {
                println!("Service state: {:?}", status.state);
                if let Some(error) = &status.error {
                    println!("Service error: {}", error);
                }
            }
            Err(e) => println!("Could not get status: {}", e),
        }

        // Check why the service is blocked
        println!("Checking why service is blocked...");
        match handle.why(&service_name) {
            Ok(why) => {
                println!("Blocked: {}", why.blocked);
                if let Some(_conflict) = &why.process_conflict {
                    println!("Process conflict detected (field populated)");
                    // Note: process_conflict field may be Some but details depend on API version
                }
            }
            Err(e) => println!("Could not get why: {}", e),
        }

        // Clean up
        println!("Cleaning up...");
        let _ = handle.service_delete(&service_name);
        println!("Service deleted\n");
    }

    #[test]
    #[ignore = "Requires building zinit binary first (cargo build)"]
    fn test_kill_others_with_process_filter() {
        println!("\n=== Integration Test: kill_others with process_filter ===\n");

        // Start zinit server
        let server = match ZinitServer::start() {
            Ok(s) => {
                println!("Started zinit server on {:?}", s.socket_path());
                s
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Connect to the server
        let handle = match connect_to_server(server.socket_path()) {
            Ok(h) => {
                println!("Connected to zinit server");
                h
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Verify connection
        if let Err(e) = handle.ping() {
            eprintln!("Skipping test: ping failed: {}", e);
            return;
        }

        // Start a test process
        let test_process = match TestProcess::start_sleep(60) {
            Ok(p) => {
                println!("Started test process: {} (PID: {})", p.name_hint(), p.pid());
                p
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        let original_pid = test_process.pid();
        assert!(
            process_exists(original_pid),
            "Test process should be running"
        );
        println!("Verified test process is running (PID: {})", original_pid);

        // Create a service with process_filter AND kill_others
        let service_name = format!("kill-proc-filter-test-{}", std::process::id());
        let config = ServiceConfigBuilder::new(&service_name)
            .exec("echo 'Service started after killing sleep process'")
            .process_filter("sleep") // Will match our test process
            .kill_others()
            .build();

        println!(
            "Creating service '{}' with process_filter='sleep' AND kill_others=true",
            service_name
        );

        match handle.service_set(config) {
            Ok(_) => println!("Service created successfully"),
            Err(e) => {
                eprintln!("Failed to create service: {}", e);
                return;
            }
        }

        // Start the service
        println!("Starting service (should kill matching processes)...");
        match handle.start(&service_name) {
            Ok(_) => println!("Service start succeeded"),
            Err(e) => println!(
                "Service start returned: {} (may be expected for oneshot)",
                e
            ),
        }

        // Wait for kill_others to take effect
        thread::sleep(Duration::from_millis(1000));

        // The original process should be dead
        let process_dead = !process_exists(original_pid);
        println!(
            "Original process (PID {}) dead: {}",
            original_pid, process_dead
        );

        // Check service status
        println!("Checking final service status...");
        match handle.status(&service_name) {
            Ok(status) => {
                println!("Service state: {:?}", status.state);
                if let Some(error) = &status.error {
                    println!("Service error: {}", error);
                }
            }
            Err(e) => println!("Could not get status: {}", e),
        }

        // Clean up
        println!("Cleaning up...");
        let _ = handle.stop(&service_name);
        let _ = handle.service_delete(&service_name);
        println!("Service deleted");

        // Verify the process was actually killed
        assert!(
            process_dead,
            "Process should have been killed by kill_others"
        );

        println!("\nTest completed successfully!\n");
    }

    #[test]
    #[ignore = "Requires building zinit binary first (cargo build)"]
    fn test_multiple_process_matches() {
        println!("\n=== Integration Test: multiple matching processes ===\n");

        // Start zinit server
        let server = match ZinitServer::start() {
            Ok(s) => {
                println!("Started zinit server on {:?}", s.socket_path());
                s
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Connect to the server
        let handle = match connect_to_server(server.socket_path()) {
            Ok(h) => h,
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        if let Err(e) = handle.ping() {
            eprintln!("Skipping test: ping failed: {}", e);
            return;
        }

        // Start multiple test processes
        println!("Starting multiple test processes...");
        let process1 = match TestProcess::start_sleep(60) {
            Ok(p) => {
                println!("  Started process 1 (PID: {})", p.pid());
                p
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        let process2 = match TestProcess::start_sleep(60) {
            Ok(p) => {
                println!("  Started process 2 (PID: {})", p.pid());
                p
            }
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        let pid1 = process1.pid();
        let pid2 = process2.pid();

        // Create service with kill_others
        let service_name = format!("multi-kill-test-{}", std::process::id());
        let config = ServiceConfigBuilder::new(&service_name)
            .exec("echo 'Service with multiple killed processes'")
            .process_filter("sleep")
            .kill_others()
            .build();

        println!("Creating service with kill_others (will kill both sleep processes)...");
        match handle.service_set(config) {
            Ok(_) => println!("Service created"),
            Err(e) => {
                eprintln!("Failed to create service: {}", e);
                return;
            }
        }

        // Start the service
        println!("Starting service...");
        let _ = handle.start(&service_name);

        // Wait for kill_others
        thread::sleep(Duration::from_millis(1000));

        // Both processes should be dead
        let pid1_dead = !process_exists(pid1);
        let pid2_dead = !process_exists(pid2);

        println!("Process 1 (PID {}) dead: {}", pid1, pid1_dead);
        println!("Process 2 (PID {}) dead: {}", pid2, pid2_dead);

        // Clean up
        let _ = handle.stop(&service_name);
        let _ = handle.service_delete(&service_name);

        // Both should be dead
        assert!(pid1_dead, "Process 1 should be killed");
        assert!(pid2_dead, "Process 2 should be killed");

        println!("\nTest completed successfully!\n");
    }
}