Skip to content

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)

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 is running, and after it ends, its exit code and the reason it 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, and sandbox.job(id) returns one by its id.
  • job.log() reads the job’s output from the start, or from after the id of 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 sandbox
async for entry in job.log():
print(entry.id, entry.entry)
job = await job.get()
print(job.running, job.code)

It prints:

Output (Python)
4ea37caf True
1 Stdout(line='1')
2 Stdout(line='2')
3 Stdout(line='3')
4 SandboxJobEnd(code=0, reason=None)
False 0

A 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)

Each line prints as soon as the command writes it, one second apart:

Output
stdout: step 1/3
stdout: step 2/3
stdout: step 3/3
stderr: cache miss
exited 0

A 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 exec returns. It is one request only if the loop starts before your code awaits anything else, as in for 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 own

The second job prints one line for each second it waited, because the first job kept running the whole time. For example:

Output (Python, random wait: 4 s)
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() # 137

Exit 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, ...)

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()

Troubleshooting

  1. 422, not_started

    Cause: 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", "..."].

  2. 400, invalid

    Cause: 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") runs l: always pass a list.

  3. 404, not_found, from job(id), get or log

    Cause: 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.

  4. the job was removed before it ended

    Cause: The job was removed while complete was waiting for it.

    Fix: Don’t remove a job you are completing.

  5. 409, ended

    Cause: The sandbox’s VM has stopped permanently, or write_stdin was called on a job started without stdin, or whose stdin is already closed, or that has ended.

    Fix: Start the job with stdin turned on. If the sandbox has ended, remove it and create another.

  6. Exit code 137 with a reason

    Cause: The job was stopped: see the reasons above.

    Fix: Raise timeout_ms for timeout. For oom, create the sandbox with more memory_mib.

Next