pub struct SandboxBuilder { /* private fields */ }Expand description
Builder pattern for sandbox creation
Implementations§
Source§impl SandboxBuilder
impl SandboxBuilder
Sourcepub fn new(id: &str) -> Self
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
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 17)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}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 let mut final_exit_code = result.exit_code;
31 let mut final_signal = result.signal;
32
33 for chunk in stream.into_iter() {
34 match chunk {
35 StreamChunk::Stdout(line) => {
36 println!("[STDOUT] {}", line);
37 }
38 StreamChunk::Stderr(line) => {
39 eprintln!("[STDERR] {}", line);
40 }
41 StreamChunk::Exit { exit_code, signal } => {
42 println!("\nProcess exited with code: {}", exit_code);
43 if let Some(sig) = signal {
44 println!("Killed by signal: {}", sig);
45 }
46 final_exit_code = exit_code;
47 final_signal = signal;
48 }
49 }
50 }
51
52 // Update result with the actual exit code from streaming
53 let mut result = result;
54 result.exit_code = final_exit_code;
55 result.signal = final_signal;
56
57 println!("\nExecution stats:");
58 println!(" Exit code: {}", result.exit_code);
59 println!(" Wall time: {} ms", result.wall_time_ms);
60 println!(" Memory peak: {} bytes", result.memory_peak);
61
62 // Check for seccomp errors and return error if found
63 result.check_seccomp_error()?;
64
65 Ok(())
66}examples/stream_non_blocking.rs (line 17)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("non-blocking-example")
18 .memory_limit_str("256M")?
19 .cpu_limit_percent(50)
20 .seccomp_profile(SeccompProfile::Unrestricted)
21 .root(tmp.path())
22 .build()?;
23
24 println!("Running process with non-blocking stream reads...\n");
25
26 // Run a process that outputs slowly
27 let (result, stream) = sandbox.run_with_stream(
28 "/bin/bash",
29 &[
30 "-c",
31 "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
32 ],
33 )?;
34
35 println!("Non-blocking polling:");
36
37 let mut received_chunks = 0;
38 let mut polling_attempts = 0;
39 let mut final_exit_code = result.exit_code;
40
41 loop {
42 polling_attempts += 1;
43
44 // Try to read without blocking
45 match stream.try_recv()? {
46 Some(chunk) => match chunk {
47 StreamChunk::Stdout(line) => {
48 println!("[STDOUT] {}", line);
49 received_chunks += 1;
50 }
51 StreamChunk::Stderr(line) => {
52 eprintln!("[STDERR] {}", line);
53 received_chunks += 1;
54 }
55 StreamChunk::Exit {
56 exit_code,
57 signal: _,
58 } => {
59 println!("Process exited with code: {}", exit_code);
60 // Capture the real exit code from the stream
61 final_exit_code = exit_code;
62 break;
63 }
64 },
65 None => {
66 // No data available right now, we could do other work here
67 std::thread::sleep(Duration::from_millis(10));
68 }
69 }
70
71 // Safety limit to prevent infinite loop in case of issues
72 if polling_attempts > 10000 {
73 println!("Safety timeout reached");
74 break;
75 }
76 }
77
78 // Update result with the actual exit code from streaming
79 let mut result = result;
80 result.exit_code = final_exit_code;
81
82 println!("\nStatistics:");
83 println!(" Chunks received: {}", received_chunks);
84 println!(" Polling attempts: {}", polling_attempts);
85 println!(" Exit code: {}", result.exit_code);
86 println!(" Wall time: {} ms", result.wall_time_ms);
87
88 // Check for seccomp errors and return error if found
89 result.check_seccomp_error()?;
90
91 Ok(())
92}Sourcepub fn memory_limit(self, bytes: u64) -> Self
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
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}Sourcepub fn memory_limit_str(self, s: &str) -> Result<Self>
pub fn memory_limit_str(self, s: &str) -> Result<Self>
Set memory limit from string (e.g., “100M”)
Examples found in repository?
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}More examples
examples/stream_long_running.rs (line 18)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}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 let mut final_exit_code = result.exit_code;
31 let mut final_signal = result.signal;
32
33 for chunk in stream.into_iter() {
34 match chunk {
35 StreamChunk::Stdout(line) => {
36 println!("[STDOUT] {}", line);
37 }
38 StreamChunk::Stderr(line) => {
39 eprintln!("[STDERR] {}", line);
40 }
41 StreamChunk::Exit { exit_code, signal } => {
42 println!("\nProcess exited with code: {}", exit_code);
43 if let Some(sig) = signal {
44 println!("Killed by signal: {}", sig);
45 }
46 final_exit_code = exit_code;
47 final_signal = signal;
48 }
49 }
50 }
51
52 // Update result with the actual exit code from streaming
53 let mut result = result;
54 result.exit_code = final_exit_code;
55 result.signal = final_signal;
56
57 println!("\nExecution stats:");
58 println!(" Exit code: {}", result.exit_code);
59 println!(" Wall time: {} ms", result.wall_time_ms);
60 println!(" Memory peak: {} bytes", result.memory_peak);
61
62 // Check for seccomp errors and return error if found
63 result.check_seccomp_error()?;
64
65 Ok(())
66}examples/stream_non_blocking.rs (line 18)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("non-blocking-example")
18 .memory_limit_str("256M")?
19 .cpu_limit_percent(50)
20 .seccomp_profile(SeccompProfile::Unrestricted)
21 .root(tmp.path())
22 .build()?;
23
24 println!("Running process with non-blocking stream reads...\n");
25
26 // Run a process that outputs slowly
27 let (result, stream) = sandbox.run_with_stream(
28 "/bin/bash",
29 &[
30 "-c",
31 "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
32 ],
33 )?;
34
35 println!("Non-blocking polling:");
36
37 let mut received_chunks = 0;
38 let mut polling_attempts = 0;
39 let mut final_exit_code = result.exit_code;
40
41 loop {
42 polling_attempts += 1;
43
44 // Try to read without blocking
45 match stream.try_recv()? {
46 Some(chunk) => match chunk {
47 StreamChunk::Stdout(line) => {
48 println!("[STDOUT] {}", line);
49 received_chunks += 1;
50 }
51 StreamChunk::Stderr(line) => {
52 eprintln!("[STDERR] {}", line);
53 received_chunks += 1;
54 }
55 StreamChunk::Exit {
56 exit_code,
57 signal: _,
58 } => {
59 println!("Process exited with code: {}", exit_code);
60 // Capture the real exit code from the stream
61 final_exit_code = exit_code;
62 break;
63 }
64 },
65 None => {
66 // No data available right now, we could do other work here
67 std::thread::sleep(Duration::from_millis(10));
68 }
69 }
70
71 // Safety limit to prevent infinite loop in case of issues
72 if polling_attempts > 10000 {
73 println!("Safety timeout reached");
74 break;
75 }
76 }
77
78 // Update result with the actual exit code from streaming
79 let mut result = result;
80 result.exit_code = final_exit_code;
81
82 println!("\nStatistics:");
83 println!(" Chunks received: {}", received_chunks);
84 println!(" Polling attempts: {}", polling_attempts);
85 println!(" Exit code: {}", result.exit_code);
86 println!(" Wall time: {} ms", result.wall_time_ms);
87
88 // Check for seccomp errors and return error if found
89 result.check_seccomp_error()?;
90
91 Ok(())
92}Sourcepub fn cpu_limit_percent(self, percent: u32) -> Self
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
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 19)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}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 let mut final_exit_code = result.exit_code;
31 let mut final_signal = result.signal;
32
33 for chunk in stream.into_iter() {
34 match chunk {
35 StreamChunk::Stdout(line) => {
36 println!("[STDOUT] {}", line);
37 }
38 StreamChunk::Stderr(line) => {
39 eprintln!("[STDERR] {}", line);
40 }
41 StreamChunk::Exit { exit_code, signal } => {
42 println!("\nProcess exited with code: {}", exit_code);
43 if let Some(sig) = signal {
44 println!("Killed by signal: {}", sig);
45 }
46 final_exit_code = exit_code;
47 final_signal = signal;
48 }
49 }
50 }
51
52 // Update result with the actual exit code from streaming
53 let mut result = result;
54 result.exit_code = final_exit_code;
55 result.signal = final_signal;
56
57 println!("\nExecution stats:");
58 println!(" Exit code: {}", result.exit_code);
59 println!(" Wall time: {} ms", result.wall_time_ms);
60 println!(" Memory peak: {} bytes", result.memory_peak);
61
62 // Check for seccomp errors and return error if found
63 result.check_seccomp_error()?;
64
65 Ok(())
66}examples/stream_non_blocking.rs (line 19)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("non-blocking-example")
18 .memory_limit_str("256M")?
19 .cpu_limit_percent(50)
20 .seccomp_profile(SeccompProfile::Unrestricted)
21 .root(tmp.path())
22 .build()?;
23
24 println!("Running process with non-blocking stream reads...\n");
25
26 // Run a process that outputs slowly
27 let (result, stream) = sandbox.run_with_stream(
28 "/bin/bash",
29 &[
30 "-c",
31 "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
32 ],
33 )?;
34
35 println!("Non-blocking polling:");
36
37 let mut received_chunks = 0;
38 let mut polling_attempts = 0;
39 let mut final_exit_code = result.exit_code;
40
41 loop {
42 polling_attempts += 1;
43
44 // Try to read without blocking
45 match stream.try_recv()? {
46 Some(chunk) => match chunk {
47 StreamChunk::Stdout(line) => {
48 println!("[STDOUT] {}", line);
49 received_chunks += 1;
50 }
51 StreamChunk::Stderr(line) => {
52 eprintln!("[STDERR] {}", line);
53 received_chunks += 1;
54 }
55 StreamChunk::Exit {
56 exit_code,
57 signal: _,
58 } => {
59 println!("Process exited with code: {}", exit_code);
60 // Capture the real exit code from the stream
61 final_exit_code = exit_code;
62 break;
63 }
64 },
65 None => {
66 // No data available right now, we could do other work here
67 std::thread::sleep(Duration::from_millis(10));
68 }
69 }
70
71 // Safety limit to prevent infinite loop in case of issues
72 if polling_attempts > 10000 {
73 println!("Safety timeout reached");
74 break;
75 }
76 }
77
78 // Update result with the actual exit code from streaming
79 let mut result = result;
80 result.exit_code = final_exit_code;
81
82 println!("\nStatistics:");
83 println!(" Chunks received: {}", received_chunks);
84 println!(" Polling attempts: {}", polling_attempts);
85 println!(" Exit code: {}", result.exit_code);
86 println!(" Wall time: {} ms", result.wall_time_ms);
87
88 // Check for seccomp errors and return error if found
89 result.check_seccomp_error()?;
90
91 Ok(())
92}Sourcepub fn max_pids(self, max: u32) -> Self
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}Sourcepub fn seccomp_profile(self, profile: SeccompProfile) -> Self
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
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}examples/stream_long_running.rs (line 21)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}examples/stream_non_blocking.rs (line 20)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("non-blocking-example")
18 .memory_limit_str("256M")?
19 .cpu_limit_percent(50)
20 .seccomp_profile(SeccompProfile::Unrestricted)
21 .root(tmp.path())
22 .build()?;
23
24 println!("Running process with non-blocking stream reads...\n");
25
26 // Run a process that outputs slowly
27 let (result, stream) = sandbox.run_with_stream(
28 "/bin/bash",
29 &[
30 "-c",
31 "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
32 ],
33 )?;
34
35 println!("Non-blocking polling:");
36
37 let mut received_chunks = 0;
38 let mut polling_attempts = 0;
39 let mut final_exit_code = result.exit_code;
40
41 loop {
42 polling_attempts += 1;
43
44 // Try to read without blocking
45 match stream.try_recv()? {
46 Some(chunk) => match chunk {
47 StreamChunk::Stdout(line) => {
48 println!("[STDOUT] {}", line);
49 received_chunks += 1;
50 }
51 StreamChunk::Stderr(line) => {
52 eprintln!("[STDERR] {}", line);
53 received_chunks += 1;
54 }
55 StreamChunk::Exit {
56 exit_code,
57 signal: _,
58 } => {
59 println!("Process exited with code: {}", exit_code);
60 // Capture the real exit code from the stream
61 final_exit_code = exit_code;
62 break;
63 }
64 },
65 None => {
66 // No data available right now, we could do other work here
67 std::thread::sleep(Duration::from_millis(10));
68 }
69 }
70
71 // Safety limit to prevent infinite loop in case of issues
72 if polling_attempts > 10000 {
73 println!("Safety timeout reached");
74 break;
75 }
76 }
77
78 // Update result with the actual exit code from streaming
79 let mut result = result;
80 result.exit_code = final_exit_code;
81
82 println!("\nStatistics:");
83 println!(" Chunks received: {}", received_chunks);
84 println!(" Polling attempts: {}", polling_attempts);
85 println!(" Exit code: {}", result.exit_code);
86 println!(" Wall time: {} ms", result.wall_time_ms);
87
88 // Check for seccomp errors and return error if found
89 result.check_seccomp_error()?;
90
91 Ok(())
92}Sourcepub fn root(self, path: impl AsRef<Path>) -> Self
pub fn root(self, path: impl AsRef<Path>) -> Self
Set root directory
Examples found in repository?
examples/stream_long_running.rs (line 22)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}More examples
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 let mut final_exit_code = result.exit_code;
31 let mut final_signal = result.signal;
32
33 for chunk in stream.into_iter() {
34 match chunk {
35 StreamChunk::Stdout(line) => {
36 println!("[STDOUT] {}", line);
37 }
38 StreamChunk::Stderr(line) => {
39 eprintln!("[STDERR] {}", line);
40 }
41 StreamChunk::Exit { exit_code, signal } => {
42 println!("\nProcess exited with code: {}", exit_code);
43 if let Some(sig) = signal {
44 println!("Killed by signal: {}", sig);
45 }
46 final_exit_code = exit_code;
47 final_signal = signal;
48 }
49 }
50 }
51
52 // Update result with the actual exit code from streaming
53 let mut result = result;
54 result.exit_code = final_exit_code;
55 result.signal = final_signal;
56
57 println!("\nExecution stats:");
58 println!(" Exit code: {}", result.exit_code);
59 println!(" Wall time: {} ms", result.wall_time_ms);
60 println!(" Memory peak: {} bytes", result.memory_peak);
61
62 // Check for seccomp errors and return error if found
63 result.check_seccomp_error()?;
64
65 Ok(())
66}examples/stream_non_blocking.rs (line 21)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("non-blocking-example")
18 .memory_limit_str("256M")?
19 .cpu_limit_percent(50)
20 .seccomp_profile(SeccompProfile::Unrestricted)
21 .root(tmp.path())
22 .build()?;
23
24 println!("Running process with non-blocking stream reads...\n");
25
26 // Run a process that outputs slowly
27 let (result, stream) = sandbox.run_with_stream(
28 "/bin/bash",
29 &[
30 "-c",
31 "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
32 ],
33 )?;
34
35 println!("Non-blocking polling:");
36
37 let mut received_chunks = 0;
38 let mut polling_attempts = 0;
39 let mut final_exit_code = result.exit_code;
40
41 loop {
42 polling_attempts += 1;
43
44 // Try to read without blocking
45 match stream.try_recv()? {
46 Some(chunk) => match chunk {
47 StreamChunk::Stdout(line) => {
48 println!("[STDOUT] {}", line);
49 received_chunks += 1;
50 }
51 StreamChunk::Stderr(line) => {
52 eprintln!("[STDERR] {}", line);
53 received_chunks += 1;
54 }
55 StreamChunk::Exit {
56 exit_code,
57 signal: _,
58 } => {
59 println!("Process exited with code: {}", exit_code);
60 // Capture the real exit code from the stream
61 final_exit_code = exit_code;
62 break;
63 }
64 },
65 None => {
66 // No data available right now, we could do other work here
67 std::thread::sleep(Duration::from_millis(10));
68 }
69 }
70
71 // Safety limit to prevent infinite loop in case of issues
72 if polling_attempts > 10000 {
73 println!("Safety timeout reached");
74 break;
75 }
76 }
77
78 // Update result with the actual exit code from streaming
79 let mut result = result;
80 result.exit_code = final_exit_code;
81
82 println!("\nStatistics:");
83 println!(" Chunks received: {}", received_chunks);
84 println!(" Polling attempts: {}", polling_attempts);
85 println!(" Exit code: {}", result.exit_code);
86 println!(" Wall time: {} ms", result.wall_time_ms);
87
88 // Check for seccomp errors and return error if found
89 result.check_seccomp_error()?;
90
91 Ok(())
92}Sourcepub fn timeout(self, duration: Duration) -> Self
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
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 20)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}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 let mut final_exit_code = result.exit_code;
31 let mut final_signal = result.signal;
32
33 for chunk in stream.into_iter() {
34 match chunk {
35 StreamChunk::Stdout(line) => {
36 println!("[STDOUT] {}", line);
37 }
38 StreamChunk::Stderr(line) => {
39 eprintln!("[STDERR] {}", line);
40 }
41 StreamChunk::Exit { exit_code, signal } => {
42 println!("\nProcess exited with code: {}", exit_code);
43 if let Some(sig) = signal {
44 println!("Killed by signal: {}", sig);
45 }
46 final_exit_code = exit_code;
47 final_signal = signal;
48 }
49 }
50 }
51
52 // Update result with the actual exit code from streaming
53 let mut result = result;
54 result.exit_code = final_exit_code;
55 result.signal = final_signal;
56
57 println!("\nExecution stats:");
58 println!(" Exit code: {}", result.exit_code);
59 println!(" Wall time: {} ms", result.wall_time_ms);
60 println!(" Memory peak: {} bytes", result.memory_peak);
61
62 // Check for seccomp errors and return error if found
63 result.check_seccomp_error()?;
64
65 Ok(())
66}Sourcepub fn namespaces(self, config: NamespaceConfig) -> Self
pub fn namespaces(self, config: NamespaceConfig) -> Self
Set namespace configuration
Sourcepub fn build(self) -> Result<Sandbox>
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
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 23)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("long-running-example")
18 .memory_limit_str("512M")?
19 .cpu_limit_percent(100)
20 .timeout(Duration::from_secs(30))
21 .seccomp_profile(SeccompProfile::Unrestricted)
22 .root(tmp.path())
23 .build()?;
24
25 println!("Running bash script with streaming output...\n");
26
27 // Run a bash script that outputs multiple lines
28 let (result, stream) = sandbox.run_with_stream(
29 "/bin/bash",
30 &[
31 "-c",
32 "for i in {1..5}; do echo \"Line $i from stdout\"; echo \"Error line $i\" >&2; done",
33 ],
34 )?;
35
36 println!("Streaming output:");
37
38 let mut stdout_count = 0;
39 let mut stderr_count = 0;
40 let mut final_exit_code = result.exit_code;
41
42 for chunk in stream.into_iter() {
43 match chunk {
44 StreamChunk::Stdout(line) => {
45 stdout_count += 1;
46 println!(" [OUT #{}] {}", stdout_count, line);
47 }
48 StreamChunk::Stderr(line) => {
49 stderr_count += 1;
50 eprintln!(" [ERR #{}] {}", stderr_count, line);
51 }
52 StreamChunk::Exit {
53 exit_code,
54 signal: _,
55 } => {
56 println!("Process finished with exit code: {}", exit_code);
57 final_exit_code = exit_code;
58 }
59 }
60 }
61
62 let mut result = result;
63 result.exit_code = final_exit_code;
64
65 println!("\nSummary:");
66 println!(" Stdout lines: {}", stdout_count);
67 println!(" Stderr lines: {}", stderr_count);
68 println!(" Wall time: {} ms", result.wall_time_ms);
69 println!(" Exit code: {}", result.exit_code);
70
71 result.check_seccomp_error()?;
72
73 Ok(())
74}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 let mut final_exit_code = result.exit_code;
31 let mut final_signal = result.signal;
32
33 for chunk in stream.into_iter() {
34 match chunk {
35 StreamChunk::Stdout(line) => {
36 println!("[STDOUT] {}", line);
37 }
38 StreamChunk::Stderr(line) => {
39 eprintln!("[STDERR] {}", line);
40 }
41 StreamChunk::Exit { exit_code, signal } => {
42 println!("\nProcess exited with code: {}", exit_code);
43 if let Some(sig) = signal {
44 println!("Killed by signal: {}", sig);
45 }
46 final_exit_code = exit_code;
47 final_signal = signal;
48 }
49 }
50 }
51
52 // Update result with the actual exit code from streaming
53 let mut result = result;
54 result.exit_code = final_exit_code;
55 result.signal = final_signal;
56
57 println!("\nExecution stats:");
58 println!(" Exit code: {}", result.exit_code);
59 println!(" Wall time: {} ms", result.wall_time_ms);
60 println!(" Memory peak: {} bytes", result.memory_peak);
61
62 // Check for seccomp errors and return error if found
63 result.check_seccomp_error()?;
64
65 Ok(())
66}examples/stream_non_blocking.rs (line 22)
14fn main() -> sandbox_rs::Result<()> {
15 let tmp = tempdir().expect("Failed to create temp dir");
16
17 let mut sandbox = SandboxBuilder::new("non-blocking-example")
18 .memory_limit_str("256M")?
19 .cpu_limit_percent(50)
20 .seccomp_profile(SeccompProfile::Unrestricted)
21 .root(tmp.path())
22 .build()?;
23
24 println!("Running process with non-blocking stream reads...\n");
25
26 // Run a process that outputs slowly
27 let (result, stream) = sandbox.run_with_stream(
28 "/bin/bash",
29 &[
30 "-c",
31 "for i in {1..3}; do echo \"Message $i\"; sleep 0.1; done",
32 ],
33 )?;
34
35 println!("Non-blocking polling:");
36
37 let mut received_chunks = 0;
38 let mut polling_attempts = 0;
39 let mut final_exit_code = result.exit_code;
40
41 loop {
42 polling_attempts += 1;
43
44 // Try to read without blocking
45 match stream.try_recv()? {
46 Some(chunk) => match chunk {
47 StreamChunk::Stdout(line) => {
48 println!("[STDOUT] {}", line);
49 received_chunks += 1;
50 }
51 StreamChunk::Stderr(line) => {
52 eprintln!("[STDERR] {}", line);
53 received_chunks += 1;
54 }
55 StreamChunk::Exit {
56 exit_code,
57 signal: _,
58 } => {
59 println!("Process exited with code: {}", exit_code);
60 // Capture the real exit code from the stream
61 final_exit_code = exit_code;
62 break;
63 }
64 },
65 None => {
66 // No data available right now, we could do other work here
67 std::thread::sleep(Duration::from_millis(10));
68 }
69 }
70
71 // Safety limit to prevent infinite loop in case of issues
72 if polling_attempts > 10000 {
73 println!("Safety timeout reached");
74 break;
75 }
76 }
77
78 // Update result with the actual exit code from streaming
79 let mut result = result;
80 result.exit_code = final_exit_code;
81
82 println!("\nStatistics:");
83 println!(" Chunks received: {}", received_chunks);
84 println!(" Polling attempts: {}", polling_attempts);
85 println!(" Exit code: {}", result.exit_code);
86 println!(" Wall time: {} ms", result.wall_time_ms);
87
88 // Check for seccomp errors and return error if found
89 result.check_seccomp_error()?;
90
91 Ok(())
92}Auto Trait Implementations§
impl Freeze for SandboxBuilder
impl RefUnwindSafe for SandboxBuilder
impl Send for SandboxBuilder
impl Sync for SandboxBuilder
impl Unpin for SandboxBuilder
impl UnwindSafe for SandboxBuilder
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more