# Setting up sandboxes

https://virtx.sh/docs/tutorials/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 the options below. The table uses the Python names; see [Names](https://virtx.sh/docs/sdk/#names) for Node.js and Rust. An option you leave out gets the default shown.

The image must already be on the server. `create_sandbox` doesn't pull it, and fails with `404` for a tag the server doesn't have. Pull or build the image first, as [Working with images](https://virtx.sh/docs/tutorials/images/) shows.

| Option | Default | What it does |
| --- | --- | --- |
| `name` | none | A name to find the sandbox by later with `find_sandbox`, instead of storing its id. Up to 128 letters, digits, `.`, `_` and `-`, not starting with `.` or `-`; otherwise the call fails with `400`. If another sandbox already has the name, the call fails with `409`, `exists`. |
| `vcpus` | 4 | Number of virtual CPUs. |
| `memory_mib` | 4096 | Memory, in MiB. |
| `disk_gib` | 2 | Space the sandbox can write on top of its image, in GiB, up to 1024. This data is deleted when the sandbox is removed. |
| `network` | `True` | Outbound network access. `False` blocks outbound connections and DNS lookups. With `True`, the sandbox reaches public addresses, but not the host's loopback or private addresses. |
| `ports` | none | Ports in the sandbox that you can reach from outside, even with `network` off. Pass port numbers, or port specs with a `label`. See [Networks and ports](https://virtx.sh/docs/tutorials/networks-ports/). |
| `volumes` | none | Volumes to mount at paths in the sandbox, optionally read-only. See [Mounting volumes](https://virtx.sh/docs/tutorials/mounting-volumes/). |
| `gpu`, `gpu_memory_mib` | none | Attach the host's GPU, and set how much GPU memory it may use. See [Using GPUs](https://virtx.sh/docs/tutorials/using-gpus/). |
| `abins` | none | VirtX's built-in programs to install, by name, such as `index`, `docread`, `display` and `browser`. They go in `/abin`, which is first on the sandbox's `PATH`, and each has a `SKILL.md` at `/abin/skills/{name}/`. The sandbox's `abins` field lists them. See [Using built-in programs](https://virtx.sh/docs/tutorials/built-in-programs/). |

This example creates a sandbox with 2 vCPUs, 2 GiB of memory, and no outbound network access:

**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 you create it. Each has the same limits as in `create_sandbox`, and anything you leave out stays as it is. It returns the sandbox's new size, and `up`, whether its VM is running now.

- **CPUs and memory** take effect at the VM's next boot, because a VM keeps the size it booted with. If nothing is running in the sandbox, the server stops its VM at once, and it boots with the new size for its next command. If a command is running, or its files or ports are in use, `resize` fails with `409` and the size doesn't change.
- **Disk** can only grow, and the sandbox keeps what it wrote. A size smaller than the disk the VM last booted with fails with `400`; a size equal to it cancels a grow that hasn't happened yet. The disk also grows at the VM's next boot, but resizing only the disk stops nothing and never fails because the sandbox is in use: it returns at once, and a running VM keeps its old disk until it next stops and boots again. If the disk can't grow, the VM boots with the disk as it was, and the server tries again at each boot.

A [server you run](https://virtx.sh/docs/tutorials/self-hosting/) keeps the new size across a 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

Use these calls to find sandboxes, for example ones an earlier run of your program left behind:

- `list_sandbox` returns every sandbox on the server.
- `get_sandbox` returns the sandbox with a given id.
- `find_sandbox` returns the sandbox with a given `name`, or none if no sandbox has that name.

Each result is a sandbox you can run commands in or remove. It has an `id`, a `name`, an `image`, and `running`, which says whether it can still run commands.

How long sandboxes last depends on the server:

- **Local server (`Client.spawn()`):** removes all its sandboxes when your program ends.
- **Your own server (`virtx-server-tcp`):** keeps its sandboxes, and their files, when it restarts. A sandbox boots again on its next command. Jobs that were running during the restart end with code `137` and `reason` `restarted`.

If the server can't start a sandbox again after a restart, for example because its image was deleted, the sandbox is listed with `running` set to false and an `error` that says why. The only thing you can do with it is `remove` it.

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

To reuse one sandbox per task, look it up by name first and create it only if it doesn't exist. If two programs do this at the same time, both may find nothing. One creates the sandbox, and the other gets `409` and looks the sandbox up again:

**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 returned by `find_sandbox`, `get_sandbox` or `list_sandbox` forwards its ports as the one `create_sandbox` returned does; see [Networks and ports](https://virtx.sh/docs/tutorials/networks-ports/).

## Remove a sandbox

`remove` stops a sandbox, ends its jobs, and deletes everything it wrote outside its volumes. The volumes are kept for other sandboxes to use.

**Python**

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

**Node.js**

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

**Rust**

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

## Troubleshooting

1. **`404`, `not_found`, from `create_sandbox`**

   **Cause:** The server has no image by that tag. A create does not pull.

   **Fix:** Pull or build the image first, as [Working with images](https://virtx.sh/docs/tutorials/images/) shows.

2. **`400`, `invalid`, from `create_sandbox`**

   **Cause:** An option is invalid: a bad `name`, `0` for a number, or a port listed twice.

   **Fix:** Fix the option the error message names.

3. **`409`, `exists`**

   **Cause:** Another sandbox has that `name`.

   **Fix:** Find it with `find_sandbox`, or remove it first.

4. **`409`, `ended`, on a sandbox from `list_sandbox`**

   **Cause:** The server could not start it again after a restart, as its `error` says.

   **Fix:** Remove it and create another.

5. **`409`, from `resize`**

   **Cause:** A command is running in the sandbox, or its files or ports are in use, so its VM can't be stopped to change its CPUs or memory.

   **Fix:** Wait until it is idle, then resize again. Growing only the disk is never refused for this.

6. **`400`, from `resize`**

   **Cause:** `disk_gib` is smaller than the disk the VM last booted with. A disk only grows.

   **Fix:** Give a size at least as large as the current disk.

## Next

- [Running commands](https://virtx.sh/docs/tutorials/running-commands/): run commands in the sandbox and read their output.
- [Mounting volumes](https://virtx.sh/docs/tutorials/mounting-volumes/): keep what a sandbox writes after it is removed.
