Skip to main content

IsolateSandbox

Struct IsolateSandbox 

Source
pub struct IsolateSandbox {
    pub box_id: u32,
    pub isolate_bin: String,
    pub directory_rules: Vec<DirectoryRule>,
    pub env_rules: Vec<EnvRule>,
    pub stdin_file: Option<String>,
    pub stdout_file: Option<String>,
    pub stderr_file: Option<String>,
    pub stderr_to_stdout: bool,
    pub chdir: Option<String>,
    pub meta_file: Option<PathBuf>,
    pub special_options: SpecialOptions,
}
Expand description

Main isolate sandbox implementation

Fields§

§box_id: u32§isolate_bin: String§directory_rules: Vec<DirectoryRule>§env_rules: Vec<EnvRule>§stdin_file: Option<String>§stdout_file: Option<String>§stderr_file: Option<String>§stderr_to_stdout: bool§chdir: Option<String>§meta_file: Option<PathBuf>§special_options: SpecialOptions

Implementations§

Source§

impl IsolateSandbox

Source

pub fn new(box_id: u32) -> Self

Examples found in repository?
examples/sandbox_usage.rs (line 65)
61async fn basic_example() -> Result<()> {
62    println!("=== Example 1: Basic Command Execution ===");
63
64    // Create a sandbox with box ID 0
65    let sandbox = IsolateSandbox::new(0)
66        .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67        .verbose();
68
69    // Initialize the sandbox
70    let limits = ResourceLimits::new();
71    sandbox.init(&limits).await?;
72
73    // Run a simple echo command
74    let result = sandbox
75        .run("/bin/echo", ["Hello from Isolate Sandbox!"], &limits)
76        .await?;
77
78    println!("Exit code: {:?}", result.exit_code);
79    println!("Output: {}", result.stdout.trim());
80    println!("Time used: {:.3}s", result.time_used);
81    println!("Memory used: {} KB", result.memory_used);
82
83    // Cleanup the sandbox
84    sandbox.cleanup().await?;
85    println!("✓ Basic example completed\n");
86
87    Ok(())
88}
89
90/// Example 2: Using environment variables
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub async fn init(&self, limits: &ResourceLimits) -> Result<()>

Initialize the sandbox

Examples found in repository?
examples/sandbox_usage.rs (line 71)
61async fn basic_example() -> Result<()> {
62    println!("=== Example 1: Basic Command Execution ===");
63
64    // Create a sandbox with box ID 0
65    let sandbox = IsolateSandbox::new(0)
66        .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67        .verbose();
68
69    // Initialize the sandbox
70    let limits = ResourceLimits::new();
71    sandbox.init(&limits).await?;
72
73    // Run a simple echo command
74    let result = sandbox
75        .run("/bin/echo", ["Hello from Isolate Sandbox!"], &limits)
76        .await?;
77
78    println!("Exit code: {:?}", result.exit_code);
79    println!("Output: {}", result.stdout.trim());
80    println!("Time used: {:.3}s", result.time_used);
81    println!("Memory used: {} KB", result.memory_used);
82
83    // Cleanup the sandbox
84    sandbox.cleanup().await?;
85    println!("✓ Basic example completed\n");
86
87    Ok(())
88}
89
90/// Example 2: Using environment variables
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub async fn run<I, S>( &self, program: &str, args: I, limits: &ResourceLimits, ) -> Result<ExecutionResult>
where I: IntoIterator<Item = S>, S: AsRef<str>,

Run a command in the sandbox

Examples found in repository?
examples/sandbox_usage.rs (line 75)
61async fn basic_example() -> Result<()> {
62    println!("=== Example 1: Basic Command Execution ===");
63
64    // Create a sandbox with box ID 0
65    let sandbox = IsolateSandbox::new(0)
66        .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67        .verbose();
68
69    // Initialize the sandbox
70    let limits = ResourceLimits::new();
71    sandbox.init(&limits).await?;
72
73    // Run a simple echo command
74    let result = sandbox
75        .run("/bin/echo", ["Hello from Isolate Sandbox!"], &limits)
76        .await?;
77
78    println!("Exit code: {:?}", result.exit_code);
79    println!("Output: {}", result.stdout.trim());
80    println!("Time used: {:.3}s", result.time_used);
81    println!("Memory used: {} KB", result.memory_used);
82
83    // Cleanup the sandbox
84    sandbox.cleanup().await?;
85    println!("✓ Basic example completed\n");
86
87    Ok(())
88}
89
90/// Example 2: Using environment variables
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub async fn cleanup(&self) -> Result<()>

Cleanup the sandbox

Examples found in repository?
examples/sandbox_usage.rs (line 84)
61async fn basic_example() -> Result<()> {
62    println!("=== Example 1: Basic Command Execution ===");
63
64    // Create a sandbox with box ID 0
65    let sandbox = IsolateSandbox::new(0)
66        .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67        .verbose();
68
69    // Initialize the sandbox
70    let limits = ResourceLimits::new();
71    sandbox.init(&limits).await?;
72
73    // Run a simple echo command
74    let result = sandbox
75        .run("/bin/echo", ["Hello from Isolate Sandbox!"], &limits)
76        .await?;
77
78    println!("Exit code: {:?}", result.exit_code);
79    println!("Output: {}", result.stdout.trim());
80    println!("Time used: {:.3}s", result.time_used);
81    println!("Memory used: {} KB", result.memory_used);
82
83    // Cleanup the sandbox
84    sandbox.cleanup().await?;
85    println!("✓ Basic example completed\n");
86
87    Ok(())
88}
89
90/// Example 2: Using environment variables
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub fn with_directory_rule(self, rule: DirectoryRule) -> Self

The following are builder options.

Examples found in repository?
examples/sandbox_usage.rs (line 140)
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub fn with_env_rule(self, rule: EnvRule) -> Self

Examples found in repository?
examples/sandbox_usage.rs (line 95)
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub fn with_stdin(self, file: impl Into<String>) -> Self

Source

pub fn with_stdout(self, file: impl Into<String>) -> Self

Source

pub fn with_stderr(self, file: impl Into<String>) -> Self

Source

pub fn with_stderr_to_stdout(self) -> Self

Source

pub fn with_chdir(self, dir: impl Into<String>) -> Self

Source

pub fn with_meta_file(self, file: impl Into<PathBuf>) -> Self

Examples found in repository?
examples/sandbox_usage.rs (line 66)
61async fn basic_example() -> Result<()> {
62    println!("=== Example 1: Basic Command Execution ===");
63
64    // Create a sandbox with box ID 0
65    let sandbox = IsolateSandbox::new(0)
66        .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67        .verbose();
68
69    // Initialize the sandbox
70    let limits = ResourceLimits::new();
71    sandbox.init(&limits).await?;
72
73    // Run a simple echo command
74    let result = sandbox
75        .run("/bin/echo", ["Hello from Isolate Sandbox!"], &limits)
76        .await?;
77
78    println!("Exit code: {:?}", result.exit_code);
79    println!("Output: {}", result.stdout.trim());
80    println!("Time used: {:.3}s", result.time_used);
81    println!("Memory used: {} KB", result.memory_used);
82
83    // Cleanup the sandbox
84    sandbox.cleanup().await?;
85    println!("✓ Basic example completed\n");
86
87    Ok(())
88}
89
90/// Example 2: Using environment variables
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}
Source

pub fn with_special_options(self, options: SpecialOptions) -> Self

Source

pub fn use_cgroups(self) -> Self

Source

pub fn disable_cgroups(self) -> Self

Source

pub fn share_network(self) -> Self

Source

pub fn no_default_dirs(self) -> Self

Source

pub fn verbose(self) -> Self

Examples found in repository?
examples/sandbox_usage.rs (line 67)
61async fn basic_example() -> Result<()> {
62    println!("=== Example 1: Basic Command Execution ===");
63
64    // Create a sandbox with box ID 0
65    let sandbox = IsolateSandbox::new(0)
66        .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67        .verbose();
68
69    // Initialize the sandbox
70    let limits = ResourceLimits::new();
71    sandbox.init(&limits).await?;
72
73    // Run a simple echo command
74    let result = sandbox
75        .run("/bin/echo", ["Hello from Isolate Sandbox!"], &limits)
76        .await?;
77
78    println!("Exit code: {:?}", result.exit_code);
79    println!("Output: {}", result.stdout.trim());
80    println!("Time used: {:.3}s", result.time_used);
81    println!("Memory used: {} KB", result.memory_used);
82
83    // Cleanup the sandbox
84    sandbox.cleanup().await?;
85    println!("✓ Basic example completed\n");
86
87    Ok(())
88}
89
90/// Example 2: Using environment variables
91async fn environment_example() -> Result<()> {
92    println!("=== Example 2: Environment Variables ===");
93
94    let sandbox = IsolateSandbox::new(1)
95        .with_env_rule(EnvRule::Set("GREETING".to_string(), "Hello".to_string()))
96        .with_env_rule(EnvRule::Set("NAME".to_string(), "Isolate".to_string()))
97        .with_env_rule(EnvRule::Inherit("PATH".to_string()))
98        .with_meta_file(PathBuf::from("/tmp/isolate_meta_1.txt"))
99        .verbose();
100
101    let limits = ResourceLimits::new();
102    sandbox.init(&limits).await?;
103
104    // Use environment variables in a bash command
105    let result = sandbox
106        .run(
107            "/bin/bash",
108            [
109                "-c",
110                "echo \"$GREETING, $NAME!\" && echo \"Current directory: $(pwd)\"",
111            ],
112            &limits,
113        )
114        .await?;
115
116    println!("Output:\n{}", result.stdout);
117    println!("Exit code: {:?}", result.exit_code);
118
119    sandbox.cleanup().await?;
120    println!("✓ Environment example completed\n");
121
122    Ok(())
123}
124
125/// Example 3: File sharing between host and sandbox
126async fn file_sharing_example() -> Result<()> {
127    println!("=== Example 3: File Sharing ===");
128
129    // Create a temporary directory on the host with proper permissions (0o755 = rwxr-xr-x)
130    let host_dir = "/tmp/isolate_shared";
131    create_dir_with_permissions(host_dir, 0o755).await?;
132    println!("Created directory: {} with permissions 0755", host_dir);
133
134    // Create a test file on the host
135    let test_data = "This is data from the host system.\nLine 2\nLine 3";
136    tokio::fs::write(format!("{}/input.txt", host_dir), test_data).await?;
137    println!("Created input file at: {}/input.txt", host_dir);
138
139    let sandbox = IsolateSandbox::new(2)
140        .with_directory_rule(DirectoryRule::bind("/data", host_dir).read_write())
141        .with_meta_file(PathBuf::from("/tmp/isolate_meta_2.txt"))
142        .verbose();
143
144    let limits = ResourceLimits::new();
145    sandbox.init(&limits).await?;
146
147    // Read the file from within the sandbox
148    println!("\n1. Reading file from sandbox:");
149    let result = sandbox
150        .run("/bin/cat", ["/data/input.txt"], &limits)
151        .await?;
152    println!("{}", result.stdout);
153
154    // Write a new file from within the sandbox
155    println!("2. Writing new file from sandbox:");
156    let result = sandbox
157        .run(
158            "/bin/bash",
159            ["-c", "echo 'Generated inside sandbox' > /data/output.txt && echo 'File written successfully'"],
160            &limits,
161        )
162        .await?;
163    println!("{}", result.stdout.trim());
164
165    // Verify the file exists on the host
166    let output_content = tokio::fs::read_to_string(format!("{}/output.txt", host_dir)).await?;
167    println!("3. Content read back from host:");
168    println!("{}", output_content.trim());
169
170    sandbox.cleanup().await?;
171    println!("✓ File sharing example completed\n");
172
173    Ok(())
174}
175
176/// Example 4: Resource limits (time and memory)
177async fn resource_limits_example() -> Result<()> {
178    println!("=== Example 4: Resource Limits ===");
179
180    let sandbox = IsolateSandbox::new(3)
181        .with_meta_file(PathBuf::from("/tmp/isolate_meta_3.txt"))
182        .verbose();
183
184    sandbox.init(&ResourceLimits::new()).await?;
185
186    // Example 4a: Time limit
187    println!("4a. Testing time limit (1 second):");
188    let time_limits = ResourceLimits::new()
189        .with_time_limit(1.0)
190        .with_wall_time_limit(2.0);
191
192    let result = sandbox
193        .run(
194            "/bin/bash",
195            [
196                "-c",
197                "echo 'Starting...'; sleep 5; echo 'Finished within time limit'",
198            ],
199            &time_limits,
200        )
201        .await?;
202
203    println!("Output: {}", result.stdout.trim());
204    println!("Time used: {:.3}s (limit: 1.0s)", result.time_used);
205    println!("Killed: {}", result.killed);
206
207    // Example 4b: Memory limit
208    println!("\n4b. Testing memory limit (32 MB):");
209    let memory_limits = ResourceLimits::new()
210        .with_memory_limit(32 * 1024) // 32 MB
211        .with_time_limit(5.0);
212
213    let result = sandbox
214        .run(
215            "/bin/bash",
216            [
217                "-c",
218                "echo 'Running with memory limit'; echo 'Memory limit: 32 MB'",
219            ],
220            &memory_limits,
221        )
222        .await?;
223
224    println!("Output: {}", result.stdout.trim());
225    println!("Memory used: {} KB (limit: 32768 KB)", result.memory_used);
226
227    sandbox.cleanup().await?;
228    println!("✓ Resource limits example completed\n");
229
230    Ok(())
231}
232
233/// Example 5: Compile and run a C program
234async fn compile_and_run_example() -> Result<()> {
235    println!("=== Example 5: Compile and Run C Program ===");
236
237    let shared_dir = "/tmp/isolate_c_example";
238    create_dir_with_permissions(shared_dir, 0o777).await?;
239    println!("Created directory: {} with permissions 0777", shared_dir);
240
241    // Write a simple C program
242    let c_code = r#"#include <stdio.h>
243
244int main() {
245    int sum = 0;
246    for (int i = 1; i <= 10; i++) {
247        sum += i;
248    }
249    printf("Sum of 1 to 10 is: %d\n", sum);
250    printf("Program executed successfully!\n");
251    return 0;
252}
253"#;
254
255    tokio::fs::write(format!("{}/program.c", shared_dir), c_code).await?;
256    println!("Created C source file at: {}/program.c", shared_dir);
257
258    let sandbox = IsolateSandbox::new(4)
259        .with_directory_rule(DirectoryRule::bind("/workspace", shared_dir).read_write())
260        .with_meta_file(PathBuf::from("/tmp/isolate_meta_4.txt"))
261        .with_env_rule(EnvRule::FullEnv)
262        .verbose();
263
264    let compile_limits = ResourceLimits::new()
265        .with_time_limit(10.0)
266        .with_memory_limit(256 * 1024); // 256 MB for compilation
267
268    sandbox.init(&compile_limits).await?;
269
270    // Compile the C program
271    println!("\n1. Compiling C program:");
272    let compile_result = sandbox
273        .run(
274            "/usr/bin/gcc",
275            ["/workspace/program.c", "-o", "/workspace/program"],
276            &compile_limits,
277        )
278        .await?;
279
280    if compile_result.exit_code == Some(0) {
281        println!("✓ Compilation successful!");
282    } else {
283        println!("✗ Compilation failed:");
284        println!("stderr: {}", compile_result.stderr);
285        sandbox.cleanup().await?;
286        return Ok(());
287    }
288
289    // Run the compiled program
290    println!("\n2. Running compiled program:");
291    let run_limits = ResourceLimits::new()
292        .with_time_limit(2.0)
293        .with_memory_limit(64 * 1024) // 64 MB
294        .with_process_limit(1);
295
296    let run_result = sandbox
297        .run("/workspace/program", Vec::<&str>::new(), &run_limits)
298        .await?;
299
300    println!("Output:\n{}", run_result.stdout);
301    println!("Exit code: {:?}", run_result.exit_code);
302    println!("Time used: {:.3}s", run_result.time_used);
303    println!("Memory used: {} KB", run_result.memory_used);
304
305    if run_result.killed {
306        println!("⚠ Program was killed (exceeded limits)");
307    }
308
309    sandbox.cleanup().await?;
310    println!("✓ Compile and run example completed\n");
311
312    Ok(())
313}

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.