pub struct Sandbox { /* private fields */ }Expand description
Active sandbox
Implementations§
Source§impl Sandbox
impl Sandbox
Sourcepub fn id(&self) -> &str
pub fn id(&self) -> &str
Get sandbox ID
Examples found in repository?
examples/basic.rs (line 18)
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 15)
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 root(&self) -> &Path
pub fn root(&self) -> &Path
Get sandbox root
Examples found in repository?
examples/basic.rs (line 19)
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 16)
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 is_running(&self) -> bool
pub fn is_running(&self) -> bool
Check if sandbox is running
Examples found in repository?
examples/basic.rs (line 22)
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}Sourcepub fn run(&mut self, program: &str, args: &[&str]) -> Result<SandboxResult>
pub fn run(&mut self, program: &str, args: &[&str]) -> Result<SandboxResult>
Run program in sandbox
Examples found in repository?
examples/basic.rs (line 31)
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}Sourcepub fn run_with_stream(
&mut self,
program: &str,
args: &[&str],
) -> Result<(SandboxResult, ProcessStream)>
pub fn run_with_stream( &mut self, program: &str, args: &[&str], ) -> Result<(SandboxResult, ProcessStream)>
Run program with streaming output
Examples found in repository?
examples/stream_basic.rs (line 25)
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
examples/stream_long_running.rs (lines 23-29)
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 (lines 22-28)
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}pub fn kill(&mut self) -> Result<()>
Sourcepub fn get_resource_usage(&self) -> Result<(u64, u64)>
pub fn get_resource_usage(&self) -> Result<(u64, u64)>
Get resource usage
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Sandbox
impl RefUnwindSafe for Sandbox
impl Send for Sandbox
impl Sync for Sandbox
impl Unpin for Sandbox
impl UnwindSafe for Sandbox
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