pmdaemon 0.1.4

PMDaemon - A high-performance, cross-platform process manager built in Rust with advanced port management and monitoring capabilities
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
//! End-to-end tests for PMDaemon with various process types
//!
//! These tests verify that PMDaemon works correctly with different types of
//! applications and scenarios, testing the complete system integration.

use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
use std::path::PathBuf;
use std::thread;
use std::time::Duration;
use tempfile::TempDir;

/// Helper struct for managing test environment
struct E2ETestEnvironment {
    temp_dir: TempDir,
    config_dir: PathBuf,
}

impl E2ETestEnvironment {
    fn new() -> Self {
        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        let config_dir = temp_dir.path().join(".pmdaemon");

        // Create config directory
        fs::create_dir_all(&config_dir).expect("Failed to create config directory");

        Self {
            temp_dir,
            config_dir,
        }
    }

    fn cmd(&self) -> Command {
        let mut cmd = Command::cargo_bin("pmdaemon").expect("Failed to find binary");
        cmd.env("PMDAEMON_HOME", &self.config_dir);
        cmd.env("NO_COLOR", "1");
        cmd.env("RUST_LOG", "error");
        cmd
    }

    fn temp_path(&self) -> &std::path::Path {
        self.temp_dir.path()
    }

    fn unique_name(&self, base: &str) -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        format!("{}-{}", base, timestamp % 1000000)
    }
}

/// Create a test script with specific content
fn create_script(dir: &std::path::Path, name: &str, content: &str) -> PathBuf {
    #[cfg(windows)]
    {
        // On Windows, create a batch file
        let script_path = dir.join(format!("{}.bat", name));
        // Convert bash script to batch equivalent
        let batch_content = convert_bash_to_batch(content);
        fs::write(&script_path, batch_content).expect("Failed to write test script");
        script_path
    }
    #[cfg(not(windows))]
    {
        let script_path = dir.join(format!("{}.sh", name));
        fs::write(&script_path, content).expect("Failed to write test script");

        // Make script executable
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&script_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap();

        script_path
    }
}

/// Convert basic bash script to Windows batch equivalent
#[cfg(windows)]
fn convert_bash_to_batch(bash_content: &str) -> String {
    let mut batch_content = String::from("@echo off\n");

    for line in bash_content.lines() {
        if line.starts_with("#!/") {
            // Skip shebang
            continue;
        } else if line.starts_with("echo ") {
            // Convert echo commands
            batch_content.push_str(&line.replace("echo ", "echo "));
            batch_content.push('\n');
        } else if line.starts_with("sleep ") {
            // Convert sleep to timeout
            let sleep_time = line
                .replace("sleep ", "")
                .trim()
                .parse::<u32>()
                .unwrap_or(1);
            batch_content.push_str(&format!("timeout /t {} /nobreak >nul\n", sleep_time));
        } else if line.contains("for i in {") && line.contains("}; do") {
            // Convert simple for loops
            if line.contains("{1..10}") {
                batch_content.push_str("for /l %%i in (1,1,10) do (\n");
            } else if line.contains("{1..5}") {
                batch_content.push_str("for /l %%i in (1,1,5) do (\n");
            }
        } else if line.trim() == "done" {
            batch_content.push_str(")\n");
        } else if line.contains("exit ") {
            batch_content.push_str(line);
            batch_content.push('\n');
        } else if !line.trim().is_empty() && !line.contains("$") {
            // Copy other simple lines
            batch_content.push_str(line);
            batch_content.push('\n');
        }
    }

    batch_content
}

/// Create a Python script
fn create_python_script(dir: &std::path::Path, name: &str, content: &str) -> PathBuf {
    let script_path = dir.join(format!("{}.py", name));
    fs::write(&script_path, content).expect("Failed to write Python script");
    script_path
}

/// Create a Node.js script
fn create_node_script(dir: &std::path::Path, name: &str, content: &str) -> PathBuf {
    let script_path = dir.join(format!("{}.js", name));
    fs::write(&script_path, content).expect("Failed to write Node.js script");
    script_path
}

#[test]
#[cfg(not(windows))]
fn test_simple_shell_script() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("shell-app");

    // Create a simple shell script that runs for a while
    let script = create_script(
        env.temp_path(),
        "simple_shell",
        r#"#!/bin/bash
echo "Shell script starting..."
for i in {1..10}; do
    echo "Iteration $i"
    sleep 1
done
echo "Shell script completed"
"#,
    );

    // Start the process
    env.cmd()
        .args(["start", script.to_str().unwrap(), "--name", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Verify it's running
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name))
        .stdout(predicate::str::contains("online"));

    // Stop and clean up
    env.cmd().args(["stop", &process_name]).assert().success();

    env.cmd().args(["delete", &process_name]).assert().success();
}

#[test]
#[cfg(not(windows))]
fn test_python_script() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("python-app");

    // Create a Python script with shebang
    let script = create_python_script(
        env.temp_path(),
        "python_app",
        r#"#!/usr/bin/env python3
import time
import sys

print("Python application starting...")
for i in range(5):
    print(f"Python iteration {i+1}")
    time.sleep(1)
print("Python application completed")
"#,
    );

    // Make script executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script, perms).unwrap();
    }

    // Start the process (Python script with shebang)
    env.cmd()
        .args(["start", script.to_str().unwrap(), "--name", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Verify it's running
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name));

    // Clean up
    env.cmd().args(["delete", &process_name]).assert().success();
}

#[test]
#[cfg(not(windows))]
fn test_node_script() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("node-app");

    // Create a Node.js script with shebang
    let script = create_node_script(
        env.temp_path(),
        "node_app",
        r#"#!/usr/bin/env node
console.log('Node.js application starting...');

let counter = 0;
const interval = setInterval(() => {
    counter++;
    console.log(`Node.js iteration ${counter}`);

    if (counter >= 5) {
        console.log('Node.js application completed');
        clearInterval(interval);
        process.exit(0);
    }
}, 1000);

// Handle graceful shutdown
process.on('SIGTERM', () => {
    console.log('Received SIGTERM, shutting down gracefully');
    clearInterval(interval);
    process.exit(0);
});
"#,
    );

    // Make script executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script, perms).unwrap();
    }

    // Start the process (Node.js script with shebang)
    env.cmd()
        .args(["start", script.to_str().unwrap(), "--name", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Verify it's running
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name));

    // Clean up
    env.cmd().args(["delete", &process_name]).assert().success();
}

#[test]
#[cfg(not(windows))]
fn test_clustering_mode() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("cluster-app");

    // Create a script suitable for clustering
    let script = create_script(
        env.temp_path(),
        "cluster_app",
        r#"#!/bin/bash
echo "Cluster instance starting with PID $$"
echo "Instance ID: ${PM2_INSTANCE_ID:-0}"
sleep 5
echo "Cluster instance completed"
"#,
    );

    // Start with clustering
    env.cmd()
        .args([
            "start",
            script.to_str().unwrap(),
            "--name",
            &process_name,
            "--instances",
            "2",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Verify instances are running
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name));

    // Clean up - try to delete, but don't fail if it doesn't exist
    let _ = env.cmd().args(["delete", &process_name]).assert();
}

#[test]
#[cfg(not(windows))]
fn test_port_management() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("port-app");

    // Create a script that simulates a server
    let script = create_script(
        env.temp_path(),
        "port_server",
        r#"#!/bin/bash
echo "Server starting on port ${PORT:-8080}"
echo "Process PID: $$"
sleep 5
echo "Server shutting down"
"#,
    );

    // Start with port allocation
    env.cmd()
        .args([
            "start",
            script.to_str().unwrap(),
            "--name",
            &process_name,
            "--port",
            "9000",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Verify port is shown in list
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name))
        .stdout(predicate::str::contains("9000"));

    // Clean up
    env.cmd().args(["delete", &process_name]).assert().success();
}

#[test]
#[cfg(not(windows))]
fn test_auto_restart() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("restart-app");

    // Create a script that exits quickly (to trigger restart)
    let script = create_script(
        env.temp_path(),
        "quick_exit",
        r#"#!/bin/bash
echo "Process starting..."
sleep 1
echo "Process exiting..."
exit 1
"#,
    );

    // Start the process (auto-restart is enabled by default)
    env.cmd()
        .args(["start", script.to_str().unwrap(), "--name", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

    // Wait for potential restart
    thread::sleep(Duration::from_millis(2000));

    // Check if process shows restart count
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name));

    // Clean up - try to delete, but don't fail if it doesn't exist
    let _ = env.cmd().args(["delete", &process_name]).assert();
}

#[test]
#[cfg(not(windows))]
fn test_graceful_shutdown() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("graceful-app");

    // Create a script that handles SIGTERM gracefully
    let script = create_script(
        env.temp_path(),
        "graceful_shutdown",
        r#"#!/bin/bash
cleanup() {
    echo "Received signal, cleaning up..."
    sleep 1
    echo "Cleanup completed, exiting gracefully"
    exit 0
}

trap cleanup SIGTERM SIGINT

echo "Process starting with PID $$"
echo "Waiting for signal..."

# Run indefinitely until signal received
while true; do
    sleep 1
done
"#,
    );

    // Start the process
    env.cmd()
        .args(["start", script.to_str().unwrap(), "--name", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Verify it's running
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name))
        .stdout(predicate::str::contains("online"));

    // Stop gracefully
    env.cmd()
        .args(["stop", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("Stopped"));

    // Clean up
    env.cmd().args(["delete", &process_name]).assert().success();
}

#[test]
#[cfg(not(windows))]
fn test_resource_monitoring() {
    let env = E2ETestEnvironment::new();
    let process_name = env.unique_name("monitor-app");

    // Create a script that uses some resources
    let script = create_script(
        env.temp_path(),
        "resource_app",
        r#"#!/bin/bash
echo "Resource-intensive process starting..."

# Simulate some CPU and memory usage
for i in {1..5}; do
    echo "Working... iteration $i"
    # Create some temporary data
    data=$(seq 1 1000)
    sleep 1
done

echo "Resource process completed"
"#,
    );

    // Start the process
    env.cmd()
        .args(["start", script.to_str().unwrap(), "--name", &process_name])
        .assert()
        .success()
        .stdout(predicate::str::contains("started"));

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

    // Check monitoring data is available
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains(&process_name));

    // Clean up
    env.cmd().args(["delete", &process_name]).assert().success();
}