# Running commands

https://virtx.sh/docs/guides/running-commands/

Run commands in a sandbox, read their output, and control them while they run.

## Run a command

`exec` takes an argv and starts a job, and `complete` follows it to its end and answers its exit code.
With `print`, it prints what the command writes as it writes it, stdout to stdout and stderr to stderr.
A nonzero exit code is the answer, not 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}");
```

A command that cannot start, such as one not found, is refused at `exec` and starts no job.

## Follow a job

Each command runs as a **job**. The server runs it apart from the request that started it, so a job keeps going when a loop is left or a connection drops, and its output is kept in a log you can read again.

The value `exec` returns is three things at once.
Completed, it answers how the job ended; iterated, it is the job's log.
Awaited, it is the job itself: its `id`, whether it is `running`, and once it has ended, its exit `code`, and its `reason` if it did not end by itself.
`get` asks for the job as it is now, a sandbox's `jobs` and `job(id)` find it again later, and the job's `log` reads its output from the start, or after the `id` of the last entry seen.
A log read from a server over HTTP whose connection breaks, the server restarted or a proxy in front of it replaced, is read on after the last entry by itself, up to five times in a row, before its error is yours. A log that stops before the job's end is read on too, and one whose job is deleted while you read it ends with the job's `end`, or, where the server sends none, fails with `404` rather than stopping short.

**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
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"
4ea37caf True
1 Stdout(line='1')
2 Stdout(line='2')
3 Stdout(line='3')
4 SandboxJobEnd(code=0)
False 0
```

A log keeps a limit's worth of entries. Past it, one `truncated` entry stands for what was dropped, and `end` still comes last.

> **Tip:**
> Building, pulling, and pushing an image are jobs too, used the same way: complete `build_image`, `pull_image`, or `push_image` for its digest, iterate it for the log, or await it for the job. See [Working with images](https://virtx.sh/docs/guides/images/).

## Stream output

To handle each line as it comes, iterate the job instead of completing it.
It yields the command's output, a line per entry, then how it ended.
Here a command reports its progress a step a second, and a warning on stderr, and the loop tells the two apart:

**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 step prints as the command writes it, a second apart, not all at once when it ends:

```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, and leaving the loop leaves the command running.

Iterated before it is awaited, `exec` starts the command and reads its output as one request where the server answers so, and as two, the job and then its log, where it does not; awaited after, it is the same job.
In Python nothing is sent until the value is first awaited or iterated, so whichever of the two comes first decides, whatever else the code awaits in between.
In Node.js the command is started as the call returns, as a promise's work is: it is one request only when the loop begins before the code awaits anything else, as `for await (const entry of sandbox.exec(cmd))` does, and two once anything is awaited between the call and the loop.
In Rust, `sandbox.exec_with_log(&args)` does the same, yielding the job first and then each entry.

## Run several commands at once

Awaiting `exec` starts a job and returns without waiting for it to end, so a command can run in the background while others run beside it.
Here one job writes a line to a file every second, and another waits a few seconds and reads what has been written so far.

**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 reader prints as many ticks as seconds it waited, since the writer kept going 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)
```

A job left in the background runs until it ends or is removed; removing the sandbox stops every job in it. An ended job is kept, with its log, for its output to be read: a sandbox keeps its last 100, and as another starts past them the one that ended first is removed. A job that runs is never removed so.

## Set a timeout

`timeout_ms` kills the process when the time runs out, which ends it with `137`, as `SIGKILL` does:

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

The job says why it ended where the process did not end by itself: its `reason`, and its log's `end`'s, is `timeout` here. A process that exits with `137` itself, or that is sent `SIGKILL`, has no `reason`, so `137` alone does not say a timeout ended it.

| `reason` | Why the process ended, killed with its code `137` |
| --- | --- |
| `timeout` | Its `timeout_ms` ran out. |
| `cancelled` | Its job was removed while it ran. Its sandbox is still there, and the command can be run again. |
| `sandbox_deleted` | Its sandbox was removed under it, and everything it had with it. |
| `vm_exited` | Its sandbox's machine exited on its own under it. |
| `oom` | Its memory ran out: it, or a process it started, was killed past the memory one command may take or the machine's, or for thrashing there. |
| `restarted` | Its server restarted while it ran, keeping its sandbox. |

A later version may add a reason. A package that does not know it keeps it as the string it was sent, so the job still reads.

## Signal or cancel a job

A job's `signal` sends a signal such as `SIGTERM` to its process and every process it started, and `remove` kills them and forgets the job: a log being read then ends with the job's `end`, its `reason` `cancelled`. Removing the sandbox ends each job that runs in it so too, its `reason` `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?;
```
