hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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");
7
+ const crypto_1 = require("crypto");
7
8
  const service_hostname_1 = require("../planner/utils/service-hostname");
8
9
  const apply_1 = require("./apply");
9
10
  const version_1 = require("../version");
@@ -15,11 +16,22 @@ const container_resources_1 = require("./container-resources");
15
16
  const job_placement_1 = require("./job-placement");
16
17
  const network_policy_1 = require("./network-policy");
17
18
  const egress_proxy_1 = require("../network/egress-proxy");
19
+ const service_rollouts_1 = require("./service-rollouts");
20
+ const quota_wait_1 = require("./quota-wait");
18
21
  // what the service was created from, to tell a changed one
19
22
  exports.DEFINITION_LABEL = 'hammerkit.dev/definition';
23
+ // how often a starting container is checked: as the liveness probe
24
+ const STARTUP_PERIOD_SECONDS = 5;
25
+ exports.DEBUG_CONTAINER_RESOURCES = {
26
+ requests: { cpu: '10m', memory: '16Mi' },
27
+ limits: { cpu: '100m', memory: '256Mi' },
28
+ };
20
29
  async function ensureKubernetesDeploymentExists(instance, env, service, persistence, secrets, stateKey,
21
30
  // the needed services by name, and the proxy of a limited network
22
- network) {
31
+ network,
32
+ // a service run (env.server.serviceRun): the Deployment the service has now, put back when
33
+ // the new one does not get ready, and what stops the wait for it
34
+ rollout = {}) {
23
35
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(service.data.envs);
24
36
  const name = (0, resources_1.getResourceName)(service, env);
25
37
  const healthcheckCommand = (0, work_service_1.getHealthcheckCommand)(service.data);
@@ -34,6 +46,16 @@ network) {
34
46
  failureThreshold: 3,
35
47
  }
36
48
  : undefined;
49
+ // the healthcheck's `timeout` for each start: until it passed once, the liveness probe
50
+ // doesn't kill a container that starts slowly, and the wait fails it with the timeout
51
+ const startupProbe = probe && service.data.healthcheck
52
+ ? {
53
+ ...probe,
54
+ // a check more than the timeout holds, and one more for the first check's offset: the
55
+ // wait fails it with the timeout before the kubelet restarts it
56
+ failureThreshold: Math.ceil(service.data.healthcheck.timeout / (STARTUP_PERIOD_SECONDS * 1000)) + 2,
57
+ }
58
+ : undefined;
37
59
  const server = env.server;
38
60
  const placement = server ? (0, job_placement_1.getPodPlacement)(server, undefined) : null;
39
61
  const workspace = (0, volumes_1.getWorkspacePodSpec)(env, persistence);
@@ -57,6 +79,9 @@ network) {
57
79
  matchLabels: (0, resources_1.getItemLabels)(service, env),
58
80
  },
59
81
  replicas: 1,
82
+ // without a healthcheck a pod is ready as soon as its container runs, also one that
83
+ // exits a second later: it counts once it ran this long without a restart
84
+ minReadySeconds: probe ? 0 : exports.MIN_READY_SECONDS,
60
85
  template: {
61
86
  metadata: {
62
87
  labels: {
@@ -83,7 +108,7 @@ network) {
83
108
  : {}),
84
109
  containers: [
85
110
  {
86
- name: service.name.replace(/:/, '-'),
111
+ name: getServiceContainerName(service),
87
112
  image: service.data.image,
88
113
  workingDir: (0, work_service_1.getServiceWorkingDir)(service.data),
89
114
  env: [
@@ -100,6 +125,7 @@ network) {
100
125
  })),
101
126
  readinessProbe: probe,
102
127
  livenessProbe: probe,
128
+ startupProbe,
103
129
  ...(0, container_resources_1.getKubernetesResources)(service.data.resources),
104
130
  volumeMounts: [...persistence.mounts.map((m) => m.mount), ...secrets.mounts],
105
131
  ...(0, job_placement_1.getContainerSecurity)(env),
@@ -110,6 +136,9 @@ network) {
110
136
  command: ['sleep'],
111
137
  args: ['3600'],
112
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,
113
142
  ...(0, job_placement_1.getContainerSecurity)(env),
114
143
  },
115
144
  ],
@@ -118,19 +147,123 @@ network) {
118
147
  },
119
148
  },
120
149
  };
121
- const deploy = await (0, apply_1.apply)(instance, deployment);
122
- if (deploy.status?.readyReplicas ?? 0 > 0) {
123
- return;
124
- }
125
- await (0, await_running_state_1.awaitDeployRunningState)(instance, env, name, {
150
+ const readiness = {
126
151
  podSelector: (0, resources_1.getItemSelector)(service, env),
127
152
  timeout: service.data.healthcheck?.timeout ?? null,
128
153
  timeoutMessage: service.data.healthcheck
129
154
  ? (0, work_healthcheck_1.getHealthcheckTimeoutMessage)(service.name, service.data.healthcheck)
130
155
  : '',
131
- });
156
+ container: getServiceContainerName(service),
157
+ subject: `service ${service.name}`,
158
+ onWaiting: (text) => service.status.write('warn', `${service.name} ${text}`),
159
+ ...(service.data.restarts !== null ? { restarts: service.data.restarts } : {}),
160
+ quotaTimeout: quota_wait_1.QUOTA_TIMEOUT,
161
+ };
162
+ if (env.server?.serviceRun) {
163
+ await rollOut(instance, env, service, deployment, readiness, rollout);
164
+ return;
165
+ }
166
+ const deploy = await (0, apply_1.apply)(instance, deployment);
167
+ if ((deploy.status?.availableReplicas ?? 0) > 0) {
168
+ return;
169
+ }
170
+ await (0, await_running_state_1.awaitDeployRunningState)(instance, env, name, readiness);
132
171
  }
133
172
  exports.ensureKubernetesDeploymentExists = ensureKubernetesDeploymentExists;
173
+ // how long the pods of a rolled service may take to get ready, as Kubernetes counts it
174
+ exports.ROLLOUT_DEADLINE_SECONDS = 600;
175
+ /**
176
+ * The Deployment of a service of a service run, which keeps it from one commit to the next:
177
+ * replaced as a whole (a merge would keep what the new one dropped, such as a variable) and
178
+ * rolled. Its requests go to the pods it has until a new one is ready. A service with
179
+ * volumes of its own stops first: two pods would write the same data. The new pod is asked
180
+ * to go where the old one runs (getClaimPodSpec), whose claims are usually attached to one
181
+ * node at a time. When the execution ends before all its services are up, the worker puts
182
+ * every Deployment it rolled back as it was (serviceRollouts).
183
+ */
184
+ async function rollOut(instance, env, service, deployment, readiness, rollout) {
185
+ const spec = deployment.spec;
186
+ const template = spec.template;
187
+ const definition = (0, service_definition_1.getServiceDefinitionHash)(service);
188
+ const stateKey = template.metadata?.labels?.['hammerkit.dev/state'] ?? '';
189
+ const ownVolumes = service.data.volumes.some((volume) => !volume.inherited);
190
+ spec.strategy = ownVolumes
191
+ ? { type: 'Recreate' }
192
+ : { type: 'RollingUpdate', rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } };
193
+ spec.progressDeadlineSeconds = exports.ROLLOUT_DEADLINE_SECONDS;
194
+ // the pods of this definition and state, apart from the ones it rolls from
195
+ template.metadata = {
196
+ ...template.metadata,
197
+ labels: { ...template.metadata?.labels, [exports.DEFINITION_LABEL]: definition },
198
+ };
199
+ const pod = getPodTemplateHash(template, service.data.projectRoot);
200
+ deployment.metadata.annotations = { ...deployment.metadata.annotations, [exports.POD_ANNOTATION]: pod };
201
+ const previous = rollout.previous;
202
+ if (previous &&
203
+ previous.metadata?.annotations?.[exports.POD_ANNOTATION] === pod &&
204
+ previous.metadata?.labels?.[exports.DEFINITION_LABEL] === definition &&
205
+ isAvailable(previous)) {
206
+ // its pod would be the same but for the state it runs at: a service that watches its
207
+ // files has them already (syncLiveFiles), and its pod stays
208
+ service_rollouts_1.serviceRollouts.add(env.namespace, deployment.metadata.name, previous);
209
+ await relabelDeployment(instance, env.namespace, deployment.metadata.name, stateKey);
210
+ service.status.write('info', `${service.name} watches its files, it got the changed ones and stays up`);
211
+ // it goes on running with them: else the move does not get up, and gets them back
212
+ await (0, await_running_state_1.watchKeptPods)(instance, env, deployment.metadata.name, { ...readiness, signal: rollout.signal });
213
+ return;
214
+ }
215
+ // put back, or removed, by the worker when the execution ends before its services are up
216
+ service_rollouts_1.serviceRollouts.add(env.namespace, deployment.metadata.name, rollout.previous);
217
+ const applied = await (0, apply_1.replaceDeployment)(instance, deployment);
218
+ if (rollout.previous) {
219
+ service.status.write('info', `${service.name} changed, its new pod takes over once it is ready`);
220
+ }
221
+ await (0, await_running_state_1.awaitDeployRollout)(instance, env, deployment.metadata.name, {
222
+ ...readiness,
223
+ podSelector: `${readiness.podSelector},hammerkit.dev/state=${stateKey},${exports.DEFINITION_LABEL}=${definition}`,
224
+ generation: applied.metadata?.generation ?? 0,
225
+ signal: rollout.signal,
226
+ });
227
+ }
228
+ // the pod a Deployment of a service run makes, but for the state it runs at
229
+ exports.POD_ANNOTATION = 'hammerkit.dev/pod';
230
+ // A move executes from a checkout of its own (`root`), which the pod's paths name: where the
231
+ // checkout is does not count, as for getServiceDefinitionHash
232
+ function getPodTemplateHash(template, root) {
233
+ const labels = { ...template.metadata?.labels };
234
+ delete labels['hammerkit.dev/state'];
235
+ const json = JSON.stringify({ ...template, metadata: { ...template.metadata, labels } });
236
+ const escaped = root ? JSON.stringify(root).slice(1, -1) : '';
237
+ return (0, crypto_1.createHash)('sha256')
238
+ .update(escaped ? json.split(escaped).join('<checkout>') : json)
239
+ .digest('hex')
240
+ .slice(0, 32);
241
+ }
242
+ exports.getPodTemplateHash = getPodTemplateHash;
243
+ // a Deployment whose pods are all of its template and ready
244
+ function isAvailable(deployment) {
245
+ const status = deployment.status;
246
+ return (!deployment.metadata?.deletionTimestamp &&
247
+ (status?.observedGeneration ?? 0) >= (deployment.metadata?.generation ?? 0) &&
248
+ (status?.updatedReplicas ?? 0) >= 1 &&
249
+ (status?.availableReplicas ?? 0) >= 1 &&
250
+ (status?.replicas ?? 0) === (status?.updatedReplicas ?? 0));
251
+ }
252
+ // The Deployment runs at the state `stateKey` now: its template, and so its pods, stay
253
+ async function relabelDeployment(instance, namespace, name, stateKey) {
254
+ await instance.appsApi.patchNamespacedDeployment({
255
+ name,
256
+ namespace,
257
+ body: [{ op: 'add', path: '/metadata/labels/hammerkit.dev~1state', value: stateKey }],
258
+ });
259
+ }
260
+ // how long the container of a service without a healthcheck has to run before it counts as up
261
+ exports.MIN_READY_SECONDS = 10;
262
+ // The container of a service's pod that runs its command, beside the `debug` one.
263
+ function getServiceContainerName(service) {
264
+ return service.name.replace(/:/, '-');
265
+ }
266
+ exports.getServiceContainerName = getServiceContainerName;
134
267
  // Kubernetes `command` replaces the image entrypoint and `args` its command.
135
268
  // A shell service sets both; an exec-form `cmd` keeps the established mapping
136
269
  // (first token as `command`, the rest as `args`).
@@ -28,7 +28,9 @@ async function ensureKubernetesServiceExists(instance, env, service) {
28
28
  ...(headless
29
29
  ? {}
30
30
  : {
31
+ // a Service of more than one port needs a name for each
31
32
  ports: service.data.ports.map((port) => ({
33
+ name: `tcp-${port.hostPort ?? port.containerPort}`,
32
34
  port: port.hostPort ?? port.containerPort,
33
35
  targetPort: port.containerPort,
34
36
  })),
@@ -1,12 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensurePersistentData = exports.packSource = 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; } });
6
+ const volumes_1 = require("./volumes");
4
7
  const apply_1 = require("./apply");
5
8
  const path_1 = require("path");
6
9
  const tar_1 = require("../utils/tar");
7
10
  const resources_1 = require("./resources");
8
11
  const await_running_state_1 = require("./await-running-state");
9
12
  const sleep_1 = require("../utils/sleep");
13
+ const abort_1 = require("../executer/abort");
10
14
  const version_1 = require("../version");
11
15
  const log_1 = require("../log");
12
16
  const ensure_kubernetes_persistent_volume_claim_exists_1 = require("./ensure-kubernetes-persistent-volume-claim-exists");
@@ -41,7 +45,41 @@ async function removeStalePod(instance, namespace, name) {
41
45
  await (0, sleep_1.sleep)(500);
42
46
  }
43
47
  }
44
- async function getPodForPersistence(instance, env, service, persistence, type, fn) {
48
+ // What the pod that copies files into and out of a claim gets: tar and find, through
49
+ // exec. Without its own, the default limit of the namespace is taken, which is sized for
50
+ // tasks (4Gi on a server), and a run's quota then has no room for the pods of its tasks.
51
+ exports.TRANSFER_POD_RESOURCES = {
52
+ requests: { cpu: '50m', memory: '64Mi' },
53
+ limits: { memory: '512Mi' },
54
+ };
55
+ // A Job waits for room under a full quota, a pod is refused: so a transfer pod is
56
+ // created again until the pods of the tasks it runs beside are done and make room
57
+ async function applyWithinQuota(instance, podSpec, service, timeout = quota_wait_1.QUOTA_TIMEOUT, pollInterval = 2000,
58
+ // a run stopped while it waits: it stops waiting
59
+ signal) {
60
+ const deadline = Date.now() + timeout;
61
+ for (let waiting = false;; waiting = true) {
62
+ if (signal) {
63
+ (0, abort_1.checkForAbort)(signal);
64
+ }
65
+ try {
66
+ return await (0, apply_1.apply)(instance, podSpec);
67
+ }
68
+ catch (e) {
69
+ if ((0, apply_1.statusCodeOf)(e) !== 403 || !/exceeded quota/i.test((0, log_1.getErrorMessage)(e)) || Date.now() >= deadline) {
70
+ throw e;
71
+ }
72
+ if (!waiting) {
73
+ service.status.write('info', `wait for room under the quota of ${podSpec.metadata.namespace}`);
74
+ }
75
+ await (0, sleep_1.sleep)(pollInterval);
76
+ }
77
+ }
78
+ }
79
+ exports.applyWithinQuota = applyWithinQuota;
80
+ async function getPodForPersistence(instance, env, service, persistence, type,
81
+ // stops a wait for room under the quota
82
+ signal, fn) {
45
83
  if (persistence.volumes.length === 0) {
46
84
  return;
47
85
  }
@@ -49,7 +87,11 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
49
87
  // and takes no upload
50
88
  const own = persistence.mounts.filter((m) => !m.workspace);
51
89
  const mounts = type === 'read'
52
- ? own.map((m) => m.mount)
90
+ ? // what a task stores are its outputs, which it mounts writable: its src and the
91
+ // outputs of its deps are not mounted, so an output inside a folder of its src
92
+ // (pkg/coverage/lcov.info) has a place in the pod even when the claim holds no src,
93
+ // after a restore into a new claim
94
+ own.filter((m) => service.data.type !== 'container-task' || !m.mount.readOnly).map((m) => m.mount)
53
95
  : own.reduce((array, v) => {
54
96
  if (!array.some((i) => i.name === v.mount.name)) {
55
97
  array.push({
@@ -60,26 +102,34 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
60
102
  }
61
103
  return array;
62
104
  }, []);
105
+ // only the claims it mounts: one of a dep it doesn't read would only bind where it goes
106
+ const volumes = persistence.volumes.filter((volume) => mounts.some((mount) => mount.name === volume.name));
63
107
  // Guarantee the claims exist right before scheduling the pod that mounts
64
108
  // them. ensurePersistentData also creates them, but store/restore reach this
65
109
  // function directly, and a claim shared with another work item can be removed
66
110
  // concurrently — without this the pod would hang Pending on "pvc not found".
67
- for (const volume of persistence.volumes) {
111
+ for (const volume of volumes) {
68
112
  await (0, ensure_kubernetes_persistent_volume_claim_exists_1.ensureKubernetesPersistentVolumeClaimExists)(instance, env, volume, service, persistence.sizes[volume.name], persistence.kept.includes(volume.name));
69
113
  }
70
114
  const name = (0, resources_1.getResourceName)(service, env, type === 'write' ? '-upload' : '-download');
115
+ // a service of a service run is up while its claim takes an upload (a move to another
116
+ // commit): the pod is not one its Service sends to
117
+ const serving = !!env.server?.serviceRun && service.data.type === 'container-service';
118
+ // and on a service run, it goes where the pods that mount the same claims run
119
+ const claims = env.server?.serviceRun ? (0, volumes_1.getClaimPodSpec)(volumes) : { labels: {} };
71
120
  const podSpec = {
72
121
  kind: 'Pod',
73
122
  apiVersion: 'v1',
74
123
  metadata: {
75
124
  namespace: env.namespace,
76
125
  name,
77
- labels: (0, resources_1.getItemLabels)(service, env),
126
+ labels: { ...(serving ? (0, job_placement_1.getRunLabels)(env) : (0, resources_1.getItemLabels)(service, env)), ...claims.labels },
78
127
  annotations: {
79
128
  'hammerkit.dev/version': (0, version_1.getVersion)(),
80
129
  },
81
130
  },
82
131
  spec: {
132
+ ...(claims.affinity ? { affinity: claims.affinity } : {}),
83
133
  // on a server the claims are bound where the pod of the task can go: the nodes
84
134
  // of its pool
85
135
  ...(env.server
@@ -95,15 +145,16 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
95
145
  command: ['sh'],
96
146
  tty: true,
97
147
  volumeMounts: mounts,
148
+ resources: exports.TRANSFER_POD_RESOURCES,
98
149
  ...(0, job_placement_1.getContainerSecurity)(env),
99
150
  },
100
151
  ],
101
- volumes: persistence.volumes,
152
+ volumes,
102
153
  },
103
154
  };
104
155
  service.status.write('debug', `create pod ${name}`);
105
156
  await removeStalePod(instance, env.namespace, name);
106
- const pod = await (0, apply_1.apply)(instance, podSpec);
157
+ const pod = await applyWithinQuota(instance, podSpec, service, quota_wait_1.QUOTA_TIMEOUT, 2000, signal);
107
158
  if (pod.status?.phase !== 'Running') {
108
159
  service.status.write('debug', `await running state ${name}`);
109
160
  await (0, await_running_state_1.awaitRunningState)(instance, env, name, 'Running');
@@ -122,18 +173,224 @@ exports.getPodForPersistence = getPodForPersistence;
122
173
  async function clearClaim(instance, env, work, pod) {
123
174
  const targetPath = `/dev/hammerkit/${work.id()}`;
124
175
  work.status.write('info', `clear what an earlier run left in ${targetPath}`);
176
+ const failure = await execInPod(instance, env, pod, [
177
+ 'find',
178
+ targetPath,
179
+ '-mindepth',
180
+ '1',
181
+ '-maxdepth',
182
+ '1',
183
+ '-exec',
184
+ 'rm',
185
+ '-rf',
186
+ '{}',
187
+ '+',
188
+ ]);
189
+ if (failure) {
190
+ throw new Error(`unable to clear ${targetPath} in ${pod}: ${failure}`);
191
+ }
192
+ }
193
+ exports.clearClaim = clearClaim;
194
+ // Runs `command` in the upload pod `pod`: what failed, or null when it went well
195
+ async function execInPod(instance, env, pod, command) {
125
196
  let failure = null;
126
- const res = await instance.exec.exec(env.namespace, pod, 'volume', ['find', targetPath, '-mindepth', '1', '-maxdepth', '1', '-exec', 'rm', '-rf', '{}', '+'], process.stdout, process.stderr, null, false, (status) => {
197
+ const res = await instance.exec.exec(env.namespace, pod, 'volume', command, process.stdout, process.stderr, null, false, (status) => {
127
198
  if (status.status !== 'Success') {
128
199
  failure = status.message ?? status.reason ?? 'unknown';
129
200
  }
130
201
  });
131
202
  await new Promise((resolve, reject) => {
132
203
  res.on('error', reject);
133
- res.on('close', () => failure ? reject(new Error(`unable to clear ${targetPath} in ${pod}: ${failure}`)) : resolve());
204
+ res.on('close', () => resolve());
134
205
  });
206
+ return failure;
207
+ }
208
+ exports.execInPod = execInPod;
209
+ // marks the folder of a state whose upload went through
210
+ const UPLOADED = '.uploaded';
211
+ // Removes the folders of the states (see getStateFilesDir) in the claim at `$1` but those
212
+ // named after it: the one the work runs at, and the ones pods of the run mount
213
+ // (it says how it went itself: a loop ends with the status of its last test in some shells)
214
+ exports.REMOVE_OTHER_STATES = `cd "$1" || exit 1
215
+ shift
216
+ for d in ${volumes_1.STATE_FILES_PREFIX}*; do
217
+ if [ ! -d "$d" ]; then continue; fi
218
+ keep=
219
+ for k in "$@"; do
220
+ if [ "$d" = "$k" ]; then keep=1; fi
221
+ done
222
+ if [ -z "$keep" ]; then rm -rf "$d" || exit 1; fi
223
+ done
224
+ exit 0`;
225
+ /**
226
+ * The folders of the states (see getStateFilesDir) of the claim `claim` that the services of
227
+ * the run mount: the pods of its Deployments, which serve or start. A pod of a service mounts
228
+ * the outputs of a task only after the task completed, so what it mounts is whole.
229
+ */
230
+ async function getStateDirsInUse(instance, namespace, claim) {
231
+ const pods = await instance.coreApi.listNamespacedPod({ namespace });
232
+ const dirs = new Set();
233
+ for (const pod of pods.items) {
234
+ const phase = pod.status?.phase;
235
+ if ((phase !== 'Running' && phase !== 'Pending') ||
236
+ !pod.metadata?.ownerReferences?.some((owner) => owner.kind === 'ReplicaSet')) {
237
+ continue;
238
+ }
239
+ const volumes = new Set((pod.spec?.volumes ?? [])
240
+ .filter((volume) => volume.persistentVolumeClaim?.claimName === claim)
241
+ .map((volume) => volume.name));
242
+ for (const container of [...(pod.spec?.initContainers ?? []), ...(pod.spec?.containers ?? [])]) {
243
+ for (const mount of container.volumeMounts ?? []) {
244
+ const dir = mount.subPath?.split('/')[0];
245
+ if (volumes.has(mount.name) && dir?.startsWith(volumes_1.STATE_FILES_PREFIX)) {
246
+ dirs.add(dir);
247
+ }
248
+ }
249
+ }
250
+ }
251
+ return dirs;
252
+ }
253
+ exports.getStateDirsInUse = getStateDirsInUse;
254
+ // Syncs the files in the claim from the folder at `$1` into the folder at `$2` (see
255
+ // LIVE_FILES_DIR), which the pod of a service mounts while it runs: what is new or changed
256
+ // is written, what is gone is removed, and nothing else is touched, so the service sees only
257
+ // the changes. A file is written in place, and the paths the pod mounts (the others) are never
258
+ // removed: the pod holds them by their inode, and would not see one made again.
259
+ exports.SYNC_FILES = `src="$1"
260
+ dst="$2"
261
+ shift 2
262
+ if [ ! -d "$src" ]; then echo "no files at $src" >&2; exit 1; fi
263
+ mkdir -p "$dst" || exit 1
264
+ cd "$src" || exit 1
265
+ find . -mindepth 1 ! -path ./${UPLOADED} | while IFS= read -r f; do
266
+ t="$dst/$f"
267
+ if [ -L "$f" ]; then
268
+ l=$(readlink "$f")
269
+ if [ -L "$t" ] && [ "$(readlink "$t")" = "$l" ]; then continue; fi
270
+ rm -rf "$t" && ln -s "$l" "$t" || exit 1
271
+ elif [ -d "$f" ]; then
272
+ if [ -L "$t" ] || { [ -e "$t" ] && [ ! -d "$t" ]; }; then rm -rf "$t" || exit 1; fi
273
+ mkdir -p "$t" || exit 1
274
+ else
275
+ if [ -L "$t" ] || [ -d "$t" ]; then rm -rf "$t" || exit 1; fi
276
+ if [ -e "$t" ]; then
277
+ if cmp -s "$f" "$t"; then continue; fi
278
+ cat "$f" > "$t" && chmod "$(stat -c %a "$f")" "$t" || exit 1
279
+ else
280
+ cp -p "$f" "$t" || exit 1
281
+ fi
282
+ fi
283
+ done || exit 1
284
+ cd "$dst" || exit 1
285
+ find . -mindepth 1 -depth | while IFS= read -r f; do
286
+ if [ -e "$src/$f" ] || [ -L "$src/$f" ]; then continue; fi
287
+ mounted=
288
+ for m in "$@"; do
289
+ if [ "$f" = "./$m" ]; then mounted=1; fi
290
+ done
291
+ if [ -z "$mounted" ]; then rm -rf "$f" || exit 1; fi
292
+ done || exit 1
293
+ exit 0`;
294
+ /**
295
+ * Syncs the files of the state `from` (see getStateFilesDir) into the folder the pod of a
296
+ * service that watches its files mounts them from (LIVE_FILES_DIR).
297
+ */
298
+ async function syncLiveFiles(instance, env, work, persistence, pod, from) {
299
+ const root = `/dev/hammerkit/${work.id()}`;
300
+ // the paths of the folder its pod mounts
301
+ const mounted = persistence.mounts.flatMap(({ mount }) => mount.subPath?.startsWith(`${volumes_1.LIVE_FILES_DIR}/`) ? [mount.subPath.slice(volumes_1.LIVE_FILES_DIR.length + 1)] : []);
302
+ const failure = await execInPod(instance, env, pod, [
303
+ 'sh',
304
+ '-c',
305
+ exports.SYNC_FILES,
306
+ 'sh',
307
+ `${root}/${from}`,
308
+ `${root}/${volumes_1.LIVE_FILES_DIR}`,
309
+ ...mounted,
310
+ ]);
311
+ if (failure) {
312
+ throw new Error(`unable to sync the files of ${work.name} into ${root}/${volumes_1.LIVE_FILES_DIR}: ${failure}`);
313
+ }
314
+ }
315
+ exports.syncLiveFiles = syncLiveFiles;
316
+ // Puts the files of the state `from` back into the folder the pod of a service that watches
317
+ // its files mounts them from: a move that did not get up leaves the service at the commit
318
+ // it was at
319
+ async function restoreLiveFiles(instance, env, work, persistence, from) {
320
+ await getPodForPersistence(instance, env, work, persistence, 'write', undefined, (pod) => syncLiveFiles(instance, env, work, persistence, pod, from));
321
+ }
322
+ exports.restoreLiveFiles = restoreLiveFiles;
323
+ // Prepares the folder of a state in the claim of a work item of a service run before its
324
+ // upload: the folders of other states go, but the ones pods of the run mount. A folder a pod
325
+ // mounts is not touched: when it is the one of this state, its files are there already.
326
+ // Returns whether the upload is needed.
327
+ async function prepareStateFiles(instance, env, work, pod, dir, inUse) {
328
+ const targetPath = `/dev/hammerkit/${work.id()}`;
329
+ await removeOtherStates(instance, env, pod, targetPath, dir, inUse);
330
+ if (inUse.has(dir) && !(await execInPod(instance, env, pod, ['test', '-e', `${targetPath}/${dir}/${UPLOADED}`]))) {
331
+ work.status.write('info', `the files of ${work.name} are there already`);
332
+ return false;
333
+ }
334
+ await clearStateDir(instance, env, pod, `${targetPath}/${dir}`);
335
+ return true;
336
+ }
337
+ // Makes each of `files` (paths in the claim of `work`, see KubernetesPersistence.files) an
338
+ // empty file unless it is one: Kubernetes would make a directory of a subPath that isn't
339
+ // there, and the task could not write the file. A directory there is what an earlier
340
+ // version left in a kept claim, and goes. A path ending in `/` is made a folder.
341
+ exports.ENSURE_OUTPUT_FILES = `cd "$1" || exit 1
342
+ shift
343
+ for f; do
344
+ case "$f" in */) mkdir -p "$f" || exit 1; continue ;; esac
345
+ if [ -d "$f" ] && [ ! -L "$f" ]; then rm -rf "$f" || exit 1; fi
346
+ if [ ! -e "$f" ] && [ ! -L "$f" ]; then mkdir -p "$(dirname "$f")" && : > "$f" || exit 1; fi
347
+ done`;
348
+ async function ensureOutputFiles(instance, env, work, pod, files) {
349
+ if (files.length === 0) {
350
+ return;
351
+ }
352
+ const made = await execInPod(instance, env, pod, [
353
+ 'sh',
354
+ '-c',
355
+ exports.ENSURE_OUTPUT_FILES,
356
+ 'sh',
357
+ `/dev/hammerkit/${work.id()}`,
358
+ ...files,
359
+ ]);
360
+ if (made) {
361
+ throw new Error(`unable to make the output files ${files.join(', ')} of ${work.name}: ${made}`);
362
+ }
363
+ }
364
+ // what a failed upload, restore or task left: tar does not remove files the commit does not have
365
+ async function clearStateDir(instance, env, pod, path) {
366
+ const cleared = await execInPod(instance, env, pod, ['rm', '-rf', path]);
367
+ if (cleared) {
368
+ throw new Error(`unable to clear ${path}: ${cleared}`);
369
+ }
370
+ }
371
+ // Before a restore of a service run into the folder `dir` of the claim of `work` (in its upload
372
+ // pod `pod`): the folders of the other states go but those of `inUse`, which pods of the run
373
+ // mount, and `dir` is emptied. A claim that took only restores holds one state, as after a Job.
374
+ async function clearStateFiles(instance, env, work, pod, dir, inUse) {
375
+ const targetPath = `/dev/hammerkit/${work.id()}`;
376
+ await removeOtherStates(instance, env, pod, targetPath, dir, inUse);
377
+ await clearStateDir(instance, env, pod, `${targetPath}/${dir}`);
378
+ }
379
+ exports.clearStateFiles = clearStateFiles;
380
+ async function removeOtherStates(instance, env, pod, targetPath, dir, inUse) {
381
+ const removed = await execInPod(instance, env, pod, [
382
+ 'sh',
383
+ '-c',
384
+ exports.REMOVE_OTHER_STATES,
385
+ 'sh',
386
+ targetPath,
387
+ dir,
388
+ ...[...inUse].sort(),
389
+ ]);
390
+ if (removed) {
391
+ throw new Error(`unable to remove the files of other commits in ${targetPath}: ${removed}`);
392
+ }
135
393
  }
136
- exports.clearClaim = clearClaim;
137
394
  // The archive that uploads a source into the claim: its file or directory, at its place in
138
395
  // the claim (see getClaimSubPath) instead of under its own name
139
396
  function packSource(source) {
@@ -166,14 +423,32 @@ options = {}) {
166
423
  for (const volume of persistence.volumes) {
167
424
  await (0, ensure_kubernetes_persistent_volume_claim_exists_1.ensureKubernetesPersistentVolumeClaimExists)(instance, env, volume, service, persistence.sizes[volume.name], persistence.kept.includes(volume.name));
168
425
  }
169
- if (persistence.sources.length === 0 && !options.reset) {
426
+ // the folder of the state is in the work's own claim: one that has none (a service that
427
+ // only mounts what its deps made) has nothing to prepare
428
+ const claim = (0, volumes_1.getVolumeName)(service, env);
429
+ const files = persistence.volumes.some((volume) => volume.persistentVolumeClaim?.claimName === claim)
430
+ ? options.files
431
+ : undefined;
432
+ if (persistence.sources.length === 0 && persistence.files.length === 0 && !options.reset && !files) {
170
433
  return;
171
434
  }
435
+ // the folders of the states the pods of the run mount, before the upload pod mounts the claim
436
+ const inUse = files ? await getStateDirsInUse(instance, env.namespace, claim) : new Set();
437
+ for (const dir of files?.keep ?? []) {
438
+ inUse.add(dir);
439
+ }
172
440
  service.status.write('debug', 'start upload container');
173
- await getPodForPersistence(instance, env, service, persistence, 'write', async (name) => {
441
+ const { signal } = environment.abortCtrl;
442
+ await getPodForPersistence(instance, env, service, persistence, 'write', signal, async (name) => {
174
443
  if (options.reset) {
175
444
  await clearClaim(instance, env, service, name);
176
445
  }
446
+ if (files && !(await prepareStateFiles(instance, env, service, name, files.dir, inUse))) {
447
+ if (files.live && service.data.type === 'container-service') {
448
+ await syncLiveFiles(instance, env, service, persistence, name, files.dir);
449
+ }
450
+ return;
451
+ }
177
452
  for (const source of persistence.sources) {
178
453
  // skip sources that don't exist on disk — nothing to upload
179
454
  if (!(await environment.file.exists(source.localPath))) {
@@ -204,6 +479,24 @@ options = {}) {
204
479
  }
205
480
  });
206
481
  }
482
+ await ensureOutputFiles(instance, env, service, name, persistence.files);
483
+ if (files) {
484
+ const dir = `/dev/hammerkit/${service.id()}/${files.dir}`;
485
+ const marked = await execInPod(instance, env, name, [
486
+ 'sh',
487
+ '-c',
488
+ 'mkdir -p "$1" && touch "$1/$2"',
489
+ 'sh',
490
+ dir,
491
+ UPLOADED,
492
+ ]);
493
+ if (marked) {
494
+ throw new Error(`unable to mark the upload of ${dir}: ${marked}`);
495
+ }
496
+ if (files.live && service.data.type === 'container-service') {
497
+ await syncLiveFiles(instance, env, service, persistence, name, files.dir);
498
+ }
499
+ }
207
500
  });
208
501
  }
209
502
  exports.ensurePersistentData = ensurePersistentData;