@getenergy/gke-sandboxes 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +223 -2
- package/dist/index.d.ts +172 -0
- package/dist/index.js +690 -0
- package/dist/kubernetes-api.d.ts +34 -0
- package/dist/kubernetes-api.js +216 -0
- package/package.json +34 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { KubernetesApiError } from './kubernetes-api.js';
|
|
5
|
+
export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
|
|
6
|
+
// Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The disk limit
|
|
7
|
+
// keeps one sandbox from filling its node. A pod that exceeds it is evicted, not refused the
|
|
8
|
+
// write, and comes back from its last snapshot.
|
|
9
|
+
export const DEFAULT_RESOURCES = {
|
|
10
|
+
requests: { cpu: '250m', memory: '1Gi', 'ephemeral-storage': '4Gi' },
|
|
11
|
+
limits: { cpu: '2', memory: '4Gi', 'ephemeral-storage': '20Gi' },
|
|
12
|
+
};
|
|
13
|
+
const SANDBOX_LABEL = 'energy-sandbox';
|
|
14
|
+
const CREATED_LABEL = 'energy-created-ms';
|
|
15
|
+
const ACQUIRED_ANNOTATION = 'getenergy.com/acquired-ms';
|
|
16
|
+
const SLEEPING_ANNOTATION = 'getenergy.com/sleeping-ms';
|
|
17
|
+
// JSON Patch paths; `~1` is a slash inside a key.
|
|
18
|
+
const ACQUIRED_PATH = '/metadata/annotations/getenergy.com~1acquired-ms';
|
|
19
|
+
const SLEEPING_PATH = '/metadata/annotations/getenergy.com~1sleeping-ms';
|
|
20
|
+
const RESTORED_ANNOTATION = 'getenergy.com/restore-verified';
|
|
21
|
+
const RESTORE_ANNOTATION = 'podsnapshot.gke.io/ps-name';
|
|
22
|
+
// GKE Dataplane V2 runs Cilium's bandwidth manager, which paces a pod's traffic out of its node to
|
|
23
|
+
// this rate, about a 16 Gbps node's share for one of 64 sandboxes. No sandbox crowds out its
|
|
24
|
+
// neighbours, and one turned against a host can send it no more than this.
|
|
25
|
+
const EGRESS_BANDWIDTH = '250M';
|
|
26
|
+
// Written by a sandbox's first pod as it starts. A woken pod without it was not restored from its
|
|
27
|
+
// snapshot.
|
|
28
|
+
const SANDBOX_ID_FILE = '/var/tmp/.energy-sandbox-id';
|
|
29
|
+
const BOOT_LOG = '/var/tmp/.energy-boot.log';
|
|
30
|
+
const START_SECONDS = 300;
|
|
31
|
+
const SNAPSHOT_SECONDS = 300;
|
|
32
|
+
const SLEEP_ABANDONED_MS = SNAPSHOT_SECONDS * 1000 + 60_000;
|
|
33
|
+
const RESTORE_CHECKS = 25;
|
|
34
|
+
const RESTORE_CHECK_MS = 100;
|
|
35
|
+
// Model commands leave orphans behind; the pod's first process reaps them.
|
|
36
|
+
const POD_LOOP = 'trap "exit 0" TERM; while :; do sleep 3600 & wait $!; done';
|
|
37
|
+
const bootScript = (shell) => `(
|
|
38
|
+
attempt=0
|
|
39
|
+
until [ "$(cat ${SANDBOX_ID_FILE} 2>/dev/null)" = "$0" ]; do
|
|
40
|
+
[ "$attempt" -lt 600 ] || exit 0
|
|
41
|
+
sleep 0.05
|
|
42
|
+
attempt=$((attempt + 1))
|
|
43
|
+
done
|
|
44
|
+
${shell}
|
|
45
|
+
) </dev/null >${BOOT_LOG} 2>&1 &
|
|
46
|
+
`;
|
|
47
|
+
// A sandbox's first pod records whose it is before anything else can happen to it: a dispatch
|
|
48
|
+
// that created the pod may be aborted before it could run a command in it.
|
|
49
|
+
const podCommand = (sandboxId, first, boot) => [
|
|
50
|
+
'sh',
|
|
51
|
+
'-c',
|
|
52
|
+
`${first ? `printf %s "$0" > ${SANDBOX_ID_FILE} || exit 1\n` : ''}${boot ? bootScript(boot.shell) : ''}${POD_LOOP}`,
|
|
53
|
+
sandboxId,
|
|
54
|
+
...(boot ? boot.args : []),
|
|
55
|
+
];
|
|
56
|
+
// The command arrives on stdin so its size never meets a URL limit, and runs with stdin closed.
|
|
57
|
+
const EXEC_COMMAND = ['sh', '-c', 'exec sh -c "$(cat)" </dev/null'];
|
|
58
|
+
const MetadataSchema = z.object({
|
|
59
|
+
name: z.string(),
|
|
60
|
+
uid: z.string(),
|
|
61
|
+
resourceVersion: z.string(),
|
|
62
|
+
creationTimestamp: z.string(),
|
|
63
|
+
deletionTimestamp: z.string().optional(),
|
|
64
|
+
labels: z.record(z.string(), z.string()).default({}),
|
|
65
|
+
annotations: z.record(z.string(), z.string()).default({}),
|
|
66
|
+
});
|
|
67
|
+
const PodSchema = z.object({
|
|
68
|
+
metadata: MetadataSchema,
|
|
69
|
+
status: z.object({
|
|
70
|
+
phase: z.string(),
|
|
71
|
+
podIP: z.string().optional(),
|
|
72
|
+
conditions: z.array(z.object({ type: z.string(), status: z.string() })).default([]),
|
|
73
|
+
// Why a pod that is no longer running ended: `Evicted` for the pod, `OOMKilled` for its
|
|
74
|
+
// container.
|
|
75
|
+
reason: z.string().optional(),
|
|
76
|
+
containerStatuses: z
|
|
77
|
+
.array(z.object({
|
|
78
|
+
state: z
|
|
79
|
+
.object({ terminated: z.object({ reason: z.string().optional() }).optional() })
|
|
80
|
+
.optional(),
|
|
81
|
+
}))
|
|
82
|
+
.default([]),
|
|
83
|
+
}),
|
|
84
|
+
});
|
|
85
|
+
const ConditionsSchema = z
|
|
86
|
+
.object({ conditions: z.array(z.object({ type: z.string(), status: z.string() })).default([]) })
|
|
87
|
+
.default({ conditions: [] });
|
|
88
|
+
const SnapshotSchema = z.object({ metadata: MetadataSchema, status: ConditionsSchema });
|
|
89
|
+
// Where GKE wrote a snapshot's files, which is what a sleeping sandbox occupies.
|
|
90
|
+
const StoredSnapshotSchema = z.object({
|
|
91
|
+
metadata: MetadataSchema,
|
|
92
|
+
status: z.object({
|
|
93
|
+
storageStatus: z.object({ gcs: z.object({ observedGCSPath: z.string().startsWith('gs://') }) }),
|
|
94
|
+
}),
|
|
95
|
+
});
|
|
96
|
+
const TriggerSchema = z.object({
|
|
97
|
+
status: z
|
|
98
|
+
.object({
|
|
99
|
+
conditions: z
|
|
100
|
+
.array(z.object({ type: z.string(), status: z.string(), message: z.string().optional() }))
|
|
101
|
+
.default([]),
|
|
102
|
+
snapshotCreated: z.object({ name: z.string() }).optional(),
|
|
103
|
+
})
|
|
104
|
+
.default({ conditions: [] }),
|
|
105
|
+
});
|
|
106
|
+
const listOf = (item) => z.object({ items: z.array(item) });
|
|
107
|
+
const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
108
|
+
const ready = (conditions) => conditions.some(({ type, status }) => type === 'Ready' && status === 'True');
|
|
109
|
+
export const terminating = (pod) => !!pod.metadata.deletionTimestamp;
|
|
110
|
+
// A sleep or a checkpoint is working on the pod. One that has not finished by now was abandoned.
|
|
111
|
+
const snapshotting = (pod) => Date.now() - Number(pod.metadata.annotations[SLEEPING_ANNOTATION]) < SLEEP_ABANDONED_MS;
|
|
112
|
+
const sleeping = (pod) => terminating(pod) || snapshotting(pod);
|
|
113
|
+
// A sleep or a checkpoint still holds the pod, and will either delete it or free it.
|
|
114
|
+
const held = (pod) => !terminating(pod) && snapshotting(pod);
|
|
115
|
+
export const sandboxState = ({ pod }) => pod?.status.phase === 'Running' && !sleeping(pod) ? 'started' : 'stopped';
|
|
116
|
+
// Orders a sandbox's pods so that the one to use comes first: not shutting down, then oldest.
|
|
117
|
+
const oldestLiveFirst = (left, right) => Number(terminating(left)) - Number(terminating(right)) ||
|
|
118
|
+
left.metadata.creationTimestamp.localeCompare(right.metadata.creationTimestamp) ||
|
|
119
|
+
left.metadata.name.localeCompare(right.metadata.name);
|
|
120
|
+
// A pod reports running a moment before its container accepts commands.
|
|
121
|
+
const starting = (pod) => pod.status.phase === 'Pending' ||
|
|
122
|
+
(pod.status.phase === 'Running' && !ready(pod.status.conditions));
|
|
123
|
+
export class SandboxInUseError extends Error {
|
|
124
|
+
constructor(name) {
|
|
125
|
+
super(`Sandbox ${name} is in use and cannot sleep yet.`);
|
|
126
|
+
this.name = 'SandboxInUseError';
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const sandboxIdSchema = z
|
|
130
|
+
.string()
|
|
131
|
+
.max(56)
|
|
132
|
+
.regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/);
|
|
133
|
+
// Only equality selectors are needed. Kubernetes validates the syntax of the label itself.
|
|
134
|
+
const labelSchema = z.record(z.string().regex(/^[A-Za-z0-9._/-]+$/), z.string().regex(/^[A-Za-z0-9._-]*$/));
|
|
135
|
+
export class GkeSandboxes {
|
|
136
|
+
kubernetes;
|
|
137
|
+
options;
|
|
138
|
+
pods;
|
|
139
|
+
triggers;
|
|
140
|
+
snapshotsPath;
|
|
141
|
+
manager;
|
|
142
|
+
idleTimeoutMs;
|
|
143
|
+
constructor(kubernetes, options) {
|
|
144
|
+
this.kubernetes = kubernetes;
|
|
145
|
+
this.options = options;
|
|
146
|
+
const namespace = z
|
|
147
|
+
.string()
|
|
148
|
+
.max(63)
|
|
149
|
+
.regex(/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/)
|
|
150
|
+
.parse(options.namespace);
|
|
151
|
+
this.manager = labelSchema.parse(options.managerLabels ?? { 'app.kubernetes.io/managed-by': 'gke-sandboxes' });
|
|
152
|
+
if (SANDBOX_LABEL in this.manager || CREATED_LABEL in this.manager)
|
|
153
|
+
throw new Error('A manager selector cannot use reserved workspace labels.');
|
|
154
|
+
this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;
|
|
155
|
+
if (!Object.keys(this.manager).length ||
|
|
156
|
+
!Number.isFinite(this.idleTimeoutMs) ||
|
|
157
|
+
this.idleTimeoutMs <= 0)
|
|
158
|
+
throw new Error('A manager label and a positive idle timeout are required.');
|
|
159
|
+
this.pods = `/api/v1/namespaces/${namespace}/pods`;
|
|
160
|
+
const api = `/apis/podsnapshot.gke.io/v1/namespaces/${namespace}`;
|
|
161
|
+
this.triggers = `${api}/podsnapshotmanualtriggers`;
|
|
162
|
+
this.snapshotsPath = `${api}/podsnapshots`;
|
|
163
|
+
}
|
|
164
|
+
selector(labels) {
|
|
165
|
+
const pairs = Object.entries(labelSchema.parse({ ...labels, ...this.manager })).map(([key, value]) => `${key}=${value}`);
|
|
166
|
+
return encodeURIComponent(pairs.join(','));
|
|
167
|
+
}
|
|
168
|
+
async acquire(id, signal, initialLabels = {}) {
|
|
169
|
+
while (true) {
|
|
170
|
+
signal.throwIfAborted();
|
|
171
|
+
const existing = await this.find(id);
|
|
172
|
+
const createdMs = Date.now();
|
|
173
|
+
const record = existing ?? {
|
|
174
|
+
name: id,
|
|
175
|
+
labels: {},
|
|
176
|
+
createdMs,
|
|
177
|
+
pod: null,
|
|
178
|
+
snapshots: [],
|
|
179
|
+
sleptMs: null,
|
|
180
|
+
};
|
|
181
|
+
const startState = existing ? sandboxState(existing) : 'missing';
|
|
182
|
+
const { pod, fresh } = await this.start(record, signal, {
|
|
183
|
+
...initialLabels,
|
|
184
|
+
...this.manager,
|
|
185
|
+
[SANDBOX_LABEL]: id,
|
|
186
|
+
[CREATED_LABEL]: String(record.createdMs),
|
|
187
|
+
});
|
|
188
|
+
if (!fresh && !(await this.markAcquired(pod)))
|
|
189
|
+
continue;
|
|
190
|
+
return {
|
|
191
|
+
sandbox: this.environment(id, 'started'),
|
|
192
|
+
startState,
|
|
193
|
+
labels: pod.metadata.labels,
|
|
194
|
+
podName: pod.metadata.name,
|
|
195
|
+
createdMs: Number(pod.metadata.labels[CREATED_LABEL]),
|
|
196
|
+
touch: () => this.touch(id),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** Open a previously listed workspace without extending its idle period on a read. */
|
|
201
|
+
async open(record, signal, freshLabels) {
|
|
202
|
+
signal.throwIfAborted();
|
|
203
|
+
await this.start(record, signal, { ...record.labels, ...freshLabels });
|
|
204
|
+
return this.environment(record.name, 'started');
|
|
205
|
+
}
|
|
206
|
+
async labelPod(podName, labels) {
|
|
207
|
+
if (!(await this.kubernetes.request('PATCH', `${this.pods}/${podName}`, { metadata: { labels } })))
|
|
208
|
+
throw new Error(`Pod ${podName} is not running.`);
|
|
209
|
+
}
|
|
210
|
+
async endpoint(sandbox, port) {
|
|
211
|
+
const pod = await this.livePod(sandbox.id);
|
|
212
|
+
if (!pod?.status.podIP || pod.status.phase !== 'Running' || sleeping(pod))
|
|
213
|
+
throw new Error(`Sandbox ${sandbox.id} is not running.`);
|
|
214
|
+
return { url: `http://${pod.status.podIP}:${port}`, headers: {} };
|
|
215
|
+
}
|
|
216
|
+
// Pod addresses are reused, so a remembered address may now belong to another sandbox.
|
|
217
|
+
async endpointIsCurrent(sandboxId, endpoint) {
|
|
218
|
+
const pod = await this.livePod(sandboxId);
|
|
219
|
+
return (!!pod?.status.podIP &&
|
|
220
|
+
pod.status.phase === 'Running' &&
|
|
221
|
+
!sleeping(pod) &&
|
|
222
|
+
new URL(endpoint.url).hostname === pod.status.podIP);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Snapshots a running sandbox and lets it run on, so a pod that dies later loses only what was
|
|
226
|
+
* written since. The sandbox is paused while the snapshot is taken.
|
|
227
|
+
*/
|
|
228
|
+
async checkpoint(sandboxId) {
|
|
229
|
+
const pod = await this.livePod(sandboxId);
|
|
230
|
+
if (!pod || pod.status.phase !== 'Running' || sleeping(pod))
|
|
231
|
+
return;
|
|
232
|
+
const claimed = await this.claim(pod, [
|
|
233
|
+
{ op: 'test', path: SLEEPING_PATH, value: pod.metadata.annotations[SLEEPING_ANNOTATION] },
|
|
234
|
+
{ op: 'replace', path: SLEEPING_PATH, value: String(Date.now()) },
|
|
235
|
+
]);
|
|
236
|
+
if (!claimed)
|
|
237
|
+
return;
|
|
238
|
+
const startedAt = Date.now();
|
|
239
|
+
try {
|
|
240
|
+
await this.dropOlderSnapshots(sandboxId, await this.snapshot(pod));
|
|
241
|
+
this.report('checkpoint', pod.metadata.labels, pod, startedAt, null);
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
this.report('checkpoint', pod.metadata.labels, pod, startedAt, error);
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
await this.kubernetes.request('PATCH', `${this.pods}/${pod.metadata.name}`, {
|
|
249
|
+
metadata: { annotations: { [SLEEPING_ANNOTATION]: '0' } },
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async sleepUnused() {
|
|
254
|
+
const idleBefore = Date.now() - this.idleTimeoutMs;
|
|
255
|
+
// All at once: a sleep waits on its snapshot, and one request sweeps the whole cluster, so
|
|
256
|
+
// sleeping in turn reaches only the first few of many idle sandboxes before its deadline.
|
|
257
|
+
await Promise.all((await this.list({})).map(async ({ pod }) => {
|
|
258
|
+
if (!pod || sleeping(pod) || pod.status.phase !== 'Running')
|
|
259
|
+
return;
|
|
260
|
+
if (Number(pod.metadata.annotations[ACQUIRED_ANNOTATION]) > idleBefore)
|
|
261
|
+
return;
|
|
262
|
+
// One sandbox that cannot sleep must not keep the rest awake; the next sweep retries it.
|
|
263
|
+
// A failed sleep has been reported, and one in use is no failure.
|
|
264
|
+
await this.sleepPod(pod).catch(() => undefined);
|
|
265
|
+
}));
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Every sandbox that exists, awake or asleep, with whose it is and where its snapshots are
|
|
269
|
+
* stored. Usage is metered by pod and by stored snapshot, and neither names an owner.
|
|
270
|
+
*/
|
|
271
|
+
async inventory() {
|
|
272
|
+
const query = `?labelSelector=${this.selector({})}`;
|
|
273
|
+
const [pods, snapshots] = await Promise.all([
|
|
274
|
+
this.kubernetes.request('GET', `${this.pods}${query}`),
|
|
275
|
+
this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
|
|
276
|
+
]);
|
|
277
|
+
const sandboxes = new Map();
|
|
278
|
+
const sandbox = ({ labels }) => {
|
|
279
|
+
const sandboxId = labels[SANDBOX_LABEL];
|
|
280
|
+
const found = sandboxes.get(sandboxId) ?? {
|
|
281
|
+
sandboxId,
|
|
282
|
+
labels,
|
|
283
|
+
state: 'stopped',
|
|
284
|
+
snapshots: [],
|
|
285
|
+
};
|
|
286
|
+
sandboxes.set(sandboxId, found);
|
|
287
|
+
return found;
|
|
288
|
+
};
|
|
289
|
+
for (const pod of listOf(PodSchema).parse(pods).items) {
|
|
290
|
+
const found = sandbox(pod.metadata);
|
|
291
|
+
// A pod that is going to sleep no longer accepts work.
|
|
292
|
+
if (pod.status.phase === 'Running' && !sleeping(pod))
|
|
293
|
+
found.state = 'running';
|
|
294
|
+
}
|
|
295
|
+
// A snapshot still being written has no stored files yet.
|
|
296
|
+
for (const item of listOf(z.unknown()).parse(snapshots).items) {
|
|
297
|
+
const stored = StoredSnapshotSchema.safeParse(item);
|
|
298
|
+
if (stored.success)
|
|
299
|
+
sandbox(stored.data.metadata).snapshots.push({
|
|
300
|
+
path: stored.data.status.storageStatus.gcs.observedGCSPath,
|
|
301
|
+
createdAt: stored.data.metadata.creationTimestamp,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return [...sandboxes.values()];
|
|
305
|
+
}
|
|
306
|
+
async deleteMatching(match) {
|
|
307
|
+
if (!Object.keys(match).some((key) => !(key in this.manager)))
|
|
308
|
+
throw new Error('A deletion selector is required.');
|
|
309
|
+
const labels = this.selector(match);
|
|
310
|
+
await Promise.all([this.pods, this.snapshotsPath, this.triggers].map((path) => this.kubernetes.request('DELETE', `${path}?labelSelector=${labels}`)));
|
|
311
|
+
}
|
|
312
|
+
async find(id) {
|
|
313
|
+
sandboxIdSchema.parse(id);
|
|
314
|
+
return (await this.list({ [SANDBOX_LABEL]: id }))[0] ?? null;
|
|
315
|
+
}
|
|
316
|
+
/** Every sandbox with these labels, awake or asleep, newest first. */
|
|
317
|
+
async list(labels) {
|
|
318
|
+
const query = `?labelSelector=${this.selector(labels)}`;
|
|
319
|
+
const [pods, snapshots] = await Promise.all([
|
|
320
|
+
this.kubernetes.request('GET', `${this.pods}${query}`),
|
|
321
|
+
this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
|
|
322
|
+
]);
|
|
323
|
+
const sandboxes = new Map();
|
|
324
|
+
const sandbox = (metadata) => {
|
|
325
|
+
const name = metadata.labels[SANDBOX_LABEL];
|
|
326
|
+
const found = sandboxes.get(name) ?? {
|
|
327
|
+
name,
|
|
328
|
+
labels: metadata.labels,
|
|
329
|
+
createdMs: Number(metadata.labels[CREATED_LABEL]),
|
|
330
|
+
pod: null,
|
|
331
|
+
snapshots: [],
|
|
332
|
+
sleptMs: null,
|
|
333
|
+
};
|
|
334
|
+
sandboxes.set(name, found);
|
|
335
|
+
return found;
|
|
336
|
+
};
|
|
337
|
+
// A woken sandbox gets a new pod while its previous one may still be shutting down.
|
|
338
|
+
for (const pod of listOf(PodSchema).parse(pods).items.sort(oldestLiveFirst).reverse())
|
|
339
|
+
sandbox(pod.metadata).pod = pod;
|
|
340
|
+
for (const snapshot of listOf(SnapshotSchema)
|
|
341
|
+
.parse(snapshots)
|
|
342
|
+
.items.filter(({ status }) => ready(status.conditions))
|
|
343
|
+
.sort((left, right) => right.metadata.creationTimestamp.localeCompare(left.metadata.creationTimestamp))) {
|
|
344
|
+
const found = sandbox(snapshot.metadata);
|
|
345
|
+
// A sandbox recreated under the same id must not wake from its predecessor's snapshot.
|
|
346
|
+
if (snapshot.metadata.labels[CREATED_LABEL] !== found.labels[CREATED_LABEL])
|
|
347
|
+
continue;
|
|
348
|
+
found.sleptMs ??= Date.parse(snapshot.metadata.creationTimestamp);
|
|
349
|
+
found.snapshots.push(snapshot.metadata.name);
|
|
350
|
+
}
|
|
351
|
+
return [...sandboxes.values()].sort((left, right) => right.createdMs - left.createdMs);
|
|
352
|
+
}
|
|
353
|
+
async livePods(sandboxId) {
|
|
354
|
+
return listOf(PodSchema).parse(await this.kubernetes.request('GET', `${this.pods}?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`)).items;
|
|
355
|
+
}
|
|
356
|
+
/** The sandbox's pod to use: the one that is not shutting down, or null. */
|
|
357
|
+
async livePod(sandboxId) {
|
|
358
|
+
return (await this.livePods(sandboxId)).sort(oldestLiveFirst)[0] ?? null;
|
|
359
|
+
}
|
|
360
|
+
/** Returns the sandbox's running pod, waking or creating it first. */
|
|
361
|
+
async start(sandbox, signal, initialLabels) {
|
|
362
|
+
const id = sandbox.name;
|
|
363
|
+
let pod = sandbox.pod;
|
|
364
|
+
let snapshot = sandbox.snapshots[0];
|
|
365
|
+
// A sleep ends with the pod shutting down, and a checkpoint with the pod free again. One that
|
|
366
|
+
// was abandoned ends when its mark expires, so the wait lasts until then and needs no deadline
|
|
367
|
+
// of its own: a shorter one would fail the dispatch moments before the pod is usable.
|
|
368
|
+
while (pod && held(pod)) {
|
|
369
|
+
await this.kubernetes.watch(this.pods, pod.metadata.name, (found) => (found && held(PodSchema.parse(found)) ? undefined : true), Number(pod.metadata.annotations[SLEEPING_ANNOTATION]) + SLEEP_ABANDONED_MS, signal);
|
|
370
|
+
const [current] = await this.list({ [SANDBOX_LABEL]: id });
|
|
371
|
+
pod = current?.pod ?? null;
|
|
372
|
+
snapshot = current?.snapshots[0];
|
|
373
|
+
if (current)
|
|
374
|
+
sandbox.labels = current.labels;
|
|
375
|
+
}
|
|
376
|
+
const startedAt = Date.now();
|
|
377
|
+
if (pod && (terminating(pod) || !['Running', 'Pending'].includes(pod.status.phase))) {
|
|
378
|
+
if (!terminating(pod)) {
|
|
379
|
+
// Everything written since the last snapshot is gone with the pod.
|
|
380
|
+
const reason = pod.status.containerStatuses.find(({ state }) => state?.terminated?.reason)?.state
|
|
381
|
+
?.terminated?.reason ??
|
|
382
|
+
pod.status.reason ??
|
|
383
|
+
pod.status.phase;
|
|
384
|
+
this.options.onPodLost?.(sandbox.labels, pod.status.phase, reason, !!snapshot);
|
|
385
|
+
await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
|
|
386
|
+
}
|
|
387
|
+
// The pod's last snapshot may be newer than the listing. One of another creation under
|
|
388
|
+
// this id belongs to a sandbox that was replaced, not to this one.
|
|
389
|
+
const [listed] = await this.list({ [SANDBOX_LABEL]: id });
|
|
390
|
+
snapshot =
|
|
391
|
+
listed && listed.labels[CREATED_LABEL] === sandbox.labels[CREATED_LABEL]
|
|
392
|
+
? listed.snapshots[0]
|
|
393
|
+
: undefined;
|
|
394
|
+
pod = null;
|
|
395
|
+
}
|
|
396
|
+
let created = false;
|
|
397
|
+
if (!pod) {
|
|
398
|
+
// A fresh filesystem must also get the caller's initial labels.
|
|
399
|
+
if (!snapshot)
|
|
400
|
+
sandbox.labels = initialLabels;
|
|
401
|
+
// A new name every time, so a wake never waits for the previous pod to finish shutting down.
|
|
402
|
+
const name = `${id}-${randomBytes(3).toString('hex')}`;
|
|
403
|
+
const own = PodSchema.parse(await this.kubernetes.request('POST', this.pods, this.manifest(sandbox, name, snapshot)));
|
|
404
|
+
// Another dispatch or file request may have created one at the same moment. Both keep the
|
|
405
|
+
// older one. This pod counts whether or not the listing has it yet.
|
|
406
|
+
pod = [
|
|
407
|
+
own,
|
|
408
|
+
...(await this.livePods(id)).filter(({ metadata }) => metadata.name !== name),
|
|
409
|
+
].sort(oldestLiveFirst)[0];
|
|
410
|
+
created = pod === own;
|
|
411
|
+
if (!created)
|
|
412
|
+
await this.kubernetes.request('DELETE', `${this.pods}/${name}`);
|
|
413
|
+
}
|
|
414
|
+
// Only the caller whose pod it is reports the start; one that waits for another's does not.
|
|
415
|
+
const operation = created ? (snapshot ? 'wake' : 'create') : null;
|
|
416
|
+
const createdAt = Date.now();
|
|
417
|
+
try {
|
|
418
|
+
if (starting(pod)) {
|
|
419
|
+
// The pod as it is once it has started or can no longer start, or null once it is gone.
|
|
420
|
+
const started = await this.kubernetes.watch(this.pods, pod.metadata.name, (found) => {
|
|
421
|
+
const current = found ? PodSchema.parse(found) : null;
|
|
422
|
+
return current && starting(current) ? undefined : current;
|
|
423
|
+
}, startedAt + START_SECONDS * 1000, signal);
|
|
424
|
+
if (started === undefined)
|
|
425
|
+
throw new Error(`Sandbox ${id} did not finish starting.`);
|
|
426
|
+
pod = started;
|
|
427
|
+
}
|
|
428
|
+
if (pod?.status.phase !== 'Running')
|
|
429
|
+
throw new Error(`Sandbox ${id} failed to start.`);
|
|
430
|
+
// A second caller can see a restored pod before its creator has checked the files.
|
|
431
|
+
if (pod.metadata.annotations[RESTORE_ANNOTATION] &&
|
|
432
|
+
!pod.metadata.annotations[RESTORED_ANNOTATION])
|
|
433
|
+
await this.confirmRestored(pod, id);
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
if (operation)
|
|
437
|
+
this.report(operation, sandbox.labels, pod, createdAt, error, signal);
|
|
438
|
+
throw error;
|
|
439
|
+
}
|
|
440
|
+
if (operation)
|
|
441
|
+
this.report(operation, sandbox.labels, pod, createdAt, null);
|
|
442
|
+
return { pod, fresh: created };
|
|
443
|
+
}
|
|
444
|
+
report(operation, labels, pod, startedAt, error, signal) {
|
|
445
|
+
const outcome = !error ? 'succeeded' : signal?.aborted ? 'aborted' : 'failed';
|
|
446
|
+
const event = {
|
|
447
|
+
operation,
|
|
448
|
+
outcome,
|
|
449
|
+
labels,
|
|
450
|
+
pod: pod?.metadata.name,
|
|
451
|
+
podIp: pod?.status.podIP,
|
|
452
|
+
durationMs: Date.now() - startedAt,
|
|
453
|
+
error,
|
|
454
|
+
};
|
|
455
|
+
if (this.options.onOperation)
|
|
456
|
+
this.options.onOperation(event);
|
|
457
|
+
else if (event.outcome === 'failed')
|
|
458
|
+
console.error(event);
|
|
459
|
+
}
|
|
460
|
+
// GKE starts a pod empty when it cannot restore the requested snapshot. Using that pod would
|
|
461
|
+
// replace saved files with an empty filesystem. Keep the snapshot for the next wake.
|
|
462
|
+
async confirmRestored(pod, id) {
|
|
463
|
+
const path = `${this.pods}/${pod.metadata.name}`;
|
|
464
|
+
const check = new TextEncoder().encode(`test "$(cat ${quote(SANDBOX_ID_FILE)} 2>/dev/null)" = ${quote(id)}`);
|
|
465
|
+
// GKE fills in the files as the container starts, so the first looks can come too early.
|
|
466
|
+
for (let attempt = 0; attempt < RESTORE_CHECKS; attempt++) {
|
|
467
|
+
const { exitCode } = await this.kubernetes.exec(path, EXEC_COMMAND, check, 30);
|
|
468
|
+
if (exitCode === 0) {
|
|
469
|
+
await this.kubernetes.request('PATCH', path, {
|
|
470
|
+
metadata: { annotations: { [RESTORED_ANNOTATION]: 'true' } },
|
|
471
|
+
});
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
await new Promise((resolve) => setTimeout(resolve, RESTORE_CHECK_MS));
|
|
475
|
+
}
|
|
476
|
+
await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
|
|
477
|
+
throw new Error(`Sandbox ${id} was not restored from its snapshot.`);
|
|
478
|
+
}
|
|
479
|
+
manifest(sandbox, name, snapshot) {
|
|
480
|
+
return {
|
|
481
|
+
apiVersion: 'v1',
|
|
482
|
+
kind: 'Pod',
|
|
483
|
+
metadata: {
|
|
484
|
+
name,
|
|
485
|
+
labels: sandbox.labels,
|
|
486
|
+
annotations: {
|
|
487
|
+
[ACQUIRED_ANNOTATION]: String(Date.now()),
|
|
488
|
+
[SLEEPING_ANNOTATION]: '0',
|
|
489
|
+
'kubernetes.io/egress-bandwidth': EGRESS_BANDWIDTH,
|
|
490
|
+
...(snapshot ? { [RESTORE_ANNOTATION]: snapshot } : {}),
|
|
491
|
+
},
|
|
492
|
+
},
|
|
493
|
+
spec: {
|
|
494
|
+
runtimeClassName: 'gvisor',
|
|
495
|
+
serviceAccountName: this.options.serviceAccount,
|
|
496
|
+
automountServiceAccountToken: false,
|
|
497
|
+
enableServiceLinks: false,
|
|
498
|
+
// A restarted container would start from the image, silently without the sandbox's files.
|
|
499
|
+
restartPolicy: 'Never',
|
|
500
|
+
terminationGracePeriodSeconds: 5,
|
|
501
|
+
volumes: [
|
|
502
|
+
// A rootfs-only snapshot leaves volumes out, so /tmp is scratch: on the node's disk while
|
|
503
|
+
// the pod lives, empty in a woken pod, and never uploaded with a snapshot.
|
|
504
|
+
{ name: 'scratch', emptyDir: {} },
|
|
505
|
+
...(this.options.runtime
|
|
506
|
+
? [
|
|
507
|
+
{
|
|
508
|
+
name: 'runtime',
|
|
509
|
+
image: {
|
|
510
|
+
reference: this.options.runtime.image,
|
|
511
|
+
pullPolicy: 'IfNotPresent',
|
|
512
|
+
},
|
|
513
|
+
},
|
|
514
|
+
]
|
|
515
|
+
: []),
|
|
516
|
+
],
|
|
517
|
+
containers: [
|
|
518
|
+
{
|
|
519
|
+
name: 'sandbox',
|
|
520
|
+
image: this.options.image,
|
|
521
|
+
command: podCommand(sandbox.name, !snapshot, this.options.boot?.(sandbox.labels) ?? null),
|
|
522
|
+
volumeMounts: [
|
|
523
|
+
{ name: 'scratch', mountPath: '/tmp' },
|
|
524
|
+
...(this.options.runtime
|
|
525
|
+
? [
|
|
526
|
+
{
|
|
527
|
+
name: 'runtime',
|
|
528
|
+
mountPath: this.options.runtime.mountPath,
|
|
529
|
+
readOnly: true,
|
|
530
|
+
},
|
|
531
|
+
]
|
|
532
|
+
: []),
|
|
533
|
+
],
|
|
534
|
+
resources: this.options.resources ?? DEFAULT_RESOURCES,
|
|
535
|
+
},
|
|
536
|
+
],
|
|
537
|
+
},
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
// A dispatch and the sweep both claim a pod by patching it on the condition that the other's
|
|
541
|
+
// annotation is unchanged since they read it. The pod's resource version cannot serve: the
|
|
542
|
+
// kubelet's status updates change it all the time.
|
|
543
|
+
claim(pod, patch) {
|
|
544
|
+
return this.kubernetes.request('PATCH', `${this.pods}/${pod.metadata.name}`, patch).then((result) => result !== null, (error) => {
|
|
545
|
+
if (error instanceof KubernetesApiError && [409, 422].includes(error.status))
|
|
546
|
+
return false;
|
|
547
|
+
throw error;
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
/** Records the dispatch. Returns false when the sweep claimed the pod first. */
|
|
551
|
+
markAcquired(pod) {
|
|
552
|
+
return this.claim(pod, [
|
|
553
|
+
{ op: 'test', path: SLEEPING_PATH, value: pod.metadata.annotations[SLEEPING_ANNOTATION] },
|
|
554
|
+
{ op: 'replace', path: SLEEPING_PATH, value: '0' },
|
|
555
|
+
{ op: 'replace', path: ACQUIRED_PATH, value: String(Date.now()) },
|
|
556
|
+
]);
|
|
557
|
+
}
|
|
558
|
+
/** Reports that the sandbox is in use, which restarts its idle period. */
|
|
559
|
+
async touch(sandboxId) {
|
|
560
|
+
const pod = await this.livePod(sandboxId);
|
|
561
|
+
if (!pod)
|
|
562
|
+
return;
|
|
563
|
+
await this.kubernetes.request('PATCH', `${this.pods}/${pod.metadata.name}`, {
|
|
564
|
+
metadata: { annotations: { [ACQUIRED_ANNOTATION]: String(Date.now()) } },
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
async sleep(id) {
|
|
568
|
+
const pod = await this.livePod(id);
|
|
569
|
+
if (!pod || terminating(pod))
|
|
570
|
+
return;
|
|
571
|
+
if (held(pod))
|
|
572
|
+
throw new SandboxInUseError(id);
|
|
573
|
+
await this.sleepPod(pod);
|
|
574
|
+
}
|
|
575
|
+
async sleepPod(pod) {
|
|
576
|
+
const name = pod.metadata.labels[SANDBOX_LABEL];
|
|
577
|
+
const path = `${this.pods}/${pod.metadata.name}`;
|
|
578
|
+
const acquired = pod.metadata.annotations[ACQUIRED_ANNOTATION];
|
|
579
|
+
if (Date.now() - Number(acquired) < this.idleTimeoutMs)
|
|
580
|
+
throw new SandboxInUseError(name);
|
|
581
|
+
const claimed = await this.claim(pod, [
|
|
582
|
+
{ op: 'test', path: ACQUIRED_PATH, value: acquired },
|
|
583
|
+
{ op: 'test', path: SLEEPING_PATH, value: pod.metadata.annotations[SLEEPING_ANNOTATION] },
|
|
584
|
+
{ op: 'replace', path: SLEEPING_PATH, value: String(Date.now()) },
|
|
585
|
+
]);
|
|
586
|
+
if (!claimed)
|
|
587
|
+
throw new SandboxInUseError(name);
|
|
588
|
+
const startedAt = Date.now();
|
|
589
|
+
try {
|
|
590
|
+
if (this.options.drain && !(await this.options.drain(this.environment(name, 'started'))))
|
|
591
|
+
throw new SandboxInUseError(name);
|
|
592
|
+
const snapshot = await this.snapshot(pod);
|
|
593
|
+
await this.kubernetes.request('DELETE', path, {
|
|
594
|
+
preconditions: { uid: pod.metadata.uid },
|
|
595
|
+
});
|
|
596
|
+
await this.dropOlderSnapshots(name, snapshot);
|
|
597
|
+
this.report('sleep', pod.metadata.labels, pod, startedAt, null);
|
|
598
|
+
}
|
|
599
|
+
catch (error) {
|
|
600
|
+
// A service that still has work declined; that is no failed sleep.
|
|
601
|
+
if (!(error instanceof SandboxInUseError))
|
|
602
|
+
this.report('sleep', pod.metadata.labels, pod, startedAt, error);
|
|
603
|
+
await this.kubernetes.request('PATCH', path, {
|
|
604
|
+
metadata: { annotations: { [SLEEPING_ANNOTATION]: '0' } },
|
|
605
|
+
});
|
|
606
|
+
throw error;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
// A pod restores from its newest snapshot; older ones only cost storage.
|
|
610
|
+
async dropOlderSnapshots(sandboxId, newest) {
|
|
611
|
+
const { items } = listOf(SnapshotSchema).parse(await this.kubernetes.request('GET', `${this.snapshotsPath}?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`));
|
|
612
|
+
await Promise.all(items
|
|
613
|
+
.filter(({ metadata }) => metadata.name !== newest)
|
|
614
|
+
.map(({ metadata }) => this.kubernetes.request('DELETE', `${this.snapshotsPath}/${metadata.name}`)));
|
|
615
|
+
}
|
|
616
|
+
async snapshot(pod) {
|
|
617
|
+
// An interrupted wake can leave a running pod whose files nobody has verified.
|
|
618
|
+
if (pod.metadata.annotations[RESTORE_ANNOTATION] &&
|
|
619
|
+
!pod.metadata.annotations[RESTORED_ANNOTATION])
|
|
620
|
+
await this.confirmRestored(pod, pod.metadata.labels[SANDBOX_LABEL]);
|
|
621
|
+
const trigger = `${pod.metadata.name}-${Date.now()}`;
|
|
622
|
+
const labels = pod.metadata.labels;
|
|
623
|
+
await this.kubernetes.request('POST', this.triggers, {
|
|
624
|
+
apiVersion: 'podsnapshot.gke.io/v1',
|
|
625
|
+
kind: 'PodSnapshotManualTrigger',
|
|
626
|
+
metadata: { name: trigger, labels },
|
|
627
|
+
spec: { targetPod: pod.metadata.name },
|
|
628
|
+
});
|
|
629
|
+
try {
|
|
630
|
+
const deadline = Date.now() + SNAPSHOT_SECONDS * 1000;
|
|
631
|
+
const inTime = (found) => {
|
|
632
|
+
if (found === undefined)
|
|
633
|
+
throw new Error(`Sandbox ${pod.metadata.name} was not snapshotted in time.`);
|
|
634
|
+
return found;
|
|
635
|
+
};
|
|
636
|
+
// The trigger names its snapshot, and the snapshot then reports that its files are stored.
|
|
637
|
+
const name = inTime(await this.kubernetes.watch(this.triggers, trigger, (found) => {
|
|
638
|
+
const { status } = TriggerSchema.parse(found);
|
|
639
|
+
const failed = status.conditions.find(({ type, status }) => type === 'Triggered' && status === 'False');
|
|
640
|
+
if (failed)
|
|
641
|
+
throw new Error(`Sandbox ${pod.metadata.name} snapshot failed: ${failed.message}`);
|
|
642
|
+
return status.snapshotCreated?.name;
|
|
643
|
+
}, deadline, null));
|
|
644
|
+
inTime(await this.kubernetes.watch(this.snapshotsPath, name, (found) => ready(SnapshotSchema.parse(found).status.conditions) || undefined, deadline, null));
|
|
645
|
+
return name;
|
|
646
|
+
}
|
|
647
|
+
finally {
|
|
648
|
+
await this.kubernetes.request('DELETE', `${this.triggers}/${trigger}`);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
async delete(id) {
|
|
652
|
+
sandboxIdSchema.parse(id);
|
|
653
|
+
await this.deleteMatching({ [SANDBOX_LABEL]: id });
|
|
654
|
+
}
|
|
655
|
+
environment(name, state) {
|
|
656
|
+
// Looked up for every command: a sandbox that slept and woke since runs in another pod.
|
|
657
|
+
const podPath = async () => {
|
|
658
|
+
const pod = await this.livePod(name);
|
|
659
|
+
if (!pod)
|
|
660
|
+
throw new Error(`Sandbox ${name} is not running.`);
|
|
661
|
+
return `${this.pods}/${pod.metadata.name}`;
|
|
662
|
+
};
|
|
663
|
+
return {
|
|
664
|
+
id: name,
|
|
665
|
+
state,
|
|
666
|
+
process: {
|
|
667
|
+
executeCommand: async (command, cwd = '/', env = {}, timeout = 60) => {
|
|
668
|
+
const script = [
|
|
669
|
+
`cd ${quote(cwd)} || exit 1`,
|
|
670
|
+
...Object.entries(env).map(([key, value]) => {
|
|
671
|
+
if (!/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(key))
|
|
672
|
+
throw new Error('Invalid environment variable name.');
|
|
673
|
+
return `export ${key}=${quote(value)}`;
|
|
674
|
+
}),
|
|
675
|
+
command,
|
|
676
|
+
].join('\n');
|
|
677
|
+
const { exitCode, output } = await this.kubernetes.exec(await podPath(), EXEC_COMMAND, new TextEncoder().encode(script), timeout);
|
|
678
|
+
return { exitCode, result: output };
|
|
679
|
+
},
|
|
680
|
+
},
|
|
681
|
+
fs: {
|
|
682
|
+
uploadFile: async (local, remote, timeout = 300) => {
|
|
683
|
+
const { exitCode, output } = await this.kubernetes.exec(await podPath(), ['sh', '-c', 'cat > "$0"', remote], await readFile(local), timeout);
|
|
684
|
+
if (exitCode !== 0)
|
|
685
|
+
throw new Error(`Could not upload ${remote}: ${output}`);
|
|
686
|
+
},
|
|
687
|
+
},
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
}
|