@getenergy/gke-sandboxes 0.1.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 +48 -180
- package/dist/index.d.ts +25 -3
- package/dist/index.js +235 -14
- package/dist/kubernetes-api.d.ts +9 -1
- package/dist/kubernetes-api.js +29 -18
- 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,127 +1,30 @@
|
|
|
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
|
-
## Where GKE Sandboxes works well
|
|
13
|
-
|
|
14
|
-
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.
|
|
15
|
-
|
|
16
|
-
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)
|
|
17
|
-
|
|
18
|
-
## Running cost at 4 vCPU and 8 GB
|
|
19
|
-
|
|
20
|
-
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)
|
|
21
|
-
|
|
22
|
-
**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)
|
|
23
|
-
|
|
24
|
-
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)
|
|
25
|
-
|
|
26
|
-
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.
|
|
27
|
-
|
|
28
|
-
## Storage for a 20 GB sleeping sandbox
|
|
29
|
-
|
|
30
|
-
<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.">
|
|
31
|
-
|
|
32
|
-
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)
|
|
33
|
-
|
|
34
|
-
**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)
|
|
35
|
-
|
|
36
|
-
**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)
|
|
37
|
-
|
|
38
|
-
**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)
|
|
39
|
-
|
|
40
|
-
## Performance against Agent37
|
|
41
|
-
|
|
42
|
-
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)
|
|
43
|
-
|
|
44
|
-
| Metric | GKE on C4D | Agent37 standard |
|
|
45
|
-
| --- | ---: | ---: |
|
|
46
|
-
| Compute per sandbox, 730 hours | $7.80 at scale, estimated | $8.80 list price |
|
|
47
|
-
| Clone the repo | 1.6 s | 8.3 s |
|
|
48
|
-
| Cold dependency install | 13.5 s | 24.1 s |
|
|
49
|
-
| Build | 67 s | 100 s |
|
|
50
|
-
| V8 web tooling throughput | 22.8 runs/s | 17.5 runs/s |
|
|
51
|
-
|
|
52
|
-
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)
|
|
53
|
-
|
|
54
|
-
## Create, sleep, and wake times
|
|
55
|
-
|
|
56
|
-
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 one pod kept ready. 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)
|
|
57
|
-
|
|
58
|
-
<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.">
|
|
59
|
-
|
|
60
|
-
<details>
|
|
61
|
-
<summary>Read the timings as a table</summary>
|
|
62
|
-
|
|
63
|
-
| Provider | Start fresh | Save snapshot | Start from snapshot |
|
|
64
|
-
| --- | ---: | ---: | ---: |
|
|
65
|
-
| gke-sandboxes | 1.32 s | 2.82 s | 3.54 s |
|
|
66
|
-
| Modal | 0.38 s | 0.94 s | 0.98 s |
|
|
67
|
-
| Vercel Sandbox | 0.52 s | 1.15 s | 1.12 s |
|
|
68
|
-
| Superserve | 0.52 s | 0.38 s | 0.55 s |
|
|
69
|
-
| Upstash Ephemeral Box | 0.68 s | 2.12 s | 1.13 s |
|
|
70
|
-
| Freestyle | 0.69 s | 0.43 s | 0.75 s |
|
|
71
|
-
| E2B | 0.79 s | 1.83 s | 1.12 s |
|
|
72
|
-
| Luxor | 1.09 s | 6.87 s | 1.88 s |
|
|
73
|
-
| Boat | 1.12 s | — | — |
|
|
74
|
-
| Daytona | 1.25 s | 7.35 s | 2.38 s |
|
|
75
|
-
| Upstash Box | 2.68 s | 2.14 s | 4.89 s |
|
|
76
|
-
|
|
77
|
-
</details>
|
|
12
|
+
## Set it up
|
|
78
13
|
|
|
79
|
-
|
|
14
|
+
Paste this into Claude Code, Cursor, Codex or another coding agent:
|
|
80
15
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
| Provider | Runs | Pause | Resume |
|
|
87
|
-
| --- | ---: | ---: | ---: |
|
|
88
|
-
| E2B | 100 | 1.30 s | 0.36 s |
|
|
89
|
-
| Freestyle | 100 | 0.32 s | 0.19 s |
|
|
90
|
-
| Luxor | 77 | 60.53 s | 2.13 s |
|
|
91
|
-
| Superserve | 100 | 0.40 s | 0.22 s |
|
|
92
|
-
| Upstash Box | 99 | 0.84 s | 0.33 s |
|
|
93
|
-
|
|
94
|
-
</details>
|
|
95
|
-
|
|
96
|
-
**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)
|
|
97
|
-
|
|
98
|
-
**One ready sandbox.** With pooling off, the median wait was **2.68 s**. With one unused pod kept ready, it was **1.32 s** across all requests. **40 of 60** requests claimed a ready pod. When the pool was empty, the caller started a new one. Pooling cut the median by 1.35 s (51%), while the 95th percentile rose from 3.18 s to 3.50 s.
|
|
99
|
-
|
|
100
|
-
| GKE start path | Requests | Median | 95th percentile |
|
|
101
|
-
| --- | ---: | ---: | ---: |
|
|
102
|
-
| Pool off | 60 | 2.68 s | 3.18 s |
|
|
103
|
-
| Pool on, all requests | 60 | 1.32 s | 3.50 s |
|
|
104
|
-
| Ready pod available | 40 | 1.21 s | 1.51 s |
|
|
105
|
-
| Pool empty | 20 | 3.28 s | 3.61 s |
|
|
106
|
-
|
|
107
|
-
We replayed the same traffic with pooling off and on. Every six seconds, one request arrived, then two together at the next interval. All 120 requests ran `true` successfully and passed the sandbox identity check. Each got a distinct gVisor pod, which we deleted after the check. The pool started each block full and refilled in the background. The hit rate depends on arrivals and refill time. Pooling here applies to new sandbox IDs. Waking a saved ID still restores its snapshot. The quickstart defaults to creating pods on demand. [Pool benchmark](examples/benchmark-warm-pool.ts) · [Every request](docs/benchmarks/gke-warm-pool-2026-11-17.csv)
|
|
108
|
-
|
|
109
|
-
**Cost of keeping one pod ready.** A ready pod reserved 4 vCPU and 8 GiB. Both runs fit on the same sandbox node, so the pool added **$0 per hour** to the cluster’s VM and boot disk rate during this test. If keeping spare pods pushes an Iowa cluster up by one `e2-highmem-16` node for 730 hours, budget **about $543 extra** at on-demand list rates with its 150 GiB balanced boot disk. That is the price of the whole added node. [Google VM rates](https://cloud.google.com/products/compute/pricing/general-purpose) · [Disk rates](https://cloud.google.com/compute/disks-image-pricing)
|
|
110
|
-
|
|
111
|
-
## When to choose a managed provider
|
|
112
|
-
|
|
113
|
-
| If you need… | What to consider |
|
|
114
|
-
| --- | --- |
|
|
115
|
-
| 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) |
|
|
116
|
-
| 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) |
|
|
117
|
-
| 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/) |
|
|
118
|
-
| 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) |
|
|
16
|
+
```text
|
|
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
|
|
19
|
+
```
|
|
119
20
|
|
|
120
|
-
|
|
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).
|
|
121
22
|
|
|
122
|
-
|
|
23
|
+
Then use it from your backend, on Node.js 22+ or Bun:
|
|
123
24
|
|
|
124
|
-
|
|
25
|
+
```sh
|
|
26
|
+
npm install @getenergy/gke-sandboxes
|
|
27
|
+
```
|
|
125
28
|
|
|
126
29
|
```ts
|
|
127
30
|
import { GkeSandboxes, KubernetesApi } from '@getenergy/gke-sandboxes';
|
|
@@ -132,93 +35,58 @@ const sandboxes = new GkeSandboxes(new KubernetesApi(clusterUrl, getGoogleAccess
|
|
|
132
35
|
image: 'docker.io/library/debian:bookworm-slim',
|
|
133
36
|
});
|
|
134
37
|
|
|
38
|
+
// Creates the sandbox, returns the running one, or wakes it from its snapshot.
|
|
135
39
|
const { sandbox } = await sandboxes.acquire('session-42', AbortSignal.timeout(300_000));
|
|
136
|
-
await sandbox.
|
|
137
|
-
|
|
138
|
-
if (exitCode !== 0) throw new Error(result);
|
|
139
|
-
await sandboxes.checkpoint(sandbox.id);
|
|
40
|
+
const { exitCode, result } = await sandbox.process.executeCommand('echo hello');
|
|
41
|
+
await sandboxes.sleep(sandbox.id);
|
|
140
42
|
```
|
|
141
43
|
|
|
142
|
-
|
|
143
|
-
- **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.
|
|
144
|
-
- **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.
|
|
145
|
-
- **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.
|
|
44
|
+
[Full client guide](docs/client.md)
|
|
146
45
|
|
|
147
|
-
##
|
|
46
|
+
## Features
|
|
148
47
|
|
|
149
|
-
|
|
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.
|
|
150
57
|
|
|
151
|
-
|
|
58
|
+
[Client guide](docs/client.md) · [Operating limits](docs/limits.md)
|
|
152
59
|
|
|
153
|
-
|
|
60
|
+
## How it compares
|
|
154
61
|
|
|
155
|
-
|
|
156
|
-
export TF_VAR_project_id=your-disposable-project
|
|
157
|
-
export TF_VAR_operator_member=user:you@example.com
|
|
158
|
-
export TF_VAR_region=us-central1
|
|
159
|
-
export TF_VAR_max_sandbox_nodes=3
|
|
160
|
-
|
|
161
|
-
bun install
|
|
162
|
-
terraform -chdir=infra init
|
|
163
|
-
terraform -chdir=infra apply
|
|
164
|
-
export KUBECONFIG="$(mktemp)"
|
|
165
|
-
gcloud container clusters get-credentials sandboxes --dns-endpoint \
|
|
166
|
-
--project="$TF_VAR_project_id" --region="$TF_VAR_region"
|
|
167
|
-
terraform -chdir=infra output -raw manifests | kubectl apply -f -
|
|
168
|
-
bun examples/verify.ts \
|
|
169
|
-
--endpoint "$(terraform -chdir=infra output -raw endpoint)" \
|
|
170
|
-
--controller "$(terraform -chdir=infra output -raw controller)"
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
The verifier creates a sandbox, writes a file, puts the sandbox to sleep, and waits for the original pod to disappear. It then wakes the sandbox, checks the file contents, and deletes the sandbox. Add `--concurrency 4 --rounds 3` to time twelve cycles, four at a time.
|
|
62
|
+
One sandbox at 4 vCPU and 8 GB. Costs are list prices for compute and storage only.
|
|
174
63
|
|
|
175
|
-
|
|
64
|
+
#### Cost while awake
|
|
176
65
|
|
|
177
|
-
|
|
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.
|
|
178
67
|
|
|
179
|
-
|
|
180
|
-
export TF_VAR_sandbox_machine_type=c4d-highmem-16
|
|
181
|
-
export TF_VAR_sandbox_node_disk_type=hyperdisk-balanced
|
|
182
|
-
export TF_VAR_sandbox_max_pods_per_node=256
|
|
183
|
-
```
|
|
68
|
+
#### Cost while asleep
|
|
184
69
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
```ts
|
|
188
|
-
resources: {
|
|
189
|
-
requests: { cpu: '100m', memory: '850Mi', 'ephemeral-storage': '4Gi' },
|
|
190
|
-
limits: { cpu: '4', memory: '8Gi', 'ephemeral-storage': '20Gi' },
|
|
191
|
-
},
|
|
192
|
-
```
|
|
70
|
+
A sleeping sandbox is a snapshot in Cloud Storage. Machines you keep running still appear on your bill.
|
|
193
71
|
|
|
194
|
-
|
|
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.">
|
|
195
73
|
|
|
196
|
-
|
|
74
|
+
#### Start and wake
|
|
197
75
|
|
|
198
|
-
|
|
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.
|
|
199
77
|
|
|
200
|
-
|
|
201
|
-
kubectl get pods,podsnapshots -n sandboxes
|
|
202
|
-
terraform -chdir=infra output -raw manifests | kubectl delete --ignore-not-found -f -
|
|
203
|
-
terraform -chdir=infra destroy
|
|
204
|
-
```
|
|
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.">
|
|
205
79
|
|
|
206
|
-
|
|
80
|
+
#### Speed once running
|
|
207
81
|
|
|
208
|
-
|
|
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.
|
|
209
83
|
|
|
210
|
-
|
|
84
|
+
#### What sleep keeps
|
|
211
85
|
|
|
212
|
-
-
|
|
213
|
-
- **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`.
|
|
214
|
-
- **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.
|
|
215
|
-
- **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.
|
|
216
|
-
- **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.
|
|
217
87
|
|
|
218
|
-
|
|
88
|
+
#### When a managed provider fits better
|
|
219
89
|
|
|
220
|
-
|
|
221
|
-
bun examples/cost.ts examples/cost-inputs.json
|
|
222
|
-
```
|
|
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.
|
|
223
91
|
|
|
224
|
-
|
|
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[];
|
|
@@ -115,6 +125,17 @@ export declare class GkeSandboxes {
|
|
|
115
125
|
createdMs: number;
|
|
116
126
|
touch: () => Promise<void>;
|
|
117
127
|
}>;
|
|
128
|
+
/** Creates single-use sandboxes with generated IDs. Reopen a saved ID with acquire(). */
|
|
129
|
+
warmPool(name: string): {
|
|
130
|
+
create: (signal: AbortSignal, labels?: Labels) => Promise<{
|
|
131
|
+
sandbox: SandboxEnvironment;
|
|
132
|
+
podName: string;
|
|
133
|
+
fromPool: boolean;
|
|
134
|
+
touch: () => Promise<void>;
|
|
135
|
+
}>;
|
|
136
|
+
reconcile: (size: number) => Promise<void>;
|
|
137
|
+
maintain(size: number, signal: AbortSignal): Promise<void>;
|
|
138
|
+
};
|
|
118
139
|
/** Open a previously listed workspace without extending its idle period on a read. */
|
|
119
140
|
open(record: SandboxRecord, signal: AbortSignal, freshLabels: Labels): Promise<SandboxEnvironment>;
|
|
120
141
|
labelPod(podName: string, labels: Labels): Promise<void>;
|
|
@@ -169,4 +190,5 @@ export declare class GkeSandboxes {
|
|
|
169
190
|
private snapshot;
|
|
170
191
|
delete(id: string): Promise<void>;
|
|
171
192
|
environment(name: string, state: 'started' | 'stopped'): SandboxEnvironment;
|
|
193
|
+
private makeEnvironment;
|
|
172
194
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import {
|
|
1
|
+
import { createHash, randomBytes, randomInt, randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { createWriteStream } from 'node:fs';
|
|
4
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
5
|
+
import { finished } from 'node:stream/promises';
|
|
3
6
|
import { z } from 'zod';
|
|
4
7
|
import { KubernetesApiError } from './kubernetes-api.js';
|
|
8
|
+
import { MEMORY_WATCHDOG } from './memory-watchdog.js';
|
|
5
9
|
export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
|
|
6
10
|
// Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The disk limit
|
|
7
11
|
// keeps one sandbox from filling its node. A pod that exceeds it is evicted, not refused the
|
|
@@ -12,6 +16,8 @@ export const DEFAULT_RESOURCES = {
|
|
|
12
16
|
};
|
|
13
17
|
const SANDBOX_LABEL = 'energy-sandbox';
|
|
14
18
|
const CREATED_LABEL = 'energy-created-ms';
|
|
19
|
+
const POOL_LABEL = 'getenergy.com/warm-pool';
|
|
20
|
+
const TEMPLATE_LABEL = 'getenergy.com/warm-template';
|
|
15
21
|
const ACQUIRED_ANNOTATION = 'getenergy.com/acquired-ms';
|
|
16
22
|
const SLEEPING_ANNOTATION = 'getenergy.com/sleeping-ms';
|
|
17
23
|
// JSON Patch paths; `~1` is a slash inside a key.
|
|
@@ -46,15 +52,60 @@ const bootScript = (shell) => `(
|
|
|
46
52
|
`;
|
|
47
53
|
// A sandbox's first pod records whose it is before anything else can happen to it: a dispatch
|
|
48
54
|
// that created the pod may be aborted before it could run a command in it.
|
|
49
|
-
const podCommand = (sandboxId, first, boot) => [
|
|
55
|
+
const podCommand = (sandboxId, first, boot, watchdog) => [
|
|
50
56
|
'sh',
|
|
51
57
|
'-c',
|
|
52
|
-
`${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}`,
|
|
53
64
|
sandboxId,
|
|
54
65
|
...(boot ? boot.args : []),
|
|
55
66
|
];
|
|
56
67
|
// The command arrives on stdin so its size never meets a URL limit, and runs with stdin closed.
|
|
57
|
-
|
|
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
|
+
];
|
|
58
109
|
const MetadataSchema = z.object({
|
|
59
110
|
name: z.string(),
|
|
60
111
|
uid: z.string(),
|
|
@@ -149,7 +200,7 @@ export class GkeSandboxes {
|
|
|
149
200
|
.regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/)
|
|
150
201
|
.parse(options.namespace);
|
|
151
202
|
this.manager = labelSchema.parse(options.managerLabels ?? { 'app.kubernetes.io/managed-by': 'gke-sandboxes' });
|
|
152
|
-
if (SANDBOX_LABEL
|
|
203
|
+
if ([SANDBOX_LABEL, CREATED_LABEL, POOL_LABEL, TEMPLATE_LABEL].some((key) => key in this.manager))
|
|
153
204
|
throw new Error('A manager selector cannot use reserved workspace labels.');
|
|
154
205
|
this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;
|
|
155
206
|
if (!Object.keys(this.manager).length ||
|
|
@@ -197,6 +248,145 @@ export class GkeSandboxes {
|
|
|
197
248
|
};
|
|
198
249
|
}
|
|
199
250
|
}
|
|
251
|
+
/** Creates single-use sandboxes with generated IDs. Reopen a saved ID with acquire(). */
|
|
252
|
+
warmPool(name) {
|
|
253
|
+
sandboxIdSchema.parse(name);
|
|
254
|
+
if (this.options.boot)
|
|
255
|
+
throw new Error('Warm pools require an image that can start before caller labels are known.');
|
|
256
|
+
const poolLabels = { ...this.manager, [POOL_LABEL]: name };
|
|
257
|
+
const spare = (id) => this.manifest({ name: id, labels: poolLabels }, id, undefined);
|
|
258
|
+
const template = createHash('sha256')
|
|
259
|
+
.update(JSON.stringify(spare('template').spec))
|
|
260
|
+
.digest('hex')
|
|
261
|
+
.slice(0, 32);
|
|
262
|
+
const list = async (labels) => listOf(PodSchema)
|
|
263
|
+
.parse(await this.kubernetes.request('GET', `${this.pods}?labelSelector=${this.selector(labels)},!${SANDBOX_LABEL}`))
|
|
264
|
+
.items.filter((pod) => !terminating(pod));
|
|
265
|
+
const requestedLabels = { ...poolLabels, [TEMPLATE_LABEL]: template };
|
|
266
|
+
// One maintainer per named pool. Claims can come from any replica. A versioned delete
|
|
267
|
+
// prevents a resize or image rollout from deleting a pod another replica just handed out.
|
|
268
|
+
const reconcile = async (size) => {
|
|
269
|
+
z.number().int().nonnegative().parse(size);
|
|
270
|
+
const idle = await list(poolLabels);
|
|
271
|
+
const usable = idle
|
|
272
|
+
.filter((pod) => pod.metadata.labels[TEMPLATE_LABEL] === template &&
|
|
273
|
+
['Pending', 'Running'].includes(pod.status.phase))
|
|
274
|
+
.sort(oldestLiveFirst);
|
|
275
|
+
const keep = new Set(usable.slice(0, size).map((pod) => pod.metadata.uid));
|
|
276
|
+
await Promise.all([
|
|
277
|
+
...idle
|
|
278
|
+
.filter((pod) => !keep.has(pod.metadata.uid))
|
|
279
|
+
.map(async ({ metadata }) => {
|
|
280
|
+
try {
|
|
281
|
+
await this.kubernetes.request('DELETE', `${this.pods}/${metadata.name}`, {
|
|
282
|
+
preconditions: { uid: metadata.uid, resourceVersion: metadata.resourceVersion },
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
if (!(error instanceof KubernetesApiError && error.status === 409))
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
}),
|
|
290
|
+
...Array.from({ length: Math.max(0, size - keep.size) }, () => {
|
|
291
|
+
const pod = spare(randomUUID());
|
|
292
|
+
pod.metadata.labels = requestedLabels;
|
|
293
|
+
return this.kubernetes.request('POST', this.pods, pod);
|
|
294
|
+
}),
|
|
295
|
+
]);
|
|
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
|
+
};
|
|
313
|
+
const create = async (signal, labels = {}) => {
|
|
314
|
+
labelSchema.parse(labels);
|
|
315
|
+
for (const key of [
|
|
316
|
+
SANDBOX_LABEL,
|
|
317
|
+
CREATED_LABEL,
|
|
318
|
+
POOL_LABEL,
|
|
319
|
+
TEMPLATE_LABEL,
|
|
320
|
+
...Object.keys(this.manager),
|
|
321
|
+
])
|
|
322
|
+
if (key in labels)
|
|
323
|
+
throw new Error(`Reserved pool label: ${key}`);
|
|
324
|
+
const startedAt = Date.now();
|
|
325
|
+
signal.throwIfAborted();
|
|
326
|
+
reading ??= available().finally(() => {
|
|
327
|
+
reading = undefined;
|
|
328
|
+
});
|
|
329
|
+
const pods = await reading;
|
|
330
|
+
while (pods.length) {
|
|
331
|
+
signal.throwIfAborted();
|
|
332
|
+
const pod = pods.pop();
|
|
333
|
+
const version = podVersion(pod);
|
|
334
|
+
if (reserved.has(version))
|
|
335
|
+
continue;
|
|
336
|
+
reserved.add(version);
|
|
337
|
+
const id = pod.metadata.name;
|
|
338
|
+
const now = String(Date.now());
|
|
339
|
+
try {
|
|
340
|
+
const claimed = await this.kubernetes.request('PATCH', `${this.pods}/${id}`, {
|
|
341
|
+
metadata: {
|
|
342
|
+
resourceVersion: pod.metadata.resourceVersion,
|
|
343
|
+
labels: {
|
|
344
|
+
...labels,
|
|
345
|
+
[SANDBOX_LABEL]: id,
|
|
346
|
+
[CREATED_LABEL]: now,
|
|
347
|
+
[POOL_LABEL]: null,
|
|
348
|
+
[TEMPLATE_LABEL]: null,
|
|
349
|
+
},
|
|
350
|
+
annotations: { [ACQUIRED_ANNOTATION]: now },
|
|
351
|
+
},
|
|
352
|
+
});
|
|
353
|
+
if (!claimed)
|
|
354
|
+
continue;
|
|
355
|
+
this.report('create', PodSchema.parse(claimed).metadata.labels, pod, startedAt, null);
|
|
356
|
+
return {
|
|
357
|
+
sandbox: this.makeEnvironment(id, 'started', id),
|
|
358
|
+
podName: id,
|
|
359
|
+
fromPool: true,
|
|
360
|
+
touch: () => this.touch(id),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
if (!(error instanceof KubernetesApiError && error.status === 409)) {
|
|
365
|
+
reserved.delete(version);
|
|
366
|
+
throw error;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const { sandbox, podName, touch } = await this.acquire(randomUUID(), signal, labels);
|
|
371
|
+
return { sandbox, podName, touch, fromPool: false };
|
|
372
|
+
};
|
|
373
|
+
return {
|
|
374
|
+
create,
|
|
375
|
+
reconcile,
|
|
376
|
+
async maintain(size, signal) {
|
|
377
|
+
while (!signal.aborted) {
|
|
378
|
+
await reconcile(size);
|
|
379
|
+
try {
|
|
380
|
+
await delay(1000, undefined, { signal });
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
if (!signal.aborted)
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
}
|
|
200
390
|
/** Open a previously listed workspace without extending its idle period on a read. */
|
|
201
391
|
async open(record, signal, freshLabels) {
|
|
202
392
|
signal.throwIfAborted();
|
|
@@ -269,7 +459,7 @@ export class GkeSandboxes {
|
|
|
269
459
|
* stored. Usage is metered by pod and by stored snapshot, and neither names an owner.
|
|
270
460
|
*/
|
|
271
461
|
async inventory() {
|
|
272
|
-
const query = `?labelSelector=${this.selector({})}`;
|
|
462
|
+
const query = `?labelSelector=${this.selector({})},${SANDBOX_LABEL}`;
|
|
273
463
|
const [pods, snapshots] = await Promise.all([
|
|
274
464
|
this.kubernetes.request('GET', `${this.pods}${query}`),
|
|
275
465
|
this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
|
|
@@ -315,7 +505,7 @@ export class GkeSandboxes {
|
|
|
315
505
|
}
|
|
316
506
|
/** Every sandbox with these labels, awake or asleep, newest first. */
|
|
317
507
|
async list(labels) {
|
|
318
|
-
const query = `?labelSelector=${this.selector(labels)}`;
|
|
508
|
+
const query = `?labelSelector=${this.selector(labels)},${SANDBOX_LABEL}`;
|
|
319
509
|
const [pods, snapshots] = await Promise.all([
|
|
320
510
|
this.kubernetes.request('GET', `${this.pods}${query}`),
|
|
321
511
|
this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
|
|
@@ -464,7 +654,7 @@ export class GkeSandboxes {
|
|
|
464
654
|
const check = new TextEncoder().encode(`test "$(cat ${quote(SANDBOX_ID_FILE)} 2>/dev/null)" = ${quote(id)}`);
|
|
465
655
|
// GKE fills in the files as the container starts, so the first looks can come too early.
|
|
466
656
|
for (let attempt = 0; attempt < RESTORE_CHECKS; attempt++) {
|
|
467
|
-
const { exitCode } = await this.kubernetes.exec(path,
|
|
657
|
+
const { exitCode } = await this.kubernetes.exec(path, execCommand(30), check, 30);
|
|
468
658
|
if (exitCode === 0) {
|
|
469
659
|
await this.kubernetes.request('PATCH', path, {
|
|
470
660
|
metadata: { annotations: { [RESTORED_ANNOTATION]: 'true' } },
|
|
@@ -518,7 +708,9 @@ export class GkeSandboxes {
|
|
|
518
708
|
{
|
|
519
709
|
name: 'sandbox',
|
|
520
710
|
image: this.options.image,
|
|
521
|
-
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 ?? [] }),
|
|
522
714
|
volumeMounts: [
|
|
523
715
|
{ name: 'scratch', mountPath: '/tmp' },
|
|
524
716
|
...(this.options.runtime
|
|
@@ -653,8 +845,21 @@ export class GkeSandboxes {
|
|
|
653
845
|
await this.deleteMatching({ [SANDBOX_LABEL]: id });
|
|
654
846
|
}
|
|
655
847
|
environment(name, state) {
|
|
656
|
-
|
|
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();
|
|
657
857
|
const podPath = async () => {
|
|
858
|
+
if (firstPod) {
|
|
859
|
+
const path = `${this.pods}/${firstPod}`;
|
|
860
|
+
firstPod = null;
|
|
861
|
+
return path;
|
|
862
|
+
}
|
|
658
863
|
const pod = await this.livePod(name);
|
|
659
864
|
if (!pod)
|
|
660
865
|
throw new Error(`Sandbox ${name} is not running.`);
|
|
@@ -664,7 +869,7 @@ export class GkeSandboxes {
|
|
|
664
869
|
id: name,
|
|
665
870
|
state,
|
|
666
871
|
process: {
|
|
667
|
-
executeCommand: async (command, cwd = '/', env = {}, timeout = 60) => {
|
|
872
|
+
executeCommand: async (command, cwd = '/', env = {}, timeout = 60, options = {}) => {
|
|
668
873
|
const script = [
|
|
669
874
|
`cd ${quote(cwd)} || exit 1`,
|
|
670
875
|
...Object.entries(env).map(([key, value]) => {
|
|
@@ -674,8 +879,8 @@ export class GkeSandboxes {
|
|
|
674
879
|
}),
|
|
675
880
|
command,
|
|
676
881
|
].join('\n');
|
|
677
|
-
const { exitCode, output } = await this.kubernetes.exec(await podPath(),
|
|
678
|
-
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 };
|
|
679
884
|
},
|
|
680
885
|
},
|
|
681
886
|
fs: {
|
|
@@ -684,6 +889,22 @@ export class GkeSandboxes {
|
|
|
684
889
|
if (exitCode !== 0)
|
|
685
890
|
throw new Error(`Could not upload ${remote}: ${output}`);
|
|
686
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
|
+
},
|
|
687
908
|
},
|
|
688
909
|
};
|
|
689
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,7 +170,8 @@ export class KubernetesApi {
|
|
|
168
170
|
socket.binaryType = 'arraybuffer';
|
|
169
171
|
const finished = Promise.withResolvers();
|
|
170
172
|
const output = [];
|
|
171
|
-
let
|
|
173
|
+
let kept = 0;
|
|
174
|
+
let truncated = false;
|
|
172
175
|
const timer = setTimeout(() => {
|
|
173
176
|
finished.reject(new Error(`Sandbox command timed out after ${timeoutSeconds} seconds.`));
|
|
174
177
|
socket.close();
|
|
@@ -186,31 +189,39 @@ export class KubernetesApi {
|
|
|
186
189
|
socket.onmessage = ({ data }) => {
|
|
187
190
|
const frame = new Uint8Array(data);
|
|
188
191
|
const payload = frame.subarray(1);
|
|
189
|
-
if (frame[0] === STDOUT || frame[0] === STDERR)
|
|
190
|
-
|
|
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
|
+
}
|
|
191
200
|
if (frame[0] !== STATUS)
|
|
192
201
|
return;
|
|
193
|
-
//
|
|
202
|
+
// GKE sends the final status after stdout and stderr. Node can keep the socket
|
|
203
|
+
// open after this frame, so waiting for a close event can time out a finished command.
|
|
194
204
|
try {
|
|
195
|
-
status = ExecStatusSchema.parse(JSON.parse(new TextDecoder().decode(payload)));
|
|
205
|
+
const status = ExecStatusSchema.parse(JSON.parse(new TextDecoder().decode(payload)));
|
|
206
|
+
const exitCode = status.details?.causes?.find(({ reason }) => reason === 'ExitCode');
|
|
207
|
+
if (status.status === 'Failure' && !exitCode) {
|
|
208
|
+
finished.reject(new Error(`Sandbox command failed: ${status.message}`));
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
finished.resolve({
|
|
212
|
+
exitCode: exitCode ? Number(exitCode.message) : 0,
|
|
213
|
+
output: Buffer.concat(output).toString('utf8'),
|
|
214
|
+
truncated,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
196
217
|
}
|
|
197
218
|
catch (error) {
|
|
198
219
|
finished.reject(new Error('Sandbox command returned an unreadable status.', { cause: error }));
|
|
199
|
-
socket.close();
|
|
200
220
|
}
|
|
221
|
+
socket.close();
|
|
201
222
|
};
|
|
202
223
|
socket.onerror = () => finished.reject(new Error('Sandbox command connection failed.'));
|
|
203
|
-
socket.onclose = () =>
|
|
204
|
-
if (!status)
|
|
205
|
-
return finished.reject(new Error('Sandbox command ended without a status.'));
|
|
206
|
-
const exitCode = status.details?.causes?.find(({ reason }) => reason === 'ExitCode');
|
|
207
|
-
if (status.status === 'Failure' && !exitCode)
|
|
208
|
-
return finished.reject(new Error(`Sandbox command failed: ${status.message}`));
|
|
209
|
-
finished.resolve({
|
|
210
|
-
exitCode: exitCode ? Number(exitCode.message) : 0,
|
|
211
|
-
output: Buffer.concat(output).toString('utf8'),
|
|
212
|
-
});
|
|
213
|
-
};
|
|
224
|
+
socket.onclose = () => finished.reject(new Error('Sandbox command ended without a status.'));
|
|
214
225
|
return finished.promise.finally(() => clearTimeout(timer));
|
|
215
226
|
}
|
|
216
227
|
}
|
|
@@ -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",
|