@getenergy/gke-sandboxes 0.4.1 → 0.6.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/dist/index.js CHANGED
@@ -1,11 +1,14 @@
1
- import { createHash, randomInt, randomUUID } from 'node:crypto';
1
+ import { createHash, randomBytes, 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';
5
5
  import { finished } from 'node:stream/promises';
6
6
  import { z } from 'zod';
7
+ import { CommandServerUnreachableError, directExec, } from './command-channel.js';
8
+ import { COMMAND_SERVER } from './command-server-binary.js';
7
9
  import { KubernetesApiError } from './kubernetes-api.js';
8
10
  import { MEMORY_WATCHDOG } from './memory-watchdog.js';
11
+ export { CommandServerUnreachableError } from './command-channel.js';
9
12
  export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
10
13
  // Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The kubelet
11
14
  // counts a sandbox's root filesystem, scratch /tmp and logs against the disk limit and evicts a
@@ -26,6 +29,37 @@ const ACQUIRED_PATH = '/metadata/annotations/getenergy.com~1acquired-ms';
26
29
  const SLEEPING_PATH = '/metadata/annotations/getenergy.com~1sleeping-ms';
27
30
  const RESTORED_ANNOTATION = 'getenergy.com/restore-verified';
28
31
  const RESTORE_ANNOTATION = 'podsnapshot.gke.io/ps-name';
32
+ // A pod started from another sandbox's snapshot holds that sandbox's id file until it is checked.
33
+ const FORK_SOURCE_ANNOTATION = 'getenergy.com/forked-from';
34
+ // Marks the record of a snapshot taken with snapshot(id), which no later checkpoint or sleep
35
+ // removes. GKE lets nothing but its own controller change a snapshot, so the mark is a Lease named
36
+ // after it, which goes when the snapshot does.
37
+ const KEPT_LABEL = 'getenergy.com/kept-snapshot';
38
+ const keptLease = (snapshot) => `${snapshot}.kept`;
39
+ // The record that a new sandbox's id is taken, and by which pod, while that pod may not carry the
40
+ // sandbox's labels yet. Pod names never contain a dot, so it can share no name with a pod's Lease.
41
+ const IDENTITY_SUFFIX = '.sandbox';
42
+ const identityLease = (id) => `${id}${IDENTITY_SUFFIX}`;
43
+ // A pod is named after the snapshot it starts from. Kubernetes creates a name once, so callers that
44
+ // start a sandbox at the same moment get one pod between them.
45
+ const podNameFor = (id, snapshot) => `${id}-${createHash('sha256')
46
+ .update(snapshot ?? '')
47
+ .digest('hex')
48
+ .slice(0, 6)}`;
49
+ // A JSON Patch path to a label; `~1` is a slash inside a key.
50
+ const labelPath = (key) => `/metadata/labels/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`;
51
+ // A pool pod that its claimer has not yet labelled is labelled by the pool's maintainer after this.
52
+ const ADOPT_AFTER_MS = 30_000;
53
+ // A pool pod taken but never handed out is removed after this: the hand-out's command alone may take
54
+ // 30 seconds.
55
+ const HAND_OUT_ABANDONED_MS = 120_000;
56
+ // What a pod's command server listens on and accepts. Only the pod's own record holds the token,
57
+ // so a caller that reads the pod can reach it and a neighbouring pod cannot.
58
+ const COMMAND_PORT_ANNOTATION = 'getenergy.com/command-port';
59
+ const COMMAND_TOKEN_ANNOTATION = 'getenergy.com/command-token';
60
+ const COMMAND_SERVER_MOUNT = '/opt/gke-sandboxes';
61
+ // One ConfigMap per build of the server, so pods of an earlier release keep theirs.
62
+ const COMMAND_SERVER_CONFIG = `gke-sandboxes-command-server-${COMMAND_SERVER.sha256.slice(0, 12)}`;
29
63
  // GKE Dataplane V2 runs Cilium's bandwidth manager, which paces a pod's traffic out of its node to
30
64
  // this rate, about a 16 Gbps node's share for one of 64 sandboxes. No sandbox crowds out its
31
65
  // neighbours, and one turned against a host can send it no more than this.
@@ -70,10 +104,16 @@ const bootScript = (shell) => `(
70
104
  `;
71
105
  // A sandbox's first pod records whose it is before anything else can happen to it: a dispatch
72
106
  // that created the pod may be aborted before it could run a command in it.
73
- const podCommand = (sandboxId, first, boot, watchdog) => [
107
+ const podCommand = (sandboxId, first, boot, watchdog, commandServer) => [
74
108
  'sh',
75
109
  '-c',
76
110
  `${first ? `printf %s "$0" > ${SANDBOX_ID_FILE} || exit 1\n` : ''}${
111
+ // Restarted if it ever ends: without it the sandbox takes no commands. The programs the
112
+ // sandbox starts do not inherit the token, though anything in the sandbox can still find it:
113
+ // it lets a caller into this sandbox only.
114
+ commandServer
115
+ ? `(while :; do "${COMMAND_SERVER_MOUNT}/command-server-$(uname -m)"; sleep 1; done) </dev/null &\nunset GKE_SANDBOXES_COMMAND_TOKEN GKE_SANDBOXES_COMMAND_PORT\n`
116
+ : ''}${
77
117
  // Its own shell, so that its $$ is the watchdog and not the pod's first process.
78
118
  watchdog
79
119
  ? // Kubernetes reads `$$` in a command as an escaped `$`, so the script's own are doubled.
@@ -165,9 +205,21 @@ const StoredSnapshotSchema = z.object({
165
205
  // A sandbox's keep-alive. Reports of use renew it instead of writing to the pod: GKE checks every
166
206
  // pod write with an admission webhook, which is several times slower and queues under load.
167
207
  const LeaseSchema = z.object({
168
- metadata: z.object({ name: z.string() }),
169
- spec: z.object({ renewTime: z.string().optional() }).default({}),
208
+ metadata: z.object({
209
+ name: z.string(),
210
+ resourceVersion: z.string().default(''),
211
+ labels: z.record(z.string(), z.string()).default({}),
212
+ }),
213
+ spec: z
214
+ .object({
215
+ renewTime: z.string().optional(),
216
+ acquireTime: z.string().optional(),
217
+ holderIdentity: z.string().optional(),
218
+ })
219
+ .default({}),
170
220
  });
221
+ // Kubernetes reads a Lease's times only with six decimals.
222
+ const leaseTime = () => new Date().toISOString().replace('Z', '000Z');
171
223
  const renewedMs = (lease) => lease ? Date.parse(LeaseSchema.parse(lease).spec.renewTime ?? '') || 0 : 0;
172
224
  const TriggerSchema = z.object({
173
225
  status: z
@@ -180,6 +232,7 @@ const TriggerSchema = z.object({
180
232
  .default({ conditions: [] }),
181
233
  });
182
234
  const listOf = (item) => z.object({ items: z.array(item) });
235
+ const withoutPoolLabels = ({ [POOL_LABEL]: _, [TEMPLATE_LABEL]: __, ...labels }) => labels;
183
236
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
184
237
  const ready = (conditions) => conditions.some(({ type, status }) => type === 'Ready' && status === 'True');
185
238
  export const terminating = (pod) => !!pod.metadata.deletionTimestamp;
@@ -218,6 +271,10 @@ export class GkeSandboxes {
218
271
  manager;
219
272
  idleTimeoutMs;
220
273
  diskBytes;
274
+ configMaps;
275
+ commandServer;
276
+ // Pool pods this process is labelling as the sandboxes they were handed out as.
277
+ adopting = new Map();
221
278
  constructor(kubernetes, options) {
222
279
  this.kubernetes = kubernetes;
223
280
  this.options = options;
@@ -241,6 +298,9 @@ export class GkeSandboxes {
241
298
  throw new Error('A manager label and a positive idle timeout are required.');
242
299
  this.pods = `/api/v1/namespaces/${namespace}/pods`;
243
300
  this.leases = `/apis/coordination.k8s.io/v1/namespaces/${namespace}/leases`;
301
+ this.configMaps = `/api/v1/namespaces/${namespace}/configmaps`;
302
+ if (options.directCommands)
303
+ z.number().int().min(1).max(65535).parse(options.directCommands.port);
244
304
  const api = `/apis/podsnapshot.gke.io/v1/namespaces/${namespace}`;
245
305
  this.triggers = `${api}/podsnapshotmanualtriggers`;
246
306
  this.snapshotsPath = `${api}/podsnapshots`;
@@ -249,10 +309,22 @@ export class GkeSandboxes {
249
309
  const pairs = Object.entries(labelSchema.parse({ ...labels, ...this.manager })).map(([key, value]) => `${key}=${value}`);
250
310
  return encodeURIComponent(pairs.join(','));
251
311
  }
252
- async acquire(id, signal, initialLabels = {}) {
312
+ /**
313
+ * Returns the sandbox's running pod, waking it from its newest snapshot or creating it. With
314
+ * `from`, a sandbox that does not exist yet starts from that snapshot, which may be another
315
+ * sandbox's (see `snapshot`).
316
+ */
317
+ async acquire(id, signal, initialLabels = {}, { from } = {}) {
318
+ sandboxIdSchema.parse(id);
319
+ const base = from === undefined ? undefined : await this.forkSource(from);
320
+ return this.acquireFound(id, signal, initialLabels, base, await this.find(id));
321
+ }
322
+ async acquireFound(id, signal, initialLabels, base, found) {
323
+ if (found && base)
324
+ throw new Error(`Sandbox ${id} already exists.`);
325
+ let existing = found;
253
326
  while (true) {
254
327
  signal.throwIfAborted();
255
- const existing = await this.find(id);
256
328
  const createdMs = Date.now();
257
329
  const record = existing ?? {
258
330
  name: id,
@@ -268,82 +340,138 @@ export class GkeSandboxes {
268
340
  ...this.manager,
269
341
  [SANDBOX_LABEL]: id,
270
342
  [CREATED_LABEL]: String(record.createdMs),
271
- });
272
- if (!fresh && !(await this.markAcquired(pod)))
343
+ }, existing ? undefined : base);
344
+ if (!fresh && !(await this.markAcquired(pod))) {
345
+ existing = await this.find(id);
273
346
  continue;
347
+ }
274
348
  return {
275
- sandbox: this.makeEnvironment(id, 'started', pod.metadata.name),
349
+ sandbox: this.makeEnvironment(id, 'started', pod),
276
350
  startState,
277
- labels: pod.metadata.labels,
351
+ labels: withoutPoolLabels(pod.metadata.labels),
278
352
  podName: pod.metadata.name,
279
353
  createdMs: Number(pod.metadata.labels[CREATED_LABEL]),
280
354
  touch: () => this.touch(id),
281
355
  };
282
356
  }
283
357
  }
284
- /** Creates single-use sandboxes with generated IDs. Reopen a saved ID with acquire(). */
358
+ // Where a sandbox started with `from` gets its files, and whose id file they hold.
359
+ async forkSource(name) {
360
+ const found = await this.kubernetes.request('GET', `${this.snapshotsPath}/${name}`);
361
+ const snapshot = found ? SnapshotSchema.parse(found) : null;
362
+ const sourceId = snapshot?.metadata.labels[SANDBOX_LABEL];
363
+ if (!snapshot || !sourceId || !ready(snapshot.status.conditions))
364
+ throw new Error(`Snapshot ${name} does not exist or is not ready.`);
365
+ return { name, sourceId };
366
+ }
367
+ /**
368
+ * Running sandboxes kept ready, so that a new one starts without waiting for a pod. A sandbox is
369
+ * handed out by creating a Lease named after its pod, which GKE's admission webhooks do not
370
+ * check: claims stay fast when many arrive at once. The pod is labelled as the sandbox it became
371
+ * afterwards; until then the Lease carries its labels, and lookups read them from there.
372
+ */
285
373
  warmPool(name) {
286
374
  sandboxIdSchema.parse(name);
287
- if (this.options.boot)
288
- throw new Error('Warm pools require an image that can start before caller labels are known.');
375
+ const sandboxes = this;
289
376
  const poolLabels = { ...this.manager, [POOL_LABEL]: name };
290
- const spare = (id) => this.manifest({ name: id, labels: poolLabels }, id, undefined);
377
+ const spare = (id) => this.manifest({ name: id, labels: poolLabels }, id, undefined, { boot: false });
291
378
  const template = createHash('sha256')
292
379
  .update(JSON.stringify(spare('template').spec))
293
380
  .digest('hex')
294
381
  .slice(0, 32);
295
- const list = async (labels) => listOf(PodSchema)
382
+ const requestedLabels = { ...poolLabels, [TEMPLATE_LABEL]: template };
383
+ const spares = async (labels) => listOf(PodSchema)
296
384
  .parse(await this.kubernetes.request('GET', `${this.pods}?labelSelector=${this.selector(labels)},!${SANDBOX_LABEL}`))
297
385
  .items.filter((pod) => !terminating(pod));
298
- const requestedLabels = { ...poolLabels, [TEMPLATE_LABEL]: template };
299
- // One maintainer per named pool. Claims can come from any replica. A versioned delete
300
- // prevents a resize or image rollout from deleting a pod another replica just handed out.
386
+ // A pool pod with a Lease named after it is taken: by a caller handing it out, or by a
387
+ // maintainer removing it. It is handed out once a record names it as a sandbox's pod.
388
+ const claims = async () => {
389
+ const { items } = listOf(LeaseSchema).parse(await this.kubernetes.request('GET', `${this.leases}?labelSelector=${this.selector({})}`));
390
+ return {
391
+ taken: new Map(items.map((lease) => [lease.metadata.name, lease])),
392
+ handedOut: new Map(items
393
+ .filter(({ metadata }) => metadata.name.endsWith(IDENTITY_SUFFIX))
394
+ .map((lease) => [lease.spec.holderIdentity ?? '', lease])),
395
+ };
396
+ };
397
+ const takeLease = (pod, holder) => this.kubernetes
398
+ .request('POST', this.leases, {
399
+ apiVersion: 'coordination.k8s.io/v1',
400
+ kind: 'Lease',
401
+ metadata: {
402
+ name: pod.metadata.name,
403
+ labels: this.manager,
404
+ ownerReferences: [
405
+ { apiVersion: 'v1', kind: 'Pod', name: pod.metadata.name, uid: pod.metadata.uid },
406
+ ],
407
+ },
408
+ spec: { holderIdentity: holder, acquireTime: leaseTime(), renewTime: leaseTime() },
409
+ })
410
+ .then(() => true, (error) => {
411
+ if (error instanceof KubernetesApiError && error.status === 409)
412
+ return false;
413
+ throw error;
414
+ });
415
+ const age = (lease) => Date.now() - (Date.parse(lease?.spec.acquireTime ?? '') || Date.now());
416
+ // One maintainer per named pool; claims can come from any replica. A spare is removed only
417
+ // after the maintainer has taken its Lease, so a pod being handed out is never deleted.
301
418
  const reconcile = async (size) => {
302
419
  z.number().int().nonnegative().parse(size);
303
- const idle = await list(poolLabels);
304
- const usable = idle
420
+ const [idle, { taken, handedOut }] = await Promise.all([spares(poolLabels), claims()]);
421
+ const free = idle.filter((pod) => !taken.has(pod.metadata.name));
422
+ const usable = free
305
423
  .filter((pod) => pod.metadata.labels[TEMPLATE_LABEL] === template &&
306
424
  ['Pending', 'Running'].includes(pod.status.phase))
307
425
  .sort(oldestLiveFirst);
308
426
  const keep = new Set(usable.slice(0, size).map((pod) => pod.metadata.uid));
309
427
  await Promise.all([
310
- ...idle
428
+ ...idle.map((pod) => {
429
+ const { name } = pod.metadata;
430
+ const record = handedOut.get(name);
431
+ // Handed out, but its caller stopped before it labelled the pod.
432
+ if (record)
433
+ return age(record) > ADOPT_AFTER_MS ? this.adopt(name, record.metadata.labels) : null;
434
+ // Taken by a caller, or a maintainer, that stopped before it finished. A caller may have
435
+ // given it an id file and a service, so it is not put back.
436
+ return taken.has(name) && age(taken.get(name)) > HAND_OUT_ABANDONED_MS
437
+ ? this.kubernetes.request('DELETE', `${this.pods}/${name}`)
438
+ : null;
439
+ }),
440
+ ...free
311
441
  .filter((pod) => !keep.has(pod.metadata.uid))
312
- .map(async ({ metadata }) => {
313
- try {
314
- await this.kubernetes.request('DELETE', `${this.pods}/${metadata.name}`, {
315
- preconditions: { uid: metadata.uid, resourceVersion: metadata.resourceVersion },
316
- });
317
- }
318
- catch (error) {
319
- if (!(error instanceof KubernetesApiError && error.status === 409))
320
- throw error;
321
- }
442
+ .map(async (pod) => {
443
+ if (await takeLease(pod, ''))
444
+ await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
322
445
  }),
323
446
  ...Array.from({ length: Math.max(0, size - keep.size) }, () => {
324
447
  const pod = spare(randomUUID());
325
448
  pod.metadata.labels = requestedLabels;
326
- return this.kubernetes.request('POST', this.pods, pod);
449
+ return this.createPod(pod);
327
450
  }),
328
451
  ]);
329
452
  };
330
- // Share one list among concurrent callers. Keep each chosen pod version reserved until
331
- // the API stops listing it. That also covers a list issued while a claim is in flight.
453
+ // Share one list among concurrent callers, and keep each chosen pod reserved until the list
454
+ // shows it taken, so that callers in this process try different pods.
332
455
  let reading;
333
456
  const reserved = new Set();
334
- const podVersion = ({ metadata }) => metadata.uid + '/' + metadata.resourceVersion;
335
- const available = async () => {
336
- const pods = (await list(requestedLabels)).filter((pod) => pod.status.phase === 'Running' && ready(pod.status.conditions));
337
- const versions = new Set(pods.map(podVersion));
338
- for (const version of reserved)
339
- if (!versions.has(version))
340
- reserved.delete(version);
341
- // Independent backend replicas can see the same list. Vary their first choice;
342
- // the versioned Kubernetes patch still decides exclusive ownership.
343
- const offset = pods.length ? randomInt(pods.length) : 0;
344
- return pods.slice(offset).concat(pods.slice(0, offset));
345
- };
346
- const create = async (signal, labels = {}) => {
457
+ const available = () => (reading ??= Promise.all([spares(requestedLabels), claims()])
458
+ .then(([pods, { taken }]) => {
459
+ const free = pods.filter((pod) => pod.status.phase === 'Running' &&
460
+ ready(pod.status.conditions) &&
461
+ !taken.has(pod.metadata.name));
462
+ const listed = new Set(free.map((pod) => pod.metadata.name));
463
+ for (const pod of reserved)
464
+ if (!listed.has(pod))
465
+ reserved.delete(pod);
466
+ // Replicas see the same list. Varying their first choice spares them conflicts; the
467
+ // Lease still decides which caller gets a pod.
468
+ const offset = free.length ? randomInt(free.length) : 0;
469
+ return free.slice(offset).concat(free.slice(0, offset));
470
+ })
471
+ .finally(() => {
472
+ reading = undefined;
473
+ }));
474
+ const checkLabels = (labels) => {
347
475
  labelSchema.parse(labels);
348
476
  for (const key of [
349
477
  SANDBOX_LABEL,
@@ -354,57 +482,113 @@ export class GkeSandboxes {
354
482
  ])
355
483
  if (key in labels)
356
484
  throw new Error(`Reserved pool label: ${key}`);
485
+ };
486
+ // Hands out a spare as the sandbox `id`, or as one named after its pod when `id` is null.
487
+ // Returns null when the pool has nothing ready, and 'taken' when another caller created `id`
488
+ // at the same moment. Nothing but this caller sees the pod as the sandbox until the record of
489
+ // the hand-out exists, which is written last.
490
+ const claim = async (id, labels, signal, listed) => {
357
491
  const startedAt = Date.now();
358
- signal.throwIfAborted();
359
- reading ??= available().finally(() => {
360
- reading = undefined;
361
- });
362
- const pods = await reading;
492
+ const pods = [...(await listed)];
363
493
  while (pods.length) {
364
494
  signal.throwIfAborted();
365
495
  const pod = pods.pop();
366
- const version = podVersion(pod);
367
- if (reserved.has(version))
496
+ const podName = pod.metadata.name;
497
+ if (reserved.has(podName))
498
+ continue;
499
+ reserved.add(podName);
500
+ const sandboxId = id ?? podName;
501
+ if (!(await takeLease(pod, sandboxId)))
502
+ continue;
503
+ // A maintainer that removed the pod first held its Lease until the pod went, and Kubernetes
504
+ // then deleted that Lease too, so the pod may be gone or shutting down by now.
505
+ const current = await this.kubernetes.request('GET', `${this.pods}/${podName}`);
506
+ if (!current || terminating(PodSchema.parse(current)))
368
507
  continue;
369
- reserved.add(version);
370
- const id = pod.metadata.name;
371
- const now = String(Date.now());
508
+ const sandboxLabels = {
509
+ ...labels,
510
+ ...this.manager,
511
+ [SANDBOX_LABEL]: sandboxId,
512
+ [CREATED_LABEL]: String(Date.now()),
513
+ };
514
+ // The pod recorded its own name as the sandbox it holds, and started no service, because
515
+ // it started before either was known.
516
+ const boot = this.options.boot?.(sandboxLabels);
517
+ const prepare = sandboxId !== podName || !!boot;
372
518
  try {
373
- const claimed = await this.kubernetes.request('PATCH', `${this.pods}/${id}`, {
374
- metadata: {
375
- resourceVersion: pod.metadata.resourceVersion,
376
- labels: {
377
- ...labels,
378
- [SANDBOX_LABEL]: id,
379
- [CREATED_LABEL]: now,
380
- [POOL_LABEL]: null,
381
- [TEMPLATE_LABEL]: null,
382
- },
383
- annotations: { [ACQUIRED_ANNOTATION]: now },
384
- },
385
- });
386
- if (!claimed)
387
- continue;
388
- this.report('create', PodSchema.parse(claimed).metadata.labels, pod, startedAt, null);
389
- return {
390
- sandbox: this.makeEnvironment(id, 'started', id),
391
- podName: id,
392
- fromPool: true,
393
- touch: () => this.touch(id),
394
- };
519
+ if (prepare) {
520
+ const { exitCode, output } = await this.runIn(pod, [
521
+ 'sh',
522
+ '-c',
523
+ `printf %s "$0" > ${SANDBOX_ID_FILE} || exit 1\n${boot ? bootScript(boot.shell) : ''}`,
524
+ sandboxId,
525
+ ...(boot?.args ?? []),
526
+ ], new Uint8Array(), 30);
527
+ if (exitCode !== 0)
528
+ throw new Error(`Could not hand out pod ${podName}: ${output}`);
529
+ }
530
+ if (!(await this.recordHandOut(sandboxId, pod, sandboxLabels))) {
531
+ reserved.delete(podName);
532
+ // A prepared pod holds this id and its service, so it cannot go back to the pool.
533
+ await this.kubernetes.request('DELETE', prepare ? `${this.pods}/${podName}` : `${this.leases}/${podName}`);
534
+ return 'taken';
535
+ }
395
536
  }
396
537
  catch (error) {
397
- if (!(error instanceof KubernetesApiError && error.status === 409)) {
398
- reserved.delete(version);
399
- throw error;
400
- }
538
+ this.report('create', sandboxLabels, pod, startedAt, error);
539
+ reserved.delete(podName);
540
+ await this.kubernetes.request('DELETE', `${this.pods}/${podName}`);
541
+ continue;
401
542
  }
543
+ // Off the caller's path: a pod write passes the admission webhook. A failure is retried
544
+ // before the sandbox's first snapshot and by the pool's maintainer.
545
+ this.adopt(podName, sandboxLabels).catch(() => undefined);
546
+ this.report('create', sandboxLabels, pod, startedAt, null);
547
+ pod.metadata.labels = { ...sandboxLabels, ...pod.metadata.labels };
548
+ return {
549
+ sandbox: this.makeEnvironment(sandboxId, 'started', pod),
550
+ labels: sandboxLabels,
551
+ podName,
552
+ createdMs: Number(sandboxLabels[CREATED_LABEL]),
553
+ touch: () => this.touch(sandboxId),
554
+ };
402
555
  }
403
- const { sandbox, podName, touch } = await this.acquire(randomUUID(), signal, labels);
404
- return { sandbox, podName, touch, fromPool: false };
556
+ return null;
405
557
  };
406
558
  return {
407
- create,
559
+ /**
560
+ * Returns the sandbox `id`, from the pool if it does not exist yet. An existing sandbox is
561
+ * acquired as `GkeSandboxes.acquire` does; an empty pool starts a new pod. Use the same pool
562
+ * for an id every time.
563
+ */
564
+ async acquire(id, signal, labels = {}) {
565
+ sandboxIdSchema.parse(id);
566
+ checkLabels(labels);
567
+ signal.throwIfAborted();
568
+ // Both lists at once: the spares are only needed if the sandbox is new.
569
+ const listed = available();
570
+ listed.catch(() => undefined);
571
+ const found = await sandboxes.find(id);
572
+ const claimed = found ? null : await claim(id, labels, signal, listed);
573
+ if (claimed && claimed !== 'taken')
574
+ return { ...claimed, startState: 'missing', fromPool: true };
575
+ // Taken by another caller at the same moment: the lookup now finds its pod.
576
+ const current = claimed === 'taken' ? await sandboxes.find(id) : found;
577
+ return {
578
+ ...(await sandboxes.acquireFound(id, signal, labels, undefined, current)),
579
+ fromPool: false,
580
+ };
581
+ },
582
+ /** Hands out a sandbox with a generated ID. Reopen it later with `acquire`. */
583
+ async create(signal, labels = {}) {
584
+ checkLabels(labels);
585
+ signal.throwIfAborted();
586
+ const claimed = await claim(null, labels, signal, available());
587
+ if (claimed && claimed !== 'taken')
588
+ return { ...claimed, fromPool: true };
589
+ const { sandbox, podName, touch } = await sandboxes.acquire(randomUUID(), signal, labels);
590
+ return { sandbox, podName, touch, fromPool: false };
591
+ },
408
592
  reconcile,
409
593
  async maintain(size, signal) {
410
594
  while (!signal.aborted) {
@@ -423,10 +607,12 @@ export class GkeSandboxes {
423
607
  /** Open a previously listed workspace without extending its idle period on a read. */
424
608
  async open(record, signal, freshLabels) {
425
609
  signal.throwIfAborted();
426
- await this.start(record, signal, { ...record.labels, ...freshLabels });
610
+ await this.start(record, signal, { ...record.labels, ...freshLabels }, undefined);
427
611
  return this.environment(record.name, 'started');
428
612
  }
429
613
  async labelPod(podName, labels) {
614
+ // A pool pod is labelled as its sandbox first, which adds only the labels it lacks.
615
+ await this.adopting.get(podName)?.catch(() => undefined);
430
616
  if (!(await this.kubernetes.request('PATCH', `${this.pods}/${podName}`, { metadata: { labels } })))
431
617
  throw new Error(`Pod ${podName} is not running.`);
432
618
  }
@@ -460,7 +646,7 @@ export class GkeSandboxes {
460
646
  return;
461
647
  const startedAt = Date.now();
462
648
  try {
463
- await this.dropOlderSnapshots(sandboxId, await this.snapshot(pod));
649
+ await this.dropOlderSnapshots(sandboxId, await this.takeSnapshot(pod));
464
650
  this.report('checkpoint', pod.metadata.labels, pod, startedAt, null);
465
651
  }
466
652
  catch (error) {
@@ -473,6 +659,53 @@ export class GkeSandboxes {
473
659
  });
474
660
  }
475
661
  }
662
+ /**
663
+ * Snapshots a running sandbox and keeps the snapshot until `deleteSnapshot`; no later checkpoint
664
+ * or sleep removes it. The sandbox runs on. Returns the snapshot's name: pass it as `from` to
665
+ * `acquire` to start new sandboxes with these files, as many as needed.
666
+ */
667
+ async snapshot(sandboxId) {
668
+ const pod = await this.livePod(sandboxId);
669
+ if (!pod || pod.status.phase !== 'Running' || sleeping(pod))
670
+ throw new Error(`Sandbox ${sandboxId} is not running.`);
671
+ const claimed = await this.claim(pod, [
672
+ { op: 'test', path: SLEEPING_PATH, value: pod.metadata.annotations[SLEEPING_ANNOTATION] },
673
+ { op: 'replace', path: SLEEPING_PATH, value: String(Date.now()) },
674
+ ]);
675
+ if (!claimed)
676
+ throw new SandboxInUseError(sandboxId);
677
+ const startedAt = Date.now();
678
+ try {
679
+ const name = await this.takeSnapshot(pod);
680
+ const { metadata } = SnapshotSchema.parse(await this.kubernetes.request('GET', `${this.snapshotsPath}/${name}`));
681
+ await this.kubernetes.request('POST', this.leases, {
682
+ apiVersion: 'coordination.k8s.io/v1',
683
+ kind: 'Lease',
684
+ metadata: {
685
+ name: keptLease(name),
686
+ labels: { ...this.manager, [SANDBOX_LABEL]: sandboxId, [KEPT_LABEL]: 'true' },
687
+ ownerReferences: [
688
+ { apiVersion: 'podsnapshot.gke.io/v1', kind: 'PodSnapshot', name, uid: metadata.uid },
689
+ ],
690
+ },
691
+ spec: { holderIdentity: name },
692
+ });
693
+ this.report('snapshot', pod.metadata.labels, pod, startedAt, null);
694
+ return name;
695
+ }
696
+ catch (error) {
697
+ this.report('snapshot', pod.metadata.labels, pod, startedAt, error);
698
+ throw error;
699
+ }
700
+ finally {
701
+ await this.kubernetes.request('PATCH', `${this.pods}/${pod.metadata.name}`, {
702
+ metadata: { annotations: { [SLEEPING_ANNOTATION]: '0' } },
703
+ });
704
+ }
705
+ }
706
+ async deleteSnapshot(name) {
707
+ await this.kubernetes.request('DELETE', `${this.snapshotsPath}/${name}`);
708
+ }
476
709
  async sleepUnused() {
477
710
  const idleBefore = Date.now() - this.idleTimeoutMs;
478
711
  const [sandboxes, leases] = await Promise.all([
@@ -539,7 +772,12 @@ export class GkeSandboxes {
539
772
  if (!Object.keys(match).some((key) => !(key in this.manager)))
540
773
  throw new Error('A deletion selector is required.');
541
774
  const labels = this.selector(match);
542
- await Promise.all([this.pods, this.snapshotsPath, this.triggers].map((path) => this.kubernetes.request('DELETE', `${path}?labelSelector=${labels}`)));
775
+ // A pool pod handed out moments ago may not carry the labels yet; the record of it does.
776
+ const { items } = listOf(LeaseSchema).parse(await this.kubernetes.request('GET', `${this.leases}?labelSelector=${labels}`));
777
+ await Promise.all(items
778
+ .filter(({ metadata, spec }) => metadata.name.endsWith(IDENTITY_SUFFIX) && spec.holderIdentity)
779
+ .map(({ spec }) => this.kubernetes.request('DELETE', `${this.pods}/${spec.holderIdentity}`)));
780
+ await Promise.all([this.pods, this.snapshotsPath, this.triggers, this.leases].map((path) => this.kubernetes.request('DELETE', `${path}?labelSelector=${labels}`)));
543
781
  }
544
782
  async find(id) {
545
783
  sandboxIdSchema.parse(id);
@@ -548,9 +786,10 @@ export class GkeSandboxes {
548
786
  /** Every sandbox with these labels, awake or asleep, newest first. */
549
787
  async list(labels) {
550
788
  const query = `?labelSelector=${this.selector(labels)},${SANDBOX_LABEL}`;
551
- const [pods, snapshots] = await Promise.all([
789
+ const [pods, snapshots, leases] = await Promise.all([
552
790
  this.kubernetes.request('GET', `${this.pods}${query}`),
553
791
  this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
792
+ this.kubernetes.request('GET', `${this.leases}${query}`),
554
793
  ]);
555
794
  const sandboxes = new Map();
556
795
  const sandbox = (metadata) => {
@@ -569,6 +808,15 @@ export class GkeSandboxes {
569
808
  // A woken sandbox gets a new pod while its previous one may still be shutting down.
570
809
  for (const pod of listOf(PodSchema).parse(pods).items.sort(oldestLiveFirst).reverse())
571
810
  sandbox(pod.metadata).pod = pod;
811
+ // A pool pod handed out moments ago may not carry its sandbox's labels yet; the record of the
812
+ // hand-out does.
813
+ const unlabelled = listOf(LeaseSchema)
814
+ .parse(leases)
815
+ .items.filter(({ metadata }) => metadata.name.endsWith(IDENTITY_SUFFIX) &&
816
+ !sandboxes.get(metadata.labels[SANDBOX_LABEL])?.pod);
817
+ for (const pod of await Promise.all(unlabelled.map((lease) => this.claimedPod(lease))))
818
+ if (pod && POOL_LABEL in pod.metadata.labels)
819
+ sandbox(pod.metadata).pod = pod;
572
820
  for (const snapshot of listOf(SnapshotSchema)
573
821
  .parse(snapshots)
574
822
  .items.filter(({ status }) => ready(status.conditions))
@@ -583,17 +831,164 @@ export class GkeSandboxes {
583
831
  return [...sandboxes.values()].sort((left, right) => right.createdMs - left.createdMs);
584
832
  }
585
833
  async livePods(sandboxId) {
586
- return listOf(PodSchema).parse(await this.kubernetes.request('GET', `${this.pods}?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`)).items;
834
+ const query = `?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`;
835
+ const { items } = listOf(PodSchema).parse(await this.kubernetes.request('GET', `${this.pods}${query}`));
836
+ if (items.length)
837
+ return items;
838
+ // A pool pod handed out moments ago may not carry its sandbox's labels yet; the record of the
839
+ // hand-out does.
840
+ const leases = listOf(LeaseSchema).parse(await this.kubernetes.request('GET', `${this.leases}${query}`));
841
+ const pods = await Promise.all(leases.items
842
+ .filter(({ metadata }) => metadata.name.endsWith(IDENTITY_SUFFIX))
843
+ .map((lease) => this.claimedPod(lease)));
844
+ return pods.filter((pod) => pod !== null && POOL_LABEL in pod.metadata.labels);
845
+ }
846
+ /**
847
+ * The pod a sandbox's id record names, with the sandbox's labels from the record if it is a pool
848
+ * pod that does not carry them yet. It keeps its pool label until it does, which is how a
849
+ * snapshot knows to label it first.
850
+ */
851
+ async claimedPod(record) {
852
+ const holder = record.spec.holderIdentity;
853
+ const found = holder ? await this.kubernetes.request('GET', `${this.pods}/${holder}`) : null;
854
+ if (!found)
855
+ return null;
856
+ const pod = PodSchema.parse(found);
857
+ if (POOL_LABEL in pod.metadata.labels)
858
+ pod.metadata.labels = { ...record.metadata.labels, ...pod.metadata.labels };
859
+ return pod;
860
+ }
861
+ /**
862
+ * Records that a pool pod was handed out as the sandbox `id`. Returns false when another caller
863
+ * created `id` first. The record goes with the pod.
864
+ */
865
+ async recordHandOut(id, pod, labels) {
866
+ try {
867
+ await this.kubernetes.request('POST', this.leases, {
868
+ apiVersion: 'coordination.k8s.io/v1',
869
+ kind: 'Lease',
870
+ metadata: {
871
+ name: identityLease(id),
872
+ labels,
873
+ ownerReferences: [
874
+ { apiVersion: 'v1', kind: 'Pod', name: pod.metadata.name, uid: pod.metadata.uid },
875
+ ],
876
+ },
877
+ spec: { holderIdentity: pod.metadata.name, acquireTime: leaseTime() },
878
+ });
879
+ return true;
880
+ }
881
+ catch (error) {
882
+ if (error instanceof KubernetesApiError && error.status === 409)
883
+ return false;
884
+ throw error;
885
+ }
886
+ }
887
+ /**
888
+ * Records that the new sandbox `id` is the pod `podName`'s, before that pod is created. Returns
889
+ * null when it is, or the pool pod another caller already handed out as `id`, which is then this
890
+ * caller's too. A record whose pod is gone or has failed is replaced.
891
+ */
892
+ async takeIdentity(id, podName) {
893
+ const name = identityLease(id);
894
+ while (true) {
895
+ try {
896
+ await this.kubernetes.request('POST', this.leases, {
897
+ apiVersion: 'coordination.k8s.io/v1',
898
+ kind: 'Lease',
899
+ metadata: { name, labels: { ...this.manager, [SANDBOX_LABEL]: id } },
900
+ spec: { holderIdentity: podName, acquireTime: leaseTime() },
901
+ });
902
+ return null;
903
+ }
904
+ catch (error) {
905
+ if (!(error instanceof KubernetesApiError && error.status === 409))
906
+ throw error;
907
+ }
908
+ const found = await this.kubernetes.request('GET', `${this.leases}/${name}`);
909
+ if (!found)
910
+ continue;
911
+ const record = LeaseSchema.parse(found);
912
+ // Another caller starting the same pod, whose name it then shares.
913
+ if (record.spec.holderIdentity === podName)
914
+ return null;
915
+ const pod = await this.claimedPod(record);
916
+ if (pod && !terminating(pod) && ['Running', 'Pending'].includes(pod.status.phase))
917
+ return pod;
918
+ await this.kubernetes
919
+ .request('DELETE', `${this.leases}/${name}`, {
920
+ preconditions: { resourceVersion: record.metadata.resourceVersion },
921
+ })
922
+ .catch((error) => {
923
+ if (!(error instanceof KubernetesApiError && error.status === 409))
924
+ throw error;
925
+ });
926
+ }
927
+ }
928
+ /**
929
+ * Labels a pool pod as the sandbox it was handed out as. Only labels the pod lacks are added, so
930
+ * labels set on it since it was handed out stay. Callers in this process take turns.
931
+ */
932
+ adopt(podName, labels) {
933
+ const path = `${this.pods}/${podName}`;
934
+ const running = (this.adopting.get(podName) ?? Promise.resolve())
935
+ .catch(() => undefined)
936
+ .then(async () => {
937
+ for (let attempt = 0; attempt < 5; attempt++) {
938
+ const found = await this.kubernetes.request('GET', path);
939
+ if (!found)
940
+ return;
941
+ const pod = PodSchema.parse(found);
942
+ if (!(POOL_LABEL in pod.metadata.labels))
943
+ return;
944
+ const added = Object.entries(withoutPoolLabels(labels)).filter(([key]) => !(key in pod.metadata.labels));
945
+ try {
946
+ await this.kubernetes.request('PATCH', path, [
947
+ // The labels as they were read, so one set in between is not overwritten.
948
+ { op: 'test', path: '/metadata/labels', value: pod.metadata.labels },
949
+ { op: 'remove', path: labelPath(POOL_LABEL) },
950
+ ...(TEMPLATE_LABEL in pod.metadata.labels
951
+ ? [{ op: 'remove', path: labelPath(TEMPLATE_LABEL) }]
952
+ : []),
953
+ ...added.map(([key, value]) => ({ op: 'add', path: labelPath(key), value })),
954
+ { op: 'add', path: ACQUIRED_PATH, value: String(Date.now()) },
955
+ ]);
956
+ return;
957
+ }
958
+ catch (error) {
959
+ if (!(error instanceof KubernetesApiError && [409, 422].includes(error.status)))
960
+ throw error;
961
+ }
962
+ }
963
+ throw new Error(`Pod ${podName}'s labels kept changing while it was labelled.`);
964
+ });
965
+ this.adopting.set(podName, running);
966
+ running
967
+ .finally(() => {
968
+ if (this.adopting.get(podName) === running)
969
+ this.adopting.delete(podName);
970
+ })
971
+ .catch(() => undefined);
972
+ return running;
973
+ }
974
+ /** Runs a command in a pod, through its command server if it has one. */
975
+ runIn(pod, command, stdin, timeoutSeconds) {
976
+ const address = this.commandAddress(pod);
977
+ return address
978
+ ? directExec(address, command, stdin, timeoutSeconds, {}, true)
979
+ : this.kubernetes.exec(`${this.pods}/${pod.metadata.name}`, command, stdin, timeoutSeconds);
587
980
  }
588
981
  /** The sandbox's pod to use: the one that is not shutting down, or null. */
589
982
  async livePod(sandboxId) {
590
983
  return (await this.livePods(sandboxId)).sort(oldestLiveFirst)[0] ?? null;
591
984
  }
592
985
  /** Returns the sandbox's running pod, waking or creating it first. */
593
- async start(sandbox, signal, initialLabels) {
986
+ async start(sandbox, signal, initialLabels, fork) {
987
+ let base = fork;
594
988
  const id = sandbox.name;
595
989
  let pod = sandbox.pod;
596
- let snapshot = sandbox.snapshots[0];
990
+ // A sandbox started from another's snapshot starts from it again until it has one of its own.
991
+ let snapshot = sandbox.snapshots[0] ?? base?.name;
597
992
  // A sleep ends with the pod shutting down, and a checkpoint with the pod free again. One that
598
993
  // was abandoned ends when its mark expires, so the wait lasts until then and needs no deadline
599
994
  // of its own: a shorter one would fail the dispatch moments before the pod is usable.
@@ -601,7 +996,7 @@ export class GkeSandboxes {
601
996
  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);
602
997
  const [current] = await this.list({ [SANDBOX_LABEL]: id });
603
998
  pod = current?.pod ?? null;
604
- snapshot = current?.snapshots[0];
999
+ snapshot = current?.snapshots[0] ?? base?.name;
605
1000
  if (current)
606
1001
  sandbox.labels = current.labels;
607
1002
  }
@@ -610,39 +1005,64 @@ export class GkeSandboxes {
610
1005
  while (true) {
611
1006
  signal.throwIfAborted();
612
1007
  if (pod && (terminating(pod) || !['Running', 'Pending'].includes(pod.status.phase))) {
1008
+ // The pod's last snapshot may be newer than the listing. One of another creation under
1009
+ // this id belongs to a sandbox that was replaced, not to this one.
1010
+ const [listed] = await this.list({ [SANDBOX_LABEL]: id });
1011
+ const current = listed?.labels[CREATED_LABEL] === sandbox.labels[CREATED_LABEL] ? listed : undefined;
1012
+ // A fork that has no snapshot of its own yet starts from its source's again.
1013
+ const { [RESTORE_ANNOTATION]: restored, [FORK_SOURCE_ANNOTATION]: sourceId } = pod.metadata.annotations;
1014
+ if (restored && sourceId)
1015
+ base ??= { name: restored, sourceId };
1016
+ snapshot = current?.snapshots[0] ?? base?.name;
613
1017
  if (!terminating(pod)) {
614
- // Everything written since the last snapshot is gone with the pod.
1018
+ // Everything written since that snapshot is gone with the pod. The report comes before
1019
+ // the pod is deleted, so a start that fails here reports the loss when it is retried.
615
1020
  const reason = pod.status.containerStatuses.find(({ state }) => state?.terminated?.reason)?.state
616
1021
  ?.terminated?.reason ??
617
1022
  pod.status.reason ??
618
1023
  pod.status.phase;
619
- this.options.onPodLost?.(sandbox.labels, pod.status.phase, reason, !!snapshot);
1024
+ // `sleptMs` is when the newest snapshot, the one this start restores, was taken.
1025
+ const takenMs = snapshot ? current?.sleptMs : null;
1026
+ this.options.onPodLost?.(sandbox.labels, pod.status.phase, reason, !!snapshot, takenMs != null && Number.isFinite(takenMs)
1027
+ ? {
1028
+ recoveryPointAt: new Date(takenMs).toISOString(),
1029
+ recoveryPointAgeMs: Math.max(0, Date.now() - takenMs),
1030
+ }
1031
+ : {});
620
1032
  await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
621
1033
  }
622
- // The pod's last snapshot may be newer than the listing. One of another creation under
623
- // this id belongs to a sandbox that was replaced, not to this one.
624
- const [listed] = await this.list({ [SANDBOX_LABEL]: id });
625
- snapshot =
626
- listed && listed.labels[CREATED_LABEL] === sandbox.labels[CREATED_LABEL]
627
- ? listed.snapshots[0]
628
- : undefined;
629
1034
  pod = null;
630
1035
  }
631
1036
  if (pod)
632
1037
  break;
633
1038
  // A fresh filesystem must also get the caller's initial labels.
634
- if (!snapshot)
1039
+ const forked = !!base && snapshot === base.name;
1040
+ if (!snapshot || (forked && !sandbox.labels[SANDBOX_LABEL]))
635
1041
  sandbox.labels = initialLabels;
636
- // Named after the snapshot it starts from. Kubernetes creates a name once, so callers that
637
- // start the sandbox at the same moment get one pod between them. And a wake never waits
638
- // for the pod it replaces to finish shutting down, which started from an earlier snapshot.
639
- const name = `${id}-${createHash('sha256')
640
- .update(snapshot ?? '')
641
- .digest('hex')
642
- .slice(0, 6)}`;
1042
+ // A wake never waits for the pod it replaces to finish shutting down, which started from an
1043
+ // earlier snapshot and so has another name.
1044
+ const name = podNameFor(id, snapshot);
1045
+ if (!snapshot) {
1046
+ // A warm pool may be handing out a pod as this sandbox at the same moment.
1047
+ const holder = await this.takeIdentity(id, name);
1048
+ if (holder) {
1049
+ pod = holder;
1050
+ break;
1051
+ }
1052
+ }
643
1053
  try {
644
- pod = PodSchema.parse(await this.kubernetes.request('POST', this.pods, this.manifest(sandbox, name, snapshot)));
1054
+ pod = PodSchema.parse(await this.createPod(this.manifest(sandbox, name, snapshot, {
1055
+ boot: true,
1056
+ forkedFrom: forked ? base?.sourceId : undefined,
1057
+ })));
645
1058
  created = true;
1059
+ // The record of its id now goes with the pod.
1060
+ if (!snapshot)
1061
+ await this.kubernetes.request('PATCH', `${this.leases}/${identityLease(id)}`, {
1062
+ metadata: {
1063
+ ownerReferences: [{ apiVersion: 'v1', kind: 'Pod', name, uid: pod.metadata.uid }],
1064
+ },
1065
+ });
646
1066
  break;
647
1067
  }
648
1068
  catch (error) {
@@ -710,10 +1130,13 @@ export class GkeSandboxes {
710
1130
  // replace saved files with an empty filesystem. Keep the snapshot for the next wake.
711
1131
  async confirmRestored(pod, id) {
712
1132
  const path = `${this.pods}/${pod.metadata.name}`;
713
- const check = new TextEncoder().encode(`test "$(cat ${quote(SANDBOX_ID_FILE)} 2>/dev/null)" = ${quote(id)}`);
1133
+ const file = quote(SANDBOX_ID_FILE);
1134
+ // A pod started from another sandbox's snapshot holds that sandbox's id until it is checked.
1135
+ const source = pod.metadata.annotations[FORK_SOURCE_ANNOTATION];
1136
+ const check = new TextEncoder().encode(`found="$(cat ${file} 2>/dev/null)"\n[ "$found" = ${quote(id)} ]${source ? ` || { [ "$found" = ${quote(source)} ] && printf %s ${quote(id)} > ${file}; }` : ''}`);
714
1137
  // GKE fills in the files as the container starts, so the first looks can come too early.
715
1138
  for (let attempt = 0; attempt < RESTORE_CHECKS; attempt++) {
716
- const { exitCode } = await this.kubernetes.exec(path, execCommand(30), check, 30);
1139
+ const { exitCode } = await this.runIn(pod, execCommand(30), check, 30);
717
1140
  if (exitCode === 0) {
718
1141
  await this.kubernetes.request('PATCH', path, {
719
1142
  metadata: { annotations: { [RESTORED_ANNOTATION]: 'true' } },
@@ -725,7 +1148,39 @@ export class GkeSandboxes {
725
1148
  await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
726
1149
  throw new Error(`Sandbox ${id} was not restored from its snapshot.`);
727
1150
  }
728
- manifest(sandbox, name, snapshot) {
1151
+ /** Where the pod's command server is, or null for a pod that is reached through the API. */
1152
+ commandAddress(pod) {
1153
+ const { annotations } = pod.metadata;
1154
+ const token = annotations[COMMAND_TOKEN_ANNOTATION];
1155
+ const port = Number(annotations[COMMAND_PORT_ANNOTATION]);
1156
+ return this.options.directCommands && token && port && pod.status.podIP
1157
+ ? { host: pod.status.podIP, port, token }
1158
+ : null;
1159
+ }
1160
+ /** Creates a pod, after the command server it mounts, once per process. */
1161
+ async createPod(manifest) {
1162
+ if (this.options.directCommands)
1163
+ await (this.commandServer ??= this.kubernetes
1164
+ .request('POST', this.configMaps, {
1165
+ apiVersion: 'v1',
1166
+ kind: 'ConfigMap',
1167
+ metadata: { name: COMMAND_SERVER_CONFIG, labels: this.manager },
1168
+ binaryData: Object.fromEntries(Object.entries(COMMAND_SERVER.binaries).map(([machine, binary]) => [
1169
+ `command-server-${machine}`,
1170
+ binary,
1171
+ ])),
1172
+ })
1173
+ .then(() => undefined, (error) => {
1174
+ // Another process, or an earlier run of this one, already published this build.
1175
+ if (error instanceof KubernetesApiError && error.status === 409)
1176
+ return;
1177
+ this.commandServer = undefined;
1178
+ throw error;
1179
+ }));
1180
+ return this.kubernetes.request('POST', this.pods, manifest);
1181
+ }
1182
+ manifest(sandbox, name, snapshot, { boot, forkedFrom }) {
1183
+ const { directCommands, capabilities } = this.options;
729
1184
  return {
730
1185
  apiVersion: 'v1',
731
1186
  kind: 'Pod',
@@ -741,6 +1196,13 @@ export class GkeSandboxes {
741
1196
  // cannot size the scratch volume at /tmp, so the kubelet's limit still bounds that.
742
1197
  'dev.gvisor.flag.overlay2': `root:self,size=${this.diskBytes}`,
743
1198
  ...(snapshot ? { [RESTORE_ANNOTATION]: snapshot } : {}),
1199
+ ...(forkedFrom ? { [FORK_SOURCE_ANNOTATION]: forkedFrom } : {}),
1200
+ ...(directCommands
1201
+ ? {
1202
+ [COMMAND_PORT_ANNOTATION]: String(directCommands.port),
1203
+ [COMMAND_TOKEN_ANNOTATION]: randomBytes(32).toString('hex'),
1204
+ }
1205
+ : {}),
744
1206
  },
745
1207
  },
746
1208
  spec: {
@@ -766,14 +1228,34 @@ export class GkeSandboxes {
766
1228
  },
767
1229
  ]
768
1230
  : []),
1231
+ ...(directCommands
1232
+ ? [
1233
+ {
1234
+ name: 'command-server',
1235
+ configMap: { name: COMMAND_SERVER_CONFIG, defaultMode: 0o555 },
1236
+ },
1237
+ ]
1238
+ : []),
769
1239
  ],
770
1240
  containers: [
771
1241
  {
772
1242
  name: 'sandbox',
773
1243
  image: this.options.image,
774
- command: podCommand(sandbox.name, !snapshot, this.options.boot?.(sandbox.labels) ?? null, this.options.memoryWatchdog === false
1244
+ command: podCommand(sandbox.name, !snapshot, (boot && this.options.boot?.(sandbox.labels)) || null, this.options.memoryWatchdog === false
775
1245
  ? null
776
- : { protect: this.options.memoryWatchdog?.protect ?? [] }),
1246
+ : { protect: this.options.memoryWatchdog?.protect ?? [] }, !!directCommands),
1247
+ // The pod's own annotations, so the pod template is the same for every pod.
1248
+ ...(directCommands
1249
+ ? {
1250
+ env: [
1251
+ ['GKE_SANDBOXES_COMMAND_TOKEN', COMMAND_TOKEN_ANNOTATION],
1252
+ ['GKE_SANDBOXES_COMMAND_PORT', COMMAND_PORT_ANNOTATION],
1253
+ ].map(([name, annotation]) => ({
1254
+ name,
1255
+ valueFrom: { fieldRef: { fieldPath: `metadata.annotations['${annotation}']` } },
1256
+ })),
1257
+ }
1258
+ : {}),
777
1259
  volumeMounts: [
778
1260
  { name: 'scratch', mountPath: '/tmp' },
779
1261
  ...(this.options.runtime
@@ -785,8 +1267,14 @@ export class GkeSandboxes {
785
1267
  },
786
1268
  ]
787
1269
  : []),
1270
+ ...(directCommands
1271
+ ? [{ name: 'command-server', mountPath: COMMAND_SERVER_MOUNT, readOnly: true }]
1272
+ : []),
788
1273
  ],
789
1274
  resources: this.options.resources ?? DEFAULT_RESOURCES,
1275
+ ...(capabilities?.length
1276
+ ? { securityContext: { capabilities: { add: capabilities } } }
1277
+ : {}),
790
1278
  },
791
1279
  ],
792
1280
  },
@@ -839,19 +1327,23 @@ export class GkeSandboxes {
839
1327
  throw error;
840
1328
  }
841
1329
  }
842
- async sleep(id) {
1330
+ /**
1331
+ * Puts a sandbox to sleep once nothing has used it for the idle period. With `now`, it sleeps
1332
+ * at once whenever it was last used, which is how a caller pauses it; `drain` is still asked.
1333
+ */
1334
+ async sleep(id, { now = false } = {}) {
843
1335
  const pod = await this.livePod(id);
844
1336
  if (!pod || terminating(pod))
845
1337
  return;
846
1338
  if (held(pod))
847
1339
  throw new SandboxInUseError(id);
848
- await this.sleepPod(pod);
1340
+ await this.sleepPod(pod, now);
849
1341
  }
850
- async sleepPod(pod) {
1342
+ async sleepPod(pod, now = false) {
851
1343
  const name = pod.metadata.labels[SANDBOX_LABEL];
852
1344
  const path = `${this.pods}/${pod.metadata.name}`;
853
1345
  const acquired = pod.metadata.annotations[ACQUIRED_ANNOTATION];
854
- if (Date.now() - Number(acquired) < this.idleTimeoutMs)
1346
+ if (!now && Date.now() - Number(acquired) < this.idleTimeoutMs)
855
1347
  throw new SandboxInUseError(name);
856
1348
  const claimed = await this.claim(pod, [
857
1349
  { op: 'test', path: ACQUIRED_PATH, value: acquired },
@@ -864,11 +1356,11 @@ export class GkeSandboxes {
864
1356
  try {
865
1357
  // Read after the claim, so a report of use made while the sweep was deciding still counts.
866
1358
  const renewed = renewedMs(await this.kubernetes.request('GET', `${this.leases}/${pod.metadata.name}`));
867
- if (Date.now() - renewed < this.idleTimeoutMs)
1359
+ if (!now && Date.now() - renewed < this.idleTimeoutMs)
868
1360
  throw new SandboxInUseError(name);
869
1361
  if (this.options.drain && !(await this.options.drain(this.environment(name, 'started'))))
870
1362
  throw new SandboxInUseError(name);
871
- const snapshot = await this.snapshot(pod);
1363
+ const snapshot = await this.takeSnapshot(pod);
872
1364
  await this.kubernetes.request('DELETE', path, {
873
1365
  preconditions: { uid: pod.metadata.uid },
874
1366
  });
@@ -885,14 +1377,30 @@ export class GkeSandboxes {
885
1377
  throw error;
886
1378
  }
887
1379
  }
888
- // A pod restores from its newest snapshot; older ones only cost storage.
1380
+ // A pod restores from its newest snapshot; older ones only cost storage, unless they were kept.
889
1381
  async dropOlderSnapshots(sandboxId, newest) {
890
- const { items } = listOf(SnapshotSchema).parse(await this.kubernetes.request('GET', `${this.snapshotsPath}?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`));
891
- await Promise.all(items
892
- .filter(({ metadata }) => metadata.name !== newest)
1382
+ const query = `?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`;
1383
+ const [snapshots, leases] = await Promise.all([
1384
+ this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
1385
+ this.kubernetes.request('GET', `${this.leases}${query},${KEPT_LABEL}`),
1386
+ ]);
1387
+ const kept = new Set(listOf(LeaseSchema)
1388
+ .parse(leases)
1389
+ .items.map(({ spec }) => spec.holderIdentity));
1390
+ await Promise.all(listOf(SnapshotSchema)
1391
+ .parse(snapshots)
1392
+ .items.filter(({ metadata }) => metadata.name !== newest && !kept.has(metadata.name))
893
1393
  .map(({ metadata }) => this.kubernetes.request('DELETE', `${this.snapshotsPath}/${metadata.name}`)));
894
1394
  }
895
- async snapshot(pod) {
1395
+ async takeSnapshot(pod) {
1396
+ // GKE copies the pod's labels onto the snapshot, and a sleeping sandbox is found by them.
1397
+ if (POOL_LABEL in pod.metadata.labels) {
1398
+ await this.adopt(pod.metadata.name, pod.metadata.labels);
1399
+ pod = {
1400
+ ...pod,
1401
+ metadata: { ...pod.metadata, labels: withoutPoolLabels(pod.metadata.labels) },
1402
+ };
1403
+ }
896
1404
  // An interrupted wake can leave a running pod whose files nobody has verified.
897
1405
  if (pod.metadata.annotations[RESTORE_ANNOTATION] &&
898
1406
  !pod.metadata.annotations[RESTORED_ANNOTATION])
@@ -941,16 +1449,31 @@ export class GkeSandboxes {
941
1449
  setImmediate(() => {
942
1450
  firstPod = null;
943
1451
  }).unref();
944
- const podPath = async () => {
945
- if (firstPod) {
946
- const path = `${this.pods}/${firstPod}`;
947
- firstPod = null;
948
- return path;
949
- }
950
- const pod = await this.livePod(name);
1452
+ // The command server this handle last reached. The pod need not be looked up again for every
1453
+ // command: the server must show that it holds the pod's token before it is told what to run,
1454
+ // so a pod that is gone, or whose address another pod has taken, is sent nothing and runs
1455
+ // nothing. The sandbox's pod is then looked up as for a first command.
1456
+ let reached = null;
1457
+ const run = async (command, stdin, timeout, options = {}) => {
1458
+ if (reached)
1459
+ try {
1460
+ return await directExec(reached, command, stdin, timeout, options, false);
1461
+ }
1462
+ catch (error) {
1463
+ if (!(error instanceof CommandServerUnreachableError))
1464
+ throw error;
1465
+ reached = null;
1466
+ }
1467
+ const pod = firstPod ?? (await this.livePod(name));
1468
+ firstPod = null;
951
1469
  if (!pod)
952
1470
  throw new Error(`Sandbox ${name} is not running.`);
953
- return `${this.pods}/${pod.metadata.name}`;
1471
+ const address = this.commandAddress(pod);
1472
+ if (!address)
1473
+ return this.kubernetes.exec(`${this.pods}/${pod.metadata.name}`, command, stdin, timeout, options);
1474
+ const result = await directExec(address, command, stdin, timeout, options, true);
1475
+ reached = address;
1476
+ return result;
954
1477
  };
955
1478
  return {
956
1479
  id: name,
@@ -966,13 +1489,13 @@ export class GkeSandboxes {
966
1489
  }),
967
1490
  command,
968
1491
  ].join('\n');
969
- const { exitCode, output, truncated } = await this.kubernetes.exec(await podPath(), execCommand(timeout), new TextEncoder().encode(script), timeout, options);
1492
+ const { exitCode, output, truncated } = await run(execCommand(timeout), new TextEncoder().encode(script), timeout, options);
970
1493
  return { exitCode, result: output, truncated };
971
1494
  },
972
1495
  },
973
1496
  fs: {
974
1497
  uploadFile: async (local, remote, timeout = 300) => {
975
- const { exitCode, output } = await this.kubernetes.exec(await podPath(), ['sh', '-c', 'cat > "$0"', remote], await readFile(local), timeout);
1498
+ const { exitCode, output } = await run(['sh', '-c', 'cat > "$0"', remote], await readFile(local), timeout);
976
1499
  if (exitCode !== 0)
977
1500
  throw new Error(`Could not upload ${remote}: ${output}`);
978
1501
  },
@@ -980,12 +1503,10 @@ export class GkeSandboxes {
980
1503
  const file = createWriteStream(local);
981
1504
  const errors = [];
982
1505
  // The file's bytes go straight to disk; only what `cat` complains about is kept.
983
- const { exitCode } = await this.kubernetes
984
- .exec(await podPath(), ['sh', '-c', 'cat "$0"', remote], new Uint8Array(), timeout, {
1506
+ const { exitCode } = await run(['sh', '-c', 'cat "$0"', remote], new Uint8Array(), timeout, {
985
1507
  maxOutputBytes: 0,
986
1508
  onOutput: (chunk, stream) => stream === 'stdout' ? file.write(chunk.slice()) : errors.push(chunk.slice()),
987
- })
988
- .finally(() => file.end());
1509
+ }).finally(() => file.end());
989
1510
  await finished(file);
990
1511
  if (exitCode === 0)
991
1512
  return;