stream_long_running/
stream_long_running.rs

1//! Example: Streaming from a long-running process
2//!
3//! This example shows how to stream output from a process that outputs
4//! multiple lines over time, including both stdout and stderr.
5//!
6//! Note: This example uses SeccompProfile::Unrestricted because bash requires
7//! many syscalls for proper operation. For simple commands like `echo`, you can
8//! use more restrictive profiles like Minimal or Compute.
9
10use sandbox_rs::{SandboxBuilder, SeccompProfile, StreamChunk};
11use std::time::Duration;
12use tempfile::tempdir;
13
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}