@getenergy/gke-sandboxes 0.3.1 → 0.4.1

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.d.ts CHANGED
@@ -36,6 +36,7 @@ export type SandboxResources = {
36
36
  limits: ResourceList;
37
37
  };
38
38
  export declare const DEFAULT_RESOURCES: SandboxResources;
39
+ export declare const DEFAULT_DISK = "20Gi";
39
40
  export type GkeSandboxOptions = {
40
41
  namespace: string;
41
42
  image: string;
@@ -48,6 +49,13 @@ export type GkeSandboxOptions = {
48
49
  };
49
50
  /** What a sandbox reserves on its node and may use at most. Defaults to `DEFAULT_RESOURCES`. */
50
51
  resources?: SandboxResources;
52
+ /**
53
+ * The size of a sandbox's root filesystem, `DEFAULT_DISK` unless given. `df` reports it and a
54
+ * write past it fails. It must be below the `ephemeral-storage` limit: the difference is what a
55
+ * full sandbox may still hold in /tmp before it is evicted. A sleeping sandbox holding more than
56
+ * this does not wake.
57
+ */
58
+ disk?: string;
51
59
  /**
52
60
  * A sandbox that reaches its memory limit is killed whole. By default each sandbox watches its
53
61
  * own memory and ends its largest processes first. `protect` lists command-line fragments of
@@ -111,10 +119,12 @@ export declare class GkeSandboxes {
111
119
  private readonly kubernetes;
112
120
  private readonly options;
113
121
  private readonly pods;
122
+ private readonly leases;
114
123
  private readonly triggers;
115
124
  private readonly snapshotsPath;
116
125
  private readonly manager;
117
126
  private readonly idleTimeoutMs;
127
+ private readonly diskBytes;
118
128
  constructor(kubernetes: KubernetesApi, options: GkeSandboxOptions);
119
129
  private selector;
120
130
  acquire(id: string, signal: AbortSignal, initialLabels?: Labels): Promise<{
package/dist/index.js CHANGED
@@ -7,13 +7,14 @@ import { z } from 'zod';
7
7
  import { KubernetesApiError } from './kubernetes-api.js';
8
8
  import { MEMORY_WATCHDOG } from './memory-watchdog.js';
9
9
  export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
10
- // Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The disk limit
11
- // keeps one sandbox from filling its node. A pod that exceeds it is evicted, not refused the
12
- // write, and comes back from its last snapshot.
10
+ // Sandboxes are mostly idle, so nodes are packed by the request, not by the limit. The kubelet
11
+ // counts a sandbox's root filesystem, scratch /tmp and logs against the disk limit and evicts a
12
+ // pod that exceeds it, so the limit is what one sandbox may take of its node's disk.
13
13
  export const DEFAULT_RESOURCES = {
14
14
  requests: { cpu: '250m', memory: '1Gi', 'ephemeral-storage': '4Gi' },
15
- limits: { cpu: '2', memory: '4Gi', 'ephemeral-storage': '20Gi' },
15
+ limits: { cpu: '2', memory: '4Gi', 'ephemeral-storage': '40Gi' },
16
16
  };
17
+ export const DEFAULT_DISK = '20Gi';
17
18
  const SANDBOX_LABEL = 'energy-sandbox';
18
19
  const CREATED_LABEL = 'energy-created-ms';
19
20
  const POOL_LABEL = 'getenergy.com/warm-pool';
@@ -29,6 +30,23 @@ const RESTORE_ANNOTATION = 'podsnapshot.gke.io/ps-name';
29
30
  // this rate, about a 16 Gbps node's share for one of 64 sandboxes. No sandbox crowds out its
30
31
  // neighbours, and one turned against a host can send it no more than this.
31
32
  const EGRESS_BANDWIDTH = '250M';
33
+ const QUANTITY_UNITS = {
34
+ Ki: 2 ** 10,
35
+ Mi: 2 ** 20,
36
+ Gi: 2 ** 30,
37
+ Ti: 2 ** 40,
38
+ k: 1e3,
39
+ M: 1e6,
40
+ G: 1e9,
41
+ T: 1e12,
42
+ };
43
+ // gVisor takes a size in bytes, not a Kubernetes quantity.
44
+ const quantityBytes = (quantity) => {
45
+ const [, amount, unit] = /^(\d+(?:\.\d+)?)(Ki|Mi|Gi|Ti|k|M|G|T)?$/.exec(quantity) ?? [];
46
+ if (!amount)
47
+ throw new Error(`Unsupported disk size: ${quantity}`);
48
+ return Math.floor(Number(amount) * (unit ? QUANTITY_UNITS[unit] : 1));
49
+ };
32
50
  // Written by a sandbox's first pod as it starts. A woken pod without it was not restored from its
33
51
  // snapshot.
34
52
  const SANDBOX_ID_FILE = '/var/tmp/.energy-sandbox-id';
@@ -144,6 +162,13 @@ const StoredSnapshotSchema = z.object({
144
162
  storageStatus: z.object({ gcs: z.object({ observedGCSPath: z.string().startsWith('gs://') }) }),
145
163
  }),
146
164
  });
165
+ // A sandbox's keep-alive. Reports of use renew it instead of writing to the pod: GKE checks every
166
+ // pod write with an admission webhook, which is several times slower and queues under load.
167
+ const LeaseSchema = z.object({
168
+ metadata: z.object({ name: z.string() }),
169
+ spec: z.object({ renewTime: z.string().optional() }).default({}),
170
+ });
171
+ const renewedMs = (lease) => lease ? Date.parse(LeaseSchema.parse(lease).spec.renewTime ?? '') || 0 : 0;
147
172
  const TriggerSchema = z.object({
148
173
  status: z
149
174
  .object({
@@ -187,10 +212,12 @@ export class GkeSandboxes {
187
212
  kubernetes;
188
213
  options;
189
214
  pods;
215
+ leases;
190
216
  triggers;
191
217
  snapshotsPath;
192
218
  manager;
193
219
  idleTimeoutMs;
220
+ diskBytes;
194
221
  constructor(kubernetes, options) {
195
222
  this.kubernetes = kubernetes;
196
223
  this.options = options;
@@ -203,11 +230,17 @@ export class GkeSandboxes {
203
230
  if ([SANDBOX_LABEL, CREATED_LABEL, POOL_LABEL, TEMPLATE_LABEL].some((key) => key in this.manager))
204
231
  throw new Error('A manager selector cannot use reserved workspace labels.');
205
232
  this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;
233
+ const disk = options.disk ?? DEFAULT_DISK;
234
+ const limit = (options.resources ?? DEFAULT_RESOURCES).limits['ephemeral-storage'];
235
+ this.diskBytes = quantityBytes(disk);
236
+ if (this.diskBytes >= quantityBytes(limit))
237
+ throw new Error(`The disk (${disk}) must be below the ephemeral-storage limit (${limit}), which also covers /tmp and logs.`);
206
238
  if (!Object.keys(this.manager).length ||
207
239
  !Number.isFinite(this.idleTimeoutMs) ||
208
240
  this.idleTimeoutMs <= 0)
209
241
  throw new Error('A manager label and a positive idle timeout are required.');
210
242
  this.pods = `/api/v1/namespaces/${namespace}/pods`;
243
+ this.leases = `/apis/coordination.k8s.io/v1/namespaces/${namespace}/leases`;
211
244
  const api = `/apis/podsnapshot.gke.io/v1/namespaces/${namespace}`;
212
245
  this.triggers = `${api}/podsnapshotmanualtriggers`;
213
246
  this.snapshotsPath = `${api}/podsnapshots`;
@@ -442,13 +475,22 @@ export class GkeSandboxes {
442
475
  }
443
476
  async sleepUnused() {
444
477
  const idleBefore = Date.now() - this.idleTimeoutMs;
478
+ const [sandboxes, leases] = await Promise.all([
479
+ this.list({}),
480
+ this.kubernetes.request('GET', `${this.leases}?labelSelector=${this.selector({})}`),
481
+ ]);
482
+ const renewed = new Map(listOf(LeaseSchema)
483
+ .parse(leases)
484
+ .items.map((lease) => [lease.metadata.name, renewedMs(lease)]));
445
485
  // All at once: a sleep waits on its snapshot, and one request sweeps the whole cluster, so
446
486
  // sleeping in turn reaches only the first few of many idle sandboxes before its deadline.
447
- await Promise.all((await this.list({})).map(async ({ pod }) => {
487
+ await Promise.all(sandboxes.map(async ({ pod }) => {
448
488
  if (!pod || sleeping(pod) || pod.status.phase !== 'Running')
449
489
  return;
450
490
  if (Number(pod.metadata.annotations[ACQUIRED_ANNOTATION]) > idleBefore)
451
491
  return;
492
+ if ((renewed.get(pod.metadata.name) ?? 0) > idleBefore)
493
+ return;
452
494
  // One sandbox that cannot sleep must not keep the rest awake; the next sweep retries it.
453
495
  // A failed sleep has been reported, and one in use is no failure.
454
496
  await this.sleepPod(pod).catch(() => undefined);
@@ -694,6 +736,10 @@ export class GkeSandboxes {
694
736
  [ACQUIRED_ANNOTATION]: String(Date.now()),
695
737
  [SLEEPING_ANNOTATION]: '0',
696
738
  'kubernetes.io/egress-bandwidth': EGRESS_BANDWIDTH,
739
+ // gVisor gives the root filesystem this size. Without it the filesystem has none: `df`
740
+ // reports 8 EiB free, and the only limit is the kubelet's, which evicts the pod. gVisor
741
+ // cannot size the scratch volume at /tmp, so the kubelet's limit still bounds that.
742
+ 'dev.gvisor.flag.overlay2': `root:self,size=${this.diskBytes}`,
697
743
  ...(snapshot ? { [RESTORE_ANNOTATION]: snapshot } : {}),
698
744
  },
699
745
  },
@@ -769,9 +815,29 @@ export class GkeSandboxes {
769
815
  const pod = await this.livePod(sandboxId);
770
816
  if (!pod)
771
817
  return;
772
- await this.kubernetes.request('PATCH', `${this.pods}/${pod.metadata.name}`, {
773
- metadata: { annotations: { [ACQUIRED_ANNOTATION]: String(Date.now()) } },
774
- });
818
+ const { name, uid } = pod.metadata;
819
+ // Kubernetes reads this time only with six decimals.
820
+ const spec = { renewTime: new Date().toISOString().replace('Z', '000Z') };
821
+ if (await this.kubernetes.request('PATCH', `${this.leases}/${name}`, { spec }))
822
+ return;
823
+ // The pod owns its lease, so Kubernetes deletes the lease with the pod.
824
+ try {
825
+ await this.kubernetes.request('POST', this.leases, {
826
+ apiVersion: 'coordination.k8s.io/v1',
827
+ kind: 'Lease',
828
+ metadata: {
829
+ name,
830
+ labels: this.manager,
831
+ ownerReferences: [{ apiVersion: 'v1', kind: 'Pod', name, uid }],
832
+ },
833
+ spec,
834
+ });
835
+ }
836
+ catch (error) {
837
+ // Another report created it at the same moment, with the same time.
838
+ if (!(error instanceof KubernetesApiError && error.status === 409))
839
+ throw error;
840
+ }
775
841
  }
776
842
  async sleep(id) {
777
843
  const pod = await this.livePod(id);
@@ -796,6 +862,10 @@ export class GkeSandboxes {
796
862
  throw new SandboxInUseError(name);
797
863
  const startedAt = Date.now();
798
864
  try {
865
+ // Read after the claim, so a report of use made while the sweep was deciding still counts.
866
+ const renewed = renewedMs(await this.kubernetes.request('GET', `${this.leases}/${pod.metadata.name}`));
867
+ if (Date.now() - renewed < this.idleTimeoutMs)
868
+ throw new SandboxInUseError(name);
799
869
  if (this.options.drain && !(await this.options.drain(this.environment(name, 'started'))))
800
870
  throw new SandboxInUseError(name);
801
871
  const snapshot = await this.snapshot(pod);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getenergy/gke-sandboxes",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {