# Run a container from a Durable Object

`@kite/containers` gives a Durable Object the API of Cloudflare's
`ctx.container`, backed by a SandboxPool in your cluster. Each container that
the object starts runs as a sandbox on the pool. A sandbox is the cluster's
record of one container that the pool runs. Each request to the container goes
through the cluster's API. To run code written for `ctx.container` on Kite, use
`containerFor(ctx, env, { pool })` in place of `ctx.container`.

## What you need

- `kubectl` signed in to the cluster, with permission to create a
  SandboxPool, a ServiceAccount, a Role and a RoleBinding.
- A Worker with a Durable Object class, which you deploy with Wrangler.
- For snapshots, a cluster that stores them. See
  [Store snapshots of sandboxes](/docs/configure/#store-snapshots-of-sandboxes).

## Create a pool

Each container gets the CPU and memory in the pool's `spec.container`. The
pool runs reservation Pods, each with the CPU and memory in
`spec.reservation`, and runs its containers inside them. This pool runs them
under gVisor, through the RuntimeClass `gvisor`, because a
[memory snapshot](#snapshots) needs gVisor.
[Run a pod in a sandboxed runtime](/docs/sandboxed-runtimes/) creates that
RuntimeClass.

```yaml
apiVersion: kiteplane.dev/v1alpha1
kind: SandboxPool
metadata:
  name: kernels
  namespace: default
spec:
  runtimeClassName: gvisor
  reservation: { cpu: "2", memory: 4Gi }
  container: { cpu: 500m, memory: 1Gi }
```

```bash
kubectl apply -f pool.yaml
```

```text
sandboxpool.kiteplane.dev/kernels created
```

## Create the object's identity

The object calls the cluster's API as a ServiceAccount. This Role allows every
call that the package makes:

```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: kernels
  namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: kernels
  namespace: default
rules:
  - apiGroups: ["kiteplane.dev"]
    resources: ["sandboxpools/sandboxes"]
    resourceNames: ["kernels"]
    verbs: ["create", "get", "delete", "patch"]
  - apiGroups: ["kiteplane.dev"]
    resources: ["sandboxpools/snapshots"]
    resourceNames: ["kernels"]
    verbs: ["create"]
  - apiGroups: ["kiteplane.dev"]
    resources: ["sandboxpools/proxy"]
    resourceNames: ["kernels"]
    verbs: ["get", "create", "update", "patch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: kernels
  namespace: default
subjects:
  - kind: ServiceAccount
    name: kernels
    namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: kernels
```

| Resource                 | Verbs                                                                                                                                                                                 | Used by                                                                      |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `sandboxpools/sandboxes` | `create`, `get`, `delete`, `patch`                                                                                                                                                    | `start()`, `monitor()`, `destroy()`, `signal()` and `setInactivityTimeout()` |
| `sandboxpools/snapshots` | `create`. Add `get`, `patch` and `delete` to list, tag or delete snapshots through the API                                                                                            | `snapshotContainer()`                                                        |
| `sandboxpools/proxy`     | `get` for GET and for a WebSocket, `create` for POST, `update` for PUT, `patch` for PATCH and `delete` for DELETE. Leave out the verbs of methods that your container does not accept | `getTcpPort().fetch()`                                                       |

`resourceNames` limits the Role to the pool `kernels`.

Apply the manifest. Then create a Secret, and a token for the ServiceAccount
that is bound to that Secret:

```bash
kubectl apply -f kernels.yaml
kubectl create secret generic kernels-token-1
kubectl create token kernels --bound-object-kind Secret \
  --bound-object-name kernels-token-1 --duration=720h
```

`kubectl create token` prints the token. The token stays valid for 30 days, or
until you delete the Secret `kernels-token-1`, whichever comes first. To
replace the token:

1. Create the Secret `kernels-token-2` and a token bound to it.
2. Store the new token in the Worker, as in the next section.
3. Delete `kernels-token-1`.

:::caution
If the token leaks, delete its Secret at once.
:::

## Connect the Worker to the cluster

Set the cluster's address and the pool's namespace in your Wrangler
configuration:

```jsonc
{
  "vars": {
    "KITE_URL": "https://kite.example.com",
    "KITE_NAMESPACE": "default",
  },
}
```

Then store the token as a secret. Wrangler asks for its value:

```bash
npx wrangler secret put KITE_TOKEN
```

| Binding          | Value                                              | Default   |
| ---------------- | -------------------------------------------------- | --------- |
| `KITE_URL`       | The cluster's address                              | None      |
| `KITE`           | A service binding to the cluster's Worker          | None      |
| `KITE_TOKEN`     | The token that the package sends as a bearer token | None      |
| `KITE_NAMESPACE` | The namespace of the pool                          | `default` |

When your Worker and the cluster's Worker are in the same Cloudflare account,
you can add a service binding to the cluster's Worker as `KITE` instead of
setting `KITE_URL`. The package sends its requests through `KITE` if it is
set, and to `KITE_URL` if not. The options `api`, `token` and `namespace` of
`containerFor` override the bindings.

## Start a container

Add Kite's registry to your project's `.npmrc`, and install the package:

```text
@kite:registry=https://releases.runkite.io/npm/
```

```bash
npm install @kite/containers
```

Call `containerFor` in the object's constructor, and use what it returns where
Cloudflare's code uses `this.ctx.container`:

```ts

  container: KiteContainer;

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.container = containerFor(ctx, env, { pool: "kernels" });
  }

  async fetch(request: Request): Promise<Response> {
    if (!this.container.running) {
      this.container.start({ image: "ghcr.io/example/kernel:1", enableInternet: true });
      await this.container.setInactivityTimeout(10 * 60 * 1000);
    }
    return this.container.getTcpPort(8080).fetch(request);
  }
}
```

- `containerFor` stores the id of the object's sandbox in the object's
  storage. It reads the sandbox before the object handles its first request,
  so an object that restarts finds its container.
- `running` is true while the sandbox is pending or running.
- `start()` returns at once, and every other member waits until the sandbox
  is running.
- `getTcpPort(8080).fetch()` returns the container's response, whatever its
  status code. It throws when the cluster refuses the request or cannot send
  it to the container: when the token is not allowed, the container has
  stopped, or nothing in the container listens on the port yet.

:::note
A server in the container starts to listen a moment after the sandbox is
running, so retry the first request.
:::

After a request, the pool lists the sandbox as `Running`:

```bash
kubectl get --raw /apis/kiteplane.dev/v1alpha1/namespaces/default/sandboxpools/kernels/sandboxes
```

## Snapshots

`snapshotContainer()` saves the container's files and returns a snapshot.
Store the snapshot, and pass it to `start()` to start a container with those
files:

```ts
const snapshot = await this.container.snapshotContainer({ name: "before-upgrade" });
await this.ctx.storage.put("snapshot", snapshot);

// Later, when no container runs:
const saved = await this.ctx.storage.get<ContainerSnapshot>("snapshot");
if (saved) this.container.start({ containerSnapshot: saved, enableInternet: true });
```

A snapshot contains the files that the container wrote or deleted. A container
started from it runs its image's entrypoint again, or the `entrypoint` that you
pass. The cluster deletes a snapshot 30 days after it was taken or last
restored.

To save the memory of the container's processes too, such as a notebook's
variables, pass `memory: true`:

```ts
const snapshot = await this.container.snapshotContainer({ name: "kernel", memory: true });
```

A memory snapshot needs a pool under gVisor, on amd64 nodes. Its `kind` is
`Memory`. A container that you start from it runs the same
processes, with the memory that they had when you took the snapshot.
Do not pass `start()` an `entrypoint`, or the container starts from the
snapshot's files only.
[Memory snapshots](/docs/sandbox-pools/#memory-snapshots) says which
containers can take one, and when a node starts the container from the files
instead.

## Stop a container

A container stops when it has had no request and no open WebSocket through
the cluster's API for the length of its inactivity timeout. The timeout is 10
minutes, or the duration that you set with `setInactivityTimeout()`. The pool
then reports the sandbox as `Stopped`, with the reason `Idle`. The container's
files are lost unless you took a snapshot.

`destroy()` deletes the sandbox and stops its container at once. `signal(9)` and
`signal(15)` do the same. A `start()` after a container has stopped deletes the
stopped sandbox.

## Differences from Cloudflare

### `start()`

- Requires `image` or `containerSnapshot`.
- Ignores `instance` and `labels`, because the pool sets each container's size.
- With `enableInternet: false`, the container cannot connect to any host
  outside the cluster.
- Throws for `directorySnapshots`.

### `running`

- Turns false when the package next reads the sandbox: when the object starts,
  when the cluster refuses a request to the container, or while `monitor()`
  waits.
- A request after the container stopped throws once, and `running` is false
  after it.

### `getTcpPort().fetch()`

- The container does not receive the request's `Authorization`,
  `Proxy-Authorization`, `Accept-Encoding`, `Cf-Access-*`, `Impersonate-*` and
  `X-Remote-*` headers, or the `CF_Authorization` cookie.
- [Sandbox pools](/docs/sandbox-pools/#limits) gives the size limits of a
  request, a response and a WebSocket message.

### `setInactivityTimeout()`

- The timeout counts from the last request or WebSocket to the container, not
  from the object's last event, so a container can stop while its object works
  without calling it.
- The cluster keeps the timeout with the sandbox, so an object that restarts
  does not need to set it again.
- The duration must be finite and greater than 0. Any other value throws a
  `TypeError`, and nothing is sent.

### `monitor()`

- Resolves when the container exits with any code, and rejects with the
  sandbox's message when it fails.
- Until then, it reads the sandbox repeatedly. The wait between reads starts at
  1 second and doubles up to 30 seconds.

:::caution
Each read's timer keeps the object in memory, and Cloudflare bills the object
for that time. Cloudflare keeps the object in memory for at most 15 minutes.
:::

### Other members

| Member                                                                                                                                         | On Kite                                                                                                                                          |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `signal()`                                                                                                                                     | Accepts only `9` and `15`, which delete the sandbox. Throws for any other signal                                                                 |
| `snapshotContainer()`                                                                                                                          | Returns a snapshot with the `name` that you pass, which the cluster does not store. Also takes `memory: true`, and returns the snapshot's `kind` |
| `inspect()`                                                                                                                                    | Returns the sandbox's image, which for a container started from a snapshot is the snapshot's image, and no labels                                |
| `images`                                                                                                                                       | Is empty                                                                                                                                         |
| `exec()`, `getTcpPort().connect()`, `interceptOutboundHttp()`, `interceptOutboundHttps()`, `interceptAllOutboundHttp()`, `snapshotDirectory()` | Throw                                                                                                                                            |
