@getenergy/gke-sandboxes 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -210
- package/dist/index.d.ts +14 -3
- package/dist/index.js +120 -15
- package/dist/kubernetes-api.d.ts +9 -1
- package/dist/kubernetes-api.js +14 -3
- package/dist/memory-watchdog.d.ts +1 -0
- package/dist/memory-watchdog.js +113 -0
- package/package.json +13 -1
package/README.md
CHANGED
|
@@ -1,145 +1,31 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gke-sandboxes
|
|
2
2
|
|
|
3
|
-
Give each cloud agent
|
|
3
|
+
Give each cloud agent its own Linux sandbox, in your own Google Cloud project. A sandbox runs commands and keeps files. Put it to sleep while the user is away, and open the same ID later to get the files back.
|
|
4
|
+
|
|
5
|
+
It costs about **$7.80 a month** to keep a 4 vCPU / 8 GB sandbox awake, less than every managed provider we priced.
|
|
4
6
|
|
|
5
7
|
<picture>
|
|
6
8
|
<source media="(max-width: 600px)" srcset="docs/assets/running-sandbox.png">
|
|
7
|
-
<img src="docs/assets/running-sandbox-wide.png" width="100%" alt="Monthly compute cost for
|
|
9
|
+
<img src="docs/assets/running-sandbox-wide.png" width="100%" alt="Monthly compute cost for a 4 vCPU and 8 GB sandbox that is awake for 730 hours at about 2% CPU. gke-sandboxes on C4D machines costs an estimated $7.80 per sandbox when many sandboxes split the machine costs (1×). At list price, Agent37 costs $8.80 (1.13×), Modal $25.75 (3.3×), Vercel Sandbox $130.91 (16.8×), Daytona $241.78 (31×), and E2B $241.78 (31×). Disk and plan fees are extra.">
|
|
8
10
|
</picture>
|
|
9
11
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
## Set it up with your coding agent
|
|
12
|
+
## Set it up
|
|
13
13
|
|
|
14
14
|
Paste this into Claude Code, Cursor, Codex or another coding agent:
|
|
15
15
|
|
|
16
16
|
```text
|
|
17
|
-
Set up
|
|
18
|
-
|
|
19
|
-
Clone https://github.com/comp-work/gke-sandboxes and follow skills/setup-gke-sandboxes/SKILL.md step by step.
|
|
20
|
-
Ask me for my project ID, region and Google account before creating anything, and tell me what it will cost.
|
|
17
|
+
Set up gke-sandboxes in my Google Cloud project. Follow these instructions step by step:
|
|
18
|
+
https://raw.githubusercontent.com/comp-work/gke-sandboxes/main/skills/setup-gke-sandboxes/SKILL.md
|
|
21
19
|
```
|
|
22
20
|
|
|
23
|
-
The agent deploys the cluster with Terraform, runs the verifier, and shows you how to connect your backend.
|
|
24
|
-
|
|
25
|
-
## Where GKE Sandboxes works well
|
|
26
|
-
|
|
27
|
-
Use it when your product runs agents for many users and each session needs its own files, tools, and processes. You choose the container image. One agent might patch a repo and run its test suite. Another might run Python over a customer’s data and save a report. Each runs in its own gVisor pod. Your backend decides who can open each sandbox.
|
|
28
|
-
|
|
29
|
-
This setup pays off when you have **many sessions to keep and only some of them are busy at once**. Active agents share the cluster’s machines. Sleeping agents leave a snapshot in Cloud Storage. A 20 GB snapshot costs about **37¢ for a month** in Iowa. Putting an agent to sleep frees CPU and memory immediately after its pod is removed. Your compute bill falls when the cluster can use fewer machines. [Storage rates and comparison](#storage-for-a-20-gb-sleeping-sandbox)
|
|
30
|
-
|
|
31
|
-
## Running cost at 4 vCPU and 8 GB
|
|
32
|
-
|
|
33
|
-
For **730 running hours**, we estimate **$7.80 per sandbox** when many sandboxes share GKE machines at on-demand rates. Agent37 standard lists **$8.80** for compute. Daytona and E2B each list **$241.78** for 4 vCPU and 8 GiB, about **31×** the GKE estimate. [Agent37 pricing](https://www.agent37.com/pricing) · [Daytona pricing](https://www.daytona.io/pricing) · [E2B pricing](https://e2b.dev/pricing)
|
|
34
|
-
|
|
35
|
-
**Vercel Sandbox costs $161.18** for the same 730 running hours at 10% average CPU use, the assumption Vercel uses in its pricing examples. At Pro list rates in its default region (iad1), Vercel bills $0.0212 per GB-hour for memory and $0.128 per active CPU-hour. The 8 GB alone costs $123.81 over 730 hours, even when the code is waiting. Those hours span sessions because Pro allows up to 24 hours per session. [Vercel Sandbox pricing](https://vercel.com/docs/sandbox/pricing)
|
|
36
|
-
|
|
37
|
-
The $7.80 figure is for `c4d-highmem-16` machines, about $709 a month each in Iowa, holding **128 sandboxes** apiece. It adds 40% for spare machines, node disks, system nodes, and the cluster fee. A sandbox can use up to four CPUs and spends much of its time below that limit. If every agent needs all four at once, budget for more machines. [Deploy that configuration](#deploy-on-c4d)
|
|
38
|
-
|
|
39
|
-
The quickstart’s defaults are E2 machines holding about 64 sandboxes each, which comes to about **$12 per sandbox** by the same method. The managed providers’ figures exclude disks, plan fees, credits, and discounts. On GKE you operate the cluster yourself. On E2B this configuration requires a Pro plan, and the hours can span sessions.
|
|
40
|
-
|
|
41
|
-
## Storage for a 20 GB sleeping sandbox
|
|
42
|
-
|
|
43
|
-
<img src="docs/assets/monthly-cost.png" width="100%" alt="Storage for 20 GB retained for 730 hours. GKE snapshot about $0.37, Agent37 retained disk $1.80, Vercel Sandbox snapshot $1.60 on Pro, Daytona archived container $0, E2B paused sandbox $0 extra on Pro. Plan fees and infrastructure are excluded.">
|
|
44
|
-
|
|
45
|
-
For the same **20 billion bytes kept for 730 hours**, a GKE file snapshot in Iowa costs about **$0.37** (18.63 GiB in Cloud Storage Standard). Agent37 stops charging for compute during sleep and charges **$1.80** for a 20 GB disk. GKE machines you keep running still appear on your cluster bill. [Google Cloud Storage pricing](https://cloud.google.com/storage/pricing) · [Agent37 pricing](https://www.agent37.com/pricing)
|
|
46
|
-
|
|
47
|
-
**Vercel Sandbox charges $1.60 a month** to keep a 20 GB filesystem snapshot on Pro, at $0.08 per GB-month. For the full 730 hours, set retention to at least 31 days. The default is 30 days after last use. [Vercel Sandbox pricing](https://vercel.com/docs/sandbox/pricing) · [Snapshot retention](https://vercel.com/docs/sandbox/concepts/snapshots#snapshot-retention)
|
|
48
|
-
|
|
49
|
-
**Daytona charges $0 once a container is archived.** Its files can be restored when you start it again. If you leave it stopped instead, Daytona bills for reserved disk at $0.000108 per GiB-hour after the first 5 GiB. [Daytona billing](https://www.daytona.io/docs/billing) · [Daytona pricing](https://www.daytona.io/pricing)
|
|
50
|
-
|
|
51
|
-
**E2B charges $0 extra to keep this sandbox paused on Pro.** The $150 monthly plan includes 20 GiB of disk **per sandbox**. Its separate concurrency limit covers 100 running sandboxes, with paid options for more. Paused sandboxes can retain files and memory indefinitely. [E2B pricing](https://e2b.dev/pricing) · [E2B disk and concurrency limits](https://github.com/e2b-dev/e2b/blob/main/spec/openapi.yml) · [E2B pause and resume](https://docs.e2b.dev/sandbox/persistence)
|
|
52
|
-
|
|
53
|
-
## Performance against Agent37
|
|
54
|
-
|
|
55
|
-
We ran the same commands on the same revision of Better Auth. **The build took 67 seconds on GKE and 100 seconds on Agent37 standard.** The GKE column is one run per test on a C4D machine with one sandbox. Agent37 publishes medians. Both used a 4 vCPU / 8 GB limit. The V8 row uses the benchmark’s current GitHub version on GKE and a pinned Phoronix profile on Agent37. [GKE benchmark script](examples/benchmark-build.sh) · [Agent37 results and benchmark code](https://www.agent37.com/benchmarks)
|
|
56
|
-
|
|
57
|
-
| Metric | GKE on C4D | Agent37 standard |
|
|
58
|
-
| --- | ---: | ---: |
|
|
59
|
-
| Compute per sandbox, 730 hours | $7.80 at scale, estimated | $8.80 list price |
|
|
60
|
-
| Clone the repo | 1.6 s | 8.3 s |
|
|
61
|
-
| Cold dependency install | 13.5 s | 24.1 s |
|
|
62
|
-
| Build | 67 s | 100 s |
|
|
63
|
-
| V8 web tooling throughput | 22.8 runs/s | 17.5 runs/s |
|
|
64
|
-
|
|
65
|
-
On the same machine packed with 95 other sandboxes, each using about 7% of a CPU as an idle agent sandbox does, the build took **81 seconds** and V8 throughput fell to **16.1 runs/s**. With four builds running at once among them, each took about **155 seconds**. Agent37’s VM tier reports a **65.9-second** median build. The 67-second result is for a sandbox alone on its machine, and the $7.80 estimate is for a packed one. We have no matching test under load on Agent37 or head-to-head speed measurements for Daytona, E2B, or Vercel. The quickstart’s default E2 machines are slower: the same build took 154 seconds alone on `e2-highmem-16`. [Agent37 benchmark](https://www.agent37.com/benchmarks)
|
|
66
|
-
|
|
67
|
-
## Create, sleep, and wake times
|
|
68
|
-
|
|
69
|
-
Sandbox Bench tested ten managed sandbox configurations at **4 vCPU and 8 GB** from one server in Florida. Energy ran GKE separately at the same CPU and memory limits. Both start timers end when the first shell command (`true`) succeeds. For gke-sandboxes, the startup median includes all 60 requests with a two-pod pool. Managed providers report medians over 100 starts each. Snapshot medians come from 30 separate trials per configuration where measured. [Benchmark](https://aisandboxbench.com/) · [Pinned results](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/benchmark.same-spec.json) · [Timer code](https://github.com/opencoredev/sandbox-sdk/blob/56e60d6f42a9b11efb487b5364efc325831e976a/bench/src/v2-runner.ts)
|
|
70
|
-
|
|
71
|
-
<img src="docs/assets/sandbox-lifecycle.png" width="100%" alt="Median fresh start, snapshot save and start from snapshot for GKE and ten managed configurations. All timings are in the table below.">
|
|
72
|
-
|
|
73
|
-
<details>
|
|
74
|
-
<summary>Read the timings as a table</summary>
|
|
75
|
-
|
|
76
|
-
| Provider | Start fresh | Save snapshot | Start from snapshot |
|
|
77
|
-
| --- | ---: | ---: | ---: |
|
|
78
|
-
| gke-sandboxes | 1.06 s | 2.82 s | 3.54 s |
|
|
79
|
-
| Modal | 0.38 s | 0.94 s | 0.98 s |
|
|
80
|
-
| Vercel Sandbox | 0.52 s | 1.15 s | 1.12 s |
|
|
81
|
-
| Superserve | 0.52 s | 0.38 s | 0.55 s |
|
|
82
|
-
| Upstash Ephemeral Box | 0.68 s | 2.12 s | 1.13 s |
|
|
83
|
-
| Freestyle | 0.69 s | 0.43 s | 0.75 s |
|
|
84
|
-
| E2B | 0.79 s | 1.83 s | 1.12 s |
|
|
85
|
-
| Luxor | 1.09 s | 6.87 s | 1.88 s |
|
|
86
|
-
| Boat | 1.12 s | — | — |
|
|
87
|
-
| Daytona | 1.25 s | 7.35 s | 2.38 s |
|
|
88
|
-
| Upstash Box | 2.68 s | 2.14 s | 4.89 s |
|
|
89
|
-
|
|
90
|
-
</details>
|
|
91
|
-
|
|
92
|
-
Saving a snapshot times the provider’s snapshot call. Starting from it creates a new sandbox and runs a command. The saved image and its size can differ by provider. Vercel also stops the source sandbox when it snapshots. Boat had no snapshot result. The benchmark excluded an earlier batch after Daytona snapshot timeouts. [Benchmark notes](https://aisandboxbench.com/) · [Published exclusions](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/benchmark.same-spec.json)
|
|
93
|
-
|
|
94
|
-
<details>
|
|
95
|
-
<summary>Pause and resume an existing sandbox</summary>
|
|
96
|
-
|
|
97
|
-
For providers the benchmark classified as preserving running processes, it also timed the pause and resume calls separately. These medians end when each call returns. The first command after resume was timed separately. [Stage timings](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/traces.same-spec.json) · [Run notes](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/benchmark.same-spec.json)
|
|
98
|
-
|
|
99
|
-
| Provider | Runs | Pause | Resume |
|
|
100
|
-
| --- | ---: | ---: | ---: |
|
|
101
|
-
| E2B | 100 | 1.30 s | 0.36 s |
|
|
102
|
-
| Freestyle | 100 | 0.32 s | 0.19 s |
|
|
103
|
-
| Luxor | 77 | 60.53 s | 2.13 s |
|
|
104
|
-
| Superserve | 100 | 0.40 s | 0.22 s |
|
|
105
|
-
| Upstash Box | 99 | 0.84 s | 0.33 s |
|
|
106
|
-
|
|
107
|
-
</details>
|
|
108
|
-
|
|
109
|
-
**How we measured GKE.** We ran 100 fresh starts and 30 save, sleep and restore cycles from a Mac against a warm GKE node in Iowa. The node already had the Debian image. Creating a new gVisor pod and reaching its first command took 2.33 s at the median in this run, and 2.68 s over the 60 on-demand requests of the pool comparison below, which ran later the same day. Each restore reopened the sandbox in a new pod and ran `true`. The six source files from Sandbox Bench’s Vite app totaled 36,324 bytes. The median saved snapshot occupied **74.3 KiB** in Cloud Storage. Sleep, including removal of the old pod, took **4.02 s** at the median. We checked all six files after every restore. The shared benchmark used a Florida client and its own prepared images, so the network path and snapshot contents differ. [GKE measurements](docs/benchmarks/gke-lifecycle-2026-11-17.csv) · [GKE benchmark code](examples/benchmark-lifecycle.ts)
|
|
21
|
+
The agent deploys the cluster with Terraform, runs the verifier, and shows you how to connect your backend. Or [deploy it by hand](docs/deploy.md).
|
|
110
22
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
| Ready sandboxes | Requests that got a ready pod | Median start | 95th percentile |
|
|
114
|
-
| --- | ---: | ---: | ---: |
|
|
115
|
-
| 1 | 40 / 60 | 1.16 s | 3.63 s |
|
|
116
|
-
| 2 | 60 / 60 | 1.06 s | 1.60 s |
|
|
117
|
-
|
|
118
|
-
Each request got its own sandbox. After its first command, we checked its ID and deleted the pod. Longer agent sessions can leave less room for replacements. The quickstart creates pods on demand. To reproduce the table, run the pool benchmark with `--baselineSize 1 --poolSize 2`. [Enable a warm pool](#keep-sandboxes-ready-for-new-sessions) · [Benchmark code](examples/benchmark-warm-pool.ts) · [All 120 starts](docs/benchmarks/gke-warm-pool-sizing-2026-11-17.csv)
|
|
119
|
-
|
|
120
|
-
In the earlier test, creating a pod on demand took **2.68 s** at the median and **3.18 s** at the 95th percentile. Keeping one pod ready gave **1.32 s** and **3.50 s** respectively across all 60 requests. [Earlier measurements](docs/benchmarks/gke-warm-pool-2026-11-17.csv)
|
|
121
|
-
|
|
122
|
-
**Cost of keeping two sandboxes ready.** Together the two unused pods reserved 8 vCPU and 16 GiB. Both pool sizes fit on the same sandbox node throughout the test. An extra Iowa `e2-highmem-16` node with a 150 GiB balanced boot disk would add about $543 for 730 hours at on-demand list rates. [Google VM rates](https://cloud.google.com/products/compute/pricing/general-purpose) · [Disk rates](https://cloud.google.com/compute/disks-image-pricing)
|
|
123
|
-
|
|
124
|
-
## When to choose a managed provider
|
|
125
|
-
|
|
126
|
-
| If you need… | What to consider |
|
|
127
|
-
| --- | --- |
|
|
128
|
-
| A handful of sandboxes and no cluster to run | Agent37 meters compute by the minute. Daytona offers pay-as-you-go compute. With GKE, you manage capacity, upgrades, and recovery, and pay for machines between jobs. [Agent37](https://www.agent37.com/pricing) · [Daytona](https://www.daytona.io/pricing) |
|
|
129
|
-
| A running process to pick up where it left off | E2B and Agent37 can preserve memory through sleep. This quickstart restores files. GKE supports whole-pod snapshots on compatible machines, but this client has only been verified with file restores. [GKE snapshot modes](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/pod-snapshots) · [E2B](https://docs.e2b.dev/sandbox/persistence) · [Agent37](https://www.agent37.com/compare/daytona) |
|
|
130
|
-
| A preview URL to send to a user | Daytona ships expiring, revocable links. Agent37 offers authenticated URLs and custom domains. This setup keeps pods private. To share a preview, add a proxy that checks access to the sandbox and port. [Daytona previews](https://www.daytona.io/docs/en/preview/) · [Agent37 networking](https://www.agent37.com/) |
|
|
131
|
-
| GPU access or a separate VM kernel per sandbox | The quickstart runs on CPUs with gVisor. Daytona offers GPU sandboxes. E2B gives each sandbox a Firecracker microVM. [Daytona GPUs](https://www.daytona.io/pricing) · [E2B isolation](https://e2b.dev/security) |
|
|
132
|
-
|
|
133
|
-
## Use from a backend
|
|
134
|
-
|
|
135
|
-
Install the client in your backend. It runs on Node.js 22 or later and on Bun.
|
|
23
|
+
Then use it from your backend, on Node.js 22+ or Bun:
|
|
136
24
|
|
|
137
25
|
```sh
|
|
138
26
|
npm install @getenergy/gke-sandboxes
|
|
139
27
|
```
|
|
140
28
|
|
|
141
|
-
Your backend chooses a sandbox ID after checking the user’s access. Calling `acquire` with that ID creates a sandbox, returns the running one, or wakes it from its snapshot.
|
|
142
|
-
|
|
143
29
|
```ts
|
|
144
30
|
import { GkeSandboxes, KubernetesApi } from '@getenergy/gke-sandboxes';
|
|
145
31
|
|
|
@@ -149,112 +35,58 @@ const sandboxes = new GkeSandboxes(new KubernetesApi(clusterUrl, getGoogleAccess
|
|
|
149
35
|
image: 'docker.io/library/debian:bookworm-slim',
|
|
150
36
|
});
|
|
151
37
|
|
|
38
|
+
// Creates the sandbox, returns the running one, or wakes it from its snapshot.
|
|
152
39
|
const { sandbox } = await sandboxes.acquire('session-42', AbortSignal.timeout(300_000));
|
|
153
|
-
await sandbox.
|
|
154
|
-
|
|
155
|
-
if (exitCode !== 0) throw new Error(result);
|
|
156
|
-
await sandboxes.checkpoint(sandbox.id);
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
- **Keep active work running.** Call the returned `touch()` periodically while an agent is busy. Schedule `sleepUnused()` from your backend. By default a sandbox can sleep after five idle minutes. If jobs run in the background, supply `drain(sandbox)` to check for work before sleep. Returning `false` keeps it awake. Explicit `sleep(id)` checks the same conditions.
|
|
160
|
-
- **Manage saved files.** Use `find(id)` to inspect a sandbox without waking it. Call `delete(id)` when its files can be discarded and other callers have finished with the ID.
|
|
161
|
-
- **Bring your tools.** Use a stable image with POSIX shell utilities and writable `/var/tmp`. Pin the image digest in production. To share a read-only set of tools across sandboxes, pass `runtime: { image, mountPath }`. Use `boot(labels)` to start a service once the filesystem is ready.
|
|
162
|
-
- **Size the sandbox.** Pass `resources: { requests, limits }` to set what a sandbox reserves on its node and the most it may use. The requests decide how many sandboxes fit on a machine.
|
|
163
|
-
|
|
164
|
-
### Keep sandboxes ready for new sessions
|
|
165
|
-
|
|
166
|
-
Run one pool maintainer in your backend. This example keeps two unused sandboxes ready so two agents can start at once. Give every backend replica the same pool name, namespace, image and resource settings.
|
|
167
|
-
|
|
168
|
-
```ts
|
|
169
|
-
const pool = sandboxes.warmPool('agents');
|
|
170
|
-
|
|
171
|
-
// In one long-running worker. Abort the signal on shutdown.
|
|
172
|
-
await pool.maintain(2, shutdownSignal);
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
In the request handler, call `create` for a new session. It claims a ready sandbox once or creates one on demand when the pool is empty. Store the returned ID with its owner. When the user comes back, call `sandboxes.acquire(id, signal)` to reopen it.
|
|
176
|
-
|
|
177
|
-
```ts
|
|
178
|
-
const { sandbox, fromPool, touch } = await pool.create(signal);
|
|
40
|
+
const { exitCode, result } = await sandbox.process.executeCommand('echo hello');
|
|
41
|
+
await sandboxes.sleep(sandbox.id);
|
|
179
42
|
```
|
|
180
43
|
|
|
181
|
-
|
|
44
|
+
[Full client guide](docs/client.md)
|
|
182
45
|
|
|
183
|
-
##
|
|
46
|
+
## Features
|
|
184
47
|
|
|
185
|
-
|
|
48
|
+
- **Sleep and wake.** A sleeping sandbox is a snapshot in Cloud Storage and uses no CPU or memory. Opening its ID wakes it with its files.
|
|
49
|
+
- **Idle sandboxes sleep on their own.** A sweeper puts a sandbox to sleep after five minutes without use.
|
|
50
|
+
- **Isolated.** Each sandbox is its own gVisor pod, with incoming traffic blocked and no access to your cloud credentials.
|
|
51
|
+
- **Your image.** Use any container image with a POSIX shell.
|
|
52
|
+
- **Commands and files.** Run commands with timeouts and streamed output. Upload and download files.
|
|
53
|
+
- **Memory guard.** A runaway program is ended before it takes the whole sandbox down.
|
|
54
|
+
- **Warm pool.** Keep a few sandboxes ready so a new session starts in under half a second.
|
|
55
|
+
- **Preview links.** An example proxy serves a sandbox’s web server through signed links that expire.
|
|
56
|
+
- **Hooks.** Callbacks report every operation’s timing and failures to your own logging.
|
|
186
57
|
|
|
187
|
-
|
|
58
|
+
[Client guide](docs/client.md) · [Operating limits](docs/limits.md)
|
|
188
59
|
|
|
189
|
-
|
|
60
|
+
## How it compares
|
|
190
61
|
|
|
191
|
-
|
|
192
|
-
export TF_VAR_project_id=your-disposable-project
|
|
193
|
-
export TF_VAR_operator_member=user:you@example.com
|
|
194
|
-
export TF_VAR_region=us-central1
|
|
195
|
-
export TF_VAR_max_sandbox_nodes=3
|
|
196
|
-
|
|
197
|
-
bun install
|
|
198
|
-
terraform -chdir=infra init
|
|
199
|
-
terraform -chdir=infra apply
|
|
200
|
-
export KUBECONFIG="$(mktemp)"
|
|
201
|
-
gcloud container clusters get-credentials sandboxes --dns-endpoint \
|
|
202
|
-
--project="$TF_VAR_project_id" --region="$TF_VAR_region"
|
|
203
|
-
terraform -chdir=infra output -raw manifests | kubectl apply -f -
|
|
204
|
-
bun examples/verify.ts \
|
|
205
|
-
--endpoint "$(terraform -chdir=infra output -raw endpoint)" \
|
|
206
|
-
--controller "$(terraform -chdir=infra output -raw controller)"
|
|
207
|
-
```
|
|
62
|
+
One sandbox at 4 vCPU and 8 GB. Costs are list prices for compute and storage only.
|
|
208
63
|
|
|
209
|
-
|
|
64
|
+
#### Cost while awake
|
|
210
65
|
|
|
211
|
-
|
|
66
|
+
Every bar in the chart above prices the same mostly idle sandbox, at the 2% CPU that Energy’s running sandboxes averaged. Daytona, E2B and Agent37 charge for the full size while it runs. Vercel charges for the CPU in use and all of the memory. Modal charges for what is used. The GKE figure is an estimate for 128 sandboxes sharing each C4D machine, with 40% added for spare machines and cluster overhead. Agents that run hotter fit fewer to a machine: at 6% CPU it is about $15.50.
|
|
212
67
|
|
|
213
|
-
|
|
68
|
+
#### Cost while asleep
|
|
214
69
|
|
|
215
|
-
|
|
216
|
-
export TF_VAR_sandbox_machine_type=c4d-highmem-16
|
|
217
|
-
export TF_VAR_sandbox_node_disk_type=hyperdisk-balanced
|
|
218
|
-
export TF_VAR_sandbox_max_pods_per_node=256
|
|
219
|
-
```
|
|
70
|
+
A sleeping sandbox is a snapshot in Cloud Storage. Machines you keep running still appear on your bill.
|
|
220
71
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
```ts
|
|
224
|
-
resources: {
|
|
225
|
-
requests: { cpu: '100m', memory: '850Mi', 'ephemeral-storage': '4Gi' },
|
|
226
|
-
limits: { cpu: '4', memory: '8Gi', 'ephemeral-storage': '20Gi' },
|
|
227
|
-
},
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
These requests fit 128 sandboxes on a `c4d-highmem-16`, which has about 116 GiB of memory left for pods. Memory is the limit to watch. A node that runs out evicts sandboxes, and they come back from their last snapshot. Measure what your agents use before lowering the memory request. C4D capacity varies by zone. When we tested, one of three Iowa zones had none.
|
|
72
|
+
<img src="docs/assets/monthly-cost.png" width="100%" alt="Storage for 20 GB retained for 730 hours. GKE snapshot about $0.37, Agent37 retained disk $1.80, Vercel Sandbox snapshot $1.60 on Pro, Daytona archived container $0, E2B paused sandbox $0 extra on Pro. Plan fees and infrastructure are excluded.">
|
|
231
73
|
|
|
232
|
-
|
|
74
|
+
#### Start and wake
|
|
233
75
|
|
|
234
|
-
|
|
76
|
+
Medians. The GKE start time is with two sandboxes kept ready; without one it is about 2.7 s. The other providers were timed by Sandbox Bench from a different region, so read the rows as neighbors, not a ranking. GKE wakes slower than most, and slower still with many files: about 6.5 s at 25,000 files.
|
|
235
77
|
|
|
236
|
-
|
|
237
|
-
kubectl get pods,podsnapshots -n sandboxes
|
|
238
|
-
terraform -chdir=infra output -raw manifests | kubectl delete --ignore-not-found -f -
|
|
239
|
-
terraform -chdir=infra destroy
|
|
240
|
-
```
|
|
78
|
+
<img src="docs/assets/sandbox-lifecycle.png" width="100%" alt="Median fresh start, snapshot save and start from snapshot for GKE and ten managed configurations. All timings are in the table below.">
|
|
241
79
|
|
|
242
|
-
|
|
80
|
+
#### Speed once running
|
|
243
81
|
|
|
244
|
-
|
|
82
|
+
Building Better Auth took 67 s on a C4D machine with one sandbox, 81 s on a machine packed with 95 idle ones, and 100 s on Agent37. We have no build timings for the other providers.
|
|
245
83
|
|
|
246
|
-
|
|
84
|
+
#### What sleep keeps
|
|
247
85
|
|
|
248
|
-
-
|
|
249
|
-
- **Wake time and snapshot size.** Both grow with the number of files, more than with their bytes. GKE recreates every file before the sandbox starts. In Energy’s production cluster a sandbox with about 25,000 files wakes in about 6.5 s, and ones with about 200,000 files took 30 to 45 s. In a test, 200,000 small files totaling 98 MB produced a 3 GB snapshot. Keep package caches and other disposable files on `/tmp`.
|
|
250
|
-
- **Capacity.** By default a sandbox requests 0.25 vCPU, 1 GiB of memory, and 4 GiB of temporary storage. Its limits are 2 vCPU, 4 GiB, and 20 GiB respectively. Change them with `resources`. A low-priority placeholder pod keeps capacity available for new sandboxes. Size the pool for your peak traffic and regional quota.
|
|
251
|
-
- **Access.** Keep the client in a trusted backend. It can execute commands and read files across its namespace. Your app owns user authorization and billing. The network rules allow DNS and outgoing public internet traffic and block incoming pod traffic. Keep the workload identity metadata endpoint blocked.
|
|
252
|
-
- **Identity.** Use a DNS-label sandbox ID of up to 56 characters. To keep custom labels across sleep, include them in the snapshot policy’s grouping rules. Use separate manager selectors or namespaces for independent deployments. The `onOperation` and `onPodLost` callbacks report timings and failures.
|
|
86
|
+
gke-sandboxes restores files, not running processes. E2B and Agent37 can keep memory through sleep.
|
|
253
87
|
|
|
254
|
-
|
|
88
|
+
#### When a managed provider fits better
|
|
255
89
|
|
|
256
|
-
|
|
257
|
-
bun examples/cost.ts examples/cost-inputs.json
|
|
258
|
-
```
|
|
90
|
+
The trade is that you run the cluster: capacity, upgrades and recovery are yours. A managed provider is the better choice if you need only a handful of sandboxes, running processes that survive sleep, GPUs, or a VM kernel per sandbox.
|
|
259
91
|
|
|
260
|
-
|
|
92
|
+
[Full comparison, with sources and method](docs/comparison.md)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { type KubernetesApi } from './kubernetes-api.js';
|
|
3
|
-
export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
|
|
2
|
+
import { type ExecOptions, type KubernetesApi } from './kubernetes-api.js';
|
|
3
|
+
export { KubernetesApi, KubernetesApiError, type ExecOptions } from './kubernetes-api.js';
|
|
4
4
|
export type SandboxEnvironment = {
|
|
5
5
|
id: string;
|
|
6
6
|
state: 'started' | 'stopped';
|
|
7
7
|
process: {
|
|
8
|
-
executeCommand(command: string, cwd?: string, env?: Record<string, string>, timeout?: number): Promise<{
|
|
8
|
+
executeCommand(command: string, cwd?: string, env?: Record<string, string>, timeout?: number, options?: ExecOptions): Promise<{
|
|
9
9
|
exitCode: number;
|
|
10
10
|
result: string;
|
|
11
|
+
truncated: boolean;
|
|
11
12
|
}>;
|
|
12
13
|
};
|
|
13
14
|
fs: {
|
|
14
15
|
uploadFile(local: string, remote: string, timeout?: number): Promise<void>;
|
|
16
|
+
downloadFile(remote: string, local: string, timeout?: number): Promise<void>;
|
|
15
17
|
};
|
|
16
18
|
};
|
|
17
19
|
type Labels = Record<string, string>;
|
|
@@ -46,6 +48,14 @@ export type GkeSandboxOptions = {
|
|
|
46
48
|
};
|
|
47
49
|
/** What a sandbox reserves on its node and may use at most. Defaults to `DEFAULT_RESOURCES`. */
|
|
48
50
|
resources?: SandboxResources;
|
|
51
|
+
/**
|
|
52
|
+
* A sandbox that reaches its memory limit is killed whole. By default each sandbox watches its
|
|
53
|
+
* own memory and ends its largest processes first. `protect` lists command-line fragments of
|
|
54
|
+
* processes it must never end, such as a service started by `boot`. Pass `false` to turn it off.
|
|
55
|
+
*/
|
|
56
|
+
memoryWatchdog?: false | {
|
|
57
|
+
protect?: string[];
|
|
58
|
+
};
|
|
49
59
|
boot?: (labels: Labels) => {
|
|
50
60
|
shell: string;
|
|
51
61
|
args: string[];
|
|
@@ -180,4 +190,5 @@ export declare class GkeSandboxes {
|
|
|
180
190
|
private snapshot;
|
|
181
191
|
delete(id: string): Promise<void>;
|
|
182
192
|
environment(name: string, state: 'started' | 'stopped'): SandboxEnvironment;
|
|
193
|
+
private makeEnvironment;
|
|
183
194
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
1
|
+
import { createHash, randomBytes, randomInt, randomUUID } from 'node:crypto';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
-
import {
|
|
3
|
+
import { createWriteStream } from 'node:fs';
|
|
4
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
5
|
+
import { finished } from 'node:stream/promises';
|
|
4
6
|
import { z } from 'zod';
|
|
5
7
|
import { KubernetesApiError } from './kubernetes-api.js';
|
|
8
|
+
import { MEMORY_WATCHDOG } from './memory-watchdog.js';
|
|
6
9
|
export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
|
|
7
10
|
// Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The disk limit
|
|
8
11
|
// keeps one sandbox from filling its node. A pod that exceeds it is evicted, not refused the
|
|
@@ -49,15 +52,60 @@ const bootScript = (shell) => `(
|
|
|
49
52
|
`;
|
|
50
53
|
// A sandbox's first pod records whose it is before anything else can happen to it: a dispatch
|
|
51
54
|
// that created the pod may be aborted before it could run a command in it.
|
|
52
|
-
const podCommand = (sandboxId, first, boot) => [
|
|
55
|
+
const podCommand = (sandboxId, first, boot, watchdog) => [
|
|
53
56
|
'sh',
|
|
54
57
|
'-c',
|
|
55
|
-
`${first ? `printf %s "$0" > ${SANDBOX_ID_FILE} || exit 1\n` : ''}${
|
|
58
|
+
`${first ? `printf %s "$0" > ${SANDBOX_ID_FILE} || exit 1\n` : ''}${
|
|
59
|
+
// Its own shell, so that its $$ is the watchdog and not the pod's first process.
|
|
60
|
+
watchdog
|
|
61
|
+
? // Kubernetes reads `$$` in a command as an escaped `$`, so the script's own are doubled.
|
|
62
|
+
`"$(command -v bash || echo sh)" -c ${quote(MEMORY_WATCHDOG.replaceAll('$$', () => '$$$$'))} gke-sandboxes-memory-watchdog ${watchdog.protect.map(quote).join(' ')} </dev/null &\n`
|
|
63
|
+
: ''}${boot ? bootScript(boot.shell) : ''}${POD_LOOP}`,
|
|
56
64
|
sandboxId,
|
|
57
65
|
...(boot ? boot.args : []),
|
|
58
66
|
];
|
|
59
67
|
// The command arrives on stdin so its size never meets a URL limit, and runs with stdin closed.
|
|
60
|
-
|
|
68
|
+
// Closing the connection does not stop the command, so a timer in the sandbox does: when the time
|
|
69
|
+
// is up it ends the command and every process descended from it, found through /proc so that no
|
|
70
|
+
// tool beyond the shell is needed. The caller's own timer rejects at the same moment.
|
|
71
|
+
const EXEC_WRAPPER = `script=$(cat)
|
|
72
|
+
sh -c "$script" </dev/null &
|
|
73
|
+
child=$!
|
|
74
|
+
(
|
|
75
|
+
trap 'kill "$nap" 2>/dev/null; exit 0' TERM
|
|
76
|
+
sleep "$1" &
|
|
77
|
+
nap=$!
|
|
78
|
+
wait "$nap"
|
|
79
|
+
pids=$child
|
|
80
|
+
grew=1
|
|
81
|
+
while [ -n "$grew" ]; do
|
|
82
|
+
grew=
|
|
83
|
+
for stat in /proc/[0-9]*/stat; do
|
|
84
|
+
read -r line < "$stat" 2>/dev/null || continue
|
|
85
|
+
pid=\${stat#/proc/}
|
|
86
|
+
pid=\${pid%/stat}
|
|
87
|
+
rest=\${line##*) }
|
|
88
|
+
rest=\${rest#* }
|
|
89
|
+
case " $pids " in *" $pid "*) continue ;; esac
|
|
90
|
+
case " $pids " in *" \${rest%% *} "*) pids="$pids $pid"; grew=1 ;; esac
|
|
91
|
+
done
|
|
92
|
+
done
|
|
93
|
+
kill -TERM $pids 2>/dev/null
|
|
94
|
+
sleep 2
|
|
95
|
+
kill -KILL $pids 2>/dev/null
|
|
96
|
+
) >/dev/null 2>&1 &
|
|
97
|
+
timer=$!
|
|
98
|
+
wait "$child"
|
|
99
|
+
code=$?
|
|
100
|
+
kill "$timer" 2>/dev/null
|
|
101
|
+
exit "$code"`;
|
|
102
|
+
const execCommand = (timeoutSeconds) => [
|
|
103
|
+
'sh',
|
|
104
|
+
'-c',
|
|
105
|
+
EXEC_WRAPPER,
|
|
106
|
+
'gke-sandboxes-exec',
|
|
107
|
+
String(timeoutSeconds),
|
|
108
|
+
];
|
|
61
109
|
const MetadataSchema = z.object({
|
|
62
110
|
name: z.string(),
|
|
63
111
|
uid: z.string(),
|
|
@@ -246,6 +294,22 @@ export class GkeSandboxes {
|
|
|
246
294
|
}),
|
|
247
295
|
]);
|
|
248
296
|
};
|
|
297
|
+
// Share one list among concurrent callers. Keep each chosen pod version reserved until
|
|
298
|
+
// the API stops listing it. That also covers a list issued while a claim is in flight.
|
|
299
|
+
let reading;
|
|
300
|
+
const reserved = new Set();
|
|
301
|
+
const podVersion = ({ metadata }) => metadata.uid + '/' + metadata.resourceVersion;
|
|
302
|
+
const available = async () => {
|
|
303
|
+
const pods = (await list(requestedLabels)).filter((pod) => pod.status.phase === 'Running' && ready(pod.status.conditions));
|
|
304
|
+
const versions = new Set(pods.map(podVersion));
|
|
305
|
+
for (const version of reserved)
|
|
306
|
+
if (!versions.has(version))
|
|
307
|
+
reserved.delete(version);
|
|
308
|
+
// Independent backend replicas can see the same list. Vary their first choice;
|
|
309
|
+
// the versioned Kubernetes patch still decides exclusive ownership.
|
|
310
|
+
const offset = pods.length ? randomInt(pods.length) : 0;
|
|
311
|
+
return pods.slice(offset).concat(pods.slice(0, offset));
|
|
312
|
+
};
|
|
249
313
|
const create = async (signal, labels = {}) => {
|
|
250
314
|
labelSchema.parse(labels);
|
|
251
315
|
for (const key of [
|
|
@@ -259,9 +323,17 @@ export class GkeSandboxes {
|
|
|
259
323
|
throw new Error(`Reserved pool label: ${key}`);
|
|
260
324
|
const startedAt = Date.now();
|
|
261
325
|
signal.throwIfAborted();
|
|
262
|
-
|
|
263
|
-
|
|
326
|
+
reading ??= available().finally(() => {
|
|
327
|
+
reading = undefined;
|
|
328
|
+
});
|
|
329
|
+
const pods = await reading;
|
|
330
|
+
while (pods.length) {
|
|
264
331
|
signal.throwIfAborted();
|
|
332
|
+
const pod = pods.pop();
|
|
333
|
+
const version = podVersion(pod);
|
|
334
|
+
if (reserved.has(version))
|
|
335
|
+
continue;
|
|
336
|
+
reserved.add(version);
|
|
265
337
|
const id = pod.metadata.name;
|
|
266
338
|
const now = String(Date.now());
|
|
267
339
|
try {
|
|
@@ -282,15 +354,17 @@ export class GkeSandboxes {
|
|
|
282
354
|
continue;
|
|
283
355
|
this.report('create', PodSchema.parse(claimed).metadata.labels, pod, startedAt, null);
|
|
284
356
|
return {
|
|
285
|
-
sandbox: this.
|
|
357
|
+
sandbox: this.makeEnvironment(id, 'started', id),
|
|
286
358
|
podName: id,
|
|
287
359
|
fromPool: true,
|
|
288
360
|
touch: () => this.touch(id),
|
|
289
361
|
};
|
|
290
362
|
}
|
|
291
363
|
catch (error) {
|
|
292
|
-
if (!(error instanceof KubernetesApiError && error.status === 409))
|
|
364
|
+
if (!(error instanceof KubernetesApiError && error.status === 409)) {
|
|
365
|
+
reserved.delete(version);
|
|
293
366
|
throw error;
|
|
367
|
+
}
|
|
294
368
|
}
|
|
295
369
|
}
|
|
296
370
|
const { sandbox, podName, touch } = await this.acquire(randomUUID(), signal, labels);
|
|
@@ -580,7 +654,7 @@ export class GkeSandboxes {
|
|
|
580
654
|
const check = new TextEncoder().encode(`test "$(cat ${quote(SANDBOX_ID_FILE)} 2>/dev/null)" = ${quote(id)}`);
|
|
581
655
|
// GKE fills in the files as the container starts, so the first looks can come too early.
|
|
582
656
|
for (let attempt = 0; attempt < RESTORE_CHECKS; attempt++) {
|
|
583
|
-
const { exitCode } = await this.kubernetes.exec(path,
|
|
657
|
+
const { exitCode } = await this.kubernetes.exec(path, execCommand(30), check, 30);
|
|
584
658
|
if (exitCode === 0) {
|
|
585
659
|
await this.kubernetes.request('PATCH', path, {
|
|
586
660
|
metadata: { annotations: { [RESTORED_ANNOTATION]: 'true' } },
|
|
@@ -634,7 +708,9 @@ export class GkeSandboxes {
|
|
|
634
708
|
{
|
|
635
709
|
name: 'sandbox',
|
|
636
710
|
image: this.options.image,
|
|
637
|
-
command: podCommand(sandbox.name, !snapshot, this.options.boot?.(sandbox.labels) ?? null
|
|
711
|
+
command: podCommand(sandbox.name, !snapshot, this.options.boot?.(sandbox.labels) ?? null, this.options.memoryWatchdog === false
|
|
712
|
+
? null
|
|
713
|
+
: { protect: this.options.memoryWatchdog?.protect ?? [] }),
|
|
638
714
|
volumeMounts: [
|
|
639
715
|
{ name: 'scratch', mountPath: '/tmp' },
|
|
640
716
|
...(this.options.runtime
|
|
@@ -769,8 +845,21 @@ export class GkeSandboxes {
|
|
|
769
845
|
await this.deleteMatching({ [SANDBOX_LABEL]: id });
|
|
770
846
|
}
|
|
771
847
|
environment(name, state) {
|
|
772
|
-
|
|
848
|
+
return this.makeEnvironment(name, state, null);
|
|
849
|
+
}
|
|
850
|
+
makeEnvironment(name, state, firstPod) {
|
|
851
|
+
// Only the immediate handoff can use the claim directly. A handle kept over I/O
|
|
852
|
+
// may have slept and woken in another pod, even before its first command.
|
|
853
|
+
if (firstPod)
|
|
854
|
+
setImmediate(() => {
|
|
855
|
+
firstPod = null;
|
|
856
|
+
}).unref();
|
|
773
857
|
const podPath = async () => {
|
|
858
|
+
if (firstPod) {
|
|
859
|
+
const path = `${this.pods}/${firstPod}`;
|
|
860
|
+
firstPod = null;
|
|
861
|
+
return path;
|
|
862
|
+
}
|
|
774
863
|
const pod = await this.livePod(name);
|
|
775
864
|
if (!pod)
|
|
776
865
|
throw new Error(`Sandbox ${name} is not running.`);
|
|
@@ -780,7 +869,7 @@ export class GkeSandboxes {
|
|
|
780
869
|
id: name,
|
|
781
870
|
state,
|
|
782
871
|
process: {
|
|
783
|
-
executeCommand: async (command, cwd = '/', env = {}, timeout = 60) => {
|
|
872
|
+
executeCommand: async (command, cwd = '/', env = {}, timeout = 60, options = {}) => {
|
|
784
873
|
const script = [
|
|
785
874
|
`cd ${quote(cwd)} || exit 1`,
|
|
786
875
|
...Object.entries(env).map(([key, value]) => {
|
|
@@ -790,8 +879,8 @@ export class GkeSandboxes {
|
|
|
790
879
|
}),
|
|
791
880
|
command,
|
|
792
881
|
].join('\n');
|
|
793
|
-
const { exitCode, output } = await this.kubernetes.exec(await podPath(),
|
|
794
|
-
return { exitCode, result: output };
|
|
882
|
+
const { exitCode, output, truncated } = await this.kubernetes.exec(await podPath(), execCommand(timeout), new TextEncoder().encode(script), timeout, options);
|
|
883
|
+
return { exitCode, result: output, truncated };
|
|
795
884
|
},
|
|
796
885
|
},
|
|
797
886
|
fs: {
|
|
@@ -800,6 +889,22 @@ export class GkeSandboxes {
|
|
|
800
889
|
if (exitCode !== 0)
|
|
801
890
|
throw new Error(`Could not upload ${remote}: ${output}`);
|
|
802
891
|
},
|
|
892
|
+
downloadFile: async (remote, local, timeout = 300) => {
|
|
893
|
+
const file = createWriteStream(local);
|
|
894
|
+
const errors = [];
|
|
895
|
+
// The file's bytes go straight to disk; only what `cat` complains about is kept.
|
|
896
|
+
const { exitCode } = await this.kubernetes
|
|
897
|
+
.exec(await podPath(), ['sh', '-c', 'cat "$0"', remote], new Uint8Array(), timeout, {
|
|
898
|
+
maxOutputBytes: 0,
|
|
899
|
+
onOutput: (chunk, stream) => stream === 'stdout' ? file.write(chunk.slice()) : errors.push(chunk.slice()),
|
|
900
|
+
})
|
|
901
|
+
.finally(() => file.end());
|
|
902
|
+
await finished(file);
|
|
903
|
+
if (exitCode === 0)
|
|
904
|
+
return;
|
|
905
|
+
await rm(local, { force: true });
|
|
906
|
+
throw new Error(`Could not download ${remote}: ${Buffer.concat(errors).toString('utf8').trim()}`);
|
|
907
|
+
},
|
|
803
908
|
},
|
|
804
909
|
};
|
|
805
910
|
}
|
package/dist/kubernetes-api.d.ts
CHANGED
|
@@ -5,7 +5,15 @@ export declare class KubernetesApiError extends Error {
|
|
|
5
5
|
export type KubernetesExecResult = {
|
|
6
6
|
exitCode: number;
|
|
7
7
|
output: string;
|
|
8
|
+
truncated: boolean;
|
|
8
9
|
};
|
|
10
|
+
export type ExecOptions = {
|
|
11
|
+
/** Called with each piece of output as it arrives, before any cap is applied. */
|
|
12
|
+
onOutput?: (chunk: Uint8Array, stream: 'stdout' | 'stderr') => void;
|
|
13
|
+
/** How much output to keep for the result. More than this is dropped and `truncated` is set. */
|
|
14
|
+
maxOutputBytes?: number;
|
|
15
|
+
};
|
|
16
|
+
export declare const DEFAULT_MAX_OUTPUT_BYTES: number;
|
|
9
17
|
/** The few Kubernetes API calls sandboxes need: JSON resources, watches and exec. */
|
|
10
18
|
export declare class KubernetesApi {
|
|
11
19
|
private readonly baseUrl;
|
|
@@ -30,5 +38,5 @@ export declare class KubernetesApi {
|
|
|
30
38
|
/** One watch's events, until the server ends it, the connection breaks or `ended` aborts. */
|
|
31
39
|
private events;
|
|
32
40
|
/** Runs a command in a pod's container, feeding it `stdin` and collecting its output. */
|
|
33
|
-
exec(podPath: string, command: string[], stdin: Uint8Array, timeoutSeconds: number): Promise<KubernetesExecResult>;
|
|
41
|
+
exec(podPath: string, command: string[], stdin: Uint8Array, timeoutSeconds: number, { onOutput, maxOutputBytes }?: ExecOptions): Promise<KubernetesExecResult>;
|
|
34
42
|
}
|
package/dist/kubernetes-api.js
CHANGED
|
@@ -31,6 +31,8 @@ export class KubernetesApiError extends Error {
|
|
|
31
31
|
this.name = 'KubernetesApiError';
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
+
// A command that prints without end must not exhaust the caller's memory.
|
|
35
|
+
export const DEFAULT_MAX_OUTPUT_BYTES = 32 * 2 ** 20;
|
|
34
36
|
/** The few Kubernetes API calls sandboxes need: JSON resources, watches and exec. */
|
|
35
37
|
export class KubernetesApi {
|
|
36
38
|
baseUrl;
|
|
@@ -152,7 +154,7 @@ export class KubernetesApi {
|
|
|
152
154
|
}
|
|
153
155
|
}
|
|
154
156
|
/** Runs a command in a pod's container, feeding it `stdin` and collecting its output. */
|
|
155
|
-
async exec(podPath, command, stdin, timeoutSeconds) {
|
|
157
|
+
async exec(podPath, command, stdin, timeoutSeconds, { onOutput, maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES } = {}) {
|
|
156
158
|
const url = new URL(`${podPath}/exec`, this.baseUrl);
|
|
157
159
|
url.protocol = 'wss:';
|
|
158
160
|
for (const stream of ['stdin', 'stdout', 'stderr'])
|
|
@@ -168,6 +170,8 @@ export class KubernetesApi {
|
|
|
168
170
|
socket.binaryType = 'arraybuffer';
|
|
169
171
|
const finished = Promise.withResolvers();
|
|
170
172
|
const output = [];
|
|
173
|
+
let kept = 0;
|
|
174
|
+
let truncated = false;
|
|
171
175
|
const timer = setTimeout(() => {
|
|
172
176
|
finished.reject(new Error(`Sandbox command timed out after ${timeoutSeconds} seconds.`));
|
|
173
177
|
socket.close();
|
|
@@ -185,8 +189,14 @@ export class KubernetesApi {
|
|
|
185
189
|
socket.onmessage = ({ data }) => {
|
|
186
190
|
const frame = new Uint8Array(data);
|
|
187
191
|
const payload = frame.subarray(1);
|
|
188
|
-
if (frame[0] === STDOUT || frame[0] === STDERR)
|
|
189
|
-
|
|
192
|
+
if (frame[0] === STDOUT || frame[0] === STDERR) {
|
|
193
|
+
onOutput?.(payload, frame[0] === STDOUT ? 'stdout' : 'stderr');
|
|
194
|
+
const fits = payload.subarray(0, Math.max(0, maxOutputBytes - kept));
|
|
195
|
+
if (fits.byteLength)
|
|
196
|
+
output.push(fits);
|
|
197
|
+
kept += fits.byteLength;
|
|
198
|
+
truncated ||= fits.byteLength < payload.byteLength;
|
|
199
|
+
}
|
|
190
200
|
if (frame[0] !== STATUS)
|
|
191
201
|
return;
|
|
192
202
|
// GKE sends the final status after stdout and stderr. Node can keep the socket
|
|
@@ -201,6 +211,7 @@ export class KubernetesApi {
|
|
|
201
211
|
finished.resolve({
|
|
202
212
|
exitCode: exitCode ? Number(exitCode.message) : 0,
|
|
203
213
|
output: Buffer.concat(output).toString('utf8'),
|
|
214
|
+
truncated,
|
|
204
215
|
});
|
|
205
216
|
}
|
|
206
217
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const MEMORY_WATCHDOG = "limit_file=/sys/fs/cgroup/memory/memory.limit_in_bytes\nusage_file=/sys/fs/cgroup/memory/memory.usage_in_bytes\n[ -r \"$limit_file\" ] && [ -r \"$usage_file\" ] || exit 0\nread limit < \"$limit_file\"\n[ \"$limit\" -lt 1125899906842624 ] || exit 0\nmargin=$((limit / 8))\n[ \"$margin\" -ge 268435456 ] || margin=268435456\n[ \"$margin\" -le $((limit / 4)) ] || margin=$((limit / 4))\nthreshold=$((limit - margin))\nsmall=67108864\ngib() { echo \"$(($1 / 1073741824)).$(($1 % 1073741824 * 10 / 1073741824))\"; }\ntick=/tmp/.gke-sandboxes-memory-watchdog.tick\nquick=\nrm -f \"$tick\"\nif [ -n \"${BASH_VERSION:-}\" ] && mkfifo \"$tick\" 2>/dev/null && (exec 9<>\"$tick\") 2>/dev/null; then\n exec 9<>\"$tick\"\n quick=1\nfi\nnap() {\n ms=$((($threshold - $1) / 8589935))\n [ \"$ms\" -ge 30 ] || ms=30\n [ \"$ms\" -le 500 ] || ms=500\n if [ \"$ms\" -lt 100 ]; then ms=0.0$ms; else ms=0.$ms; fi\n if [ -n \"$quick\" ]; then read -t \"$ms\" _ <&9; else sleep \"$ms\"; fi\n}\nunrelieved=\nwhile :; do\n read usage < \"$usage_file\" || usage=0\n if [ \"$usage\" -lt \"$threshold\" ]; then\n unrelieved=\n nap \"$usage\"\n continue\n fi\n shared=0\n while read key value unit; do\n if [ \"$key\" = Shmem: ]; then shared=$((value * 1024)); break; fi\n done < /proc/meminfo\n shm_files=$(df -Pk /dev/shm 2>/dev/null | { read header; read device blocks used rest; echo $((used * 1024)); })\n files=$((shared - ${shm_files:-0}))\n [ \"$files\" -gt 0 ] || files=0\n usage=$((usage - files))\n if [ \"$usage\" -lt \"$threshold\" ]; then\n unrelieved=\n nap \"$usage\"\n continue\n fi\n need=$((usage - threshold + small))\n freed=0\n ended=\n while [ \"$freed\" -lt \"$need\" ]; do\n victim=\n victim_bytes=0\n for dir in /proc/[0-9]*; do\n pid=${dir#/proc/}\n [ \"$pid\" -ne 1 ] && [ \"$pid\" -ne $$ ] || continue\n case \" $ended \" in *\" $pid \"*) continue ;; esac\n read size resident rest < \"$dir/statm\" 2>/dev/null || continue\n bytes=$((resident * 4096))\n [ \"$bytes\" -ge \"$small\" ] && [ \"$bytes\" -gt \"$victim_bytes\" ] || continue\n if [ $# -gt 0 ]; then\n command=$(tr '\\000' ' ' < \"$dir/cmdline\" 2>/dev/null)\n protected=\n for fragment in \"$@\"; do\n case \"$command\" in *\"$fragment\"*) protected=1 ;; esac\n done\n [ -z \"$protected\" ] || continue\n fi\n victim=$pid\n victim_bytes=$bytes\n done\n [ -n \"$victim\" ] || break\n printf '\\ngke-sandboxes ended this process: the sandbox was about to run out of memory (%s GiB) and this process held %s GiB of it. Running it again unchanged will end the same way. Use less memory, for example by working through the data in smaller pieces.\\n' \"$(gib \"$limit\")\" \"$(gib \"$victim_bytes\")\" > \"/proc/$victim/fd/2\" 2>/dev/null\n name=$(tr '\\000' ' ' < \"/proc/$victim/cmdline\" 2>/dev/null | tr -d '\"\\\\\\001-\\037' | cut -c1-200)\n kill -9 \"$victim\" 2>/dev/null\n printf '{\"event\":\"sandbox_memory_pressure\",\"outcome\":\"process_ended\",\"pid\":%s,\"command\":\"%s\",\"resident_bytes\":%s,\"usage_bytes\":%s,\"threshold_bytes\":%s,\"limit_bytes\":%s}\\n' \"$victim\" \"$name\" \"$victim_bytes\" \"$usage\" \"$threshold\" \"$limit\"\n ended=\"$ended $victim\"\n freed=$((freed + victim_bytes))\n done\n if [ -z \"$ended\" ] && [ -z \"$unrelieved\" ]; then\n printf '{\"event\":\"sandbox_memory_pressure\",\"outcome\":\"nothing_to_end\",\"usage_bytes\":%s,\"threshold_bytes\":%s,\"limit_bytes\":%s}\\n' \"$usage\" \"$threshold\" \"$limit\"\n unrelieved=1\n fi\n sleep 1\ndone\n";
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// gVisor has no out-of-memory killer of its own: a sandbox that reaches its memory limit is killed
|
|
2
|
+
// whole, with every process and everything written since its last snapshot. This script runs in
|
|
3
|
+
// each sandbox and ends its largest processes before that, so a runaway program costs a command
|
|
4
|
+
// and not the sandbox. It is plain POSIX shell, so it runs in any image the sandbox can.
|
|
5
|
+
//
|
|
6
|
+
// Its arguments are command-line fragments of processes that must never be ended.
|
|
7
|
+
//
|
|
8
|
+
// - gVisor reports the limit and the use in the older cgroup layout. Without those files, or with
|
|
9
|
+
// no limit, the script exits.
|
|
10
|
+
// - The threshold is an eighth of the limit below it, at least 256 MiB and at most a quarter of
|
|
11
|
+
// the limit.
|
|
12
|
+
// - Every look costs CPU, about a millisecond in gVisor, so it looks only as often as it must. A
|
|
13
|
+
// program can take about 4 GiB in a second. The wait before the next look is half the time such
|
|
14
|
+
// a program would need to reach the threshold from here: half a second in an idle sandbox, and
|
|
15
|
+
// 30 ms once use is close.
|
|
16
|
+
// - Waiting should not start a process, which costs four times a look. Under bash it waits with
|
|
17
|
+
// \`read -t\` on a pipe nothing writes to. Other shells use \`sleep\`: busybox's \`read -t\` came
|
|
18
|
+
// back at once with a fractional timeout, which made the loop spin.
|
|
19
|
+
// - Once a sandbox has been snapshotted or woken, gVisor reports every file on its disk as shared
|
|
20
|
+
// memory and adds it to the use. Those files do not count against the limit, so they are taken
|
|
21
|
+
// out. Files in /dev/shm are shared memory too, and do count.
|
|
22
|
+
// - It ends the processes holding the most, largest first, as few as bring use back under. Never
|
|
23
|
+
// the pod's first process, itself, a protected process, or one under 64 MiB. It first writes
|
|
24
|
+
// the reason to the process's error output, which is what its command shows the caller.
|
|
25
|
+
// - Memory returns a moment after a kill, so it waits a second before it looks again.
|
|
26
|
+
// - Each time it acts it prints one JSON line. It shares the pod's first process's output, so the
|
|
27
|
+
// line lands in the container's log, which GKE sends to Cloud Logging as structured fields with
|
|
28
|
+
// the pod's name and labels.
|
|
29
|
+
export const MEMORY_WATCHDOG = `limit_file=/sys/fs/cgroup/memory/memory.limit_in_bytes
|
|
30
|
+
usage_file=/sys/fs/cgroup/memory/memory.usage_in_bytes
|
|
31
|
+
[ -r "$limit_file" ] && [ -r "$usage_file" ] || exit 0
|
|
32
|
+
read limit < "$limit_file"
|
|
33
|
+
[ "$limit" -lt 1125899906842624 ] || exit 0
|
|
34
|
+
margin=$((limit / 8))
|
|
35
|
+
[ "$margin" -ge 268435456 ] || margin=268435456
|
|
36
|
+
[ "$margin" -le $((limit / 4)) ] || margin=$((limit / 4))
|
|
37
|
+
threshold=$((limit - margin))
|
|
38
|
+
small=67108864
|
|
39
|
+
gib() { echo "$(($1 / 1073741824)).$(($1 % 1073741824 * 10 / 1073741824))"; }
|
|
40
|
+
tick=/tmp/.gke-sandboxes-memory-watchdog.tick
|
|
41
|
+
quick=
|
|
42
|
+
rm -f "$tick"
|
|
43
|
+
if [ -n "\${BASH_VERSION:-}" ] && mkfifo "$tick" 2>/dev/null && (exec 9<>"$tick") 2>/dev/null; then
|
|
44
|
+
exec 9<>"$tick"
|
|
45
|
+
quick=1
|
|
46
|
+
fi
|
|
47
|
+
nap() {
|
|
48
|
+
ms=$((($threshold - $1) / 8589935))
|
|
49
|
+
[ "$ms" -ge 30 ] || ms=30
|
|
50
|
+
[ "$ms" -le 500 ] || ms=500
|
|
51
|
+
if [ "$ms" -lt 100 ]; then ms=0.0$ms; else ms=0.$ms; fi
|
|
52
|
+
if [ -n "$quick" ]; then read -t "$ms" _ <&9; else sleep "$ms"; fi
|
|
53
|
+
}
|
|
54
|
+
unrelieved=
|
|
55
|
+
while :; do
|
|
56
|
+
read usage < "$usage_file" || usage=0
|
|
57
|
+
if [ "$usage" -lt "$threshold" ]; then
|
|
58
|
+
unrelieved=
|
|
59
|
+
nap "$usage"
|
|
60
|
+
continue
|
|
61
|
+
fi
|
|
62
|
+
shared=0
|
|
63
|
+
while read key value unit; do
|
|
64
|
+
if [ "$key" = Shmem: ]; then shared=$((value * 1024)); break; fi
|
|
65
|
+
done < /proc/meminfo
|
|
66
|
+
shm_files=$(df -Pk /dev/shm 2>/dev/null | { read header; read device blocks used rest; echo $((used * 1024)); })
|
|
67
|
+
files=$((shared - \${shm_files:-0}))
|
|
68
|
+
[ "$files" -gt 0 ] || files=0
|
|
69
|
+
usage=$((usage - files))
|
|
70
|
+
if [ "$usage" -lt "$threshold" ]; then
|
|
71
|
+
unrelieved=
|
|
72
|
+
nap "$usage"
|
|
73
|
+
continue
|
|
74
|
+
fi
|
|
75
|
+
need=$((usage - threshold + small))
|
|
76
|
+
freed=0
|
|
77
|
+
ended=
|
|
78
|
+
while [ "$freed" -lt "$need" ]; do
|
|
79
|
+
victim=
|
|
80
|
+
victim_bytes=0
|
|
81
|
+
for dir in /proc/[0-9]*; do
|
|
82
|
+
pid=\${dir#/proc/}
|
|
83
|
+
[ "$pid" -ne 1 ] && [ "$pid" -ne $$ ] || continue
|
|
84
|
+
case " $ended " in *" $pid "*) continue ;; esac
|
|
85
|
+
read size resident rest < "$dir/statm" 2>/dev/null || continue
|
|
86
|
+
bytes=$((resident * 4096))
|
|
87
|
+
[ "$bytes" -ge "$small" ] && [ "$bytes" -gt "$victim_bytes" ] || continue
|
|
88
|
+
if [ $# -gt 0 ]; then
|
|
89
|
+
command=$(tr '\\000' ' ' < "$dir/cmdline" 2>/dev/null)
|
|
90
|
+
protected=
|
|
91
|
+
for fragment in "$@"; do
|
|
92
|
+
case "$command" in *"$fragment"*) protected=1 ;; esac
|
|
93
|
+
done
|
|
94
|
+
[ -z "$protected" ] || continue
|
|
95
|
+
fi
|
|
96
|
+
victim=$pid
|
|
97
|
+
victim_bytes=$bytes
|
|
98
|
+
done
|
|
99
|
+
[ -n "$victim" ] || break
|
|
100
|
+
printf '\\ngke-sandboxes ended this process: the sandbox was about to run out of memory (%s GiB) and this process held %s GiB of it. Running it again unchanged will end the same way. Use less memory, for example by working through the data in smaller pieces.\\n' "$(gib "$limit")" "$(gib "$victim_bytes")" > "/proc/$victim/fd/2" 2>/dev/null
|
|
101
|
+
name=$(tr '\\000' ' ' < "/proc/$victim/cmdline" 2>/dev/null | tr -d '"\\\\\\001-\\037' | cut -c1-200)
|
|
102
|
+
kill -9 "$victim" 2>/dev/null
|
|
103
|
+
printf '{"event":"sandbox_memory_pressure","outcome":"process_ended","pid":%s,"command":"%s","resident_bytes":%s,"usage_bytes":%s,"threshold_bytes":%s,"limit_bytes":%s}\\n' "$victim" "$name" "$victim_bytes" "$usage" "$threshold" "$limit"
|
|
104
|
+
ended="$ended $victim"
|
|
105
|
+
freed=$((freed + victim_bytes))
|
|
106
|
+
done
|
|
107
|
+
if [ -z "$ended" ] && [ -z "$unrelieved" ]; then
|
|
108
|
+
printf '{"event":"sandbox_memory_pressure","outcome":"nothing_to_end","usage_bytes":%s,"threshold_bytes":%s,"limit_bytes":%s}\\n' "$usage" "$threshold" "$limit"
|
|
109
|
+
unrelieved=1
|
|
110
|
+
fi
|
|
111
|
+
sleep 1
|
|
112
|
+
done
|
|
113
|
+
`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getenergy/gke-sandboxes",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -17,6 +17,18 @@
|
|
|
17
17
|
},
|
|
18
18
|
"description": "Run persistent, isolated workspaces on your own GKE cluster.",
|
|
19
19
|
"license": "Apache-2.0",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/comp-work/gke-sandboxes.git"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/comp-work/gke-sandboxes#readme",
|
|
25
|
+
"keywords": [
|
|
26
|
+
"gke",
|
|
27
|
+
"gvisor",
|
|
28
|
+
"sandbox",
|
|
29
|
+
"agents",
|
|
30
|
+
"kubernetes"
|
|
31
|
+
],
|
|
20
32
|
"files": [
|
|
21
33
|
"dist",
|
|
22
34
|
"README.md",
|