Running commands
Run commands in a sandbox, read their output, and control them while they run.
Run a command
exec starts a command in the sandbox. Pass the command as a list of arguments (an argv), not as one string.
complete waits for the command to finish and returns its exit code. With print, it also prints the command’s stdout and stderr as they are written.
A nonzero exit code is returned as a value. It is not raised as an error.
code = await sandbox.exec(["uname", "-a"]).complete(print=True)print("exited", code)const code = await sandbox.exec(['uname', '-a']).complete({ print: true })console.log('exited', code)let code = sandbox.exec(&SandboxExecArgs::new(["uname", "-a"])).complete(true).await?;println!("exited {code}");If the command can’t start, for example because it isn’t installed in the image, the call fails with 422, not_started, and no job is created.
In Python, the error is raised where you first await, iterate or complete the value, because nothing is sent to the server before that.
Follow a job
Each command runs as a job. A job runs independently of the request that started it: it keeps running if your loop exits or your connection drops, and the server keeps its output in a log you can read again.
exec returns a value you can use in three ways:
- Await it to get the job: its
id, whether it isrunning, and after it ends, its exitcodeand thereasonit was stopped, if it didn’t exit on its own. - Iterate it to read the job’s log, entry by entry.
- Call
complete()to wait for the job to end and get its exit code.
To check on a job later:
job.get()returns the job’s current state.sandbox.jobs()lists a sandbox’s jobs, andsandbox.job(id)returns one by its id.job.log()reads the job’s output from the start, or from after theidof the last entry you read.
Over HTTP, if the connection breaks while you read a log (for example because the server restarted or a proxy in front of it was replaced), the client reconnects and continues after the last entry. It retries up to five times in a row before it raises the error. A log that stops before the job’s end entry is read on the same way, over HTTP or stdio. If the job is removed while you read its log, the log ends with the job’s end entry, or fails with 404 if the server doesn’t send one.
job = await sandbox.exec(["sh", "-c", "for i in 1 2 3; do echo $i; sleep 1; done"])print(job.id, job.running)
job = await sandbox.job(job.id) # later, from the sandboxasync for entry in job.log(): print(entry.id, entry.entry)
job = await job.get()print(job.running, job.code)let job = await sandbox.exec(['sh', '-c', 'for i in 1 2 3; do echo $i; sleep 1; done'])console.log(job.id, job.running)
job = await sandbox.job(job.id) // later, from the sandboxfor await (const entry of job.log()) console.log(entry)
job = await job.get()console.log(job.running, job.code)use futures::StreamExt; // cargo add futures: a log is a Stream
let args = SandboxExecArgs::new(["sh", "-c", "for i in 1 2 3; do echo $i; sleep 1; done"]);let job = sandbox.exec(&args).await?;println!("{} {}", job.id(), job.info().running);
let job = sandbox.job(job.id()).await?; // later, from the sandboxlet mut log = job.log(None);while let Some(entry) = log.next().await { let entry = entry?; println!("{} {:?}", entry.id, entry.entry);}
let job = job.get().await?;println!("{} {:?}", job.info().running, job.info().code);It prints:
4ea37caf True1 Stdout(line='1')2 Stdout(line='2')3 Stdout(line='3')4 SandboxJobEnd(code=0, reason=None)False 0A log holds a limited number of entries. When a job writes more, the dropped entries are replaced by a single truncated entry, and the end entry still comes last.
Stream output
To handle each line of output as it arrives, iterate the job instead of calling complete().
Each entry is one line of stdout or stderr, and the last entry says how the job ended.
In this example, a command prints one progress line per second to stdout and a warning to stderr, and the loop handles each kind separately:
cmd = ["sh", "-c", "for i in 1 2 3; do echo step $i/3; sleep 1; done; echo cache miss >&2"]async for entry in sandbox.exec(cmd): match entry.entry: case Stdout(line): print("stdout:", line) case Stderr(line): print("stderr:", line) case SandboxJobEnd(code): print("exited", code)const cmd = ['sh', '-c', 'for i in 1 2 3; do echo step $i/3; sleep 1; done; echo cache miss >&2']for await (const entry of sandbox.exec(cmd)) { if ('stdout' in entry) console.log('stdout:', entry.stdout) else if ('stderr' in entry) console.log('stderr:', entry.stderr) else if ('end' in entry) console.log('exited', entry.end.code)}let cmd = ["sh", "-c", "for i in 1 2 3; do echo step $i/3; sleep 1; done; echo cache miss >&2"];let mut log = sandbox.exec(&SandboxExecArgs::new(cmd)).log();while let Some(entry) = log.next().await { match entry?.entry { SandboxJobEntry::Stdout(line) => println!("stdout: {line}"), SandboxJobEntry::Stderr(line) => println!("stderr: {line}"), SandboxJobEntry::End(end) => println!("exited {}", end.code), _ => {} }}Each line prints as soon as the command writes it, one second apart:
stdout: step 1/3stdout: step 2/3stdout: step 3/3stderr: cache missexited 0A line longer than 64 KiB arrives as several entries. Exiting the loop early doesn’t stop the command.
When you iterate exec directly, the client starts the command and reads its output in a single request, if the server supports it. Otherwise it sends two requests: one to start the job and one to read its log. Either way, awaiting the value afterwards returns the same job.
- Python: nothing is sent until you first await or iterate the value, so whichever you do first decides how the request is made.
- Node.js: the command starts when
execreturns. It is one request only if the loop starts before your code awaits anything else, as infor await (const entry of sandbox.exec(cmd)). - Rust: use
sandbox.exec_with_log(&args), which yields the job first and then each log entry.
Run several commands at once
Awaiting exec starts a job and returns without waiting for it to end, so you can run several commands at the same time.
In this example, one job appends a line to a file every second, and a second job waits a few seconds and then prints the file.
writer = await sandbox.exec(["sh", "-c", "i=0; while true; do i=$((i+1)); echo tick $i >> /tmp/events; sleep 1; done"])
async for entry in sandbox.exec(["sh", "-c", "sleep $((RANDOM % 5 + 1)); cat /tmp/events"]): print(entry.entry) # Stdout(line='tick 1'), Stdout(line='tick 2'), ...
await writer.remove() # kills the writer, which never ends on its ownconst writer = await sandbox.exec(['sh', '-c', 'i=0; while true; do i=$((i+1)); echo tick $i >> /tmp/events; sleep 1; done'])
for await (const entry of sandbox.exec(['sh', '-c', 'sleep $((RANDOM % 5 + 1)); cat /tmp/events'])) { console.log(entry) // { id: 1, stdout: 'tick 1' }, { id: 2, stdout: 'tick 2' }, ...}
await writer.remove() // kills the writer, which never ends on its ownlet args = SandboxExecArgs::new(["sh", "-c", "i=0; while true; do i=$((i+1)); echo tick $i >> /tmp/events; sleep 1; done"]);let writer = sandbox.exec(&args).await?;
let mut log = sandbox.exec(&SandboxExecArgs::new(["sh", "-c", "sleep $((RANDOM % 5 + 1)); cat /tmp/events"])).log();while let Some(entry) = log.next().await { println!("{:?}", entry?.entry); // Stdout("tick 1"), Stdout("tick 2"), ...}
writer.remove().await?; // kills the writer, which never ends on its ownThe second job prints one line for each second it waited, because the first job kept running the whole time. For example:
Stdout(line='tick 1')Stdout(line='tick 2')Stdout(line='tick 3')Stdout(line='tick 4')SandboxJobEnd(code=0, reason=None)A background job runs until it exits or you remove it. Removing the sandbox stops every job in it.
After a job ends, the sandbox keeps it and its log so you can read the output. Each sandbox keeps its last 100 ended jobs; when another job starts past them, the one that ended first is deleted. Running jobs are never deleted this way.
Set a timeout
timeout_ms kills the command when the time runs out. The job then ends with exit code 137, the same code SIGKILL gives:
code = await sandbox.exec(["sleep", "60"], timeout_ms=10_000).complete() # 137const code = await sandbox.exec(['sleep', '60'], { timeoutMs: 10_000 }).complete() // 137let mut args = SandboxExecArgs::new(["sleep", "60"]);args.timeout_ms = Some(10_000);let code = sandbox.exec(&args).complete(false).await?; // 137Exit code 137 alone doesn’t tell you a timeout happened, because a process can also exit with 137 itself or receive SIGKILL from elsewhere. When VirtX stops a job, it sets the job’s reason, and the reason on the log’s end entry, to say why. Here it is timeout.
reason |
Why VirtX stopped the command (exit code 137) |
|---|---|
timeout |
timeout_ms ran out. |
cancelled |
The job was removed while it ran. The sandbox still exists, and you can run the command again. |
sandbox_deleted |
The sandbox was removed while the command ran. |
vm_exited |
The sandbox’s VM exited on its own. |
oom |
The command, or a process it started, ran out of memory: it went past the memory one command may use, or the sandbox’s memory, or the sandbox was thrashing. |
restarted |
The server restarted while the command ran. The sandbox was kept. |
A later version of VirtX may add a reason. A client that doesn’t know it keeps it as the string the server sent, so the job can still be read.
Write to a command’s stdin
To send input to a command, start it with stdin turned on, then call write_stdin. Pass eof to close stdin after the write, so the command knows the input has ended.
Await each write before you send the next one, so the writes arrive in order.
job = await sandbox.exec(["cat"], stdin=True)await job.write_stdin("one\n")await job.write_stdin("two\n", eof=True)async for entry in job.log(): print(entry.entry) # Stdout(line='one'), Stdout(line='two'), SandboxJobEnd(code=0, ...)const job = await sandbox.exec(['cat'], { stdin: true })await job.writeStdin('one\n')await job.writeStdin('two\n', true) // true closes stdin after this writefor await (const entry of job.log()) console.log(entry)let job = sandbox.exec(&SandboxExecArgs::new(["cat"]).stdin(true)).await?;job.write_stdin(Some("one\n"), false).await?;job.write_stdin(Some("two\n"), true).await?; // true closes stdin after this writelet mut log = job.log(None);while let Some(entry) = log.next().await { println!("{:?}", entry?.entry);}If the command closes its stdin while you are writing, the write fails with 409, ended, and the error’s written field says how many bytes were delivered.
Signal or cancel a job
signal sends a signal, such as SIGTERM, to the job’s process and every process it started.
remove kills those processes and deletes the job. A log you are reading then ends with the job’s end entry, with reason set to cancelled. Removing the sandbox also kills its running jobs, with reason set to sandbox_deleted.
job = await sandbox.exec(["sleep", "600"])await job.signal("SIGTERM")await job.remove()const job = await sandbox.exec(['sleep', '600'])await job.signal('SIGTERM')await job.remove()let job = sandbox.exec(&SandboxExecArgs::new(["sleep", "600"])).await?;job.signal("SIGTERM").await?;job.remove().await?;Troubleshooting
-
422,not_startedCause: The command was not found, or could not start. No job is made.
Fix: Check the first word of the command. For shell syntax such as pipes or
$VAR, run["sh", "-c", "..."]. -
400,invalidCause: The command was empty.
Fix: Pass a list of arguments, with at least the program to run. In Python, a string isn’t refused but split into its characters, so
exec("ls")runsl: always pass a list. -
404,not_found, fromjob(id),getorlogCause: The job was removed, or it was deleted to make room: a sandbox keeps its last 100 ended jobs, and deletes the oldest as another starts.
Fix: Read a job’s output before 100 more jobs start, or have the command write its output to a file on a volume.
-
the job was removed before it endedCause: The job was removed while
completewas waiting for it.Fix: Don’t remove a job you are completing.
-
409,endedCause: The sandbox’s VM has stopped permanently, or
write_stdinwas called on a job started withoutstdin, or whose stdin is already closed, or that has ended.Fix: Start the job with
stdinturned on. If the sandbox has ended, remove it and create another. -
Exit code
137with areasonCause: The job was stopped: see the reasons above.
Fix: Raise
timeout_msfortimeout. Foroom, create the sandbox with morememory_mib.
Next
- Reading and writing files: put a command’s input in and get its output back without running anything.
- Networks and ports: reach a server a command started in the sandbox.