# Setting up sandboxes

https://virtx.sh/docs/guides/setting-sandboxes/

Create a sandbox with the CPUs, memory, network, ports, storage, and GPU a task needs, and resize it later.

## Create a sandbox

`create_sandbox` takes an image and these options, named here as in Python. Whatever is left out, the server picks.

The image has to be on the server already, pulled or built as [Images](https://virtx.sh/docs/guides/images/) shows: a create does not pull it, and refuses a tag the server has no image by with `404`.

| Option | Default | What it does |
| --- | --- | --- |
| `name` | none | A name to find it again by, with `find_sandbox`, rather than keeping its id: letters, digits, `.`, `_` and `-`, not starting with `.` or `-`, at most 128. One another sandbox has is refused with `409`, `exists`, until that one is removed. |
| `vcpus` | 4 | Its CPUs. |
| `memory_mib` | 4096 | Its memory, in MiB. |
| `disk_gib` | 2 | How much it may write over its image, in GiB, at most 1024. What it writes there goes when it is removed. |
| `network` | `True` | `False` blocks its outbound connections and name lookups. With it on, it reaches public addresses, not this host's loopback or private ones. |
| `ports` | none | Ports in it to reach from outside, even with `network` off: numbers for TCP, or specs with a `label`, an `http` `protocol` and `inbound` rules; see [Networks and ports](https://virtx.sh/docs/guides/networks-ports/). |
| `volumes` | none | Volumes mounted at paths in it, read-only if asked; see [Mounting volumes](https://virtx.sh/docs/guides/mounting-volumes/). |
| `gpu`, `gpu_memory_mib` | none | A GPU and the memory it may hold; see [Using GPUs](https://virtx.sh/docs/guides/using-gpus/). |
| `abins` | none | virtx's own programs, by name, such as `index`, `docread` and `display`, at `/abin` and first on its `PATH`, each with its `SKILL.md` at `/abin/skills/{name}/`. The sandbox answers them as `abins`. |

This makes a sandbox with 2 vCPUs, 2 GiB of memory, and no way out:

**Python**

```python
sandbox = await client.create_sandbox(
    "alpine:latest", vcpus=2, memory_mib=2048, network=False
)
```

**Node.js**

```js
const sandbox = await client.createSandbox('alpine:latest', {
  vcpus: 2,
  memoryMib: 2048,
  network: false,
})
```

**Rust**

```rust
let args = SandboxCreateArgs::new("alpine:latest")
    .vcpus(2)
    .memory_mib(2048)
    .network(false);
let sandbox = client.create_sandbox(&args).await?;
```

## Resize a sandbox

`resize` changes a sandbox's `vcpus`, `memory_mib` and `disk_gib` after it is made, each held to what `create_sandbox` holds it to; whatever is left out stays as it is. It answers the sandbox's size as it is to be, and `up`, whether its VM is up now.

- A VM is the size it booted with, so `vcpus` and `memory_mib` take effect at its next boot. A sandbox in which nothing runs has its VM stopped at once, and boots with its new size for its next command; one with a command running, or its files or ports in use, is refused with `409` and keeps its size.
- `disk_gib` only grows, keeping what the sandbox wrote; one smaller than the disk the VM last booted with is refused with `400`, and one down to it takes back a grow not yet made. The disk grows at the VM's next boot too, but a resize of the disk alone stops nothing and is never refused for the sandbox being in use: it answers at once, `up` still `true` for a VM that is up, which keeps its old size until it is next stopped and boots again. A grow that cannot be made boots the VM on its disk as it was, and is tried again at each boot.

A [server you run](https://virtx.sh/docs/guides/self-hosting/) keeps the new size across its restart.

**Python**

```python
resized = await sandbox.resize(vcpus=8, memory_mib=8192, disk_gib=16)
print(resized.vcpus, resized.memory_mib, resized.disk_gib, resized.up)
```

**Node.js**

```js
const resized = await sandbox.resize({ vcpus: 8, memoryMib: 8192, diskGib: 16 })
console.log(resized.vcpus, resized.memoryMib, resized.diskGib, resized.up)
```

**Rust**

```rust
let args = SandboxResizeArgs::default()
    .vcpus(8)
    .memory_mib(8192)
    .disk_gib(16);
let resized = sandbox.resize(&args).await?;
```

## Find sandboxes

`list_sandbox` lists every sandbox on the server, `get_sandbox` finds one by its id, and `find_sandbox` one by the `name` it was made with, answering none when no sandbox has it. Each comes back as a sandbox you can run commands in or remove, with its `id`, its `name`, its `image`, and whether it is `running`. This is how to find one a program left behind.

A [server you run](https://virtx.sh/docs/guides/self-hosting/) keeps its sandboxes when it is stopped: started again, it lists each with what it wrote, and boots it again for its next command. Their jobs are kept, each that ran then ended with code `137` and `reason` `restarted`, its log only that end. One it cannot start again, such as one whose image was deleted meanwhile, is listed with `running` false and an `error` saying why, and takes nothing but `remove`. The server `Client.spawn()` starts removes its sandboxes as your program ends.

**Python**

```python
for sandbox in await client.list_sandbox():
    print(sandbox.id, sandbox.image, sandbox.running)

sandbox = await client.get_sandbox("<sandbox id>")
sandbox = await client.find_sandbox("task-42")  # None if no sandbox has the name
```

**Node.js**

```js
for (const sandbox of await client.listSandbox()) {
  console.log(sandbox.id, sandbox.image, sandbox.running)
}

const sandbox = await client.getSandbox('<sandbox id>')
const named = await client.findSandbox('task-42') // undefined if no sandbox has the name
```

**Rust**

```rust
for sandbox in client.list_sandbox().await? {
    println!("{} {} {}", sandbox.id(), sandbox.info().image, sandbox.info().running);
}

let sandbox = client.get_sandbox("<sandbox id>").await?;
let named = client.find_sandbox("task-42").await?; // None if no sandbox has the name
```

### Find it or make it

A program that names its sandboxes, such as one per task, looks for the name first and makes the sandbox only when none has it. Two programs doing that at once can both find none: one makes it, and the other is refused with `409` and finds the one just made.

**Python**

```python
sandbox = await client.find_sandbox("task-42")
if sandbox is None:
    try:
        sandbox = await client.create_sandbox("alpine:latest", name="task-42")
    except VirtxError as error:
        if error.status != 409:
            raise
        sandbox = await client.find_sandbox("task-42")
```

**Node.js**

```js
let sandbox = await client.findSandbox('task-42')
if (sandbox === undefined) {
  try {
    sandbox = await client.createSandbox('alpine:latest', { name: 'task-42' })
  } catch (error) {
    if (!(error instanceof VirtxError) || error.status !== 409) throw error
    sandbox = await client.findSandbox('task-42')
  }
}
```

**Rust**

```rust
let sandbox = match client.find_sandbox("task-42").await? {
    Some(sandbox) => Some(sandbox),
    None => match client
        .create_sandbox(&SandboxCreateArgs::new("alpine:latest").name("task-42"))
        .await
    {
        Ok(sandbox) => Some(sandbox),
        Err(error) if error.status() == Some(409) => client.find_sandbox("task-42").await?,
        Err(error) => return Err(error),
    },
};
```

A sandbox found so has each port without its `url`, which only `create_sandbox` answers; see [Networks and ports](https://virtx.sh/docs/guides/networks-ports/).

## Remove a sandbox

`remove` stops a sandbox, ends its jobs, and deletes what it wrote over its image. Its volumes stay, for the next sandbox to use.

**Python**

```python
await sandbox.remove()
```

**Node.js**

```js
await sandbox.remove()
```

**Rust**

```rust
sandbox.remove().await?;
```
