hammerkit 2.0.0-next.9 → 2.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/kept-claims.js +12 -9
  37. package/dist/kubernetes/network-gate.js +74 -11
  38. package/dist/kubernetes/network-policy.js +32 -10
  39. package/dist/kubernetes/remove-stale-items.js +15 -2
  40. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  41. package/dist/kubernetes/sandbox-runner.js +3 -4
  42. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  43. package/dist/kubernetes/transfer-tools.js +66 -0
  44. package/dist/kubernetes/volumes.js +52 -10
  45. package/dist/optimizer/check-key.js +7 -0
  46. package/dist/optimizer/check-keys.js +19 -5
  47. package/dist/optimizer/get-work-cache-stats.js +19 -7
  48. package/dist/optimizer/work-task-cache-description.js +42 -8
  49. package/dist/planner/image-build.js +172 -0
  50. package/dist/planner/utils/append-work-dependencies.js +14 -1
  51. package/dist/planner/utils/append-work-service.js +1 -1
  52. package/dist/planner/utils/append-work-task.js +51 -1
  53. package/dist/planner/utils/assert-item-paths.js +6 -7
  54. package/dist/planner/utils/dependency-outputs.js +18 -0
  55. package/dist/planner/work-runtime-docker.js +48 -50
  56. package/dist/planner/work-runtime-kubernetes.js +1 -0
  57. package/dist/planner/work-runtime-local.js +3 -7
  58. package/dist/planner/work-secret.js +135 -13
  59. package/dist/planner/work-tree.js +10 -0
  60. package/dist/remote/collect-bundle.js +9 -1
  61. package/dist/remote/host-config.js +49 -3
  62. package/dist/remote/location.js +5 -5
  63. package/dist/remote/remote-commands.js +12 -14
  64. package/dist/remote/remote-status.js +1 -1
  65. package/dist/remote/remote-work-commands.js +20 -8
  66. package/dist/schema/build-file-image-build-schema.js +77 -0
  67. package/dist/schema/build-file-task-schema.js +9 -2
  68. package/dist/schema/reference-parser.js +10 -1
  69. package/dist/schema/work-scope-parser.js +16 -1
  70. package/dist/secrets/secret-catalog.js +8 -1
  71. package/dist/server/borrowed-quota.js +216 -0
  72. package/dist/server/capacity.js +18 -6
  73. package/dist/server/dashboard.js +8 -5
  74. package/dist/server/executor.js +58 -35
  75. package/dist/server/kubernetes-backend.js +143 -32
  76. package/dist/server/overview.js +20 -2
  77. package/dist/server/plan.js +31 -3
  78. package/dist/server/policy.js +14 -7
  79. package/dist/server/repo-access.js +4 -3
  80. package/dist/server/run-environment.js +5 -2
  81. package/dist/server/run-plan.js +18 -6
  82. package/dist/server/run-retry.js +57 -0
  83. package/dist/server/run-source-environment.js +39 -0
  84. package/dist/server/run-worker.js +38 -9
  85. package/dist/server/runs.js +63 -7
  86. package/dist/server/sandbox-files.js +232 -39
  87. package/dist/server/server-config.js +83 -6
  88. package/dist/server/server.js +107 -12
  89. package/dist/server/service-runs.js +42 -4
  90. package/dist/utils/line-splitter.js +52 -0
  91. package/dist/utils/tar.js +51 -1
  92. package/package.json +1 -1
  93. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -13,6 +13,7 @@ const git_checkout_1 = require("./git-checkout");
13
13
  const run_plan_1 = require("./run-plan");
14
14
  const work_network_1 = require("../planner/work-network");
15
15
  const execute_docker_1 = require("../executer/execute-docker");
16
+ const run_source_environment_1 = require("./run-source-environment");
16
17
  // `.git` as a file system may read it: any case, and a name Windows reads without its
17
18
  // trailing dots and spaces, or by its short name
18
19
  function isGitDirectory(segment) {
@@ -43,12 +44,21 @@ exports.defaultWorker = defaultWorker;
43
44
  // owner may write in the sandbox is not part of it. It leaves entries a run from main can
44
45
  // find, keyed by the files it ran on, as a ref run of a branch does: so only a caller who
45
46
  // may push a branch of the repository and run from it may check (server.ts).
47
+ //
48
+ // An approved run on a sandbox runs on a copy of the approved files too, but its owner
49
+ // may not use its accounts without the approval: it has a cache of its own, so what the
50
+ // owner's other runs built from files nobody approved (ignored ones) is not restored in it.
46
51
  function cacheNamespace(run) {
47
52
  const repository = run.source.type === 'ref' || (run.source.type === 'sandbox' && run.source.check);
53
+ const kind = repository
54
+ ? 'ref'
55
+ : run.source.type === 'sandbox' && (run.approvals?.length ?? 0) > 0
56
+ ? 'approved'
57
+ : run.source.type;
48
58
  const key = repository
49
59
  ? `ref\0${run.source.repo}`
50
- : `${run.source.type}\0${run.owner.iss}\0${run.owner.sub}`;
51
- return `${repository ? 'ref' : run.source.type}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
60
+ : `${kind}\0${run.owner.iss}\0${run.owner.sub}`;
61
+ return `${kind}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
52
62
  }
53
63
  exports.cacheNamespace = cacheNamespace;
54
64
  // The docker volumes of a run's services are its caller's, within the cache's source trust:
@@ -193,7 +203,7 @@ class HostExecutor {
193
203
  // what was approved is what runs: the accounts are read again from the files with
194
204
  // the environment of the run, and the run may use no more than it was admitted for
195
205
  const policy = source.type === 'sandbox' && sandboxes ? sandboxes.policy : planning.policy;
196
- const planned = await (0, run_plan_1.planRun)(bundle, run, planning.environment, policy);
206
+ const planned = await (0, run_plan_1.planRun)(bundle, run, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, run.source), policy);
197
207
  const extra = planned.accounts.filter((account) => !run.accounts.includes(account));
198
208
  if (extra.length > 0) {
199
209
  throw new Error(`the run would use ${extra.join(', ')}, which it was not admitted for`);
@@ -212,77 +222,93 @@ class HostExecutor {
212
222
  const root = this.directoryOf(run);
213
223
  let attachment;
214
224
  try {
215
- // where the process of the run starts: the checkout of a ref, or for a sandbox the
216
- // published files, so what the process and the secret providers it starts read of
217
- // their directory is never what a task wrote
218
- let cwd;
225
+ // The process of the run starts in the published files, which it reads its build files
226
+ // from, and its tasks work on other files (`work`): a checkout, a sandbox or a copy of
227
+ // one. The published files are a directory of the run no task mounts, so what the
228
+ // process parses for each task it runs, and what the secret providers it starts read
229
+ // of their directory, is what was published and never what a task wrote.
230
+ const published = (0, path_1.join)(root, 'bundle');
231
+ await (0, promises_1.mkdir)(published, { recursive: true });
232
+ await this.writeBundle(published, bundle.files);
219
233
  let input;
220
234
  let claim;
221
- // the files of the sandbox the tasks work on
235
+ // the files the tasks work on
222
236
  let work;
223
237
  const sourceStarted = new Date();
224
- if (source.type === 'sandbox' && source.check) {
225
- // a check works on the files a push of the sandbox commits, copied out of it: never
226
- // on the sandbox, whose ignored files (node_modules, outputs) its owner writes
238
+ // A check works on the files a push of the sandbox commits, copied out of it, and so
239
+ // does a run that was approved: what was approved is those files, and the sandbox has
240
+ // more (its ignored files, node_modules, outputs), which its owner and their runs write
241
+ // while the run waits and runs.
242
+ const copied = source.type === 'sandbox' && (source.check || (run.approvals?.length ?? 0) > 0);
243
+ // (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
244
+ if (source.type === 'sandbox' && copied) {
227
245
  const { registry, network } = sandboxes;
228
- cwd = (0, path_1.join)(root, 'source');
246
+ const what = source.check ? 'the check' : 'the approved run';
247
+ if (!source.check) {
248
+ // what was approved is what runs: the files may have changed since, by a run
249
+ // before this one on the sandbox (the copy checks it again, under the sandbox's lock)
250
+ const state = await registry.state(source.id, abortCtrl.signal);
251
+ if (state.tree !== source.tree) {
252
+ throw new Error(`the files of the sandbox ${source.id} changed since the run was approved, they are ${state.tree} now and were ${source.tree}, submit the run again`);
253
+ }
254
+ }
255
+ work = (0, path_1.join)(root, 'source');
229
256
  try {
230
- await registry.exportTree(source.id, source.tree, cwd, abortCtrl.signal);
257
+ await registry.exportTree(source.id, source.tree, work, abortCtrl.signal);
231
258
  }
232
259
  catch (e) {
233
- throw new Error(`the files of the sandbox ${source.id} could not be copied for the check, submit it again: ${e instanceof Error ? e.message : String(e)}`);
260
+ throw new Error(`the files of the sandbox ${source.id} could not be copied for ${what}, submit it again: ${e instanceof Error ? e.message : String(e)}`);
234
261
  }
235
262
  // a repository of its own, as a checkout of the commit is: the root of the project,
236
263
  // which the paths of the tasks' keys are relative to, is the one of git
237
- await (0, git_checkout_1.git)(['init', '--quiet', cwd], {}, abortCtrl.signal, `the check of sandbox ${source.id}`, 'init');
264
+ await (0, git_checkout_1.git)(['init', '--quiet', work], {}, abortCtrl.signal, `${what} of sandbox ${source.id}`, 'init');
238
265
  context.emit({
239
266
  type: 'log',
240
267
  task: 'hammerkit',
241
268
  stream: 'stdout',
242
- text: `check of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
269
+ text: `${source.check ? 'check' : 'approved run'} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
243
270
  });
244
- await this.writeBundle(cwd, bundle.files);
271
+ // the tasks see the published build files in place of the sandbox's own
272
+ await this.writeBundle(work, bundle.files);
245
273
  input = {
246
- entry: (0, path_1.join)(cwd, version.entry),
274
+ entry: (0, path_1.join)(published, version.entry),
275
+ directory: { read: published, work },
247
276
  ...(planning.policy.network ? { network: (0, work_network_1.toNetworkSchema)(planning.policy.network) } : {}),
248
277
  sandboxNetwork: network,
249
278
  };
250
279
  }
251
280
  else if (source.type === 'ref') {
252
- cwd = (0, path_1.join)(root, 'source');
281
+ work = (0, path_1.join)(root, 'source');
253
282
  const { repo, ref, commit: pinned } = source;
254
283
  const credentials = await repos.credentials(repo);
255
284
  let commit;
256
285
  try {
257
286
  // a woken service run starts the commit it started first, where the ref is now or not
258
287
  const fetched = run.wakes ? pinned : ref;
259
- commit = await (0, git_checkout_1.checkoutRef)(repos.url(repo), fetched, cwd, credentials.env, abortCtrl.signal, pinned);
288
+ commit = await (0, git_checkout_1.checkoutRef)(repos.url(repo), fetched, work, credentials.env, abortCtrl.signal, pinned);
260
289
  }
261
290
  catch (e) {
262
291
  throw repos.scrub(e, credentials.values);
263
292
  }
264
293
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `checked out ${repo} at ${commit}` });
265
- await this.writeBundle(cwd, bundle.files);
294
+ // the tasks see the published build files in place of the checkout's own
295
+ await this.writeBundle(work, bundle.files);
266
296
  // what the version was checked against at publish holds while it runs too
267
297
  input = {
268
- entry: (0, path_1.join)(cwd, version.entry),
298
+ entry: (0, path_1.join)(published, version.entry),
299
+ directory: { read: published, work },
269
300
  ...(planning.policy.network ? { network: (0, work_network_1.toNetworkSchema)(planning.policy.network) } : {}),
270
301
  };
271
302
  }
272
303
  else {
273
- // the published files are read from a directory of the run and work on the
274
- // sandbox, whose own build files are just files
304
+ // a run its caller may run without an approval works on the sandbox itself, whose
305
+ // own build files are just files
275
306
  const { registry, network } = sandboxes;
276
307
  // read before the run attaches: until then the walk of the last run's measure holds
277
308
  const state = await registry.state(source.id, abortCtrl.signal);
278
309
  attachment = await registry.attach(source.id, (0, path_1.join)(root, 'sandbox'));
279
310
  work = attachment.directory;
280
311
  claim = attachment.claim;
281
- // what was approved is what runs: the files may have changed since, by a run
282
- // before this one on the sandbox
283
- if (run.approvals?.length && state.tree !== source.tree) {
284
- throw new Error(`the files of the sandbox ${source.id} changed since the run was approved, they are ${state.tree} now and were ${source.tree}, submit the run again`);
285
- }
286
312
  if (claim && !this.options.placement) {
287
313
  throw new Error(`the sandbox ${source.id} is a claim on a cluster, this server runs tasks on its own docker`);
288
314
  }
@@ -292,10 +318,6 @@ class HostExecutor {
292
318
  stream: 'stdout',
293
319
  text: `sandbox ${source.id} of ${source.repo} at ${state.commit}, files ${state.tree}${state.clean ? '' : ' with changes'}`,
294
320
  });
295
- const published = (0, path_1.join)(root, 'bundle');
296
- await (0, promises_1.mkdir)(published, { recursive: true });
297
- await this.writeBundle(published, bundle.files);
298
- cwd = published;
299
321
  input = {
300
322
  entry: (0, path_1.join)(published, version.entry),
301
323
  directory: { read: published, work },
@@ -311,7 +333,7 @@ class HostExecutor {
311
333
  await (0, promises_1.mkdir)(cache, { recursive: true });
312
334
  const placement = this.options.placement;
313
335
  const namespaceStarted = new Date();
314
- const placed = placement ? await placement.prepare(run, context, { root: work ?? cwd, claim }) : undefined;
336
+ const placed = placement ? await placement.prepare(run, context, { root: work, claim }) : undefined;
315
337
  if (placed) {
316
338
  emitPhase(context, 'namespace', namespaceStarted);
317
339
  }
@@ -323,6 +345,7 @@ class HostExecutor {
323
345
  accounts: run.accounts,
324
346
  volumeScope: volumeScope(run, this.options.directory),
325
347
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
+ ...(context.durations ? { durations: context.durations } : {}),
326
349
  catalog: planning.environment.hosted?.catalog,
327
350
  ...(run.up
328
351
  ? {
@@ -334,7 +357,7 @@ class HostExecutor {
334
357
  : {}),
335
358
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
336
359
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
337
- }, cwd, { ...this.processEnvironment(home, cache), ...placed?.env }, context, abortCtrl.signal);
360
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal);
338
361
  }
339
362
  finally {
340
363
  if (placement && placed) {
@@ -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,9 +9,11 @@ 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");
16
+ const network_gate_1 = require("../kubernetes/network-gate");
15
17
  const sleep_1 = require("../utils/sleep");
16
18
  const version_1 = require("../version");
17
19
  const executor_1 = require("./executor");
@@ -98,6 +100,8 @@ function readInClusterNamespace() {
98
100
  * Policies add up, so neither selects the pods of a limited item: its own policy (see
99
101
  * buildNetworkPolicy) is all it may reach, DNS left out, and all that may reach it. An
100
102
  * egress proxy takes connections from its item only (buildProxyPolicy).
103
+ * - the pods that copy files into and out of claims: no network at all (they are limited,
104
+ * and the policies of the items whose labels they carry leave them out)
101
105
  */
102
106
  function getNamespacePolicies(namespace, deniedEgress, allowedEgress = []) {
103
107
  const metadata = (name) => ({
@@ -157,6 +161,17 @@ function getNamespacePolicies(namespace, deniedEgress, allowedEgress = []) {
157
161
  ingress: [],
158
162
  },
159
163
  },
164
+ {
165
+ apiVersion: 'networking.k8s.io/v1',
166
+ kind: 'NetworkPolicy',
167
+ metadata: metadata('hammerkit-transfer'),
168
+ spec: {
169
+ // the pods that copy files into and out of a claim, which are reached through the
170
+ // API (exec): nothing in or out
171
+ podSelector: { matchLabels: { [network_policy_1.TRANSFER_LABEL]: 'true' } },
172
+ policyTypes: ['Ingress', 'Egress'],
173
+ },
174
+ },
160
175
  ];
161
176
  }
162
177
  exports.getNamespacePolicies = getNamespacePolicies;
@@ -245,9 +260,9 @@ exports.getRunRoleBinding = getRunRoleBinding;
245
260
  * of a caller execute side by side in their namespace, up to `runs.limits.running`:
246
261
  * the objects of a run are named and found by its run label (getItemKey), so two runs
247
262
  * of the same task have their own. What two runs share are the claims the server keeps
248
- * (`backend.keepVolumes`) of a scope (getVolumeScope): the runs of one scope go one at
249
- * a time (exclusive). When a run ends, everything made for it is removed, but for the
250
- * kept claims, which go once they expired.
263
+ * (`backend.keepVolumes`) of a scope (getVolumeScope), one per task: two runs of one scope
264
+ * with a task in common go one at a time (excludes). When a run ends, everything made for it
265
+ * is removed, but for the kept claims, which go once they expired.
251
266
  */
252
267
  class KubernetesExecutor {
253
268
  constructor(config, processEnvs, options) {
@@ -255,7 +270,8 @@ class KubernetesExecutor {
255
270
  // per caller namespace, what changes objects of the whole namespace: its setup, the
256
271
  // removal of what a stopped server left, the sweeps of kept claims. The last one waiting.
257
272
  this.queues = new Map();
258
- // per caller namespace, the runs that execute in it: by run label, their volume scope
273
+ // per caller namespace, the runs that execute in it and mount kept claims: by run label,
274
+ // their volume scope
259
275
  this.active = new Map();
260
276
  // per caller namespace, when its kept claims are next looked at
261
277
  this.sweeps = new Map();
@@ -288,13 +304,27 @@ class KubernetesExecutor {
288
304
  this.keep = config.backend.keepVolumes === false ? 0 : (0, units_1.parseDuration)(config.backend.keepVolumes);
289
305
  this.keepServiceRuns = config.runs.up.keepVolumes;
290
306
  this.log = options.log;
307
+ const { quota, maxQuota, pools } = config.backend;
308
+ if (quota && maxQuota) {
309
+ this.quotas = new borrowed_quota_1.BorrowedQuotas({
310
+ quota,
311
+ maxQuota,
312
+ room: () => (0, borrowed_quota_1.readPoolRoom)(this.instance, pools),
313
+ write: async (namespace, hard) => {
314
+ await (0, apply_1.replace)(this.instance, getNamespaceQuota(namespace, hard));
315
+ },
316
+ log: options.log,
317
+ });
318
+ }
291
319
  this.host = new executor_1.HostExecutor({ ...options, placement: this.placement() });
292
320
  }
293
321
  // what the namespaces of the server's callers and service runs request and use
294
322
  capacity() {
295
323
  const prefix = this.config.backend.namespacePrefix;
324
+ const { quota, maxQuota } = this.config.backend;
296
325
  return new capacity_1.KubernetesCapacity(this.instance, {
297
326
  quotaName: POLICY_NAME,
327
+ ...(quota && maxQuota ? { share: (0, capacity_1.getQuotaResources)(quota) } : {}),
298
328
  namespaces: async () => (await this.instance.coreApi.listNamespace({ labelSelector: `${MANAGED_LABEL}=true` })).items
299
329
  .filter((namespace) => isCallerNamespace(prefix, namespace.metadata?.name ?? ''))
300
330
  .map((namespace) => ({
@@ -329,7 +359,11 @@ class KubernetesExecutor {
329
359
  runs = new Map();
330
360
  this.active.set(namespace, runs);
331
361
  }
332
- runs.set(label, getVolumeScope(run));
362
+ if (this.holds(run)) {
363
+ runs.set(label, getVolumeScope(run));
364
+ }
365
+ // the caller is promised its share while the run executes
366
+ this.quotas?.enter(namespace, run.id);
333
367
  try {
334
368
  await this.host.execute(run, context);
335
369
  }
@@ -338,6 +372,9 @@ class KubernetesExecutor {
338
372
  if (runs.size === 0 && this.active.get(namespace) === runs) {
339
373
  this.active.delete(namespace);
340
374
  }
375
+ await this.quotas
376
+ ?.leave(namespace, run.id)
377
+ .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
341
378
  }
342
379
  }
343
380
  // A service run moves to another commit in its namespace: unchanged services stay, the
@@ -403,17 +440,41 @@ class KubernetesExecutor {
403
440
  this.serviceRunsSwept = false;
404
441
  }
405
442
  }
406
- // The runs of a scope share its kept claims, which one of them may change at a time:
407
- // what a task finds in one is what the last run left there. Without kept claims, runs
408
- // share no object and nothing is held.
409
- exclusive(run) {
443
+ // The runs of a scope share the kept claim of each task, which one of them may change at a
444
+ // time: what a task finds in it is what the last run left there. Two runs of a scope go
445
+ // side by side when they have no task in common, and a run that mounts no kept claim holds
446
+ // nothing. Without kept claims, runs share no object and nothing is held.
447
+ excludes(run, other) {
448
+ const held = this.holds(run);
449
+ const theirs = this.holds(other);
450
+ if (!held || !theirs || held.scope !== theirs.scope) {
451
+ return false;
452
+ }
453
+ if (!held.tasks || !theirs.tasks) {
454
+ return true;
455
+ }
456
+ const tasks = new Set(theirs.tasks);
457
+ return held.tasks.some((task) => tasks.has(task));
458
+ }
459
+ // The kept claims a run mounts: its scope in the caller's namespace and the tasks of the
460
+ // claims (getKeptClaimTasks), all of the scope's for a run without a plan. Nothing for a
461
+ // run that mounts none.
462
+ holds(run) {
410
463
  if (this.keep === 0 || run.up) {
411
464
  return undefined;
412
465
  }
413
- return `${getCallerNamespace(this.config.backend.namespacePrefix, run.owner)}/${getVolumeScope(run)}`;
466
+ const tasks = getKeptClaimTasks(run);
467
+ if (tasks?.length === 0) {
468
+ return undefined;
469
+ }
470
+ return {
471
+ scope: `${getCallerNamespace(this.config.backend.namespacePrefix, run.owner)}/${getVolumeScope(run)}`,
472
+ tasks,
473
+ };
414
474
  }
415
- // The scopes of the runs that execute in the namespace, but `except`'s: their kept claims
416
- // are theirs to mount and stay. A server that keeps none mounts none.
475
+ // The scopes of the runs that execute in the namespace and mount kept claims, but
476
+ // `except`'s: their kept claims are theirs to mount and stay. A server that keeps none
477
+ // mounts none.
417
478
  scopesInUse(namespace, except) {
418
479
  if (this.keep === 0) {
419
480
  return new Set();
@@ -460,6 +521,8 @@ class KubernetesExecutor {
460
521
  quota: this.config.runs.up.quota,
461
522
  });
462
523
  });
524
+ // its pods take room the callers can't borrow
525
+ await this.quotas?.serviceRun(namespace, this.config.runs.up.quota ?? this.config.backend.quota);
463
526
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
464
527
  return { kubernetes: this.environmentOf(run, namespace), env: this.access.env };
465
528
  }
@@ -490,6 +553,9 @@ class KubernetesExecutor {
490
553
  }
491
554
  });
492
555
  this.sweepLeftClaims();
556
+ // the quota of the caller, and of the callers it borrows from or lends to, before its
557
+ // tasks run
558
+ await this.quotas?.apply(namespace);
493
559
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
494
560
  return {
495
561
  kubernetes: this.environmentOf(run, namespace, work, capabilitiesProblem),
@@ -526,6 +592,9 @@ class KubernetesExecutor {
526
592
  }
527
593
  else {
528
594
  this.serviceRuns.delete(namespace);
595
+ await this.quotas
596
+ ?.serviceRunEnded(namespace)
597
+ .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
529
598
  }
530
599
  }
531
600
  return;
@@ -565,6 +634,7 @@ class KubernetesExecutor {
565
634
  // The cluster as the process of a run sees it: the namespace its tasks and services go in.
566
635
  environmentOf(run, namespace, work, capabilitiesProblem) {
567
636
  const backend = this.config.backend;
637
+ const openGate = (0, network_gate_1.getOpenNetworkGate)(backend);
568
638
  return {
569
639
  type: 'kubernetes',
570
640
  namespace,
@@ -585,6 +655,7 @@ class KubernetesExecutor {
585
655
  // the claims of a service run go with its namespace
586
656
  ...(this.keep > 0 && !run.up ? { volumeScope: getVolumeScope(run) } : {}),
587
657
  ...(run.up ? { serviceRun: true } : {}),
658
+ ...(openGate ? { openGate } : {}),
588
659
  ...(backend.capabilities
589
660
  ? {
590
661
  capabilities: {
@@ -720,16 +791,54 @@ function getPrivilegedNamespaceProblem(namespace, labels, backend) {
720
791
  `${namespace} ${ENFORCE_LABEL}=baseline ${AUDIT_LABEL}- --overwrite`);
721
792
  }
722
793
  exports.getPrivilegedNamespaceProblem = getPrivilegedNamespaceProblem;
723
- // What may mount a claim a run kept: the runs of the same repository, as they share the
724
- // cache, and on a sandbox the runs of that sandbox only, whose claim is on the same node or
725
- // zone as the kept ones. The owner is the namespace's.
794
+ // The tasks of a run whose kept claims it mounts, by name: each container task of its plan,
795
+ // which mounts its own claim, while the tasks that depend on it and the services that mount its
796
+ // outputs mount it too (they have it in their plan). Another task has none: an aggregate, or a
797
+ // local task on a server that allows them. A kept claim is named after its task
798
+ // (getClaimName), so two runs with no task in common mount no claim in common, whatever
799
+ // their tasks are. Null for a run without a plan (submitted by a version that recorded none).
800
+ function getKeptClaimTasks(run) {
801
+ if (!run.plan) {
802
+ return null;
803
+ }
804
+ return Object.entries(run.plan)
805
+ .filter(([, task]) => task.kind === 'task' && task.runtime === 'docker')
806
+ .map(([name]) => name)
807
+ .sort();
808
+ }
809
+ exports.getKeptClaimTasks = getKeptClaimTasks;
810
+ // What may mount a claim a run kept: the runs of the same branch or tag of a repository,
811
+ // which share its cache, so that the runs of two branches go side by side and the runs of one find what
812
+ // the last one left; on a sandbox the runs of that sandbox only, whose claim is on the same
813
+ // node or zone as the kept ones. An approved run on a sandbox keeps nothing with those runs,
814
+ // whose outputs nobody approved, as its cache is apart from theirs: it has a scope of its own,
815
+ // per sandbox, so that approved runs on two sandboxes go side by side. The owner is the namespace's.
726
816
  function getVolumeScope(run) {
727
817
  if (run.source.type === 'sandbox' && !run.source.check) {
728
- return `sandbox-${(0, crypto_1.createHash)('sha256').update(run.source.id).digest('hex').slice(0, 24)}`;
818
+ const id = (0, crypto_1.createHash)('sha256').update(run.source.id).digest('hex').slice(0, 24);
819
+ return (run.approvals?.length ?? 0) > 0 ? `approved-${id}` : `sandbox-${id}`;
820
+ }
821
+ // a ref given as a commit hash names no branch: its runs keep the repository's claims
822
+ if (run.source.type === 'ref' && !/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(run.source.ref)) {
823
+ const key = `ref\0${run.source.repo}\0${run.source.ref}`;
824
+ return `ref-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
729
825
  }
730
826
  return (0, executor_1.cacheNamespace)(run);
731
827
  }
732
828
  exports.getVolumeScope = getVolumeScope;
829
+ function getPolicyMetadata(namespace) {
830
+ return {
831
+ name: POLICY_NAME,
832
+ namespace,
833
+ annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
834
+ labels: { [MANAGED_LABEL]: 'true' },
835
+ };
836
+ }
837
+ // The ResourceQuota of a namespace of the server
838
+ function getNamespaceQuota(namespace, hard) {
839
+ return { apiVersion: 'v1', kind: 'ResourceQuota', metadata: getPolicyMetadata(namespace), spec: { hard } };
840
+ }
841
+ exports.getNamespaceQuota = getNamespaceQuota;
733
842
  /**
734
843
  * The namespaces of callers on the cluster: named by the caller (getCallerNamespace),
735
844
  * made on first use, with the operator's quota.
@@ -817,18 +926,9 @@ class CallerNamespaces {
817
926
  ]) {
818
927
  await (0, apply_1.replace)(this.instance, policy);
819
928
  }
820
- const metadata = {
821
- name: POLICY_NAME,
822
- namespace,
823
- annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
824
- labels: { [MANAGED_LABEL]: 'true' },
825
- };
826
- const quota = {
827
- apiVersion: 'v1',
828
- kind: 'ResourceQuota',
829
- metadata,
830
- spec: { hard: serviceRun?.quota ?? backend.quota },
831
- };
929
+ const metadata = getPolicyMetadata(namespace);
930
+ const hard = serviceRun?.quota ?? backend.quota;
931
+ const quota = getNamespaceQuota(namespace, hard ?? {});
832
932
  const defaults = backend.defaultResources;
833
933
  const limits = {
834
934
  apiVersion: 'v1',
@@ -844,10 +944,21 @@ class CallerNamespaces {
844
944
  ],
845
945
  },
846
946
  };
847
- for (const [object, wanted] of [
848
- [quota, !!(serviceRun?.quota ?? backend.quota)],
947
+ // a caller who may borrow has the quota the server works out for them (BorrowedQuotas),
948
+ // written once the namespace is there: here it is made with the share, never replaced
949
+ const borrows = !!backend.maxQuota && !serviceRun;
950
+ if (borrows) {
951
+ await this.instance.objectApi.create(quota).catch((e) => {
952
+ if ((0, apply_1.statusCodeOf)(e) !== 409) {
953
+ throw e;
954
+ }
955
+ });
956
+ }
957
+ const objects = [
958
+ ...(borrows ? [] : [[quota, !!hard]]),
849
959
  [limits, !!defaults],
850
- ]) {
960
+ ];
961
+ for (const [object, wanted] of objects) {
851
962
  if (wanted) {
852
963
  await (0, apply_1.replace)(this.instance, object);
853
964
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.visibleCapacity = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.runActions = exports.getViewer = exports.describeWait = void 0;
3
+ exports.visibleCapacity = exports.filterRuns = exports.FilterRefused = exports.parseRunFilter = exports.getOverview = exports.queuePlace = exports.visibleReason = exports.toListedRun = exports.mayRead = exports.seesActivityOf = exports.seesActivity = exports.maySee = exports.decides = exports.owns = exports.mayDecide = exports.mayRetry = exports.runActions = exports.getViewer = exports.describeWait = void 0;
4
4
  const policy_1 = require("./policy");
5
5
  const runs_1 = require("./runs");
6
6
  const service_runs_1 = require("./service-runs");
@@ -19,7 +19,7 @@ function getViewer(config, principal) {
19
19
  exports.getViewer = getViewer;
20
20
  function runActions(viewer, run) {
21
21
  if ((0, runs_1.isFinal)(run.state)) {
22
- return undefined;
22
+ return mayRetry(viewer, run) ? { retry: true } : undefined;
23
23
  }
24
24
  const mine = owns(viewer, run);
25
25
  const may = {
@@ -35,6 +35,24 @@ function runActions(viewer, run) {
35
35
  return Object.keys(may).length > 0 ? may : undefined;
36
36
  }
37
37
  exports.runActions = runActions;
38
+ /**
39
+ * Whether the caller may start a run again, as far as the run tells: it is over, they read it
40
+ * whole (what a retry runs again is what they read, its arguments too), they may run anything,
41
+ * and from where it ran: a repository of their entitlements, or a sandbox of their own. Which
42
+ * accounts they may use, and whether they need an approval, is decided when they retry it.
43
+ */
44
+ function mayRetry(viewer, run) {
45
+ if (!(0, runs_1.isFinal)(run.state) || !mayRead(viewer, run) || !(0, policy_1.mayRun)(viewer.grant)) {
46
+ return false;
47
+ }
48
+ if (run.source.type === 'ref') {
49
+ return (0, repo_1.matchesAnyRepo)(viewer.grant.repos, run.source.repo);
50
+ }
51
+ // a sandbox is its owner's, while they may still keep sandboxes of its repository
52
+ const repo = run.source.type === 'sandbox' ? run.source.repo : undefined;
53
+ return (repo !== undefined && owns(viewer, run) && viewer.grant.sandboxes.some((sandbox) => (0, repo_1.matchesRepo)(sandbox.repo, repo)));
54
+ }
55
+ exports.mayRetry = mayRetry;
38
56
  // A run that waits for an approval the caller may give: not their own.
39
57
  function mayDecide(viewer, run) {
40
58
  return (run.state === 'awaiting-approval' &&
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.inspectBundle = exports.planBundle = exports.getCredentialReads = exports.PLAIN_SERVER_ENVS = exports.DefinitionError = void 0;
3
+ exports.inspectBundle = exports.planBundle = exports.getCredentialReads = exports.withSymbolicValues = exports.PLAIN_SERVER_ENVS = exports.DefinitionError = void 0;
4
4
  const promises_1 = require("fs/promises");
5
5
  const os_1 = require("os");
6
6
  const path_1 = require("path");
@@ -18,12 +18,24 @@ const log_1 = require("../log");
18
18
  const parse_error_1 = require("../schema/parse-error");
19
19
  const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
+ const run_source_envs_1 = require("../environment/run-source-envs");
21
22
  class DefinitionError extends Error {
22
23
  }
23
24
  exports.DefinitionError = DefinitionError;
24
25
  // Variables of a server that hold no credential (FR-008): a task may read these and
25
- // still take arguments, or reach any network.
26
- exports.PLAIN_SERVER_ENVS = ['PATH', 'HOME', 'CI'];
26
+ // still take arguments, or reach any network. The ones of the run's source are set for each run.
27
+ exports.PLAIN_SERVER_ENVS = ['PATH', 'HOME', 'CI', ...run_source_envs_1.RUN_SOURCE_ENVS];
28
+ // The environment of runs as a build file is read before anybody runs it (a publish, a
29
+ // proposal, POST /v1/definitions/plan): each variable but the plain ones stands for its name,
30
+ // `${NAME}`. What the server answers about a build file, a description or an image that reads
31
+ // `$NAME` included, then never holds a value a run would see. The tasks of a run read the values.
32
+ function withSymbolicValues(processEnvs) {
33
+ return Object.fromEntries(Object.entries(processEnvs).map(([name, value]) => [
34
+ name,
35
+ value === undefined || exports.PLAIN_SERVER_ENVS.includes(name.toUpperCase()) ? value : `\${${name}}`,
36
+ ]));
37
+ }
38
+ exports.withSymbolicValues = withSymbolicValues;
27
39
  // What an item holds that its command must not hand out: its secrets, and the variables
28
40
  // of the server its `envs` read, but the plain ones.
29
41
  function getCredentialReads(item) {
@@ -200,6 +212,12 @@ function findItemPolicyProblems(item, policy, root) {
200
212
  ? `which this server does not allow (${from}: ${policy.capabilities.join(', ')})`
201
213
  : `and this server allows none (${from})`));
202
214
  }
215
+ // BuildKit adds SYS_ADMIN and reads the files of the run; on a server's docker host a task
216
+ // that adds capabilities may bind none of them (refuseUncheckableBinds), so a server builds
217
+ // images only on a cluster for now
218
+ if (policy.backend === 'host' && (0, work_task_1.isWorkTask)(data) && 'build' in data && data.build) {
219
+ problems.push(`${item.name}: builds an image, which a server builds only with a kubernetes backend for now (backend.type: host)`);
220
+ }
203
221
  // what a task reads and writes is the bundle's: `src: ../..` would have the server
204
222
  // copy its own files (its credentials, other callers' caches) into the task
205
223
  for (const source of 'src' in data ? data.src : []) {
@@ -255,6 +273,15 @@ function findItemPolicyProblems(item, policy, root) {
255
273
  problems.push(`${item.name}: volume ${volume.name} is not a volume name, a path of the server can't be mounted`);
256
274
  }
257
275
  }
276
+ if (policy.readableEnvs) {
277
+ const allowed = policy.readableEnvs;
278
+ const refusedEnvs = ('envs' in data ? data.envs.processNames ?? [] : []).filter((name) => !exports.PLAIN_SERVER_ENVS.includes(name.toUpperCase()) && !allowed.includes(name));
279
+ if (refusedEnvs.length > 0) {
280
+ problems.push(`${item.name}: reads ${refusedEnvs
281
+ .map((name) => `$${name}`)
282
+ .join(', ')} of the server, which it does not list in ${policy.envsFrom ?? 'runs.env.allow'}`);
283
+ }
284
+ }
258
285
  for (const secret of secretsOf(item)) {
259
286
  const source = secret.source;
260
287
  if (policy.backend === 'kubernetes' && source.type === 'provider') {
@@ -340,6 +367,7 @@ function toPlan(root, item) {
340
367
  deps: item.deps.map((dep) => dep.name).sort(),
341
368
  // by their names in the plan, not the names the task reaches them at (`postgres` of an include)
342
369
  needs: item.needs.map((need) => need.service.name).sort(),
370
+ ...((0, work_service_1.isContainerWorkService)(data) && data.init ? { init: data.init.task.name } : {}),
343
371
  accounts,
344
372
  secrets,
345
373
  serverEnvs: 'envs' in data ? data.envs.processNames ?? [] : [],