# Running commands

https://virtx.sh/docs/tutorials/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.

**Python**

```python
code = await sandbox.exec(["uname", "-a"]).complete(print=True)
print("exited", code)
```

**Node.js**

```js
const code = await sandbox.exec(['uname', '-a']).complete({ print: true })
console.log('exited', code)
```

**Rust**

```rust
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 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.

**Python**

```python
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)
```

**Node.js**

```js
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 sandbox
for await (const entry of job.log()) console.log(entry)

job = await job.get()
console.log(job.running, job.code)
```

**Rust**

```rust
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 sandbox
let 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:

```text frame="terminal" title="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.

> **Tip:**
> Image builds, pulls and pushes are jobs too, and work the same way: call `complete()` on `build_image`, `pull_image` or `push_image` to get the image digest, iterate it to read the log, or await it to get the job. See [Working with images](https://virtx.sh/docs/tutorials/images/).

## 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:

**Python**

```python
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)
```

**Node.js**

```js
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)
}
```

**Rust**

```rust
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:

```text frame="terminal" title="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.

**Python**

```python
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
```

**Node.js**

```js
const 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 own
```

**Rust**

```rust
let 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 own
```

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

```text frame="terminal" title="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:

**Python**

```python
code = await sandbox.exec(["sleep", "60"], timeout_ms=10_000).complete()  # 137
```

**Node.js**

```js
const code = await sandbox.exec(['sleep', '60'], { timeoutMs: 10_000 }).complete() // 137
```

**Rust**

```rust
let mut args = SandboxExecArgs::new(["sleep", "60"]);
args.timeout_ms = Some(10_000);
let code = sandbox.exec(&args).complete(false).await?; // 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.

**Python**

```python
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, ...)
```

**Node.js**

```js
const job = await sandbox.exec(['cat'], { stdin: true })
await job.writeStdin('one\n')
await job.writeStdin('two\n', true) // true closes stdin after this write
for await (const entry of job.log()) console.log(entry)
```

**Rust**

```rust
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 write
let 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`.

**Python**

```python
job = await sandbox.exec(["sleep", "600"])
await job.signal("SIGTERM")
await job.remove()
```

**Node.js**

```js
const job = await sandbox.exec(['sleep', '600'])
await job.signal('SIGTERM')
await job.remove()
```

**Rust**

```rust
let job = sandbox.exec(&SandboxExecArgs::new(["sleep", "600"])).await?;
job.signal("SIGTERM").await?;
job.remove().await?;
```

## 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](#set-a-timeout).

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

## Next

- [Reading and writing files](https://virtx.sh/docs/tutorials/reading-writing-files/): put a command's input in and get its output back without running anything.
- [Networks and ports](https://virtx.sh/docs/tutorials/networks-ports/): reach a server a command started in the sandbox.
