@getenergy/gke-sandboxes 0.3.0 → 0.4.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 +7 -7
- package/dist/index.d.ts +9 -0
- package/dist/index.js +83 -38
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
|
|
3
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
4
|
|
|
5
|
-
|
|
5
|
+
A 2 vCPU / 4 GB sandbox costs about **1.9¢ for each hour it is awake**, cluster overhead included. Daytona and E2B list 16.6¢ for the same hour. A sleeping sandbox costs only its storage.
|
|
6
6
|
|
|
7
7
|
<picture>
|
|
8
8
|
<source media="(max-width: 600px)" srcset="docs/assets/running-sandbox.png">
|
|
9
|
-
<img src="docs/assets/running-sandbox-wide.png" width="100%" alt="
|
|
9
|
+
<img src="docs/assets/running-sandbox-wide.png" width="100%" alt="Cost in US cents for each hour a 2 vCPU and 4 GB sandbox is awake, at about 4% CPU. gke-sandboxes costs an estimated 1.9¢, the whole cluster bill divided by the hours its sandboxes are awake (1×). At list price for compute, Modal 3.5¢ (1.8×), Fly.io 9.2¢ (4.7×), Vercel Sandbox 9.5¢ (4.9×), Daytona 16.6¢ (8.5×), and E2B 16.6¢ (8.5×). Managed disk and plan fees are extra.">
|
|
10
10
|
</picture>
|
|
11
11
|
|
|
12
12
|
## Set it up
|
|
@@ -59,17 +59,17 @@ await sandboxes.sleep(sandbox.id);
|
|
|
59
59
|
|
|
60
60
|
## How it compares
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
Costs are for one sandbox at 2 vCPU and 4 GB. Managed providers are at list prices for compute and storage only. Timings used 4 vCPU and 8 GB.
|
|
63
63
|
|
|
64
64
|
#### Cost while awake
|
|
65
65
|
|
|
66
|
-
Every bar in the chart above prices the same mostly idle sandbox, at the
|
|
66
|
+
Every bar in the chart above prices the same mostly idle sandbox, at the 0.076 vCPU that Energy’s running sandboxes averaged, about 4% of 2 vCPU. Daytona, E2B and Fly.io 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 a whole cluster bill divided by its sandboxes: 520 awake at 56 to a machine, with two spare machines, node disks, system nodes, the cluster fee and snapshot storage. It needs that scale. A small cluster still pays for its minimum machines. Over a 730-hour month awake, 1.9¢ an hour is $14.22. Packed tighter on C4D machines, the GKE compute estimate falls to about $7.80 a month, or 1.1¢ an hour.
|
|
67
67
|
|
|
68
68
|
#### Cost while asleep
|
|
69
69
|
|
|
70
70
|
A sleeping sandbox is a snapshot in Cloud Storage. Machines you keep running still appear on your bill.
|
|
71
71
|
|
|
72
|
-
<img src="docs/assets/monthly-cost.png" width="100%" alt="Storage for 20 GB retained for 730 hours. GKE snapshot about $0.37,
|
|
72
|
+
<img src="docs/assets/monthly-cost.png" width="100%" alt="Storage for 20 GB retained for 730 hours. GKE snapshot about $0.37, Vercel Sandbox snapshot $1.60 on Pro, Daytona archived container $0, E2B paused sandbox $0 extra on Pro. Plan fees and infrastructure are excluded.">
|
|
73
73
|
|
|
74
74
|
#### Start and wake
|
|
75
75
|
|
|
@@ -79,11 +79,11 @@ Medians. The GKE start time is with two sandboxes kept ready; without one it is
|
|
|
79
79
|
|
|
80
80
|
#### Speed once running
|
|
81
81
|
|
|
82
|
-
Building Better Auth took 67 s on a C4D machine with one sandbox, 81 s on a machine packed with 95 idle ones
|
|
82
|
+
Building Better Auth took 67 s on a C4D machine with one sandbox, and 81 s on a machine packed with 95 idle ones. We have no build timings for the managed providers.
|
|
83
83
|
|
|
84
84
|
#### What sleep keeps
|
|
85
85
|
|
|
86
|
-
gke-sandboxes restores files, not running processes. E2B
|
|
86
|
+
gke-sandboxes restores files, not running processes. E2B can keep memory through sleep.
|
|
87
87
|
|
|
88
88
|
#### When a managed provider fits better
|
|
89
89
|
|
package/dist/index.d.ts
CHANGED
|
@@ -36,6 +36,7 @@ export type SandboxResources = {
|
|
|
36
36
|
limits: ResourceList;
|
|
37
37
|
};
|
|
38
38
|
export declare const DEFAULT_RESOURCES: SandboxResources;
|
|
39
|
+
export declare const DEFAULT_DISK = "20Gi";
|
|
39
40
|
export type GkeSandboxOptions = {
|
|
40
41
|
namespace: string;
|
|
41
42
|
image: string;
|
|
@@ -48,6 +49,13 @@ export type GkeSandboxOptions = {
|
|
|
48
49
|
};
|
|
49
50
|
/** What a sandbox reserves on its node and may use at most. Defaults to `DEFAULT_RESOURCES`. */
|
|
50
51
|
resources?: SandboxResources;
|
|
52
|
+
/**
|
|
53
|
+
* The size of a sandbox's root filesystem, `DEFAULT_DISK` unless given. `df` reports it and a
|
|
54
|
+
* write past it fails. It must be below the `ephemeral-storage` limit: the difference is what a
|
|
55
|
+
* full sandbox may still hold in /tmp before it is evicted. A sleeping sandbox holding more than
|
|
56
|
+
* this does not wake.
|
|
57
|
+
*/
|
|
58
|
+
disk?: string;
|
|
51
59
|
/**
|
|
52
60
|
* A sandbox that reaches its memory limit is killed whole. By default each sandbox watches its
|
|
53
61
|
* own memory and ends its largest processes first. `protect` lists command-line fragments of
|
|
@@ -115,6 +123,7 @@ export declare class GkeSandboxes {
|
|
|
115
123
|
private readonly snapshotsPath;
|
|
116
124
|
private readonly manager;
|
|
117
125
|
private readonly idleTimeoutMs;
|
|
126
|
+
private readonly diskBytes;
|
|
118
127
|
constructor(kubernetes: KubernetesApi, options: GkeSandboxOptions);
|
|
119
128
|
private selector;
|
|
120
129
|
acquire(id: string, signal: AbortSignal, initialLabels?: Labels): Promise<{
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash,
|
|
1
|
+
import { createHash, randomInt, randomUUID } from 'node:crypto';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
3
|
import { createWriteStream } from 'node:fs';
|
|
4
4
|
import { readFile, rm } from 'node:fs/promises';
|
|
@@ -7,13 +7,14 @@ import { z } from 'zod';
|
|
|
7
7
|
import { KubernetesApiError } from './kubernetes-api.js';
|
|
8
8
|
import { MEMORY_WATCHDOG } from './memory-watchdog.js';
|
|
9
9
|
export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
|
|
10
|
-
// Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The
|
|
11
|
-
//
|
|
12
|
-
//
|
|
10
|
+
// Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The kubelet
|
|
11
|
+
// counts a sandbox's root filesystem, scratch /tmp and logs against the disk limit and evicts a
|
|
12
|
+
// pod that exceeds it, so the limit is what one sandbox may take of its node's disk.
|
|
13
13
|
export const DEFAULT_RESOURCES = {
|
|
14
14
|
requests: { cpu: '250m', memory: '1Gi', 'ephemeral-storage': '4Gi' },
|
|
15
|
-
limits: { cpu: '2', memory: '4Gi', 'ephemeral-storage': '
|
|
15
|
+
limits: { cpu: '2', memory: '4Gi', 'ephemeral-storage': '40Gi' },
|
|
16
16
|
};
|
|
17
|
+
export const DEFAULT_DISK = '20Gi';
|
|
17
18
|
const SANDBOX_LABEL = 'energy-sandbox';
|
|
18
19
|
const CREATED_LABEL = 'energy-created-ms';
|
|
19
20
|
const POOL_LABEL = 'getenergy.com/warm-pool';
|
|
@@ -29,6 +30,23 @@ const RESTORE_ANNOTATION = 'podsnapshot.gke.io/ps-name';
|
|
|
29
30
|
// this rate, about a 16 Gbps node's share for one of 64 sandboxes. No sandbox crowds out its
|
|
30
31
|
// neighbours, and one turned against a host can send it no more than this.
|
|
31
32
|
const EGRESS_BANDWIDTH = '250M';
|
|
33
|
+
const QUANTITY_UNITS = {
|
|
34
|
+
Ki: 2 ** 10,
|
|
35
|
+
Mi: 2 ** 20,
|
|
36
|
+
Gi: 2 ** 30,
|
|
37
|
+
Ti: 2 ** 40,
|
|
38
|
+
k: 1e3,
|
|
39
|
+
M: 1e6,
|
|
40
|
+
G: 1e9,
|
|
41
|
+
T: 1e12,
|
|
42
|
+
};
|
|
43
|
+
// gVisor takes a size in bytes, not a Kubernetes quantity.
|
|
44
|
+
const quantityBytes = (quantity) => {
|
|
45
|
+
const [, amount, unit] = /^(\d+(?:\.\d+)?)(Ki|Mi|Gi|Ti|k|M|G|T)?$/.exec(quantity) ?? [];
|
|
46
|
+
if (!amount)
|
|
47
|
+
throw new Error(`Unsupported disk size: ${quantity}`);
|
|
48
|
+
return Math.floor(Number(amount) * (unit ? QUANTITY_UNITS[unit] : 1));
|
|
49
|
+
};
|
|
32
50
|
// Written by a sandbox's first pod as it starts. A woken pod without it was not restored from its
|
|
33
51
|
// snapshot.
|
|
34
52
|
const SANDBOX_ID_FILE = '/var/tmp/.energy-sandbox-id';
|
|
@@ -191,6 +209,7 @@ export class GkeSandboxes {
|
|
|
191
209
|
snapshotsPath;
|
|
192
210
|
manager;
|
|
193
211
|
idleTimeoutMs;
|
|
212
|
+
diskBytes;
|
|
194
213
|
constructor(kubernetes, options) {
|
|
195
214
|
this.kubernetes = kubernetes;
|
|
196
215
|
this.options = options;
|
|
@@ -203,6 +222,11 @@ export class GkeSandboxes {
|
|
|
203
222
|
if ([SANDBOX_LABEL, CREATED_LABEL, POOL_LABEL, TEMPLATE_LABEL].some((key) => key in this.manager))
|
|
204
223
|
throw new Error('A manager selector cannot use reserved workspace labels.');
|
|
205
224
|
this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;
|
|
225
|
+
const disk = options.disk ?? DEFAULT_DISK;
|
|
226
|
+
const limit = (options.resources ?? DEFAULT_RESOURCES).limits['ephemeral-storage'];
|
|
227
|
+
this.diskBytes = quantityBytes(disk);
|
|
228
|
+
if (this.diskBytes >= quantityBytes(limit))
|
|
229
|
+
throw new Error(`The disk (${disk}) must be below the ephemeral-storage limit (${limit}), which also covers /tmp and logs.`);
|
|
206
230
|
if (!Object.keys(this.manager).length ||
|
|
207
231
|
!Number.isFinite(this.idleTimeoutMs) ||
|
|
208
232
|
this.idleTimeoutMs <= 0)
|
|
@@ -239,7 +263,7 @@ export class GkeSandboxes {
|
|
|
239
263
|
if (!fresh && !(await this.markAcquired(pod)))
|
|
240
264
|
continue;
|
|
241
265
|
return {
|
|
242
|
-
sandbox: this.
|
|
266
|
+
sandbox: this.makeEnvironment(id, 'started', pod.metadata.name),
|
|
243
267
|
startState,
|
|
244
268
|
labels: pod.metadata.labels,
|
|
245
269
|
podName: pod.metadata.name,
|
|
@@ -564,42 +588,59 @@ export class GkeSandboxes {
|
|
|
564
588
|
sandbox.labels = current.labels;
|
|
565
589
|
}
|
|
566
590
|
const startedAt = Date.now();
|
|
567
|
-
if (pod && (terminating(pod) || !['Running', 'Pending'].includes(pod.status.phase))) {
|
|
568
|
-
if (!terminating(pod)) {
|
|
569
|
-
// Everything written since the last snapshot is gone with the pod.
|
|
570
|
-
const reason = pod.status.containerStatuses.find(({ state }) => state?.terminated?.reason)?.state
|
|
571
|
-
?.terminated?.reason ??
|
|
572
|
-
pod.status.reason ??
|
|
573
|
-
pod.status.phase;
|
|
574
|
-
this.options.onPodLost?.(sandbox.labels, pod.status.phase, reason, !!snapshot);
|
|
575
|
-
await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
|
|
576
|
-
}
|
|
577
|
-
// The pod's last snapshot may be newer than the listing. One of another creation under
|
|
578
|
-
// this id belongs to a sandbox that was replaced, not to this one.
|
|
579
|
-
const [listed] = await this.list({ [SANDBOX_LABEL]: id });
|
|
580
|
-
snapshot =
|
|
581
|
-
listed && listed.labels[CREATED_LABEL] === sandbox.labels[CREATED_LABEL]
|
|
582
|
-
? listed.snapshots[0]
|
|
583
|
-
: undefined;
|
|
584
|
-
pod = null;
|
|
585
|
-
}
|
|
586
591
|
let created = false;
|
|
587
|
-
|
|
592
|
+
while (true) {
|
|
593
|
+
signal.throwIfAborted();
|
|
594
|
+
if (pod && (terminating(pod) || !['Running', 'Pending'].includes(pod.status.phase))) {
|
|
595
|
+
if (!terminating(pod)) {
|
|
596
|
+
// Everything written since the last snapshot is gone with the pod.
|
|
597
|
+
const reason = pod.status.containerStatuses.find(({ state }) => state?.terminated?.reason)?.state
|
|
598
|
+
?.terminated?.reason ??
|
|
599
|
+
pod.status.reason ??
|
|
600
|
+
pod.status.phase;
|
|
601
|
+
this.options.onPodLost?.(sandbox.labels, pod.status.phase, reason, !!snapshot);
|
|
602
|
+
await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
|
|
603
|
+
}
|
|
604
|
+
// The pod's last snapshot may be newer than the listing. One of another creation under
|
|
605
|
+
// this id belongs to a sandbox that was replaced, not to this one.
|
|
606
|
+
const [listed] = await this.list({ [SANDBOX_LABEL]: id });
|
|
607
|
+
snapshot =
|
|
608
|
+
listed && listed.labels[CREATED_LABEL] === sandbox.labels[CREATED_LABEL]
|
|
609
|
+
? listed.snapshots[0]
|
|
610
|
+
: undefined;
|
|
611
|
+
pod = null;
|
|
612
|
+
}
|
|
613
|
+
if (pod)
|
|
614
|
+
break;
|
|
588
615
|
// A fresh filesystem must also get the caller's initial labels.
|
|
589
616
|
if (!snapshot)
|
|
590
617
|
sandbox.labels = initialLabels;
|
|
591
|
-
//
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
618
|
+
// Named after the snapshot it starts from. Kubernetes creates a name once, so callers that
|
|
619
|
+
// start the sandbox at the same moment get one pod between them. And a wake never waits
|
|
620
|
+
// for the pod it replaces to finish shutting down, which started from an earlier snapshot.
|
|
621
|
+
const name = `${id}-${createHash('sha256')
|
|
622
|
+
.update(snapshot ?? '')
|
|
623
|
+
.digest('hex')
|
|
624
|
+
.slice(0, 6)}`;
|
|
625
|
+
try {
|
|
626
|
+
pod = PodSchema.parse(await this.kubernetes.request('POST', this.pods, this.manifest(sandbox, name, snapshot)));
|
|
627
|
+
created = true;
|
|
628
|
+
break;
|
|
629
|
+
}
|
|
630
|
+
catch (error) {
|
|
631
|
+
if (!(error instanceof KubernetesApiError && error.status === 409))
|
|
632
|
+
throw error;
|
|
633
|
+
}
|
|
634
|
+
// The name is taken. By a pod another caller just created, which is this caller's too. Or by
|
|
635
|
+
// one that started from the same snapshot and died or was deleted: Kubernetes removes a
|
|
636
|
+
// dead pod at once, and one still shutting down has to go before its name is free.
|
|
637
|
+
const taken = await this.kubernetes.watch(this.pods, name, (found) => {
|
|
638
|
+
const current = found ? PodSchema.parse(found) : null;
|
|
639
|
+
return current && terminating(current) ? undefined : current;
|
|
640
|
+
}, startedAt + START_SECONDS * 1000, signal);
|
|
641
|
+
if (taken === undefined)
|
|
642
|
+
throw new Error(`Sandbox ${id} did not finish starting.`);
|
|
643
|
+
pod = taken;
|
|
603
644
|
}
|
|
604
645
|
// Only the caller whose pod it is reports the start; one that waits for another's does not.
|
|
605
646
|
const operation = created ? (snapshot ? 'wake' : 'create') : null;
|
|
@@ -677,6 +718,10 @@ export class GkeSandboxes {
|
|
|
677
718
|
[ACQUIRED_ANNOTATION]: String(Date.now()),
|
|
678
719
|
[SLEEPING_ANNOTATION]: '0',
|
|
679
720
|
'kubernetes.io/egress-bandwidth': EGRESS_BANDWIDTH,
|
|
721
|
+
// gVisor gives the root filesystem this size. Without it the filesystem has none: `df`
|
|
722
|
+
// reports 8 EiB free, and the only limit is the kubelet's, which evicts the pod. gVisor
|
|
723
|
+
// cannot size the scratch volume at /tmp, so the kubelet's limit still bounds that.
|
|
724
|
+
'dev.gvisor.flag.overlay2': `root:self,size=${this.diskBytes}`,
|
|
680
725
|
...(snapshot ? { [RESTORE_ANNOTATION]: snapshot } : {}),
|
|
681
726
|
},
|
|
682
727
|
},
|