@getenergy/gke-sandboxes 0.5.0 → 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/README.md CHANGED
@@ -45,13 +45,14 @@ await sandboxes.sleep(sandbox.id);
45
45
 
46
46
  ## Features
47
47
 
48
+ - **Snapshot and fork.** Keep a snapshot and start new sandboxes from it.
48
49
  - **Sleep and wake.** A sleeping sandbox is a snapshot in Cloud Storage and uses no CPU or memory. Opening its ID wakes it with its files.
49
50
  - **Idle sandboxes sleep on their own.** A sweeper puts a sandbox to sleep after five minutes without use.
50
51
  - **Isolated.** Each sandbox is its own gVisor pod, with incoming traffic blocked and no access to your cloud credentials.
51
52
  - **Your image.** Use any container image with a POSIX shell.
52
53
  - **Commands and files.** Run commands with timeouts and streamed output. Upload and download files. A backend on the cluster's network can send them straight to the sandbox, several times faster than through the Kubernetes API.
53
54
  - **Memory guard.** A runaway program is ended before it takes the whole sandbox down.
54
- - **Warm pool.** Keep a few sandboxes ready so a new session starts in under half a second.
55
+ - **Warm pool.** Keep a few sandboxes ready so a new session starts in under half a second, under your own id, even when many start at once.
55
56
  - **Preview links.** An example proxy serves a sandbox’s web server through signed links that expire.
56
57
  - **Hooks.** Callbacks report every operation’s timing and failures to your own logging.
57
58
 
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export type SandboxEnvironment = {
19
19
  };
20
20
  type Labels = Record<string, string>;
21
21
  export type SandboxEvent = {
22
- operation: 'create' | 'wake' | 'sleep' | 'checkpoint';
22
+ operation: 'create' | 'wake' | 'sleep' | 'checkpoint' | 'snapshot';
23
23
  outcome: 'succeeded' | 'aborted' | 'failed';
24
24
  labels: Labels;
25
25
  pod?: string;
@@ -65,10 +65,22 @@ export type GkeSandboxOptions = {
65
65
  memoryWatchdog?: false | {
66
66
  protect?: string[];
67
67
  };
68
+ /**
69
+ * Starts a service once the filesystem is ready: as a sandbox's first pod starts, as a woken pod
70
+ * starts, and when a warm pool hands out a sandbox, whose pod started before its labels were
71
+ * known.
72
+ */
68
73
  boot?: (labels: Labels) => {
69
74
  shell: string;
70
75
  args: string[];
71
76
  };
77
+ /**
78
+ * Linux capabilities to add to the sandbox's container, such as `['NET_ADMIN', 'SYS_ADMIN']`
79
+ * to run Docker inside it. They apply inside gVisor's own kernel, not the node's. The
80
+ * quickstart's namespace enforces the `baseline` Pod Security level, which refuses most of them:
81
+ * deploy with `TF_VAR_pod_security_level=privileged` to use them.
82
+ */
83
+ capabilities?: string[];
72
84
  /**
73
85
  * Runs commands and moves files over a connection straight to the sandbox, on this port,
74
86
  * instead of through the Kubernetes API. A command starts several times sooner and does not
@@ -82,7 +94,11 @@ export type GkeSandboxOptions = {
82
94
  };
83
95
  drain?: (sandbox: SandboxEnvironment) => Promise<boolean>;
84
96
  onOperation?: (event: SandboxEvent) => void;
85
- onPodLost?: (labels: Labels, phase: string, reason: string, hasSnapshot: boolean) => void;
97
+ /** The recovery point is empty if the selected snapshot has no usable timestamp. */
98
+ onPodLost?: (labels: Labels, phase: string, reason: string, hasSnapshot: boolean, recoveryPoint: {
99
+ recoveryPointAt?: string;
100
+ recoveryPointAgeMs?: number;
101
+ }) => void;
86
102
  };
87
103
  declare const PodSchema: z.ZodObject<{
88
104
  metadata: z.ZodObject<{
@@ -139,23 +155,78 @@ export declare class GkeSandboxes {
139
155
  private readonly diskBytes;
140
156
  private readonly configMaps;
141
157
  private commandServer;
158
+ private readonly adopting;
142
159
  constructor(kubernetes: KubernetesApi, options: GkeSandboxOptions);
143
160
  private selector;
144
- acquire(id: string, signal: AbortSignal, initialLabels?: Labels): Promise<{
161
+ /**
162
+ * Returns the sandbox's running pod, waking it from its newest snapshot or creating it. With
163
+ * `from`, a sandbox that does not exist yet starts from that snapshot, which may be another
164
+ * sandbox's (see `snapshot`).
165
+ */
166
+ acquire(id: string, signal: AbortSignal, initialLabels?: Labels, { from }?: {
167
+ from?: string;
168
+ }): Promise<{
145
169
  sandbox: SandboxEnvironment;
146
170
  startState: string;
147
- labels: Record<string, string>;
171
+ labels: {
172
+ [x: string]: string;
173
+ };
148
174
  podName: string;
149
175
  createdMs: number;
150
176
  touch: () => Promise<void>;
151
177
  }>;
152
- /** Creates single-use sandboxes with generated IDs. Reopen a saved ID with acquire(). */
178
+ private acquireFound;
179
+ private forkSource;
180
+ /**
181
+ * Running sandboxes kept ready, so that a new one starts without waiting for a pod. A sandbox is
182
+ * handed out by creating a Lease named after its pod, which GKE's admission webhooks do not
183
+ * check: claims stay fast when many arrive at once. The pod is labelled as the sandbox it became
184
+ * afterwards; until then the Lease carries its labels, and lookups read them from there.
185
+ */
153
186
  warmPool(name: string): {
154
- create: (signal: AbortSignal, labels?: Labels) => Promise<{
187
+ /**
188
+ * Returns the sandbox `id`, from the pool if it does not exist yet. An existing sandbox is
189
+ * acquired as `GkeSandboxes.acquire` does; an empty pool starts a new pod. Use the same pool
190
+ * for an id every time.
191
+ */
192
+ acquire(id: string, signal: AbortSignal, labels?: Labels): Promise<{
155
193
  sandbox: SandboxEnvironment;
194
+ labels: {
195
+ "energy-sandbox": string;
196
+ "energy-created-ms": string;
197
+ };
156
198
  podName: string;
199
+ createdMs: number;
200
+ touch: () => Promise<void>;
201
+ startState: 'missing';
157
202
  fromPool: boolean;
203
+ } | {
204
+ sandbox: SandboxEnvironment;
205
+ startState: string;
206
+ labels: {
207
+ [x: string]: string;
208
+ };
209
+ podName: string;
210
+ createdMs: number;
158
211
  touch: () => Promise<void>;
212
+ fromPool: boolean;
213
+ }>;
214
+ /** Hands out a sandbox with a generated ID. Reopen it later with `acquire`. */
215
+ create(signal: AbortSignal, labels?: Labels): Promise<{
216
+ sandbox: SandboxEnvironment;
217
+ labels: {
218
+ "energy-sandbox": string;
219
+ "energy-created-ms": string;
220
+ };
221
+ podName: string;
222
+ createdMs: number;
223
+ touch: () => Promise<void>;
224
+ fromPool: boolean;
225
+ } | {
226
+ sandbox: SandboxEnvironment;
227
+ podName: string;
228
+ touch: () => Promise<void>;
229
+ fromPool: boolean;
159
230
  }>;
160
231
  reconcile: (size: number) => Promise<void>;
161
232
  maintain(size: number, signal: AbortSignal): Promise<void>;
@@ -177,6 +248,13 @@ export declare class GkeSandboxes {
177
248
  * written since. The sandbox is paused while the snapshot is taken.
178
249
  */
179
250
  checkpoint(sandboxId: string): Promise<void>;
251
+ /**
252
+ * Snapshots a running sandbox and keeps the snapshot until `deleteSnapshot`; no later checkpoint
253
+ * or sleep removes it. The sandbox runs on. Returns the snapshot's name: pass it as `from` to
254
+ * `acquire` to start new sandboxes with these files, as many as needed.
255
+ */
256
+ snapshot(sandboxId: string): Promise<string>;
257
+ deleteSnapshot(name: string): Promise<void>;
180
258
  sleepUnused(): Promise<void>;
181
259
  /**
182
260
  * Every sandbox that exists, awake or asleep, with whose it is and where its snapshots are
@@ -196,6 +274,30 @@ export declare class GkeSandboxes {
196
274
  /** Every sandbox with these labels, awake or asleep, newest first. */
197
275
  list(labels: Record<string, string>): Promise<SandboxRecord[]>;
198
276
  private livePods;
277
+ /**
278
+ * The pod a sandbox's id record names, with the sandbox's labels from the record if it is a pool
279
+ * pod that does not carry them yet. It keeps its pool label until it does, which is how a
280
+ * snapshot knows to label it first.
281
+ */
282
+ private claimedPod;
283
+ /**
284
+ * Records that a pool pod was handed out as the sandbox `id`. Returns false when another caller
285
+ * created `id` first. The record goes with the pod.
286
+ */
287
+ private recordHandOut;
288
+ /**
289
+ * Records that the new sandbox `id` is the pod `podName`'s, before that pod is created. Returns
290
+ * null when it is, or the pool pod another caller already handed out as `id`, which is then this
291
+ * caller's too. A record whose pod is gone or has failed is replaced.
292
+ */
293
+ private takeIdentity;
294
+ /**
295
+ * Labels a pool pod as the sandbox it was handed out as. Only labels the pod lacks are added, so
296
+ * labels set on it since it was handed out stay. Callers in this process take turns.
297
+ */
298
+ private adopt;
299
+ /** Runs a command in a pod, through its command server if it has one. */
300
+ private runIn;
199
301
  /** The sandbox's pod to use: the one that is not shutting down, or null. */
200
302
  private livePod;
201
303
  /** Returns the sandbox's running pod, waking or creating it first. */
@@ -212,10 +314,16 @@ export declare class GkeSandboxes {
212
314
  private markAcquired;
213
315
  /** Reports that the sandbox is in use, which restarts its idle period. */
214
316
  private touch;
215
- sleep(id: string): Promise<void>;
317
+ /**
318
+ * Puts a sandbox to sleep once nothing has used it for the idle period. With `now`, it sleeps
319
+ * at once whenever it was last used, which is how a caller pauses it; `drain` is still asked.
320
+ */
321
+ sleep(id: string, { now }?: {
322
+ now?: boolean;
323
+ }): Promise<void>;
216
324
  private sleepPod;
217
325
  private dropOlderSnapshots;
218
- private snapshot;
326
+ private takeSnapshot;
219
327
  delete(id: string): Promise<void>;
220
328
  environment(name: string, state: 'started' | 'stopped'): SandboxEnvironment;
221
329
  private makeEnvironment;
package/dist/index.js CHANGED
@@ -29,6 +29,30 @@ const ACQUIRED_PATH = '/metadata/annotations/getenergy.com~1acquired-ms';
29
29
  const SLEEPING_PATH = '/metadata/annotations/getenergy.com~1sleeping-ms';
30
30
  const RESTORED_ANNOTATION = 'getenergy.com/restore-verified';
31
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;
32
56
  // What a pod's command server listens on and accepts. Only the pod's own record holds the token,
33
57
  // so a caller that reads the pod can reach it and a neighbouring pod cannot.
34
58
  const COMMAND_PORT_ANNOTATION = 'getenergy.com/command-port';
@@ -181,9 +205,21 @@ const StoredSnapshotSchema = z.object({
181
205
  // A sandbox's keep-alive. Reports of use renew it instead of writing to the pod: GKE checks every
182
206
  // pod write with an admission webhook, which is several times slower and queues under load.
183
207
  const LeaseSchema = z.object({
184
- metadata: z.object({ name: z.string() }),
185
- 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({}),
186
220
  });
221
+ // Kubernetes reads a Lease's times only with six decimals.
222
+ const leaseTime = () => new Date().toISOString().replace('Z', '000Z');
187
223
  const renewedMs = (lease) => lease ? Date.parse(LeaseSchema.parse(lease).spec.renewTime ?? '') || 0 : 0;
188
224
  const TriggerSchema = z.object({
189
225
  status: z
@@ -196,6 +232,7 @@ const TriggerSchema = z.object({
196
232
  .default({ conditions: [] }),
197
233
  });
198
234
  const listOf = (item) => z.object({ items: z.array(item) });
235
+ const withoutPoolLabels = ({ [POOL_LABEL]: _, [TEMPLATE_LABEL]: __, ...labels }) => labels;
199
236
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
200
237
  const ready = (conditions) => conditions.some(({ type, status }) => type === 'Ready' && status === 'True');
201
238
  export const terminating = (pod) => !!pod.metadata.deletionTimestamp;
@@ -236,6 +273,8 @@ export class GkeSandboxes {
236
273
  diskBytes;
237
274
  configMaps;
238
275
  commandServer;
276
+ // Pool pods this process is labelling as the sandboxes they were handed out as.
277
+ adopting = new Map();
239
278
  constructor(kubernetes, options) {
240
279
  this.kubernetes = kubernetes;
241
280
  this.options = options;
@@ -270,10 +309,22 @@ export class GkeSandboxes {
270
309
  const pairs = Object.entries(labelSchema.parse({ ...labels, ...this.manager })).map(([key, value]) => `${key}=${value}`);
271
310
  return encodeURIComponent(pairs.join(','));
272
311
  }
273
- 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;
274
326
  while (true) {
275
327
  signal.throwIfAborted();
276
- const existing = await this.find(id);
277
328
  const createdMs = Date.now();
278
329
  const record = existing ?? {
279
330
  name: id,
@@ -289,57 +340,108 @@ export class GkeSandboxes {
289
340
  ...this.manager,
290
341
  [SANDBOX_LABEL]: id,
291
342
  [CREATED_LABEL]: String(record.createdMs),
292
- });
293
- if (!fresh && !(await this.markAcquired(pod)))
343
+ }, existing ? undefined : base);
344
+ if (!fresh && !(await this.markAcquired(pod))) {
345
+ existing = await this.find(id);
294
346
  continue;
347
+ }
295
348
  return {
296
349
  sandbox: this.makeEnvironment(id, 'started', pod),
297
350
  startState,
298
- labels: pod.metadata.labels,
351
+ labels: withoutPoolLabels(pod.metadata.labels),
299
352
  podName: pod.metadata.name,
300
353
  createdMs: Number(pod.metadata.labels[CREATED_LABEL]),
301
354
  touch: () => this.touch(id),
302
355
  };
303
356
  }
304
357
  }
305
- /** 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
+ */
306
373
  warmPool(name) {
307
374
  sandboxIdSchema.parse(name);
308
- if (this.options.boot)
309
- throw new Error('Warm pools require an image that can start before caller labels are known.');
375
+ const sandboxes = this;
310
376
  const poolLabels = { ...this.manager, [POOL_LABEL]: name };
311
- 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 });
312
378
  const template = createHash('sha256')
313
379
  .update(JSON.stringify(spare('template').spec))
314
380
  .digest('hex')
315
381
  .slice(0, 32);
316
- const list = async (labels) => listOf(PodSchema)
382
+ const requestedLabels = { ...poolLabels, [TEMPLATE_LABEL]: template };
383
+ const spares = async (labels) => listOf(PodSchema)
317
384
  .parse(await this.kubernetes.request('GET', `${this.pods}?labelSelector=${this.selector(labels)},!${SANDBOX_LABEL}`))
318
385
  .items.filter((pod) => !terminating(pod));
319
- const requestedLabels = { ...poolLabels, [TEMPLATE_LABEL]: template };
320
- // One maintainer per named pool. Claims can come from any replica. A versioned delete
321
- // 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.
322
418
  const reconcile = async (size) => {
323
419
  z.number().int().nonnegative().parse(size);
324
- const idle = await list(poolLabels);
325
- 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
326
423
  .filter((pod) => pod.metadata.labels[TEMPLATE_LABEL] === template &&
327
424
  ['Pending', 'Running'].includes(pod.status.phase))
328
425
  .sort(oldestLiveFirst);
329
426
  const keep = new Set(usable.slice(0, size).map((pod) => pod.metadata.uid));
330
427
  await Promise.all([
331
- ...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
332
441
  .filter((pod) => !keep.has(pod.metadata.uid))
333
- .map(async ({ metadata }) => {
334
- try {
335
- await this.kubernetes.request('DELETE', `${this.pods}/${metadata.name}`, {
336
- preconditions: { uid: metadata.uid, resourceVersion: metadata.resourceVersion },
337
- });
338
- }
339
- catch (error) {
340
- if (!(error instanceof KubernetesApiError && error.status === 409))
341
- throw error;
342
- }
442
+ .map(async (pod) => {
443
+ if (await takeLease(pod, ''))
444
+ await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
343
445
  }),
344
446
  ...Array.from({ length: Math.max(0, size - keep.size) }, () => {
345
447
  const pod = spare(randomUUID());
@@ -348,23 +450,28 @@ export class GkeSandboxes {
348
450
  }),
349
451
  ]);
350
452
  };
351
- // Share one list among concurrent callers. Keep each chosen pod version reserved until
352
- // 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.
353
455
  let reading;
354
456
  const reserved = new Set();
355
- const podVersion = ({ metadata }) => metadata.uid + '/' + metadata.resourceVersion;
356
- const available = async () => {
357
- const pods = (await list(requestedLabels)).filter((pod) => pod.status.phase === 'Running' && ready(pod.status.conditions));
358
- const versions = new Set(pods.map(podVersion));
359
- for (const version of reserved)
360
- if (!versions.has(version))
361
- reserved.delete(version);
362
- // Independent backend replicas can see the same list. Vary their first choice;
363
- // the versioned Kubernetes patch still decides exclusive ownership.
364
- const offset = pods.length ? randomInt(pods.length) : 0;
365
- return pods.slice(offset).concat(pods.slice(0, offset));
366
- };
367
- 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) => {
368
475
  labelSchema.parse(labels);
369
476
  for (const key of [
370
477
  SANDBOX_LABEL,
@@ -375,57 +482,113 @@ export class GkeSandboxes {
375
482
  ])
376
483
  if (key in labels)
377
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) => {
378
491
  const startedAt = Date.now();
379
- signal.throwIfAborted();
380
- reading ??= available().finally(() => {
381
- reading = undefined;
382
- });
383
- const pods = await reading;
492
+ const pods = [...(await listed)];
384
493
  while (pods.length) {
385
494
  signal.throwIfAborted();
386
495
  const pod = pods.pop();
387
- const version = podVersion(pod);
388
- 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)))
389
502
  continue;
390
- reserved.add(version);
391
- const id = pod.metadata.name;
392
- const now = String(Date.now());
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)))
507
+ continue;
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;
393
518
  try {
394
- const claimed = await this.kubernetes.request('PATCH', `${this.pods}/${id}`, {
395
- metadata: {
396
- resourceVersion: pod.metadata.resourceVersion,
397
- labels: {
398
- ...labels,
399
- [SANDBOX_LABEL]: id,
400
- [CREATED_LABEL]: now,
401
- [POOL_LABEL]: null,
402
- [TEMPLATE_LABEL]: null,
403
- },
404
- annotations: { [ACQUIRED_ANNOTATION]: now },
405
- },
406
- });
407
- if (!claimed)
408
- continue;
409
- this.report('create', PodSchema.parse(claimed).metadata.labels, pod, startedAt, null);
410
- return {
411
- sandbox: this.makeEnvironment(id, 'started', pod),
412
- podName: id,
413
- fromPool: true,
414
- touch: () => this.touch(id),
415
- };
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
+ }
416
536
  }
417
537
  catch (error) {
418
- if (!(error instanceof KubernetesApiError && error.status === 409)) {
419
- reserved.delete(version);
420
- throw error;
421
- }
538
+ this.report('create', sandboxLabels, pod, startedAt, error);
539
+ reserved.delete(podName);
540
+ await this.kubernetes.request('DELETE', `${this.pods}/${podName}`);
541
+ continue;
422
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
+ };
423
555
  }
424
- const { sandbox, podName, touch } = await this.acquire(randomUUID(), signal, labels);
425
- return { sandbox, podName, touch, fromPool: false };
556
+ return null;
426
557
  };
427
558
  return {
428
- 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
+ },
429
592
  reconcile,
430
593
  async maintain(size, signal) {
431
594
  while (!signal.aborted) {
@@ -444,10 +607,12 @@ export class GkeSandboxes {
444
607
  /** Open a previously listed workspace without extending its idle period on a read. */
445
608
  async open(record, signal, freshLabels) {
446
609
  signal.throwIfAborted();
447
- await this.start(record, signal, { ...record.labels, ...freshLabels });
610
+ await this.start(record, signal, { ...record.labels, ...freshLabels }, undefined);
448
611
  return this.environment(record.name, 'started');
449
612
  }
450
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);
451
616
  if (!(await this.kubernetes.request('PATCH', `${this.pods}/${podName}`, { metadata: { labels } })))
452
617
  throw new Error(`Pod ${podName} is not running.`);
453
618
  }
@@ -481,7 +646,7 @@ export class GkeSandboxes {
481
646
  return;
482
647
  const startedAt = Date.now();
483
648
  try {
484
- await this.dropOlderSnapshots(sandboxId, await this.snapshot(pod));
649
+ await this.dropOlderSnapshots(sandboxId, await this.takeSnapshot(pod));
485
650
  this.report('checkpoint', pod.metadata.labels, pod, startedAt, null);
486
651
  }
487
652
  catch (error) {
@@ -494,6 +659,53 @@ export class GkeSandboxes {
494
659
  });
495
660
  }
496
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
+ }
497
709
  async sleepUnused() {
498
710
  const idleBefore = Date.now() - this.idleTimeoutMs;
499
711
  const [sandboxes, leases] = await Promise.all([
@@ -560,7 +772,12 @@ export class GkeSandboxes {
560
772
  if (!Object.keys(match).some((key) => !(key in this.manager)))
561
773
  throw new Error('A deletion selector is required.');
562
774
  const labels = this.selector(match);
563
- 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}`)));
564
781
  }
565
782
  async find(id) {
566
783
  sandboxIdSchema.parse(id);
@@ -569,9 +786,10 @@ export class GkeSandboxes {
569
786
  /** Every sandbox with these labels, awake or asleep, newest first. */
570
787
  async list(labels) {
571
788
  const query = `?labelSelector=${this.selector(labels)},${SANDBOX_LABEL}`;
572
- const [pods, snapshots] = await Promise.all([
789
+ const [pods, snapshots, leases] = await Promise.all([
573
790
  this.kubernetes.request('GET', `${this.pods}${query}`),
574
791
  this.kubernetes.request('GET', `${this.snapshotsPath}${query}`),
792
+ this.kubernetes.request('GET', `${this.leases}${query}`),
575
793
  ]);
576
794
  const sandboxes = new Map();
577
795
  const sandbox = (metadata) => {
@@ -590,6 +808,15 @@ export class GkeSandboxes {
590
808
  // A woken sandbox gets a new pod while its previous one may still be shutting down.
591
809
  for (const pod of listOf(PodSchema).parse(pods).items.sort(oldestLiveFirst).reverse())
592
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;
593
820
  for (const snapshot of listOf(SnapshotSchema)
594
821
  .parse(snapshots)
595
822
  .items.filter(({ status }) => ready(status.conditions))
@@ -604,17 +831,164 @@ export class GkeSandboxes {
604
831
  return [...sandboxes.values()].sort((left, right) => right.createdMs - left.createdMs);
605
832
  }
606
833
  async livePods(sandboxId) {
607
- 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);
608
980
  }
609
981
  /** The sandbox's pod to use: the one that is not shutting down, or null. */
610
982
  async livePod(sandboxId) {
611
983
  return (await this.livePods(sandboxId)).sort(oldestLiveFirst)[0] ?? null;
612
984
  }
613
985
  /** Returns the sandbox's running pod, waking or creating it first. */
614
- async start(sandbox, signal, initialLabels) {
986
+ async start(sandbox, signal, initialLabels, fork) {
987
+ let base = fork;
615
988
  const id = sandbox.name;
616
989
  let pod = sandbox.pod;
617
- 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;
618
992
  // A sleep ends with the pod shutting down, and a checkpoint with the pod free again. One that
619
993
  // was abandoned ends when its mark expires, so the wait lasts until then and needs no deadline
620
994
  // of its own: a shorter one would fail the dispatch moments before the pod is usable.
@@ -622,7 +996,7 @@ export class GkeSandboxes {
622
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);
623
997
  const [current] = await this.list({ [SANDBOX_LABEL]: id });
624
998
  pod = current?.pod ?? null;
625
- snapshot = current?.snapshots[0];
999
+ snapshot = current?.snapshots[0] ?? base?.name;
626
1000
  if (current)
627
1001
  sandbox.labels = current.labels;
628
1002
  }
@@ -631,39 +1005,64 @@ export class GkeSandboxes {
631
1005
  while (true) {
632
1006
  signal.throwIfAborted();
633
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;
634
1017
  if (!terminating(pod)) {
635
- // 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.
636
1020
  const reason = pod.status.containerStatuses.find(({ state }) => state?.terminated?.reason)?.state
637
1021
  ?.terminated?.reason ??
638
1022
  pod.status.reason ??
639
1023
  pod.status.phase;
640
- 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
+ : {});
641
1032
  await this.kubernetes.request('DELETE', `${this.pods}/${pod.metadata.name}`);
642
1033
  }
643
- // The pod's last snapshot may be newer than the listing. One of another creation under
644
- // this id belongs to a sandbox that was replaced, not to this one.
645
- const [listed] = await this.list({ [SANDBOX_LABEL]: id });
646
- snapshot =
647
- listed && listed.labels[CREATED_LABEL] === sandbox.labels[CREATED_LABEL]
648
- ? listed.snapshots[0]
649
- : undefined;
650
1034
  pod = null;
651
1035
  }
652
1036
  if (pod)
653
1037
  break;
654
1038
  // A fresh filesystem must also get the caller's initial labels.
655
- if (!snapshot)
1039
+ const forked = !!base && snapshot === base.name;
1040
+ if (!snapshot || (forked && !sandbox.labels[SANDBOX_LABEL]))
656
1041
  sandbox.labels = initialLabels;
657
- // Named after the snapshot it starts from. Kubernetes creates a name once, so callers that
658
- // start the sandbox at the same moment get one pod between them. And a wake never waits
659
- // for the pod it replaces to finish shutting down, which started from an earlier snapshot.
660
- const name = `${id}-${createHash('sha256')
661
- .update(snapshot ?? '')
662
- .digest('hex')
663
- .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
+ }
664
1053
  try {
665
- pod = PodSchema.parse(await this.createPod(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
+ })));
666
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
+ });
667
1066
  break;
668
1067
  }
669
1068
  catch (error) {
@@ -731,13 +1130,13 @@ export class GkeSandboxes {
731
1130
  // replace saved files with an empty filesystem. Keep the snapshot for the next wake.
732
1131
  async confirmRestored(pod, id) {
733
1132
  const path = `${this.pods}/${pod.metadata.name}`;
734
- const address = this.commandAddress(pod);
735
- 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}; }` : ''}`);
736
1137
  // GKE fills in the files as the container starts, so the first looks can come too early.
737
1138
  for (let attempt = 0; attempt < RESTORE_CHECKS; attempt++) {
738
- const { exitCode } = await (address
739
- ? directExec(address, execCommand(30), check, 30, {}, true)
740
- : this.kubernetes.exec(path, execCommand(30), check, 30));
1139
+ const { exitCode } = await this.runIn(pod, execCommand(30), check, 30);
741
1140
  if (exitCode === 0) {
742
1141
  await this.kubernetes.request('PATCH', path, {
743
1142
  metadata: { annotations: { [RESTORED_ANNOTATION]: 'true' } },
@@ -780,8 +1179,8 @@ export class GkeSandboxes {
780
1179
  }));
781
1180
  return this.kubernetes.request('POST', this.pods, manifest);
782
1181
  }
783
- manifest(sandbox, name, snapshot) {
784
- const { directCommands } = this.options;
1182
+ manifest(sandbox, name, snapshot, { boot, forkedFrom }) {
1183
+ const { directCommands, capabilities } = this.options;
785
1184
  return {
786
1185
  apiVersion: 'v1',
787
1186
  kind: 'Pod',
@@ -797,6 +1196,7 @@ export class GkeSandboxes {
797
1196
  // cannot size the scratch volume at /tmp, so the kubelet's limit still bounds that.
798
1197
  'dev.gvisor.flag.overlay2': `root:self,size=${this.diskBytes}`,
799
1198
  ...(snapshot ? { [RESTORE_ANNOTATION]: snapshot } : {}),
1199
+ ...(forkedFrom ? { [FORK_SOURCE_ANNOTATION]: forkedFrom } : {}),
800
1200
  ...(directCommands
801
1201
  ? {
802
1202
  [COMMAND_PORT_ANNOTATION]: String(directCommands.port),
@@ -841,7 +1241,7 @@ export class GkeSandboxes {
841
1241
  {
842
1242
  name: 'sandbox',
843
1243
  image: this.options.image,
844
- 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
845
1245
  ? null
846
1246
  : { protect: this.options.memoryWatchdog?.protect ?? [] }, !!directCommands),
847
1247
  // The pod's own annotations, so the pod template is the same for every pod.
@@ -872,6 +1272,9 @@ export class GkeSandboxes {
872
1272
  : []),
873
1273
  ],
874
1274
  resources: this.options.resources ?? DEFAULT_RESOURCES,
1275
+ ...(capabilities?.length
1276
+ ? { securityContext: { capabilities: { add: capabilities } } }
1277
+ : {}),
875
1278
  },
876
1279
  ],
877
1280
  },
@@ -924,19 +1327,23 @@ export class GkeSandboxes {
924
1327
  throw error;
925
1328
  }
926
1329
  }
927
- 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 } = {}) {
928
1335
  const pod = await this.livePod(id);
929
1336
  if (!pod || terminating(pod))
930
1337
  return;
931
1338
  if (held(pod))
932
1339
  throw new SandboxInUseError(id);
933
- await this.sleepPod(pod);
1340
+ await this.sleepPod(pod, now);
934
1341
  }
935
- async sleepPod(pod) {
1342
+ async sleepPod(pod, now = false) {
936
1343
  const name = pod.metadata.labels[SANDBOX_LABEL];
937
1344
  const path = `${this.pods}/${pod.metadata.name}`;
938
1345
  const acquired = pod.metadata.annotations[ACQUIRED_ANNOTATION];
939
- if (Date.now() - Number(acquired) < this.idleTimeoutMs)
1346
+ if (!now && Date.now() - Number(acquired) < this.idleTimeoutMs)
940
1347
  throw new SandboxInUseError(name);
941
1348
  const claimed = await this.claim(pod, [
942
1349
  { op: 'test', path: ACQUIRED_PATH, value: acquired },
@@ -949,11 +1356,11 @@ export class GkeSandboxes {
949
1356
  try {
950
1357
  // Read after the claim, so a report of use made while the sweep was deciding still counts.
951
1358
  const renewed = renewedMs(await this.kubernetes.request('GET', `${this.leases}/${pod.metadata.name}`));
952
- if (Date.now() - renewed < this.idleTimeoutMs)
1359
+ if (!now && Date.now() - renewed < this.idleTimeoutMs)
953
1360
  throw new SandboxInUseError(name);
954
1361
  if (this.options.drain && !(await this.options.drain(this.environment(name, 'started'))))
955
1362
  throw new SandboxInUseError(name);
956
- const snapshot = await this.snapshot(pod);
1363
+ const snapshot = await this.takeSnapshot(pod);
957
1364
  await this.kubernetes.request('DELETE', path, {
958
1365
  preconditions: { uid: pod.metadata.uid },
959
1366
  });
@@ -970,14 +1377,30 @@ export class GkeSandboxes {
970
1377
  throw error;
971
1378
  }
972
1379
  }
973
- // 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.
974
1381
  async dropOlderSnapshots(sandboxId, newest) {
975
- const { items } = listOf(SnapshotSchema).parse(await this.kubernetes.request('GET', `${this.snapshotsPath}?labelSelector=${this.selector({ [SANDBOX_LABEL]: sandboxId })}`));
976
- await Promise.all(items
977
- .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))
978
1393
  .map(({ metadata }) => this.kubernetes.request('DELETE', `${this.snapshotsPath}/${metadata.name}`)));
979
1394
  }
980
- 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
+ }
981
1404
  // An interrupted wake can leave a running pod whose files nobody has verified.
982
1405
  if (pod.metadata.annotations[RESTORE_ANNOTATION] &&
983
1406
  !pod.metadata.annotations[RESTORED_ANNOTATION])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getenergy/gke-sandboxes",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {