SandboxBuilder

Struct SandboxBuilder 

Source
pub struct SandboxBuilder { /* private fields */ }
Expand description

Builder pattern for sandbox creation

Implementations§

Source§

impl SandboxBuilder

Source

pub fn new(id: &str) -> Self

Create new builder

Examples found in repository?
examples/basic.rs (line 11)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Basic Example ===\n");
8
9    // Create a sandbox with basic configuration
10    println!("[1] Creating sandbox with memory limit...");
11    let mut sandbox = SandboxBuilder::new("example-1")
12        .memory_limit(50 * 1024 * 1024) // 50MB
13        .cpu_limit_percent(50) // 50% of one CPU
14        .timeout(Duration::from_secs(5))
15        .seccomp_profile(SeccompProfile::Minimal)
16        .build()?;
17
18    println!("[*] Sandbox created: {}", sandbox.id());
19    println!("[*] Root: {}", sandbox.root().display());
20    println!(
21        "[*] Status: {}\n",
22        if sandbox.is_running() {
23            "running"
24        } else {
25            "idle"
26        }
27    );
28
29    // Try to run a simple command
30    println!("[2] Running 'echo hello' in sandbox...");
31    let result = sandbox.run("/bin/echo", &["hello", "world"])?;
32
33    println!("[*] Execution result:");
34    println!("Exit code: {}", result.exit_code);
35    println!("Wall time: {} ms", result.wall_time_ms);
36    println!("Memory peak: {} bytes", result.memory_peak);
37    println!("CPU time: {} μs", result.cpu_time_us);
38    println!("Timed out: {}\n", result.timed_out);
39
40    Ok(())
41}
More examples
Hide additional examples
examples/stream_basic.rs (line 15)
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    for chunk in stream.into_iter() {
31        match chunk {
32            StreamChunk::Stdout(line) => {
33                println!("[STDOUT] {}", line);
34            }
35            StreamChunk::Stderr(line) => {
36                eprintln!("[STDERR] {}", line);
37            }
38            StreamChunk::Exit { exit_code, signal } => {
39                println!("\nProcess exited with code: {}", exit_code);
40                if let Some(sig) = signal {
41                    println!("Killed by signal: {}", sig);
42                }
43            }
44        }
45    }
46
47    println!("\nExecution stats:");
48    println!("  Exit code: {}", result.exit_code);
49    println!("  Wall time: {} ms", result.wall_time_ms);
50    println!("  Memory peak: {} bytes", result.memory_peak);
51
52    Ok(())
53}
examples/cgroup_limits.rs (line 11)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
examples/stream_long_running.rs (line 13)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("long-running-example")
14        .memory_limit_str("512M")?
15        .cpu_limit_percent(100)
16        .timeout(Duration::from_secs(30))
17        .root(tmp.path())
18        .build()?;
19
20    println!("Running bash script with streaming output...\n");
21
22    // Run a bash script that outputs multiple lines
23    let (result, stream) = sandbox.run_with_stream(
24        "/bin/bash",
25        &[
26            "-c",
27            "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
28        ],
29    )?;
30
31    println!("Streaming output:");
32
33    let mut stdout_count = 0;
34    let mut stderr_count = 0;
35
36    for chunk in stream.into_iter() {
37        match chunk {
38            StreamChunk::Stdout(line) => {
39                stdout_count += 1;
40                println!("  [OUT #{}] {}", stdout_count, line);
41            }
42            StreamChunk::Stderr(line) => {
43                stderr_count += 1;
44                eprintln!("  [ERR #{}] {}", stderr_count, line);
45            }
46            StreamChunk::Exit {
47                exit_code,
48                signal: _,
49            } => {
50                println!("Process finished with exit code: {}", exit_code);
51            }
52        }
53    }
54
55    println!("\nSummary:");
56    println!("  Stdout lines: {}", stdout_count);
57    println!("  Stderr lines: {}", stderr_count);
58    println!("  Wall time: {} ms", result.wall_time_ms);
59
60    Ok(())
61}
examples/stream_non_blocking.rs (line 13)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("non-blocking-example")
14        .memory_limit_str("256M")?
15        .cpu_limit_percent(50)
16        .root(tmp.path())
17        .build()?;
18
19    println!("Running process with non-blocking stream reads...\n");
20
21    // Run a process that outputs slowly
22    let (result, stream) = sandbox.run_with_stream(
23        "/bin/bash",
24        &[
25            "-c",
26            "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
27        ],
28    )?;
29
30    println!("Non-blocking polling:");
31
32    let mut received_chunks = 0;
33    let mut polling_attempts = 0;
34
35    loop {
36        polling_attempts += 1;
37
38        // Try to read without blocking
39        match stream.try_recv()? {
40            Some(chunk) => match chunk {
41                StreamChunk::Stdout(line) => {
42                    println!("[STDOUT] {}", line);
43                    received_chunks += 1;
44                }
45                StreamChunk::Stderr(line) => {
46                    eprintln!("[STDERR] {}", line);
47                    received_chunks += 1;
48                }
49                StreamChunk::Exit {
50                    exit_code,
51                    signal: _,
52                } => {
53                    println!("Process exited with code: {}", exit_code);
54                    break;
55                }
56            },
57            None => {
58                // No data available right now, we could do other work here
59                std::thread::sleep(Duration::from_millis(10));
60            }
61        }
62
63        // Safety limit to prevent infinite loop in case of issues
64        if polling_attempts > 10000 {
65            println!("Safety timeout reached");
66            break;
67        }
68    }
69
70    println!("\nStatistics:");
71    println!("  Chunks received: {}", received_chunks);
72    println!("  Polling attempts: {}", polling_attempts);
73    println!("  Exit code: {}", result.exit_code);
74    println!("  Wall time: {} ms", result.wall_time_ms);
75
76    Ok(())
77}
Source

pub fn memory_limit(self, bytes: u64) -> Self

Set memory limit

Examples found in repository?
examples/basic.rs (line 12)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Basic Example ===\n");
8
9    // Create a sandbox with basic configuration
10    println!("[1] Creating sandbox with memory limit...");
11    let mut sandbox = SandboxBuilder::new("example-1")
12        .memory_limit(50 * 1024 * 1024) // 50MB
13        .cpu_limit_percent(50) // 50% of one CPU
14        .timeout(Duration::from_secs(5))
15        .seccomp_profile(SeccompProfile::Minimal)
16        .build()?;
17
18    println!("[*] Sandbox created: {}", sandbox.id());
19    println!("[*] Root: {}", sandbox.root().display());
20    println!(
21        "[*] Status: {}\n",
22        if sandbox.is_running() {
23            "running"
24        } else {
25            "idle"
26        }
27    );
28
29    // Try to run a simple command
30    println!("[2] Running 'echo hello' in sandbox...");
31    let result = sandbox.run("/bin/echo", &["hello", "world"])?;
32
33    println!("[*] Execution result:");
34    println!("Exit code: {}", result.exit_code);
35    println!("Wall time: {} ms", result.wall_time_ms);
36    println!("Memory peak: {} bytes", result.memory_peak);
37    println!("CPU time: {} μs", result.cpu_time_us);
38    println!("Timed out: {}\n", result.timed_out);
39
40    Ok(())
41}
More examples
Hide additional examples
examples/cgroup_limits.rs (line 22)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
Source

pub fn memory_limit_str(self, s: &str) -> Result<Self>

Set memory limit from string (e.g., “100M”)

Examples found in repository?
examples/stream_basic.rs (line 16)
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    for chunk in stream.into_iter() {
31        match chunk {
32            StreamChunk::Stdout(line) => {
33                println!("[STDOUT] {}", line);
34            }
35            StreamChunk::Stderr(line) => {
36                eprintln!("[STDERR] {}", line);
37            }
38            StreamChunk::Exit { exit_code, signal } => {
39                println!("\nProcess exited with code: {}", exit_code);
40                if let Some(sig) = signal {
41                    println!("Killed by signal: {}", sig);
42                }
43            }
44        }
45    }
46
47    println!("\nExecution stats:");
48    println!("  Exit code: {}", result.exit_code);
49    println!("  Wall time: {} ms", result.wall_time_ms);
50    println!("  Memory peak: {} bytes", result.memory_peak);
51
52    Ok(())
53}
More examples
Hide additional examples
examples/cgroup_limits.rs (line 12)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
examples/stream_long_running.rs (line 14)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("long-running-example")
14        .memory_limit_str("512M")?
15        .cpu_limit_percent(100)
16        .timeout(Duration::from_secs(30))
17        .root(tmp.path())
18        .build()?;
19
20    println!("Running bash script with streaming output...\n");
21
22    // Run a bash script that outputs multiple lines
23    let (result, stream) = sandbox.run_with_stream(
24        "/bin/bash",
25        &[
26            "-c",
27            "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
28        ],
29    )?;
30
31    println!("Streaming output:");
32
33    let mut stdout_count = 0;
34    let mut stderr_count = 0;
35
36    for chunk in stream.into_iter() {
37        match chunk {
38            StreamChunk::Stdout(line) => {
39                stdout_count += 1;
40                println!("  [OUT #{}] {}", stdout_count, line);
41            }
42            StreamChunk::Stderr(line) => {
43                stderr_count += 1;
44                eprintln!("  [ERR #{}] {}", stderr_count, line);
45            }
46            StreamChunk::Exit {
47                exit_code,
48                signal: _,
49            } => {
50                println!("Process finished with exit code: {}", exit_code);
51            }
52        }
53    }
54
55    println!("\nSummary:");
56    println!("  Stdout lines: {}", stdout_count);
57    println!("  Stderr lines: {}", stderr_count);
58    println!("  Wall time: {} ms", result.wall_time_ms);
59
60    Ok(())
61}
examples/stream_non_blocking.rs (line 14)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("non-blocking-example")
14        .memory_limit_str("256M")?
15        .cpu_limit_percent(50)
16        .root(tmp.path())
17        .build()?;
18
19    println!("Running process with non-blocking stream reads...\n");
20
21    // Run a process that outputs slowly
22    let (result, stream) = sandbox.run_with_stream(
23        "/bin/bash",
24        &[
25            "-c",
26            "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
27        ],
28    )?;
29
30    println!("Non-blocking polling:");
31
32    let mut received_chunks = 0;
33    let mut polling_attempts = 0;
34
35    loop {
36        polling_attempts += 1;
37
38        // Try to read without blocking
39        match stream.try_recv()? {
40            Some(chunk) => match chunk {
41                StreamChunk::Stdout(line) => {
42                    println!("[STDOUT] {}", line);
43                    received_chunks += 1;
44                }
45                StreamChunk::Stderr(line) => {
46                    eprintln!("[STDERR] {}", line);
47                    received_chunks += 1;
48                }
49                StreamChunk::Exit {
50                    exit_code,
51                    signal: _,
52                } => {
53                    println!("Process exited with code: {}", exit_code);
54                    break;
55                }
56            },
57            None => {
58                // No data available right now, we could do other work here
59                std::thread::sleep(Duration::from_millis(10));
60            }
61        }
62
63        // Safety limit to prevent infinite loop in case of issues
64        if polling_attempts > 10000 {
65            println!("Safety timeout reached");
66            break;
67        }
68    }
69
70    println!("\nStatistics:");
71    println!("  Chunks received: {}", received_chunks);
72    println!("  Polling attempts: {}", polling_attempts);
73    println!("  Exit code: {}", result.exit_code);
74    println!("  Wall time: {} ms", result.wall_time_ms);
75
76    Ok(())
77}
Source

pub fn cpu_quota(self, quota: u64, period: u64) -> Self

Set CPU quota

Source

pub fn cpu_limit_percent(self, percent: u32) -> Self

Set CPU limit by percentage (0-100)

Examples found in repository?
examples/basic.rs (line 13)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Basic Example ===\n");
8
9    // Create a sandbox with basic configuration
10    println!("[1] Creating sandbox with memory limit...");
11    let mut sandbox = SandboxBuilder::new("example-1")
12        .memory_limit(50 * 1024 * 1024) // 50MB
13        .cpu_limit_percent(50) // 50% of one CPU
14        .timeout(Duration::from_secs(5))
15        .seccomp_profile(SeccompProfile::Minimal)
16        .build()?;
17
18    println!("[*] Sandbox created: {}", sandbox.id());
19    println!("[*] Root: {}", sandbox.root().display());
20    println!(
21        "[*] Status: {}\n",
22        if sandbox.is_running() {
23            "running"
24        } else {
25            "idle"
26        }
27    );
28
29    // Try to run a simple command
30    println!("[2] Running 'echo hello' in sandbox...");
31    let result = sandbox.run("/bin/echo", &["hello", "world"])?;
32
33    println!("[*] Execution result:");
34    println!("Exit code: {}", result.exit_code);
35    println!("Wall time: {} ms", result.wall_time_ms);
36    println!("Memory peak: {} bytes", result.memory_peak);
37    println!("CPU time: {} μs", result.cpu_time_us);
38    println!("Timed out: {}\n", result.timed_out);
39
40    Ok(())
41}
More examples
Hide additional examples
examples/stream_basic.rs (line 17)
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    for chunk in stream.into_iter() {
31        match chunk {
32            StreamChunk::Stdout(line) => {
33                println!("[STDOUT] {}", line);
34            }
35            StreamChunk::Stderr(line) => {
36                eprintln!("[STDERR] {}", line);
37            }
38            StreamChunk::Exit { exit_code, signal } => {
39                println!("\nProcess exited with code: {}", exit_code);
40                if let Some(sig) = signal {
41                    println!("Killed by signal: {}", sig);
42                }
43            }
44        }
45    }
46
47    println!("\nExecution stats:");
48    println!("  Exit code: {}", result.exit_code);
49    println!("  Wall time: {} ms", result.wall_time_ms);
50    println!("  Memory peak: {} bytes", result.memory_peak);
51
52    Ok(())
53}
examples/cgroup_limits.rs (line 13)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
examples/stream_long_running.rs (line 15)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("long-running-example")
14        .memory_limit_str("512M")?
15        .cpu_limit_percent(100)
16        .timeout(Duration::from_secs(30))
17        .root(tmp.path())
18        .build()?;
19
20    println!("Running bash script with streaming output...\n");
21
22    // Run a bash script that outputs multiple lines
23    let (result, stream) = sandbox.run_with_stream(
24        "/bin/bash",
25        &[
26            "-c",
27            "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
28        ],
29    )?;
30
31    println!("Streaming output:");
32
33    let mut stdout_count = 0;
34    let mut stderr_count = 0;
35
36    for chunk in stream.into_iter() {
37        match chunk {
38            StreamChunk::Stdout(line) => {
39                stdout_count += 1;
40                println!("  [OUT #{}] {}", stdout_count, line);
41            }
42            StreamChunk::Stderr(line) => {
43                stderr_count += 1;
44                eprintln!("  [ERR #{}] {}", stderr_count, line);
45            }
46            StreamChunk::Exit {
47                exit_code,
48                signal: _,
49            } => {
50                println!("Process finished with exit code: {}", exit_code);
51            }
52        }
53    }
54
55    println!("\nSummary:");
56    println!("  Stdout lines: {}", stdout_count);
57    println!("  Stderr lines: {}", stderr_count);
58    println!("  Wall time: {} ms", result.wall_time_ms);
59
60    Ok(())
61}
examples/stream_non_blocking.rs (line 15)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("non-blocking-example")
14        .memory_limit_str("256M")?
15        .cpu_limit_percent(50)
16        .root(tmp.path())
17        .build()?;
18
19    println!("Running process with non-blocking stream reads...\n");
20
21    // Run a process that outputs slowly
22    let (result, stream) = sandbox.run_with_stream(
23        "/bin/bash",
24        &[
25            "-c",
26            "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
27        ],
28    )?;
29
30    println!("Non-blocking polling:");
31
32    let mut received_chunks = 0;
33    let mut polling_attempts = 0;
34
35    loop {
36        polling_attempts += 1;
37
38        // Try to read without blocking
39        match stream.try_recv()? {
40            Some(chunk) => match chunk {
41                StreamChunk::Stdout(line) => {
42                    println!("[STDOUT] {}", line);
43                    received_chunks += 1;
44                }
45                StreamChunk::Stderr(line) => {
46                    eprintln!("[STDERR] {}", line);
47                    received_chunks += 1;
48                }
49                StreamChunk::Exit {
50                    exit_code,
51                    signal: _,
52                } => {
53                    println!("Process exited with code: {}", exit_code);
54                    break;
55                }
56            },
57            None => {
58                // No data available right now, we could do other work here
59                std::thread::sleep(Duration::from_millis(10));
60            }
61        }
62
63        // Safety limit to prevent infinite loop in case of issues
64        if polling_attempts > 10000 {
65            println!("Safety timeout reached");
66            break;
67        }
68    }
69
70    println!("\nStatistics:");
71    println!("  Chunks received: {}", received_chunks);
72    println!("  Polling attempts: {}", polling_attempts);
73    println!("  Exit code: {}", result.exit_code);
74    println!("  Wall time: {} ms", result.wall_time_ms);
75
76    Ok(())
77}
Source

pub fn max_pids(self, max: u32) -> Self

Set maximum PIDs

Examples found in repository?
examples/cgroup_limits.rs (line 33)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
Source

pub fn seccomp_profile(self, profile: SeccompProfile) -> Self

Set seccomp profile

Examples found in repository?
examples/basic.rs (line 15)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Basic Example ===\n");
8
9    // Create a sandbox with basic configuration
10    println!("[1] Creating sandbox with memory limit...");
11    let mut sandbox = SandboxBuilder::new("example-1")
12        .memory_limit(50 * 1024 * 1024) // 50MB
13        .cpu_limit_percent(50) // 50% of one CPU
14        .timeout(Duration::from_secs(5))
15        .seccomp_profile(SeccompProfile::Minimal)
16        .build()?;
17
18    println!("[*] Sandbox created: {}", sandbox.id());
19    println!("[*] Root: {}", sandbox.root().display());
20    println!(
21        "[*] Status: {}\n",
22        if sandbox.is_running() {
23            "running"
24        } else {
25            "idle"
26        }
27    );
28
29    // Try to run a simple command
30    println!("[2] Running 'echo hello' in sandbox...");
31    let result = sandbox.run("/bin/echo", &["hello", "world"])?;
32
33    println!("[*] Execution result:");
34    println!("Exit code: {}", result.exit_code);
35    println!("Wall time: {} ms", result.wall_time_ms);
36    println!("Memory peak: {} bytes", result.memory_peak);
37    println!("CPU time: {} μs", result.cpu_time_us);
38    println!("Timed out: {}\n", result.timed_out);
39
40    Ok(())
41}
More examples
Hide additional examples
examples/cgroup_limits.rs (line 35)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
Source

pub fn root(self, path: impl AsRef<Path>) -> Self

Set root directory

Examples found in repository?
examples/stream_basic.rs (line 19)
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    for chunk in stream.into_iter() {
31        match chunk {
32            StreamChunk::Stdout(line) => {
33                println!("[STDOUT] {}", line);
34            }
35            StreamChunk::Stderr(line) => {
36                eprintln!("[STDERR] {}", line);
37            }
38            StreamChunk::Exit { exit_code, signal } => {
39                println!("\nProcess exited with code: {}", exit_code);
40                if let Some(sig) = signal {
41                    println!("Killed by signal: {}", sig);
42                }
43            }
44        }
45    }
46
47    println!("\nExecution stats:");
48    println!("  Exit code: {}", result.exit_code);
49    println!("  Wall time: {} ms", result.wall_time_ms);
50    println!("  Memory peak: {} bytes", result.memory_peak);
51
52    Ok(())
53}
More examples
Hide additional examples
examples/stream_long_running.rs (line 17)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("long-running-example")
14        .memory_limit_str("512M")?
15        .cpu_limit_percent(100)
16        .timeout(Duration::from_secs(30))
17        .root(tmp.path())
18        .build()?;
19
20    println!("Running bash script with streaming output...\n");
21
22    // Run a bash script that outputs multiple lines
23    let (result, stream) = sandbox.run_with_stream(
24        "/bin/bash",
25        &[
26            "-c",
27            "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
28        ],
29    )?;
30
31    println!("Streaming output:");
32
33    let mut stdout_count = 0;
34    let mut stderr_count = 0;
35
36    for chunk in stream.into_iter() {
37        match chunk {
38            StreamChunk::Stdout(line) => {
39                stdout_count += 1;
40                println!("  [OUT #{}] {}", stdout_count, line);
41            }
42            StreamChunk::Stderr(line) => {
43                stderr_count += 1;
44                eprintln!("  [ERR #{}] {}", stderr_count, line);
45            }
46            StreamChunk::Exit {
47                exit_code,
48                signal: _,
49            } => {
50                println!("Process finished with exit code: {}", exit_code);
51            }
52        }
53    }
54
55    println!("\nSummary:");
56    println!("  Stdout lines: {}", stdout_count);
57    println!("  Stderr lines: {}", stderr_count);
58    println!("  Wall time: {} ms", result.wall_time_ms);
59
60    Ok(())
61}
examples/stream_non_blocking.rs (line 16)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("non-blocking-example")
14        .memory_limit_str("256M")?
15        .cpu_limit_percent(50)
16        .root(tmp.path())
17        .build()?;
18
19    println!("Running process with non-blocking stream reads...\n");
20
21    // Run a process that outputs slowly
22    let (result, stream) = sandbox.run_with_stream(
23        "/bin/bash",
24        &[
25            "-c",
26            "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
27        ],
28    )?;
29
30    println!("Non-blocking polling:");
31
32    let mut received_chunks = 0;
33    let mut polling_attempts = 0;
34
35    loop {
36        polling_attempts += 1;
37
38        // Try to read without blocking
39        match stream.try_recv()? {
40            Some(chunk) => match chunk {
41                StreamChunk::Stdout(line) => {
42                    println!("[STDOUT] {}", line);
43                    received_chunks += 1;
44                }
45                StreamChunk::Stderr(line) => {
46                    eprintln!("[STDERR] {}", line);
47                    received_chunks += 1;
48                }
49                StreamChunk::Exit {
50                    exit_code,
51                    signal: _,
52                } => {
53                    println!("Process exited with code: {}", exit_code);
54                    break;
55                }
56            },
57            None => {
58                // No data available right now, we could do other work here
59                std::thread::sleep(Duration::from_millis(10));
60            }
61        }
62
63        // Safety limit to prevent infinite loop in case of issues
64        if polling_attempts > 10000 {
65            println!("Safety timeout reached");
66            break;
67        }
68    }
69
70    println!("\nStatistics:");
71    println!("  Chunks received: {}", received_chunks);
72    println!("  Polling attempts: {}", polling_attempts);
73    println!("  Exit code: {}", result.exit_code);
74    println!("  Wall time: {} ms", result.wall_time_ms);
75
76    Ok(())
77}
Source

pub fn timeout(self, duration: Duration) -> Self

Set timeout

Examples found in repository?
examples/basic.rs (line 14)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Basic Example ===\n");
8
9    // Create a sandbox with basic configuration
10    println!("[1] Creating sandbox with memory limit...");
11    let mut sandbox = SandboxBuilder::new("example-1")
12        .memory_limit(50 * 1024 * 1024) // 50MB
13        .cpu_limit_percent(50) // 50% of one CPU
14        .timeout(Duration::from_secs(5))
15        .seccomp_profile(SeccompProfile::Minimal)
16        .build()?;
17
18    println!("[*] Sandbox created: {}", sandbox.id());
19    println!("[*] Root: {}", sandbox.root().display());
20    println!(
21        "[*] Status: {}\n",
22        if sandbox.is_running() {
23            "running"
24        } else {
25            "idle"
26        }
27    );
28
29    // Try to run a simple command
30    println!("[2] Running 'echo hello' in sandbox...");
31    let result = sandbox.run("/bin/echo", &["hello", "world"])?;
32
33    println!("[*] Execution result:");
34    println!("Exit code: {}", result.exit_code);
35    println!("Wall time: {} ms", result.wall_time_ms);
36    println!("Memory peak: {} bytes", result.memory_peak);
37    println!("CPU time: {} μs", result.cpu_time_us);
38    println!("Timed out: {}\n", result.timed_out);
39
40    Ok(())
41}
More examples
Hide additional examples
examples/stream_basic.rs (line 18)
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    for chunk in stream.into_iter() {
31        match chunk {
32            StreamChunk::Stdout(line) => {
33                println!("[STDOUT] {}", line);
34            }
35            StreamChunk::Stderr(line) => {
36                eprintln!("[STDERR] {}", line);
37            }
38            StreamChunk::Exit { exit_code, signal } => {
39                println!("\nProcess exited with code: {}", exit_code);
40                if let Some(sig) = signal {
41                    println!("Killed by signal: {}", sig);
42                }
43            }
44        }
45    }
46
47    println!("\nExecution stats:");
48    println!("  Exit code: {}", result.exit_code);
49    println!("  Wall time: {} ms", result.wall_time_ms);
50    println!("  Memory peak: {} bytes", result.memory_peak);
51
52    Ok(())
53}
examples/cgroup_limits.rs (line 23)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
examples/stream_long_running.rs (line 16)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("long-running-example")
14        .memory_limit_str("512M")?
15        .cpu_limit_percent(100)
16        .timeout(Duration::from_secs(30))
17        .root(tmp.path())
18        .build()?;
19
20    println!("Running bash script with streaming output...\n");
21
22    // Run a bash script that outputs multiple lines
23    let (result, stream) = sandbox.run_with_stream(
24        "/bin/bash",
25        &[
26            "-c",
27            "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
28        ],
29    )?;
30
31    println!("Streaming output:");
32
33    let mut stdout_count = 0;
34    let mut stderr_count = 0;
35
36    for chunk in stream.into_iter() {
37        match chunk {
38            StreamChunk::Stdout(line) => {
39                stdout_count += 1;
40                println!("  [OUT #{}] {}", stdout_count, line);
41            }
42            StreamChunk::Stderr(line) => {
43                stderr_count += 1;
44                eprintln!("  [ERR #{}] {}", stderr_count, line);
45            }
46            StreamChunk::Exit {
47                exit_code,
48                signal: _,
49            } => {
50                println!("Process finished with exit code: {}", exit_code);
51            }
52        }
53    }
54
55    println!("\nSummary:");
56    println!("  Stdout lines: {}", stdout_count);
57    println!("  Stderr lines: {}", stderr_count);
58    println!("  Wall time: {} ms", result.wall_time_ms);
59
60    Ok(())
61}
Source

pub fn namespaces(self, config: NamespaceConfig) -> Self

Set namespace configuration

Source

pub fn build(self) -> Result<Sandbox>

Build sandbox

Examples found in repository?
examples/basic.rs (line 16)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Basic Example ===\n");
8
9    // Create a sandbox with basic configuration
10    println!("[1] Creating sandbox with memory limit...");
11    let mut sandbox = SandboxBuilder::new("example-1")
12        .memory_limit(50 * 1024 * 1024) // 50MB
13        .cpu_limit_percent(50) // 50% of one CPU
14        .timeout(Duration::from_secs(5))
15        .seccomp_profile(SeccompProfile::Minimal)
16        .build()?;
17
18    println!("[*] Sandbox created: {}", sandbox.id());
19    println!("[*] Root: {}", sandbox.root().display());
20    println!(
21        "[*] Status: {}\n",
22        if sandbox.is_running() {
23            "running"
24        } else {
25            "idle"
26        }
27    );
28
29    // Try to run a simple command
30    println!("[2] Running 'echo hello' in sandbox...");
31    let result = sandbox.run("/bin/echo", &["hello", "world"])?;
32
33    println!("[*] Execution result:");
34    println!("Exit code: {}", result.exit_code);
35    println!("Wall time: {} ms", result.wall_time_ms);
36    println!("Memory peak: {} bytes", result.memory_peak);
37    println!("CPU time: {} μs", result.cpu_time_us);
38    println!("Timed out: {}\n", result.timed_out);
39
40    Ok(())
41}
More examples
Hide additional examples
examples/stream_basic.rs (line 20)
10fn main() -> sandbox_rs::Result<()> {
11    // Create a temporary directory for the sandbox
12    let tmp = tempdir().expect("Failed to create temp dir");
13
14    // Create a sandbox with streaming enabled
15    let mut sandbox = SandboxBuilder::new("stream-example")
16        .memory_limit_str("256M")?
17        .cpu_limit_percent(50)
18        .timeout(Duration::from_secs(30))
19        .root(tmp.path())
20        .build()?;
21
22    println!("Starting sandboxed process with streaming...\n");
23
24    // Run process with streaming
25    let (result, stream) = sandbox.run_with_stream("/bin/echo", &["Hello from sandbox!"])?;
26
27    println!("Process output (streaming):");
28
29    // Iterate through all output chunks
30    for chunk in stream.into_iter() {
31        match chunk {
32            StreamChunk::Stdout(line) => {
33                println!("[STDOUT] {}", line);
34            }
35            StreamChunk::Stderr(line) => {
36                eprintln!("[STDERR] {}", line);
37            }
38            StreamChunk::Exit { exit_code, signal } => {
39                println!("\nProcess exited with code: {}", exit_code);
40                if let Some(sig) = signal {
41                    println!("Killed by signal: {}", sig);
42                }
43            }
44        }
45    }
46
47    println!("\nExecution stats:");
48    println!("  Exit code: {}", result.exit_code);
49    println!("  Wall time: {} ms", result.wall_time_ms);
50    println!("  Memory peak: {} bytes", result.memory_peak);
51
52    Ok(())
53}
examples/cgroup_limits.rs (line 14)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Sandbox RS - Cgroup Resource Limits ===\n");
8
9    // Example 1: Memory limited sandbox
10    println!("[1] Example: Memory-limited sandbox (100MB)");
11    let sandbox1 = SandboxBuilder::new("mem-limited")
12        .memory_limit_str("100M")?
13        .cpu_limit_percent(100)
14        .build()?;
15    println!("[*] Created: {}", sandbox1.id());
16    println!("[*] Root: {}\n", sandbox1.root().display());
17
18    // Example 2: CPU limited sandbox
19    println!("[2] Example: CPU-limited sandbox (25% of one core)");
20    let sandbox2 = SandboxBuilder::new("cpu-limited")
21        .cpu_limit_percent(25)
22        .memory_limit(512 * 1024 * 1024) // 512MB
23        .timeout(Duration::from_secs(10))
24        .build()?;
25    println!("[*] Created: {}", sandbox2.id());
26    println!("[*] Root: {}\n", sandbox2.root().display());
27
28    // Example 3: Tight limits for untrusted code
29    println!("[3] Example: Tight limits for untrusted code");
30    let sandbox3 = SandboxBuilder::new("untrusted")
31        .memory_limit_str("64M")?
32        .cpu_limit_percent(10)
33        .max_pids(8)
34        .timeout(Duration::from_secs(5))
35        .seccomp_profile(sandbox_rs::SeccompProfile::Minimal)
36        .build()?;
37    println!("[*] Created: {}", sandbox3.id());
38    println!("[*] Root: {}\n", sandbox3.root().display());
39
40    println!("[*] All sandboxes created successfully!");
41    println!("[*] Note: Actual resource enforcement requires root permissions");
42
43    Ok(())
44}
examples/stream_long_running.rs (line 18)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("long-running-example")
14        .memory_limit_str("512M")?
15        .cpu_limit_percent(100)
16        .timeout(Duration::from_secs(30))
17        .root(tmp.path())
18        .build()?;
19
20    println!("Running bash script with streaming output...\n");
21
22    // Run a bash script that outputs multiple lines
23    let (result, stream) = sandbox.run_with_stream(
24        "/bin/bash",
25        &[
26            "-c",
27            "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
28        ],
29    )?;
30
31    println!("Streaming output:");
32
33    let mut stdout_count = 0;
34    let mut stderr_count = 0;
35
36    for chunk in stream.into_iter() {
37        match chunk {
38            StreamChunk::Stdout(line) => {
39                stdout_count += 1;
40                println!("  [OUT #{}] {}", stdout_count, line);
41            }
42            StreamChunk::Stderr(line) => {
43                stderr_count += 1;
44                eprintln!("  [ERR #{}] {}", stderr_count, line);
45            }
46            StreamChunk::Exit {
47                exit_code,
48                signal: _,
49            } => {
50                println!("Process finished with exit code: {}", exit_code);
51            }
52        }
53    }
54
55    println!("\nSummary:");
56    println!("  Stdout lines: {}", stdout_count);
57    println!("  Stderr lines: {}", stderr_count);
58    println!("  Wall time: {} ms", result.wall_time_ms);
59
60    Ok(())
61}
examples/stream_non_blocking.rs (line 17)
10fn main() -> sandbox_rs::Result<()> {
11    let tmp = tempdir().expect("Failed to create temp dir");
12
13    let mut sandbox = SandboxBuilder::new("non-blocking-example")
14        .memory_limit_str("256M")?
15        .cpu_limit_percent(50)
16        .root(tmp.path())
17        .build()?;
18
19    println!("Running process with non-blocking stream reads...\n");
20
21    // Run a process that outputs slowly
22    let (result, stream) = sandbox.run_with_stream(
23        "/bin/bash",
24        &[
25            "-c",
26            "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
27        ],
28    )?;
29
30    println!("Non-blocking polling:");
31
32    let mut received_chunks = 0;
33    let mut polling_attempts = 0;
34
35    loop {
36        polling_attempts += 1;
37
38        // Try to read without blocking
39        match stream.try_recv()? {
40            Some(chunk) => match chunk {
41                StreamChunk::Stdout(line) => {
42                    println!("[STDOUT] {}", line);
43                    received_chunks += 1;
44                }
45                StreamChunk::Stderr(line) => {
46                    eprintln!("[STDERR] {}", line);
47                    received_chunks += 1;
48                }
49                StreamChunk::Exit {
50                    exit_code,
51                    signal: _,
52                } => {
53                    println!("Process exited with code: {}", exit_code);
54                    break;
55                }
56            },
57            None => {
58                // No data available right now, we could do other work here
59                std::thread::sleep(Duration::from_millis(10));
60            }
61        }
62
63        // Safety limit to prevent infinite loop in case of issues
64        if polling_attempts > 10000 {
65            println!("Safety timeout reached");
66            break;
67        }
68    }
69
70    println!("\nStatistics:");
71    println!("  Chunks received: {}", received_chunks);
72    println!("  Polling attempts: {}", polling_attempts);
73    println!("  Exit code: {}", result.exit_code);
74    println!("  Wall time: {} ms", result.wall_time_ms);
75
76    Ok(())
77}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.