hammerkit 2.1.0 → 2.2.0-next.2

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.
Files changed (103) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cache/backends/registry/push-credentials.js +50 -0
  3. package/dist/cache/backends/registry/registry-client.js +41 -10
  4. package/dist/cache/backends/registry-cache-backend.js +6 -1
  5. package/dist/cache/cache-inventory.js +3 -0
  6. package/dist/cli.js +5 -0
  7. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  8. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  9. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/docker/item-network.js +6 -5
  12. package/dist/docker/remove-orphaned-containers.js +5 -4
  13. package/dist/environment/replace-env-variables.js +8 -5
  14. package/dist/environment/run-source-envs.js +2 -1
  15. package/dist/executer/archive-task-entry.js +1 -1
  16. package/dist/executer/check-readiness.js +8 -4
  17. package/dist/executer/docker-healthcheck.js +73 -0
  18. package/dist/executer/docker-service.js +21 -15
  19. package/dist/executer/event-cache.js +7 -1
  20. package/dist/executer/execute-work-task.js +8 -0
  21. package/dist/executer/runner-commands.js +36 -0
  22. package/dist/file/get-file-context.js +4 -7
  23. package/dist/harness/connect.js +12 -8
  24. package/dist/harness/reconnect.js +141 -0
  25. package/dist/harness/sandbox-client.js +241 -33
  26. package/dist/harness/service-tools.js +11 -2
  27. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  28. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  29. package/dist/kubernetes/follow-pod-logs.js +8 -5
  30. package/dist/kubernetes/kept-claims.js +38 -14
  31. package/dist/kubernetes/sandbox-runner.js +526 -156
  32. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  33. package/dist/kubernetes/sync-changes.js +463 -0
  34. package/dist/kubernetes/volumes.js +23 -1
  35. package/dist/network/healthcheck-request.js +38 -0
  36. package/dist/optimizer/get-work-cache-stats.js +7 -0
  37. package/dist/optimizer/work-task-cache-description.js +5 -3
  38. package/dist/planner/image-build.js +5 -0
  39. package/dist/planner/service-definition.js +2 -1
  40. package/dist/planner/utils/append-work-service.js +12 -4
  41. package/dist/planner/utils/dependency-outputs.js +7 -6
  42. package/dist/planner/validate.js +41 -0
  43. package/dist/planner/work-healthcheck.js +23 -2
  44. package/dist/planner/work-item-status.js +12 -2
  45. package/dist/planner/work-runtime-aggregate.js +1 -0
  46. package/dist/planner/work-runtime-docker.js +33 -6
  47. package/dist/planner/work-runtime-kubernetes.js +313 -70
  48. package/dist/planner/work-runtime-local.js +8 -4
  49. package/dist/planner/work-secret.js +33 -11
  50. package/dist/planner/work-service-id.js +30 -6
  51. package/dist/planner/work-service.js +2 -2
  52. package/dist/program.js +19 -1
  53. package/dist/remote/annotations.js +8 -2
  54. package/dist/remote/bundle.js +6 -8
  55. package/dist/remote/device-login.js +4 -1
  56. package/dist/remote/remote-commands.js +16 -7
  57. package/dist/remote/remote-status.js +1 -1
  58. package/dist/remote/remote-work-commands.js +220 -68
  59. package/dist/remote/server-client.js +38 -40
  60. package/dist/schema/build-file-base-task-schema.js +16 -1
  61. package/dist/schema/build-file-image-build-schema.js +5 -8
  62. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  63. package/dist/schema/reference-parser.js +108 -43
  64. package/dist/schema/work-scope-parser.js +8 -0
  65. package/dist/secrets/prefetch-secrets.js +20 -1
  66. package/dist/server/artifacts-api.js +56 -0
  67. package/dist/server/borrowed-quota.js +216 -0
  68. package/dist/server/cache-push.js +50 -0
  69. package/dist/server/capacity.js +18 -6
  70. package/dist/server/definitions-api.js +62 -8
  71. package/dist/server/executor.js +131 -31
  72. package/dist/server/http.js +4 -1
  73. package/dist/server/keep-artifacts.js +230 -0
  74. package/dist/server/kubernetes-backend.js +292 -79
  75. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  76. package/dist/server/overview.js +73 -9
  77. package/dist/server/paging.js +167 -0
  78. package/dist/server/plan.js +54 -8
  79. package/dist/server/run-access.js +24 -0
  80. package/dist/server/run-artifacts.js +171 -0
  81. package/dist/server/run-logs.js +25 -1
  82. package/dist/server/run-request.js +11 -0
  83. package/dist/server/run-source-environment.js +1 -1
  84. package/dist/server/run-worker.js +305 -40
  85. package/dist/server/runs.js +531 -105
  86. package/dist/server/sandbox-files-api.js +27 -12
  87. package/dist/server/sandbox-files.js +12 -10
  88. package/dist/server/sandbox-follow.js +54 -0
  89. package/dist/server/sandbox-pod.js +1 -1
  90. package/dist/server/sandbox-storage.js +38 -1
  91. package/dist/server/sandbox-sync.js +392 -0
  92. package/dist/server/sandboxes-api.js +116 -19
  93. package/dist/server/sandboxes.js +38 -3
  94. package/dist/server/server-config.js +133 -2
  95. package/dist/server/server.js +189 -39
  96. package/dist/server/task-order.js +56 -0
  97. package/dist/utils/project-path.js +20 -0
  98. package/dist/utils/tar-files.js +52 -0
  99. package/dist/utils/tar.js +37 -1
  100. package/package.json +1 -1
  101. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  102. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  103. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.awaitRunObjectsGone = exports.removeRunObjects = exports.CallerNamespaces = exports.getVolumeScope = exports.getPrivilegedNamespaceProblem = exports.getCapabilitiesProblem = exports.getPodSecurityLabels = exports.KubernetesExecutor = exports.getRunRoleBinding = exports.removeServiceRunNamespace = exports.getServerIngressPolicy = exports.getNamespacePolicies = exports.getClusterAccess = exports.isCallerNamespace = exports.SERVICE_RUN_LABEL = exports.getServiceRunNamespace = exports.getCallerNamespace = void 0;
3
+ exports.awaitRunObjectsGone = exports.removeRunObjects = exports.CallerNamespaces = exports.getNamespaceQuota = exports.getVolumeScope = exports.getKeptClaimTasks = exports.getPrivilegedNamespaceProblem = exports.getCapabilitiesProblem = exports.getPodSecurityLabels = exports.KubernetesExecutor = exports.getRunRoleBinding = exports.removeServiceRunNamespace = exports.getServerIngressPolicy = exports.getNamespacePolicies = exports.getClusterAccess = exports.isCallerNamespace = exports.SERVICE_RUN_LABEL = exports.getServiceRunNamespace = exports.getCallerNamespace = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const fs_1 = require("fs");
6
6
  const os_1 = require("os");
@@ -9,15 +9,19 @@ const net_1 = require("net");
9
9
  const apply_1 = require("../kubernetes/apply");
10
10
  const job_placement_1 = require("../kubernetes/job-placement");
11
11
  const capacity_1 = require("./capacity");
12
+ const borrowed_quota_1 = require("./borrowed-quota");
12
13
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
13
14
  const log_1 = require("../log");
14
15
  const network_policy_1 = require("../kubernetes/network-policy");
15
16
  const network_gate_1 = require("../kubernetes/network-gate");
16
17
  const sleep_1 = require("../utils/sleep");
18
+ const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
19
+ const sandbox_runner_1 = require("../kubernetes/sandbox-runner");
17
20
  const version_1 = require("../version");
18
21
  const executor_1 = require("./executor");
19
22
  const kept_claims_1 = require("../kubernetes/kept-claims");
20
23
  const units_1 = require("../utils/units");
24
+ const runs_1 = require("./runs");
21
25
  const server_config_1 = require("./server-config");
22
26
  // the name of the quota and limit range the server keeps in a caller's namespace
23
27
  const POLICY_NAME = 'hammerkit';
@@ -259,9 +263,9 @@ exports.getRunRoleBinding = getRunRoleBinding;
259
263
  * of a caller execute side by side in their namespace, up to `runs.limits.running`:
260
264
  * the objects of a run are named and found by its run label (getItemKey), so two runs
261
265
  * of the same task have their own. What two runs share are the claims the server keeps
262
- * (`backend.keepVolumes`) of a scope (getVolumeScope): the runs of one scope go one at
263
- * a time (exclusive). When a run ends, everything made for it is removed, but for the
264
- * kept claims, which go once they expired.
266
+ * (`backend.keepVolumes`) of a scope (getVolumeScope), one per task: two runs of one scope
267
+ * with a task in common go one at a time (excludes). When a run ends, everything made for it
268
+ * is removed, but for the kept claims, which go once they expired.
265
269
  */
266
270
  class KubernetesExecutor {
267
271
  constructor(config, processEnvs, options) {
@@ -269,7 +273,11 @@ class KubernetesExecutor {
269
273
  // per caller namespace, what changes objects of the whole namespace: its setup, the
270
274
  // removal of what a stopped server left, the sweeps of kept claims. The last one waiting.
271
275
  this.queues = new Map();
272
- // per caller namespace, the runs that execute in it: by run label, their volume scope
276
+ // per caller namespace, the runs that execute in it: by run label, the volume scope of the
277
+ // kept claims they mount, if any. Every run that executes is here, not only those that mount
278
+ // kept claims: a tidy of the namespace (after a release that failed, or the first after a
279
+ // restart) leaves the objects of all of them, a resumed run's too once it no longer counts
280
+ // as resuming
273
281
  this.active = new Map();
274
282
  // per caller namespace, when its kept claims are next looked at
275
283
  this.sweeps = new Map();
@@ -283,6 +291,9 @@ class KubernetesExecutor {
283
291
  this.serviceRuns = new Map();
284
292
  this.serviceRunsSwept = false;
285
293
  this.asleep = new Set();
294
+ // the runs whose execution got its place on the cluster, until it ended: their release
295
+ // removes what they made
296
+ this.placed = new Set();
286
297
  this.access = getClusterAccess(config.backend, processEnvs);
287
298
  this.instance = (0, kubernetes_instance_1.createKubernetesInstances)({
288
299
  type: 'kubernetes',
@@ -302,13 +313,28 @@ class KubernetesExecutor {
302
313
  this.keep = config.backend.keepVolumes === false ? 0 : (0, units_1.parseDuration)(config.backend.keepVolumes);
303
314
  this.keepServiceRuns = config.runs.up.keepVolumes;
304
315
  this.log = options.log;
316
+ const { quota, maxQuota, pools } = config.backend;
317
+ if (quota && maxQuota) {
318
+ this.quotas = new borrowed_quota_1.BorrowedQuotas({
319
+ quota,
320
+ maxQuota,
321
+ room: () => (0, borrowed_quota_1.readPoolRoom)(this.instance, pools),
322
+ write: async (namespace, hard) => {
323
+ await (0, apply_1.replace)(this.instance, getNamespaceQuota(namespace, hard));
324
+ },
325
+ log: options.log,
326
+ });
327
+ }
328
+ this.resuming = new ResumingRuns(config.backend.namespacePrefix, (run) => this.namespaceOf(run));
305
329
  this.host = new executor_1.HostExecutor({ ...options, placement: this.placement() });
306
330
  }
307
331
  // what the namespaces of the server's callers and service runs request and use
308
332
  capacity() {
309
333
  const prefix = this.config.backend.namespacePrefix;
334
+ const { quota, maxQuota } = this.config.backend;
310
335
  return new capacity_1.KubernetesCapacity(this.instance, {
311
336
  quotaName: POLICY_NAME,
337
+ ...(quota && maxQuota ? { share: (0, capacity_1.getQuotaResources)(quota) } : {}),
312
338
  namespaces: async () => (await this.instance.coreApi.listNamespace({ labelSelector: `${MANAGED_LABEL}=true` })).items
313
339
  .filter((namespace) => isCallerNamespace(prefix, namespace.metadata?.name ?? ''))
314
340
  .map((namespace) => ({
@@ -329,13 +355,61 @@ class KubernetesExecutor {
329
355
  });
330
356
  }
331
357
  async execute(run, context) {
332
- if (run.up) {
333
- if (run.source.type === 'sandbox') {
334
- throw new Error('on a cluster a service run starts from a branch, push the sandbox and start it from there');
358
+ // what a run that resumes left is this execution's from now: the end of a run that got its
359
+ // place on the cluster (release) removes it, the end of one that did not removes it here
360
+ const left = this.resuming.has(run);
361
+ try {
362
+ await this.executeOn(run, context);
363
+ }
364
+ finally {
365
+ const placed = this.placed.delete(run.id);
366
+ if (left && !placed && !(0, runs_1.isDetached)(context)) {
367
+ // the run executed: its process removed its commands when it ended
368
+ await this.removeLeft(run, false);
369
+ }
370
+ }
371
+ }
372
+ // What a run left on the cluster, that no release removes
373
+ async removeLeft(run, commands = true) {
374
+ const say = (text) => this.log?.(`run=${run.id} ${text}`);
375
+ this.resuming.forget(run);
376
+ try {
377
+ if (!run.up) {
378
+ const namespace = getCallerNamespace(this.config.backend.namespacePrefix, run.owner);
379
+ if (commands) {
380
+ await this.removeRunCommands(run, namespace, say);
381
+ }
382
+ await this.removeRun(run, namespace, say);
383
+ return;
335
384
  }
336
- // in a namespace of its own, apart from the caller's runs and their claims
385
+ // a namespace is kept only for a run that has one from start to end
386
+ const namespace = this.namespaceOf(run);
387
+ this.asleep.delete(namespace);
388
+ await this.enqueue(namespace, () => this.removeServiceRun(namespace, say));
389
+ }
390
+ catch (e) {
391
+ say(`what the run left could not be removed: ${(0, log_1.getErrorMessage)(e)}`);
392
+ }
393
+ }
394
+ // What the commands of a run on a sandbox left in its runner: they ran on over the restart
395
+ // for the run to take them up again, which it no longer does. Another run may be on the
396
+ // sandbox by now, so only the run's own commands are killed.
397
+ async removeRunCommands(run, namespace, say) {
398
+ if (run.source.type !== 'sandbox' || !this.config.backend.sandboxes.runner) {
399
+ return;
400
+ }
401
+ await (0, sandbox_runner_1.removeRunCommands)(this.instance, namespace, (0, kubernetes_sandbox_storage_1.getSandboxNames)(run.source.id).label, run.id, {
402
+ clean: false,
403
+ }).catch((e) => say(`what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
404
+ }
405
+ async executeOn(run, context) {
406
+ if (run.up) {
407
+ // in a namespace of its own, apart from the caller's runs and their claims, from a branch
408
+ // or from the files of a sandbox (copied, see HostExecutor.execute)
337
409
  return this.host.execute(run, context);
338
410
  }
411
+ // it executes: its objects are kept from a tidy as those of any run that executes
412
+ this.resuming.forget(run);
339
413
  const namespace = getCallerNamespace(this.config.backend.namespacePrefix, run.owner);
340
414
  const label = (0, job_placement_1.getRunLabelValue)(run.id);
341
415
  let runs = this.active.get(namespace);
@@ -343,7 +417,9 @@ class KubernetesExecutor {
343
417
  runs = new Map();
344
418
  this.active.set(namespace, runs);
345
419
  }
346
- runs.set(label, getVolumeScope(run));
420
+ runs.set(label, this.holds(run) ? getVolumeScope(run) : undefined);
421
+ // the caller is promised its share while the run executes
422
+ this.quotas?.enter(namespace, run.id);
347
423
  try {
348
424
  await this.host.execute(run, context);
349
425
  }
@@ -352,8 +428,19 @@ class KubernetesExecutor {
352
428
  if (runs.size === 0 && this.active.get(namespace) === runs) {
353
429
  this.active.delete(namespace);
354
430
  }
431
+ // a run the next server resumes still has its Jobs, under the quota it had
432
+ if (!(0, runs_1.isDetached)(context)) {
433
+ await this.quotas
434
+ ?.leave(namespace, run.id)
435
+ .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
436
+ }
355
437
  }
356
438
  }
439
+ // The changed files of a sandbox for the services of a service run here: they are synced in
440
+ // place, nothing of the run moves (see RunExecutor.syncFiles)
441
+ syncFiles(run, changes) {
442
+ return !!run.up && this.host.syncChildFiles(run.id, changes);
443
+ }
357
444
  // A service run moves to another commit in its namespace: unchanged services stay, the
358
445
  // others roll to their new pods (see kubernetesServiceRuntime)
359
446
  movesBeside(run) {
@@ -367,25 +454,32 @@ class KubernetesExecutor {
367
454
  }
368
455
  /**
369
456
  * A service run that slept with its volumes ended without waking: its namespace goes, with
370
- * the claims in it.
457
+ * the claims in it. A run that resumed after a restart ended: what an execution before the
458
+ * restart left goes, as no execution may have removed it (one cancelled in the queue).
371
459
  */
372
460
  async forget(run) {
373
- if (!run.up) {
374
- return;
375
- }
376
- // a namespace is kept only for a run that has one from start to end
377
- const namespace = getServiceRunNamespace(this.config.backend.namespacePrefix, run.id);
378
- this.asleep.delete(namespace);
379
- await this.enqueue(namespace, () => this.removeServiceRun(namespace, (text) => this.log?.(`run=${run.id} ${text}`)));
461
+ // the commands of a run are left only when it was restored and never executed again
462
+ await this.removeLeft(run, this.resuming.has(run));
380
463
  }
381
464
  /**
382
- * The service runs of a previous start that sleep with their volumes: their namespaces stay,
383
- * without what runs in them (a server that stopped without putting the run to sleep left
384
- * it). The namespaces of any other service run go.
465
+ * The runs of a previous start that are not over: the service runs that sleep with their
466
+ * volumes, whose namespaces stay without what runs in them (a server that stopped without
467
+ * putting the run to sleep left it), and the runs that resume (queued), whose Jobs and
468
+ * services stay where they are until they execute again or end. The namespaces of any other
469
+ * service run go.
385
470
  */
386
471
  restored(runs) {
472
+ for (const run of runs.filter((candidate) => candidate.state === 'queued')) {
473
+ try {
474
+ this.resuming.add(run, this.holds(run) ? getVolumeScope(run) : undefined);
475
+ }
476
+ catch (e) {
477
+ // its objects are not kept from a sweep, the run does not start for nothing
478
+ this.log?.(`what run ${run.id} left on the cluster is not kept for it: ${(0, log_1.getErrorMessage)(e)}`);
479
+ }
480
+ }
387
481
  if (this.keepServiceRuns) {
388
- for (const run of runs.filter((candidate) => candidate.up)) {
482
+ for (const run of runs.filter((candidate) => candidate.up && candidate.state !== 'queued')) {
389
483
  const namespace = getServiceRunNamespace(this.config.backend.namespacePrefix, run.id);
390
484
  this.asleep.add(namespace);
391
485
  this.enqueue(namespace, () => removeRunObjects(this.instance, namespace, job_placement_1.RUN_LABEL, RELEASE_TIMEOUT, { claims: false })).catch((e) => this.log?.(`what runs in the namespace ${namespace} of run ${run.id} could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
@@ -417,23 +511,51 @@ class KubernetesExecutor {
417
511
  this.serviceRunsSwept = false;
418
512
  }
419
513
  }
420
- // The runs of a scope share its kept claims, which one of them may change at a time:
421
- // what a task finds in one is what the last run left there. Without kept claims, runs
422
- // share no object and nothing is held.
423
- exclusive(run) {
514
+ // The runs of a scope share the kept claim of each task, which one of them may change at a
515
+ // time: what a task finds in it is what the last run left there. Two runs of a scope go
516
+ // side by side when they have no task in common, and a run that mounts no kept claim holds
517
+ // nothing. Without kept claims, runs share no object and nothing is held.
518
+ excludes(run, other) {
519
+ const held = this.holds(run);
520
+ const theirs = this.holds(other);
521
+ if (!held || !theirs || held.scope !== theirs.scope) {
522
+ return false;
523
+ }
524
+ if (!held.tasks || !theirs.tasks) {
525
+ return true;
526
+ }
527
+ const tasks = new Set(theirs.tasks);
528
+ return held.tasks.some((task) => tasks.has(task));
529
+ }
530
+ // The kept claims a run mounts: its scope in the caller's namespace and the tasks of the
531
+ // claims (getKeptClaimTasks), all of the scope's for a run without a plan. Nothing for a
532
+ // run that mounts none.
533
+ holds(run) {
424
534
  if (this.keep === 0 || run.up) {
425
535
  return undefined;
426
536
  }
427
- return `${getCallerNamespace(this.config.backend.namespacePrefix, run.owner)}/${getVolumeScope(run)}`;
537
+ const tasks = getKeptClaimTasks(run);
538
+ if (tasks?.length === 0) {
539
+ return undefined;
540
+ }
541
+ return {
542
+ scope: `${getCallerNamespace(this.config.backend.namespacePrefix, run.owner)}/${getVolumeScope(run)}`,
543
+ tasks,
544
+ };
428
545
  }
429
- // The scopes of the runs that execute in the namespace, but `except`'s: their kept claims
430
- // are theirs to mount and stay. A server that keeps none mounts none.
546
+ // The scopes of the runs that execute in the namespace and mount kept claims, but
547
+ // `except`'s: their kept claims are theirs to mount and stay. A server that keeps none
548
+ // mounts none.
431
549
  scopesInUse(namespace, except) {
432
550
  if (this.keep === 0) {
433
551
  return new Set();
434
552
  }
435
- return new Set([...(this.active.get(namespace) ?? new Map()).entries()]
436
- .filter(([label]) => label !== except)
553
+ return new Set([
554
+ ...(this.active.get(namespace) ?? new Map()).entries(),
555
+ // a run that resumes mounts them again
556
+ ...this.resuming.scopes(namespace),
557
+ ]
558
+ .filter(([label, scope]) => label !== except && scope !== undefined)
437
559
  .map(([, scope]) => scope));
438
560
  }
439
561
  // What changes objects of a whole namespace happens one at a time, not what its runs do
@@ -459,6 +581,9 @@ class KubernetesExecutor {
459
581
  }
460
582
  this.serviceRuns.set(namespace, (this.serviceRuns.get(namespace) ?? 0) + 1);
461
583
  this.asleep.delete(namespace);
584
+ // its execution holds the namespace now, and its release removes it
585
+ this.resuming.forget(run);
586
+ this.placed.add(run.id);
462
587
  this.sweepServiceRuns();
463
588
  const up = run.up;
464
589
  // after what a stop of its sleep left in it went (see restored)
@@ -474,8 +599,10 @@ class KubernetesExecutor {
474
599
  quota: this.config.runs.up.quota,
475
600
  });
476
601
  });
602
+ // its pods take room the callers can't borrow
603
+ await this.quotas?.serviceRun(namespace, this.config.runs.up.quota ?? this.config.backend.quota);
477
604
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
478
- return { kubernetes: this.environmentOf(run, namespace), env: this.access.env };
605
+ return { kubernetes: this.environmentOf(run, namespace, context), env: this.access.env };
479
606
  }
480
607
  const label = (0, job_placement_1.getRunLabelValue)(run.id);
481
608
  let capabilitiesProblem;
@@ -488,7 +615,9 @@ class KubernetesExecutor {
488
615
  // release failed: the objects of a run that does not execute. One that starts
489
616
  // after this waits for it here before it makes any.
490
617
  if (!this.tidy.has(namespace)) {
491
- const running = [...new Set([label, ...(this.active.get(namespace)?.keys() ?? [])])];
618
+ const running = [
619
+ ...new Set([label, ...(this.active.get(namespace)?.keys() ?? []), ...this.resuming.labels(namespace)]),
620
+ ];
492
621
  await removeRunObjects(this.instance, namespace, `${job_placement_1.RUN_LABEL},${job_placement_1.RUN_LABEL} notin (${running.join(',')})`, RELEASE_TIMEOUT);
493
622
  this.tidy.add(namespace);
494
623
  }
@@ -504,9 +633,13 @@ class KubernetesExecutor {
504
633
  }
505
634
  });
506
635
  this.sweepLeftClaims();
636
+ // the quota of the caller, and of the callers it borrows from or lends to, before its
637
+ // tasks run
638
+ await this.quotas?.apply(namespace);
507
639
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
640
+ this.placed.add(run.id);
508
641
  return {
509
- kubernetes: this.environmentOf(run, namespace, work, capabilitiesProblem),
642
+ kubernetes: this.environmentOf(run, namespace, context, work, capabilitiesProblem),
510
643
  env: this.access.env,
511
644
  };
512
645
  },
@@ -540,44 +673,42 @@ class KubernetesExecutor {
540
673
  }
541
674
  else {
542
675
  this.serviceRuns.delete(namespace);
676
+ await this.quotas
677
+ ?.serviceRunEnded(namespace)
678
+ .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
543
679
  }
544
680
  }
545
681
  return;
546
682
  }
547
- try {
548
- const selector = `${job_placement_1.RUN_LABEL}=${(0, job_placement_1.getRunLabelValue)(run.id)}`;
549
- await removeRunObjects(this.instance, namespace, selector, RELEASE_TIMEOUT);
550
- }
551
- catch (e) {
552
- // the next run removes what is left
553
- this.tidy.delete(namespace);
554
- context.emit({
555
- type: 'log',
556
- task: 'hammerkit',
557
- stream: 'stderr',
558
- text: `what the run made in ${namespace} could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
559
- });
560
- }
561
- if (this.keep > 0) {
562
- try {
563
- await (0, kept_claims_1.expireKeptClaims)(this.instance, namespace, (0, job_placement_1.getRunLabelValue)(run.id), new Date(Date.now() + this.keep));
564
- }
565
- catch (e) {
566
- // without an expiry, the next look at the namespace removes them
567
- context.emit({
568
- type: 'log',
569
- task: 'hammerkit',
570
- stream: 'stderr',
571
- text: `the claims the run kept in ${namespace} could not be given their expiry: ${(0, log_1.getErrorMessage)(e)}`,
572
- });
573
- }
574
- this.sweepLater(namespace, this.keep);
575
- }
683
+ await this.removeRun(run, namespace, (text) => context.emit({ type: 'log', task: 'hammerkit', stream: 'stderr', text }));
576
684
  },
577
685
  };
578
686
  }
687
+ // The end of a run of tasks: what it made in the caller's namespace goes, but for the claims
688
+ // it keeps, which expire from now
689
+ async removeRun(run, namespace, say) {
690
+ try {
691
+ const selector = `${job_placement_1.RUN_LABEL}=${(0, job_placement_1.getRunLabelValue)(run.id)}`;
692
+ await removeRunObjects(this.instance, namespace, selector, RELEASE_TIMEOUT);
693
+ }
694
+ catch (e) {
695
+ // the next run removes what is left
696
+ this.tidy.delete(namespace);
697
+ say(`what the run made in ${namespace} could not be removed: ${(0, log_1.getErrorMessage)(e)}`);
698
+ }
699
+ if (this.keep > 0) {
700
+ try {
701
+ await (0, kept_claims_1.expireKeptClaims)(this.instance, namespace, (0, job_placement_1.getRunLabelValue)(run.id), new Date(Date.now() + this.keep));
702
+ }
703
+ catch (e) {
704
+ // without an expiry, the next look at the namespace removes them
705
+ say(`the claims the run kept in ${namespace} could not be given their expiry: ${(0, log_1.getErrorMessage)(e)}`);
706
+ }
707
+ this.sweepLater(namespace, this.keep);
708
+ }
709
+ }
579
710
  // The cluster as the process of a run sees it: the namespace its tasks and services go in.
580
- environmentOf(run, namespace, work, capabilitiesProblem) {
711
+ environmentOf(run, namespace, context, work, capabilitiesProblem) {
581
712
  const backend = this.config.backend;
582
713
  const openGate = (0, network_gate_1.getOpenNetworkGate)(backend);
583
714
  return {
@@ -601,6 +732,8 @@ class KubernetesExecutor {
601
732
  ...(this.keep > 0 && !run.up ? { volumeScope: getVolumeScope(run) } : {}),
602
733
  ...(run.up ? { serviceRun: true } : {}),
603
734
  ...(openGate ? { openGate } : {}),
735
+ // what the execution before a restart left, its tasks and services take over
736
+ ...(context.resumed ? { resumed: { logs: context.resumed.logs } } : {}),
604
737
  ...(backend.capabilities
605
738
  ? {
606
739
  capabilities: {
@@ -631,6 +764,7 @@ class KubernetesExecutor {
631
764
  isCallerNamespace(this.config.backend.namespacePrefix, name) &&
632
765
  !this.serviceRuns.has(name) &&
633
766
  !this.asleep.has(name) &&
767
+ !this.resuming.keeps(name) &&
634
768
  !namespace.metadata?.deletionTimestamp) {
635
769
  this.log?.(`removing the namespace ${name} of a service run from before the server started`);
636
770
  await removeServiceRunNamespace(this.instance, name, 0);
@@ -692,6 +826,54 @@ class KubernetesExecutor {
692
826
  }
693
827
  }
694
828
  exports.KubernetesExecutor = KubernetesExecutor;
829
+ // What the runs that resume after a restart left on the cluster, which the sweeps leave: the
830
+ // namespaces of service runs, and per caller namespace the runs by run label, with the volume
831
+ // scope of the kept claims they mount
832
+ class ResumingRuns {
833
+ constructor(prefix, namespaceOf) {
834
+ this.prefix = prefix;
835
+ this.namespaceOf = namespaceOf;
836
+ this.serviceRuns = new Set();
837
+ this.runs = new Map();
838
+ }
839
+ add(run, scope) {
840
+ if (run.up) {
841
+ this.serviceRuns.add(this.namespaceOf(run));
842
+ return;
843
+ }
844
+ const namespace = getCallerNamespace(this.prefix, run.owner);
845
+ const runs = this.runs.get(namespace) ?? new Map();
846
+ runs.set((0, job_placement_1.getRunLabelValue)(run.id), scope);
847
+ this.runs.set(namespace, runs);
848
+ }
849
+ has(run) {
850
+ return run.up
851
+ ? this.serviceRuns.has(this.namespaceOf(run))
852
+ : !!this.runs.get(getCallerNamespace(this.prefix, run.owner))?.has((0, job_placement_1.getRunLabelValue)(run.id));
853
+ }
854
+ forget(run) {
855
+ if (run.up) {
856
+ this.serviceRuns.delete(this.namespaceOf(run));
857
+ return;
858
+ }
859
+ const namespace = getCallerNamespace(this.prefix, run.owner);
860
+ const runs = this.runs.get(namespace);
861
+ runs?.delete((0, job_placement_1.getRunLabelValue)(run.id));
862
+ if (runs?.size === 0) {
863
+ this.runs.delete(namespace);
864
+ }
865
+ }
866
+ // whether the namespace of a service run is kept for it
867
+ keeps(namespace) {
868
+ return this.serviceRuns.has(namespace);
869
+ }
870
+ labels(namespace) {
871
+ return [...(this.runs.get(namespace)?.keys() ?? [])];
872
+ }
873
+ scopes(namespace) {
874
+ return [...(this.runs.get(namespace)?.entries() ?? [])];
875
+ }
876
+ }
695
877
  const ENFORCE_LABEL = 'pod-security.kubernetes.io/enforce';
696
878
  const AUDIT_LABEL = 'pod-security.kubernetes.io/audit';
697
879
  /**
@@ -736,6 +918,22 @@ function getPrivilegedNamespaceProblem(namespace, labels, backend) {
736
918
  `${namespace} ${ENFORCE_LABEL}=baseline ${AUDIT_LABEL}- --overwrite`);
737
919
  }
738
920
  exports.getPrivilegedNamespaceProblem = getPrivilegedNamespaceProblem;
921
+ // The tasks of a run whose kept claims it mounts, by name: each container task of its plan,
922
+ // which mounts its own claim, while the tasks that depend on it and the services that mount its
923
+ // outputs mount it too (they have it in their plan). Another task has none: an aggregate, or a
924
+ // local task on a server that allows them. A kept claim is named after its task
925
+ // (getClaimName), so two runs with no task in common mount no claim in common, whatever
926
+ // their tasks are. Null for a run without a plan (submitted by a version that recorded none).
927
+ function getKeptClaimTasks(run) {
928
+ if (!run.plan) {
929
+ return null;
930
+ }
931
+ return Object.entries(run.plan)
932
+ .filter(([, task]) => task.kind === 'task' && task.runtime === 'docker')
933
+ .map(([name]) => name)
934
+ .sort();
935
+ }
936
+ exports.getKeptClaimTasks = getKeptClaimTasks;
739
937
  // What may mount a claim a run kept: the runs of the same branch or tag of a repository,
740
938
  // which share its cache, so that the runs of two branches go side by side and the runs of one find what
741
939
  // the last one left; on a sandbox the runs of that sandbox only, whose claim is on the same
@@ -755,6 +953,19 @@ function getVolumeScope(run) {
755
953
  return (0, executor_1.cacheNamespace)(run);
756
954
  }
757
955
  exports.getVolumeScope = getVolumeScope;
956
+ function getPolicyMetadata(namespace) {
957
+ return {
958
+ name: POLICY_NAME,
959
+ namespace,
960
+ annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
961
+ labels: { [MANAGED_LABEL]: 'true' },
962
+ };
963
+ }
964
+ // The ResourceQuota of a namespace of the server
965
+ function getNamespaceQuota(namespace, hard) {
966
+ return { apiVersion: 'v1', kind: 'ResourceQuota', metadata: getPolicyMetadata(namespace), spec: { hard } };
967
+ }
968
+ exports.getNamespaceQuota = getNamespaceQuota;
758
969
  /**
759
970
  * The namespaces of callers on the cluster: named by the caller (getCallerNamespace),
760
971
  * made on first use, with the operator's quota.
@@ -842,18 +1053,9 @@ class CallerNamespaces {
842
1053
  ]) {
843
1054
  await (0, apply_1.replace)(this.instance, policy);
844
1055
  }
845
- const metadata = {
846
- name: POLICY_NAME,
847
- namespace,
848
- annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
849
- labels: { [MANAGED_LABEL]: 'true' },
850
- };
851
- const quota = {
852
- apiVersion: 'v1',
853
- kind: 'ResourceQuota',
854
- metadata,
855
- spec: { hard: serviceRun?.quota ?? backend.quota },
856
- };
1056
+ const metadata = getPolicyMetadata(namespace);
1057
+ const hard = serviceRun?.quota ?? backend.quota;
1058
+ const quota = getNamespaceQuota(namespace, hard ?? {});
857
1059
  const defaults = backend.defaultResources;
858
1060
  const limits = {
859
1061
  apiVersion: 'v1',
@@ -869,10 +1071,21 @@ class CallerNamespaces {
869
1071
  ],
870
1072
  },
871
1073
  };
872
- for (const [object, wanted] of [
873
- [quota, !!(serviceRun?.quota ?? backend.quota)],
1074
+ // a caller who may borrow has the quota the server works out for them (BorrowedQuotas),
1075
+ // written once the namespace is there: here it is made with the share, never replaced
1076
+ const borrows = !!backend.maxQuota && !serviceRun;
1077
+ if (borrows) {
1078
+ await this.instance.objectApi.create(quota).catch((e) => {
1079
+ if ((0, apply_1.statusCodeOf)(e) !== 409) {
1080
+ throw e;
1081
+ }
1082
+ });
1083
+ }
1084
+ const objects = [
1085
+ ...(borrows ? [] : [[quota, !!hard]]),
874
1086
  [limits, !!defaults],
875
- ]) {
1087
+ ];
1088
+ for (const [object, wanted] of objects) {
876
1089
  if (wanted) {
877
1090
  await (0, apply_1.replace)(this.instance, object);
878
1091
  }