hammerkit 2.0.0-next.2 → 2.0.0-next.20

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 (111) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  7. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  8. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +19 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +27 -9
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +80 -11
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-source-environment.js +39 -0
  91. package/dist/server/run-worker.js +71 -9
  92. package/dist/server/runs.js +133 -7
  93. package/dist/server/sandbox-files.js +339 -55
  94. package/dist/server/sandbox-patch.js +43 -17
  95. package/dist/server/sandboxes.js +57 -23
  96. package/dist/server/server-config.js +28 -5
  97. package/dist/server/server.js +94 -16
  98. package/dist/server/service-runs.js +50 -5
  99. package/dist/server/sources.js +68 -11
  100. package/dist/server/timings.js +23 -3
  101. package/dist/utils/buffer-context.js +30 -20
  102. package/dist/utils/limit.js +30 -0
  103. package/dist/utils/line-splitter.js +52 -0
  104. package/dist/utils/read-lines.js +65 -0
  105. package/dist/utils/tar.js +51 -1
  106. package/dist/utils/units.js +36 -1
  107. package/dist/utils/web-links.js +34 -0
  108. package/package.json +1 -1
  109. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  110. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  111. package/dist/dashboard/favicon.svg +0 -1
@@ -6,6 +6,7 @@ const abort_event_1 = require("../utils/abort-event");
6
6
  const apply_1 = require("./apply");
7
7
  const sleep_1 = require("../utils/sleep");
8
8
  const cluster_state_1 = require("./cluster-state");
9
+ const quota_wait_1 = require("./quota-wait");
9
10
  // The waits below poll instead of using the client's Watch: Watch aborts every
10
11
  // request after 30s, which a pod or deployment still pulling its image outlasts.
11
12
  async function awaitRunningState(instance, env, name, phase, pollInterval = 1000) {
@@ -22,29 +23,90 @@ async function awaitRunningState(instance, env, name, phase, pollInterval = 1000
22
23
  }
23
24
  }
24
25
  exports.awaitRunningState = awaitRunningState;
25
- // Wait for a job to finish by polling its status: resolves once it succeeded,
26
- // rejects when it failed (its `Failed` condition, i.e. retries are exhausted).
27
- // On abort the job is deleted — with its pods — and an AbortError is thrown, so
28
- // a cancelled or timed-out task leaves nothing running on the cluster.
29
- async function awaitJobCompletion(instance, env, name, abort, pollInterval = 1000) {
30
- for (;;) {
31
- if (abort.aborted) {
32
- await deleteJob(instance, env, name);
33
- throw new abort_1.AbortError();
26
+ async function awaitJobCompletion(instance, env, name, abort, pollInterval = 1000, quota) {
27
+ const wait = quota
28
+ ? new quota_wait_1.QuotaWait(instance, env, {
29
+ subject: `the pod of job ${name}`,
30
+ timeout: quota.timeout,
31
+ onWaiting: quota.onWaiting,
32
+ })
33
+ : null;
34
+ // when the job last had a pod: a refusal before it is not one of the pod it waits for now
35
+ let hadPod = 0;
36
+ let refused = false;
37
+ const tell = (now) => {
38
+ if (now !== refused) {
39
+ refused = now;
40
+ quota?.onRefused?.(now);
34
41
  }
35
- const job = await instance.batchApi.readNamespacedJobStatus({ name, namespace: env.namespace });
36
- const status = job.status;
37
- if (status?.succeeded) {
38
- return;
39
- }
40
- const failed = status?.conditions?.find((c) => c.type === 'Failed' && c.status === 'True');
41
- if (failed) {
42
- throw new Error(`job ${name} failed: ${failed.message ?? failed.reason ?? 'unknown reason'}`);
42
+ };
43
+ try {
44
+ return await pollJob();
45
+ }
46
+ finally {
47
+ tell(false);
48
+ }
49
+ async function pollJob() {
50
+ for (;;) {
51
+ if (abort.aborted) {
52
+ await deleteJob(instance, env, name);
53
+ throw new abort_1.AbortError();
54
+ }
55
+ const job = await instance.batchApi.readNamespacedJobStatus({ name, namespace: env.namespace });
56
+ const status = job.status;
57
+ if (status?.succeeded) {
58
+ return;
59
+ }
60
+ const failed = status?.conditions?.find((c) => c.type === 'Failed' && c.status === 'True');
61
+ if (failed) {
62
+ throw new Error(`job ${name} failed: ${failed.message ?? failed.reason ?? 'unknown reason'}`);
63
+ }
64
+ if (wait) {
65
+ let refusal = null;
66
+ if (status?.active || status?.ready) {
67
+ hadPod = Date.now();
68
+ }
69
+ else {
70
+ // the job controller can't make the pod: no pod to wait on, only its events say why
71
+ refusal = await readJobRefusal(instance, env, name, job, hadPod);
72
+ }
73
+ tell(refusal !== null);
74
+ try {
75
+ await wait.check(refusal);
76
+ }
77
+ catch (e) {
78
+ await deleteJob(instance, env, name);
79
+ throw e;
80
+ }
81
+ }
82
+ await sleep(pollInterval, abort);
43
83
  }
44
- await sleep(pollInterval, abort);
45
84
  }
46
85
  }
47
86
  exports.awaitJobCompletion = awaitJobCompletion;
87
+ // The last `FailedCreate` of the job for its quota after `after`. Events the server may not list
88
+ // leave the wait as it was.
89
+ async function readJobRefusal(instance, env, name, job, after) {
90
+ try {
91
+ const events = await instance.coreApi.listNamespacedEvent({
92
+ namespace: env.namespace,
93
+ fieldSelector: `involvedObject.kind=Job,involvedObject.name=${name},reason=FailedCreate`,
94
+ });
95
+ const uid = job.metadata?.uid;
96
+ const latest = events.items
97
+ .filter((event) => !uid || !event.involvedObject?.uid || event.involvedObject.uid === uid)
98
+ .filter((event) => eventTime(event) > after && (0, quota_wait_1.getQuotaRefusal)(event.message))
99
+ .sort((a, b) => eventTime(b) - eventTime(a))[0];
100
+ return (0, quota_wait_1.getQuotaRefusal)(latest?.message);
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
106
+ function eventTime(event) {
107
+ const at = event.lastTimestamp ?? event.eventTime ?? event.firstTimestamp ?? event.metadata?.creationTimestamp;
108
+ return at ? new Date(at).getTime() : 0;
109
+ }
48
110
  function sleep(ms, abort) {
49
111
  if (abort.aborted) {
50
112
  return Promise.resolve();
@@ -77,6 +139,20 @@ async function deleteJob(instance, env, name) {
77
139
  }
78
140
  }
79
141
  exports.deleteJob = deleteJob;
142
+ // The Deployment says when its ReplicaSet can't make a pod: `ReplicaFailure`, `FailedCreate`.
143
+ function getDeploymentRefusal(deployment) {
144
+ const failure = deployment.status?.conditions?.find((condition) => condition.type === 'ReplicaFailure' && condition.status === 'True');
145
+ return (0, quota_wait_1.getQuotaRefusal)(failure?.message);
146
+ }
147
+ function getDeployQuotaWait(instance, env, name, readiness, now) {
148
+ return new quota_wait_1.QuotaWait(instance, env, {
149
+ subject: readiness.subject ?? name,
150
+ // without a limit of its own it waits as long as the run does
151
+ timeout: readiness.quotaTimeout ?? Number.POSITIVE_INFINITY,
152
+ onWaiting: (text) => readiness.onWaiting?.(text),
153
+ now,
154
+ });
155
+ }
80
156
  // how long a reason that may still pass (an image pull a registry refused for now, a
81
157
  // container the runtime could not create) may last before it fails the service
82
158
  exports.PASSING_FAILURE_MS = 60000;
@@ -96,12 +172,14 @@ async function awaitDeployRunningState(instance, env, name, readiness, pollInter
96
172
  let said;
97
173
  // since when a pod has had a failure that may still pass, by pod
98
174
  const failingSince = new Map();
175
+ const quota = getDeployQuotaWait(instance, env, name, readiness, now);
99
176
  for (;;) {
100
177
  const deployment = await instance.appsApi.readNamespacedDeployment({ name, namespace: env.namespace });
101
178
  // available: ready for the Deployment's minReadySeconds
102
179
  if ((deployment.status?.availableReplicas ?? 0) > 0) {
103
180
  return;
104
181
  }
182
+ await quota.check(getDeploymentRefusal(deployment));
105
183
  const created = deployment.metadata?.creationTimestamp;
106
184
  const listed = await instance.coreApi.listNamespacedPod({
107
185
  namespace: env.namespace,
@@ -163,6 +241,7 @@ async function awaitDeployRollout(instance, env, name, readiness, pollInterval =
163
241
  let runningSince = null;
164
242
  let said;
165
243
  const failingSince = new Map();
244
+ const quota = getDeployQuotaWait(instance, env, name, readiness, now);
166
245
  for (;;) {
167
246
  if (readiness.signal?.aborted) {
168
247
  throw new abort_1.AbortError();
@@ -179,6 +258,7 @@ async function awaitDeployRollout(instance, env, name, readiness, pollInterval =
179
258
  if (stalled && (status?.observedGeneration ?? 0) >= readiness.generation) {
180
259
  throw new Error(`${timeoutMessage}: ${stalled.message ?? 'its rollout made no progress'}`);
181
260
  }
261
+ await quota.check(getDeploymentRefusal(deployment));
182
262
  const listed = await instance.coreApi.listNamespacedPod({
183
263
  namespace: env.namespace,
184
264
  labelSelector: readiness.podSelector,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hasOutputsFlatteningAlike = exports.hasPathsEndingAlike = exports.byDepth = exports.getClaimSubPath = void 0;
3
+ exports.hasOutputsFlatteningAlike = exports.hasPathsEndingAlike = exports.byDepth = exports.getInheritedSourceSubPath = exports.getClaimSubPath = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const path_1 = require("path");
6
6
  const portable_path_1 = require("../planner/utils/portable-path");
@@ -45,6 +45,15 @@ function getClaimSubPath(work, path) {
45
45
  return `${name}-${(0, crypto_1.createHash)('sha256').update(own).digest('hex').slice(0, 12)}`;
46
46
  }
47
47
  exports.getClaimSubPath = getClaimSubPath;
48
+ // Where a src of one of its deps is in the claim of `work`: always with the hash of its
49
+ // path, so it is apart from the paths of the task itself, which getClaimSubPath names
50
+ // without looking at them (they are not part of the task's id, see claimLayout), and from
51
+ // the other srcs of its deps (`package.json` and `core/package.json` of an `npm ci`)
52
+ function getInheritedSourceSubPath(work, path) {
53
+ const name = (0, path_1.basename)(path) || 'root';
54
+ return `${name}-${(0, crypto_1.createHash)('sha256').update((0, portable_path_1.portablePath)(work.data.projectRoot, path)).digest('hex').slice(0, 12)}`;
55
+ }
56
+ exports.getInheritedSourceSubPath = getInheritedSourceSubPath;
48
57
  function byDepth(a, b) {
49
58
  return a.split('/').length - b.split('/').length || (a < b ? -1 : a > b ? 1 : 0);
50
59
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getServiceContainerName = exports.MIN_READY_SECONDS = exports.getPodTemplateHash = exports.POD_ANNOTATION = exports.ROLLOUT_DEADLINE_SECONDS = exports.ensureKubernetesDeploymentExists = exports.DEFINITION_LABEL = void 0;
3
+ exports.getServiceContainerName = exports.MIN_READY_SECONDS = exports.getPodTemplateHash = exports.POD_ANNOTATION = exports.ROLLOUT_DEADLINE_SECONDS = exports.ensureKubernetesDeploymentExists = exports.DEBUG_CONTAINER_RESOURCES = exports.DEFINITION_LABEL = void 0;
4
4
  const service_definition_1 = require("../planner/service-definition");
5
5
  const work_service_1 = require("../planner/work-service");
6
6
  const volumes_1 = require("./volumes");
@@ -17,10 +17,15 @@ const job_placement_1 = require("./job-placement");
17
17
  const network_policy_1 = require("./network-policy");
18
18
  const egress_proxy_1 = require("../network/egress-proxy");
19
19
  const service_rollouts_1 = require("./service-rollouts");
20
+ const quota_wait_1 = require("./quota-wait");
20
21
  // what the service was created from, to tell a changed one
21
22
  exports.DEFINITION_LABEL = 'hammerkit.dev/definition';
22
23
  // how often a starting container is checked: as the liveness probe
23
24
  const STARTUP_PERIOD_SECONDS = 5;
25
+ exports.DEBUG_CONTAINER_RESOURCES = {
26
+ requests: { cpu: '10m', memory: '16Mi' },
27
+ limits: { cpu: '100m', memory: '256Mi' },
28
+ };
24
29
  async function ensureKubernetesDeploymentExists(instance, env, service, persistence, secrets, stateKey,
25
30
  // the needed services by name, and the proxy of a limited network
26
31
  network,
@@ -131,6 +136,9 @@ rollout = {}) {
131
136
  command: ['sleep'],
132
137
  args: ['3600'],
133
138
  volumeMounts: persistence.mounts.map((m) => m.mount),
139
+ // a shell to look at the service's files: without a size of its own it would get
140
+ // the namespace's default, and count as much against its quota as the service
141
+ resources: exports.DEBUG_CONTAINER_RESOURCES,
134
142
  ...(0, job_placement_1.getContainerSecurity)(env),
135
143
  },
136
144
  ],
@@ -149,6 +157,7 @@ rollout = {}) {
149
157
  subject: `service ${service.name}`,
150
158
  onWaiting: (text) => service.status.write('warn', `${service.name} ${text}`),
151
159
  ...(service.data.restarts !== null ? { restarts: service.data.restarts } : {}),
160
+ quotaTimeout: quota_wait_1.QUOTA_TIMEOUT,
152
161
  };
153
162
  if (env.server?.serviceRun) {
154
163
  await rollOut(instance, env, service, deployment, readiness, rollout);
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensurePersistentData = exports.packSource = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = void 0;
3
+ exports.ensurePersistentData = exports.packSource = exports.clearStateFiles = exports.ENSURE_OUTPUT_FILES = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = exports.applyWithinQuota = exports.QUOTA_TIMEOUT = exports.TRANSFER_POD_RESOURCES = void 0;
4
+ const quota_wait_1 = require("./quota-wait");
5
+ Object.defineProperty(exports, "QUOTA_TIMEOUT", { enumerable: true, get: function () { return quota_wait_1.QUOTA_TIMEOUT; } });
4
6
  const volumes_1 = require("./volumes");
5
7
  const apply_1 = require("./apply");
6
8
  const path_1 = require("path");
@@ -8,12 +10,15 @@ const tar_1 = require("../utils/tar");
8
10
  const resources_1 = require("./resources");
9
11
  const await_running_state_1 = require("./await-running-state");
10
12
  const sleep_1 = require("../utils/sleep");
13
+ const abort_1 = require("../executer/abort");
11
14
  const version_1 = require("../version");
12
15
  const log_1 = require("../log");
13
16
  const ensure_kubernetes_persistent_volume_claim_exists_1 = require("./ensure-kubernetes-persistent-volume-claim-exists");
14
17
  const stream_1 = require("stream");
15
18
  const job_placement_1 = require("./job-placement");
16
19
  const assert_item_paths_1 = require("../planner/utils/assert-item-paths");
20
+ const transfer_tools_1 = require("./transfer-tools");
21
+ const network_policy_1 = require("./network-policy");
17
22
  // A previous run that crashed between creating an upload/download pod and its
18
23
  // `finally` cleanup leaves a pod behind under the same deterministic name. apply()
19
24
  // would then patch that stale pod in place — and if it is stuck in a terminal
@@ -42,7 +47,41 @@ async function removeStalePod(instance, namespace, name) {
42
47
  await (0, sleep_1.sleep)(500);
43
48
  }
44
49
  }
45
- async function getPodForPersistence(instance, env, service, persistence, type, fn) {
50
+ // What the pod that copies files into and out of a claim gets: tar and find, through
51
+ // exec. Without its own, the default limit of the namespace is taken, which is sized for
52
+ // tasks (4Gi on a server), and a run's quota then has no room for the pods of its tasks.
53
+ exports.TRANSFER_POD_RESOURCES = {
54
+ requests: { cpu: '50m', memory: '64Mi' },
55
+ limits: { memory: '512Mi' },
56
+ };
57
+ // A Job waits for room under a full quota, a pod is refused: so a transfer pod is
58
+ // created again until the pods of the tasks it runs beside are done and make room
59
+ async function applyWithinQuota(instance, podSpec, service, timeout = quota_wait_1.QUOTA_TIMEOUT, pollInterval = 2000,
60
+ // a run stopped while it waits: it stops waiting
61
+ signal) {
62
+ const deadline = Date.now() + timeout;
63
+ for (let waiting = false;; waiting = true) {
64
+ if (signal) {
65
+ (0, abort_1.checkForAbort)(signal);
66
+ }
67
+ try {
68
+ return await (0, apply_1.apply)(instance, podSpec);
69
+ }
70
+ catch (e) {
71
+ if ((0, apply_1.statusCodeOf)(e) !== 403 || !/exceeded quota/i.test((0, log_1.getErrorMessage)(e)) || Date.now() >= deadline) {
72
+ throw e;
73
+ }
74
+ if (!waiting) {
75
+ service.status.write('info', `wait for room under the quota of ${podSpec.metadata.namespace}`);
76
+ }
77
+ await (0, sleep_1.sleep)(pollInterval);
78
+ }
79
+ }
80
+ }
81
+ exports.applyWithinQuota = applyWithinQuota;
82
+ async function getPodForPersistence(instance, env, service, persistence, type,
83
+ // stops a wait for room under the quota
84
+ signal, fn) {
46
85
  if (persistence.volumes.length === 0) {
47
86
  return;
48
87
  }
@@ -50,7 +89,11 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
50
89
  // and takes no upload
51
90
  const own = persistence.mounts.filter((m) => !m.workspace);
52
91
  const mounts = type === 'read'
53
- ? own.map((m) => m.mount)
92
+ ? // what a task stores are its outputs, which it mounts writable: its src and the
93
+ // outputs of its deps are not mounted, so an output inside a folder of its src
94
+ // (pkg/coverage/lcov.info) has a place in the pod even when the claim holds no src,
95
+ // after a restore into a new claim
96
+ own.filter((m) => service.data.type !== 'container-task' || !m.mount.readOnly).map((m) => m.mount)
54
97
  : own.reduce((array, v) => {
55
98
  if (!array.some((i) => i.name === v.mount.name)) {
56
99
  array.push({
@@ -61,11 +104,19 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
61
104
  }
62
105
  return array;
63
106
  }, []);
107
+ // its tools are in a folder of their own, which no output may be in or over: it would
108
+ // replace them with what the task wrote
109
+ const overTools = mounts.find((mount) => (0, transfer_tools_1.isTransferToolsPath)(mount.mountPath));
110
+ if (overTools) {
111
+ throw new Error(`${service.name}: an output can not be at ${overTools.mountPath}, ${transfer_tools_1.TRANSFER_TOOLS_PATH} is the folder of hammerkit's tools`);
112
+ }
113
+ // only the claims it mounts: one of a dep it doesn't read would only bind where it goes
114
+ const volumes = persistence.volumes.filter((volume) => mounts.some((mount) => mount.name === volume.name));
64
115
  // Guarantee the claims exist right before scheduling the pod that mounts
65
116
  // them. ensurePersistentData also creates them, but store/restore reach this
66
117
  // function directly, and a claim shared with another work item can be removed
67
118
  // concurrently — without this the pod would hang Pending on "pvc not found".
68
- for (const volume of persistence.volumes) {
119
+ for (const volume of volumes) {
69
120
  await (0, ensure_kubernetes_persistent_volume_claim_exists_1.ensureKubernetesPersistentVolumeClaimExists)(instance, env, volume, service, persistence.sizes[volume.name], persistence.kept.includes(volume.name));
70
121
  }
71
122
  const name = (0, resources_1.getResourceName)(service, env, type === 'write' ? '-upload' : '-download');
@@ -73,14 +124,19 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
73
124
  // commit): the pod is not one its Service sends to
74
125
  const serving = !!env.server?.serviceRun && service.data.type === 'container-service';
75
126
  // and on a service run, it goes where the pods that mount the same claims run
76
- const claims = env.server?.serviceRun ? (0, volumes_1.getClaimPodSpec)(persistence.volumes) : { labels: {} };
127
+ const claims = env.server?.serviceRun ? (0, volumes_1.getClaimPodSpec)(volumes) : { labels: {} };
77
128
  const podSpec = {
78
129
  kind: 'Pod',
79
130
  apiVersion: 'v1',
80
131
  metadata: {
81
132
  namespace: env.namespace,
82
133
  name,
83
- labels: { ...(serving ? (0, job_placement_1.getRunLabels)(env) : (0, resources_1.getItemLabels)(service, env)), ...claims.labels },
134
+ labels: {
135
+ ...(serving ? (0, job_placement_1.getRunLabels)(env) : (0, resources_1.getItemLabels)(service, env)),
136
+ ...claims.labels,
137
+ // on a server it reaches nothing and nothing reaches it (see getNamespacePolicies)
138
+ ...(env.server ? (0, network_policy_1.getTransferNetworkLabels)() : {}),
139
+ },
84
140
  annotations: {
85
141
  'hammerkit.dev/version': (0, version_1.getVersion)(),
86
142
  },
@@ -95,22 +151,25 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
95
151
  ...(0, job_placement_1.getPodPlacement)(env.server, 'pool' in service.data ? service.data.pool : undefined),
96
152
  }
97
153
  : {}),
154
+ initContainers: [(0, transfer_tools_1.getTransferToolsInitContainer)()],
98
155
  containers: [
99
156
  {
100
157
  name: 'volume',
101
- image: 'alpine',
102
- command: ['sh'],
158
+ image: transfer_tools_1.HELPER_TOOLS_IMAGE,
159
+ command: (0, transfer_tools_1.inTransferPod)(['sh']),
103
160
  tty: true,
104
- volumeMounts: mounts,
161
+ env: transfer_tools_1.TRANSFER_TOOLS_ENV,
162
+ volumeMounts: [...mounts, transfer_tools_1.TRANSFER_TOOLS_MOUNT],
163
+ resources: exports.TRANSFER_POD_RESOURCES,
105
164
  ...(0, job_placement_1.getContainerSecurity)(env),
106
165
  },
107
166
  ],
108
- volumes: persistence.volumes,
167
+ volumes: [...volumes, ...transfer_tools_1.TRANSFER_TOOLS_VOLUMES],
109
168
  },
110
169
  };
111
170
  service.status.write('debug', `create pod ${name}`);
112
171
  await removeStalePod(instance, env.namespace, name);
113
- const pod = await (0, apply_1.apply)(instance, podSpec);
172
+ const pod = await applyWithinQuota(instance, podSpec, service, quota_wait_1.QUOTA_TIMEOUT, 2000, signal);
114
173
  if (pod.status?.phase !== 'Running') {
115
174
  service.status.write('debug', `await running state ${name}`);
116
175
  await (0, await_running_state_1.awaitRunningState)(instance, env, name, 'Running');
@@ -150,7 +209,7 @@ exports.clearClaim = clearClaim;
150
209
  // Runs `command` in the upload pod `pod`: what failed, or null when it went well
151
210
  async function execInPod(instance, env, pod, command) {
152
211
  let failure = null;
153
- const res = await instance.exec.exec(env.namespace, pod, 'volume', command, process.stdout, process.stderr, null, false, (status) => {
212
+ const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(command), process.stdout, process.stderr, null, false, (status) => {
154
213
  if (status.status !== 'Success') {
155
214
  failure = status.message ?? status.reason ?? 'unknown';
156
215
  }
@@ -273,7 +332,7 @@ exports.syncLiveFiles = syncLiveFiles;
273
332
  // its files mounts them from: a move that did not get up leaves the service at the commit
274
333
  // it was at
275
334
  async function restoreLiveFiles(instance, env, work, persistence, from) {
276
- await getPodForPersistence(instance, env, work, persistence, 'write', (pod) => syncLiveFiles(instance, env, work, persistence, pod, from));
335
+ await getPodForPersistence(instance, env, work, persistence, 'write', undefined, (pod) => syncLiveFiles(instance, env, work, persistence, pod, from));
277
336
  }
278
337
  exports.restoreLiveFiles = restoreLiveFiles;
279
338
  // Prepares the folder of a state in the claim of a work item of a service run before its
@@ -282,6 +341,58 @@ exports.restoreLiveFiles = restoreLiveFiles;
282
341
  // Returns whether the upload is needed.
283
342
  async function prepareStateFiles(instance, env, work, pod, dir, inUse) {
284
343
  const targetPath = `/dev/hammerkit/${work.id()}`;
344
+ await removeOtherStates(instance, env, pod, targetPath, dir, inUse);
345
+ if (inUse.has(dir) && !(await execInPod(instance, env, pod, ['test', '-e', `${targetPath}/${dir}/${UPLOADED}`]))) {
346
+ work.status.write('info', `the files of ${work.name} are there already`);
347
+ return false;
348
+ }
349
+ await clearStateDir(instance, env, pod, `${targetPath}/${dir}`);
350
+ return true;
351
+ }
352
+ // Makes each of `files` (paths in the claim of `work`, see KubernetesPersistence.files) an
353
+ // empty file unless it is one: Kubernetes would make a directory of a subPath that isn't
354
+ // there, and the task could not write the file. A directory there is what an earlier
355
+ // version left in a kept claim, and goes. A path ending in `/` is made a folder.
356
+ exports.ENSURE_OUTPUT_FILES = `cd "$1" || exit 1
357
+ shift
358
+ for f; do
359
+ case "$f" in */) mkdir -p "$f" || exit 1; continue ;; esac
360
+ if [ -d "$f" ] && [ ! -L "$f" ]; then rm -rf "$f" || exit 1; fi
361
+ if [ ! -e "$f" ] && [ ! -L "$f" ]; then mkdir -p "$(dirname "$f")" && : > "$f" || exit 1; fi
362
+ done`;
363
+ async function ensureOutputFiles(instance, env, work, pod, files) {
364
+ if (files.length === 0) {
365
+ return;
366
+ }
367
+ const made = await execInPod(instance, env, pod, [
368
+ 'sh',
369
+ '-c',
370
+ exports.ENSURE_OUTPUT_FILES,
371
+ 'sh',
372
+ `/dev/hammerkit/${work.id()}`,
373
+ ...files,
374
+ ]);
375
+ if (made) {
376
+ throw new Error(`unable to make the output files ${files.join(', ')} of ${work.name}: ${made}`);
377
+ }
378
+ }
379
+ // what a failed upload, restore or task left: tar does not remove files the commit does not have
380
+ async function clearStateDir(instance, env, pod, path) {
381
+ const cleared = await execInPod(instance, env, pod, ['rm', '-rf', path]);
382
+ if (cleared) {
383
+ throw new Error(`unable to clear ${path}: ${cleared}`);
384
+ }
385
+ }
386
+ // Before a restore of a service run into the folder `dir` of the claim of `work` (in its upload
387
+ // pod `pod`): the folders of the other states go but those of `inUse`, which pods of the run
388
+ // mount, and `dir` is emptied. A claim that took only restores holds one state, as after a Job.
389
+ async function clearStateFiles(instance, env, work, pod, dir, inUse) {
390
+ const targetPath = `/dev/hammerkit/${work.id()}`;
391
+ await removeOtherStates(instance, env, pod, targetPath, dir, inUse);
392
+ await clearStateDir(instance, env, pod, `${targetPath}/${dir}`);
393
+ }
394
+ exports.clearStateFiles = clearStateFiles;
395
+ async function removeOtherStates(instance, env, pod, targetPath, dir, inUse) {
285
396
  const removed = await execInPod(instance, env, pod, [
286
397
  'sh',
287
398
  '-c',
@@ -294,16 +405,6 @@ async function prepareStateFiles(instance, env, work, pod, dir, inUse) {
294
405
  if (removed) {
295
406
  throw new Error(`unable to remove the files of other commits in ${targetPath}: ${removed}`);
296
407
  }
297
- if (inUse.has(dir) && !(await execInPod(instance, env, pod, ['test', '-e', `${targetPath}/${dir}/${UPLOADED}`]))) {
298
- work.status.write('info', `the files of ${work.name} are there already`);
299
- return false;
300
- }
301
- // what a failed upload or task left: tar does not remove files the commit does not have
302
- const cleared = await execInPod(instance, env, pod, ['rm', '-rf', `${targetPath}/${dir}`]);
303
- if (cleared) {
304
- throw new Error(`unable to clear ${targetPath}/${dir}: ${cleared}`);
305
- }
306
- return true;
307
408
  }
308
409
  // The archive that uploads a source into the claim: its file or directory, at its place in
309
410
  // the claim (see getClaimSubPath) instead of under its own name
@@ -343,7 +444,7 @@ options = {}) {
343
444
  const files = persistence.volumes.some((volume) => volume.persistentVolumeClaim?.claimName === claim)
344
445
  ? options.files
345
446
  : undefined;
346
- if (persistence.sources.length === 0 && !options.reset && !files) {
447
+ if (persistence.sources.length === 0 && persistence.files.length === 0 && !options.reset && !files) {
347
448
  return;
348
449
  }
349
450
  // the folders of the states the pods of the run mount, before the upload pod mounts the claim
@@ -352,7 +453,8 @@ options = {}) {
352
453
  inUse.add(dir);
353
454
  }
354
455
  service.status.write('debug', 'start upload container');
355
- await getPodForPersistence(instance, env, service, persistence, 'write', async (name) => {
456
+ const { signal } = environment.abortCtrl;
457
+ await getPodForPersistence(instance, env, service, persistence, 'write', signal, async (name) => {
356
458
  if (options.reset) {
357
459
  await clearClaim(instance, env, service, name);
358
460
  }
@@ -370,7 +472,7 @@ options = {}) {
370
472
  const data = packSource(source);
371
473
  service.status.write('info', `upload ${source.localPath}`);
372
474
  const targetPath = `/dev/hammerkit/${service.id()}`;
373
- const res = await instance.exec.exec(env.namespace, name, 'volume', ['tar', 'xf', '-', '-C', targetPath], process.stdout, process.stderr, data, false, (status) => {
475
+ const res = await instance.exec.exec(env.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)(['tar', 'xf', '-', '-C', targetPath]), process.stdout, process.stderr, data, false, (status) => {
374
476
  service.status.write('debug', `upload ${source.localPath} to ${name}: ${status}`);
375
477
  });
376
478
  await new Promise((resolve, reject) => {
@@ -392,6 +494,7 @@ options = {}) {
392
494
  }
393
495
  });
394
496
  }
497
+ await ensureOutputFiles(instance, env, service, name, persistence.files);
395
498
  if (files) {
396
499
  const dir = `/dev/hammerkit/${service.id()}/${files.dir}`;
397
500
  const marked = await execInPod(instance, env, name, [