sandbox_usage/
sandbox_usage.rs1use anyhow::Result;
2use isolate_integration::sandbox::{DirectoryRule, EnvRule, IsolateSandbox, ResourceLimits};
3use std::path::PathBuf;
4
5async fn create_dir_with_permissions(path: &str, mode: u32) -> Result<()> {
16 tokio::fs::create_dir_all(path).await?;
17
18 #[cfg(unix)]
19 {
20 use std::fs::Permissions;
21 use std::os::unix::fs::PermissionsExt;
22 let permissions = Permissions::from_mode(mode);
23 tokio::fs::set_permissions(path, permissions).await?;
24 }
25
26 Ok(())
27}
28
29#[tokio::main]
30async fn main() -> Result<()> {
31 println!("=== Isolate Sandbox Usage Examples ===\n");
32 println!("Prerequisites: Make sure 'isolate' is installed on your system.");
33 println!("Installation: sudo apt-get install isolate (on Ubuntu/Debian)\n");
34
35 if let Err(e) = basic_example().await {
37 eprintln!("Basic example failed: {}", e);
38 }
39
40 if let Err(e) = environment_example().await {
41 eprintln!("Environment example failed: {}", e);
42 }
43
44 if let Err(e) = file_sharing_example().await {
45 eprintln!("File sharing example failed: {}", e);
46 }
47
48 if let Err(e) = resource_limits_example().await {
49 eprintln!("Resource limits example failed: {}", e);
50 }
51
52 if let Err(e) = compile_and_run_example().await {
53 eprintln!("Compile and run example failed: {}", e);
54 }
55
56 println!("\n=== All examples completed ===");
57 Ok(())
58}
59
60async fn basic_example() -> Result<()> {
62 println!("=== Example 1: Basic Command Execution ===");
63
64 let sandbox = IsolateSandbox::new(0)
66 .with_meta_file(PathBuf::from("/tmp/isolate_meta_0.txt"))
67 .verbose();
68
69 let limits = ResourceLimits::new();
71 sandbox.init(&limits).await?;
72
73 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 sandbox.cleanup().await?;
85 println!("✓ Basic example completed\n");
86
87 Ok(())
88}
89
90async 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 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
125async fn file_sharing_example() -> Result<()> {
127 println!("=== Example 3: File Sharing ===");
128
129 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 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 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 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 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
176async 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 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 println!("\n4b. Testing memory limit (32 MB):");
209 let memory_limits = ResourceLimits::new()
210 .with_memory_limit(32 * 1024) .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
233async 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 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); sandbox.init(&compile_limits).await?;
269
270 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 println!("\n2. Running compiled program:");
291 let run_limits = ResourceLimits::new()
292 .with_time_limit(2.0)
293 .with_memory_limit(64 * 1024) .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}