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
@@ -186,8 +186,8 @@ function registerWorkCommands(remote, context) {
186
186
  }
187
187
  return { type: 'ref', repo, ref, ...(commit ? { commit } : {}) };
188
188
  };
189
- const connect = async (name) => {
190
- const chosen = await getServer(name);
189
+ const connect = async (name, how) => {
190
+ const chosen = await getServer(name, how);
191
191
  // a CI job or an agent brings its own token, a person signs in
192
192
  const token = await (0, token_source_1.getTokenSource)(environment, chosen.name, chosen.server).token();
193
193
  return { ...chosen, token };
@@ -340,7 +340,7 @@ function registerWorkCommands(remote, context) {
340
340
  remote
341
341
  .command('run <tasks...>')
342
342
  .description('run tasks of a published build file on a server from a git ref, print their output and exit as they did')
343
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
343
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
344
344
  .addOption(new commander_1.Option('--build <hash>', 'the published version to run (sha256:...), or HAMMERKIT_BUILD; the hash of the build file here when left out'))
345
345
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
346
346
  .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out'))
@@ -355,7 +355,7 @@ function registerWorkCommands(remote, context) {
355
355
  const { definition, local } = await runDefinition(options);
356
356
  const source = await refSource(options);
357
357
  const ref = source.ref;
358
- const { name: serverName, server } = await getServer(options.server);
358
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
359
359
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
360
360
  const runOptions = {};
361
361
  for (const key of ['env', 'cache', 'timeout', 'maxTimeout']) {
@@ -407,7 +407,7 @@ function registerWorkCommands(remote, context) {
407
407
  .command('up <services...>')
408
408
  .description('start services of a published build file on a server from a git ref and keep them up until their ttl ends, ' +
409
409
  'with their endpoints at addresses of their own behind the sign-in of the server')
410
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
410
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
411
411
  .addOption(new commander_1.Option('--endpoint <service:port>', 'publish this port of a service, such as web:8080; may be given more than once').argParser(collectOption))
412
412
  .addOption(new commander_1.Option('--ttl <duration>', 'how long they stay once ready, such as 2h, then they are removed; the server default when left out'))
413
413
  .addOption(new commander_1.Option('--sleep-ttl <duration>', 'how long they stay up without a request, such as 30m, then they sleep until the next request wakes them; ' +
@@ -424,7 +424,7 @@ function registerWorkCommands(remote, context) {
424
424
  const { definition, local } = await runDefinition(options);
425
425
  const endpoints = (options.endpoint ?? []).map(service_tools_1.parseEndpoint);
426
426
  const source = await refSource(options);
427
- const { name: serverName, server } = await getServer(options.server);
427
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
428
428
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
429
429
  const submitted = await submitPublishing({ serverName, server, connection }, {
430
430
  definition,
@@ -683,11 +683,23 @@ function registerWorkCommands(remote, context) {
683
683
  const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/cancel`)).body;
684
684
  environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName}: ${run.state === 'up' || run.state === 'running' ? 'stopping' : (0, server_client_1.printable)(run.state)}\n`);
685
685
  }));
686
+ remote
687
+ .command('retry <run> [server]')
688
+ .description('start a run that is over again, as a new run of yours: the same tasks or services, settings and commit')
689
+ .action(guarded('Remote retry was not successful', async (id, name) => {
690
+ if (!RUN_ID.test(id)) {
691
+ throw new Error(`${(0, server_client_1.printable)(id)} is not a run id (run_...)`);
692
+ }
693
+ const { name: serverName, server, token } = await connect(name);
694
+ const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/retry`)).body;
695
+ environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName} retries ${(0, server_client_1.printable)(id)}: ${(0, server_client_1.printable)(run.state)}, ` +
696
+ `follow it with hammerkit remote logs ${(0, server_client_1.printable)(run.id)} --follow\n`);
697
+ }));
686
698
  remote
687
699
  .command('verify <tasks...>')
688
700
  .description('check that the server already passed tasks for the files checked out here, without running them; ' +
689
701
  'exits 1 at once for any it did not')
690
- .addOption(new commander_1.Option('--server <name>', 'the server to ask; the default of remote use when left out'))
702
+ .addOption(new commander_1.Option('--server <name>', 'the server to ask; when left out, the default of remote use or the only registered server'))
691
703
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
692
704
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
693
705
  .action(guarded('Remote verify was not successful', async (tasks, options) => {
@@ -709,7 +721,7 @@ function registerWorkCommands(remote, context) {
709
721
  keys.push({ task, key: found.key });
710
722
  }
711
723
  }
712
- const { name: serverName, server, token } = await connect(options.server);
724
+ const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
713
725
  const answer = keys.length > 0
714
726
  ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
715
727
  : { body: { checks: [] } };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildFileImageBuildTaskSchema = exports.buildFileImageBuildSchema = exports.buildFileRegistryLoginSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const build_file_base_task_schema_1 = require("./build-file-base-task-schema");
6
+ const size_schema_1 = require("./size-schema");
7
+ // A registry host, with a port where it has one: europe-west4-docker.pkg.dev, ghcr.io, localhost:5000
8
+ const REGISTRY = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/i;
9
+ // The name of an image with its tag or digest, as `docker build --tag` takes it. A comma, a
10
+ // quote or a space would end it in BuildKit's `--output`, so none of them is in one. `$NAME`
11
+ // and `${NAME}` take the value of a variable, and the name is checked again with it.
12
+ const IMAGE = /^[a-z0-9$][a-z0-9._/:@${}-]*$/i;
13
+ // A platform as BuildKit takes it: os/arch, with a variant where it has one (linux/arm/v7)
14
+ const PLATFORM = /^[a-z0-9]+\/[a-z0-9_]+(\/[a-z0-9]+)?$/;
15
+ // the password of a registry login, read like a secret of the task, never written in the build file
16
+ const registryPasswordSchema = (0, zod_1.object)({
17
+ from: (0, zod_1.string)().regex(/^[A-Za-z][A-Za-z0-9_-]*:.+$/, 'from must be env:NAME, file:path or <provider>:<ref>'),
18
+ account: (0, zod_1.string)().optional(),
19
+ })
20
+ .strict()
21
+ .describe('the password, a secret from env:NAME, file:path or <provider>:<ref>');
22
+ exports.buildFileRegistryLoginSchema = (0, zod_1.object)({
23
+ registry: (0, zod_1.string)().regex(REGISTRY, 'registry must be a host, with a port where it has one (ghcr.io, localhost:5000)'),
24
+ // a user name of basic auth holds no colon; a quote or a backslash would end it in the JSON
25
+ user: (0, zod_1.string)().regex(/^[^:"\\\s]+$/, 'user must not hold a colon, a quote, a backslash or a space'),
26
+ password: registryPasswordSchema,
27
+ })
28
+ .strict()
29
+ .describe('a sign-in to a registry, for the push and the cache');
30
+ exports.buildFileImageBuildSchema = (0, zod_1.object)({
31
+ // the folder sent to the build, relative to the task's directory
32
+ context: (0, zod_1.string)().optional().describe('the build context, `.` when left out'),
33
+ // the Dockerfile, relative to the task's directory
34
+ dockerfile: (0, zod_1.string)().optional().describe('the Dockerfile, Dockerfile in the context when left out'),
35
+ tags: (0, zod_1.union)([(0, zod_1.string)().regex(IMAGE, 'a tag must be an image name'), (0, zod_1.array)((0, zod_1.string)().regex(IMAGE)).min(1)])
36
+ .optional()
37
+ .describe('the names of the image, with their tags, as docker build --tag'),
38
+ push: (0, zod_1.boolean)().optional().describe('push the image to its registry, as docker build --push'),
39
+ // an image the layers are read from before the build and written to after it
40
+ cache: (0, zod_1.string)()
41
+ .regex(IMAGE, 'cache must be an image name, such as ghcr.io/acme/app:buildcache')
42
+ .optional()
43
+ .describe('an image in a registry the build reads its layers from and writes them to'),
44
+ // a file the task writes <name>@<digest> of the image to, which another task deploys
45
+ digest: (0, zod_1.string)().optional().describe('a file the task writes <image>@<digest> to'),
46
+ login: (0, zod_1.array)(exports.buildFileRegistryLoginSchema).optional(),
47
+ // the registries of the tags and the cache speak plain HTTP, as a registry:2 on a network of
48
+ // your own does (docker's --insecure-registry)
49
+ insecure: (0, zod_1.boolean)().optional().describe('reach the registries over plain HTTP'),
50
+ // the platforms of the image, as docker build --platform: one image for each, under one name.
51
+ // A RUN step for a platform other than the machine's runs in BuildKit's own QEMU.
52
+ platforms: (0, zod_1.union)([
53
+ (0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64'),
54
+ (0, zod_1.array)((0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64')).min(1),
55
+ ])
56
+ .optional()
57
+ .describe('the platforms to build for, such as linux/amd64 and linux/arm64, as docker build --platform'),
58
+ })
59
+ .strict()
60
+ .refine((build) => !build.push || build.tags !== undefined, {
61
+ message: 'push needs tags, the names of the image to push',
62
+ })
63
+ .refine((build) => build.digest === undefined || build.tags !== undefined, {
64
+ message: 'digest needs tags, the name the digest is written with',
65
+ })
66
+ .describe('builds a Dockerfile with BuildKit, as docker build does');
67
+ // A task that builds an image: hammerkit runs BuildKit for it, so it names no image, commands or
68
+ // shell of its own, and doesn't extend another task or take arguments.
69
+ exports.buildFileImageBuildTaskSchema = build_file_base_task_schema_1.buildFileBaseTaskSchema
70
+ .omit({ extend: true, reset: true, cmds: true, shell: true, args: true })
71
+ .extend({
72
+ build: exports.buildFileImageBuildSchema,
73
+ volumeSize: size_schema_1.sizeSchema.describe('size of its claim on Kubernetes, e.g. 10Gi').optional(),
74
+ })
75
+ .strict()
76
+ .describe('task that builds an image');
77
+ //# sourceMappingURL=build-file-image-build-schema.js.map
@@ -1,16 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBuildFileLocalTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
3
+ exports.isBuildFileLocalTaskSchema = exports.isBuildFileImageBuildTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const build_file_container_task_schema_1 = require("./build-file-container-task-schema");
6
6
  const build_file_local_task_schema_1 = require("./build-file-local-task-schema");
7
+ const build_file_image_build_schema_1 = require("./build-file-image-build-schema");
8
+ // A task with `build` is tried first: it fails at once without one, and with one its own
9
+ // errors are reported, not that the other kinds don't know `build` (zod gives the first
10
+ // option's errors that aren't fatal).
7
11
  exports.buildFileTaskSchema = (0, zod_1.union)([
12
+ build_file_image_build_schema_1.buildFileImageBuildTaskSchema,
8
13
  build_file_container_task_schema_1.buildFileContainerTaskSchema,
9
14
  build_file_local_task_schema_1.buildFileLocalTaskSchema,
10
15
  build_file_container_task_schema_1.buildFileExtendingContainerTaskSchema,
11
16
  ]);
12
17
  const isBuildFileContainerTaskSchema = (val) => 'image' in val;
13
18
  exports.isBuildFileContainerTaskSchema = isBuildFileContainerTaskSchema;
14
- const isBuildFileLocalTaskSchema = (val) => !('image' in val);
19
+ const isBuildFileImageBuildTaskSchema = (val) => 'build' in val;
20
+ exports.isBuildFileImageBuildTaskSchema = isBuildFileImageBuildTaskSchema;
21
+ const isBuildFileLocalTaskSchema = (val) => !('image' in val) && !('build' in val);
15
22
  exports.isBuildFileLocalTaskSchema = isBuildFileLocalTaskSchema;
16
23
  //# sourceMappingURL=build-file-task-schema.js.map
@@ -188,6 +188,11 @@ function applySchemaExtension(reference, task) {
188
188
  task.extension = 'applying';
189
189
  task.depBases = [];
190
190
  task.needBases = [];
191
+ // a task that builds an image extends nothing (its schema has no `extend`)
192
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
193
+ task.extension = 'applied';
194
+ return;
195
+ }
191
196
  const reset = new Set(task.schema.reset ?? []);
192
197
  if (!task.schema.extend) {
193
198
  if (reset.size > 0) {
@@ -198,6 +203,10 @@ function applySchemaExtension(reference, task) {
198
203
  }
199
204
  const name = task.schema.extend;
200
205
  const extend = findPublished(task.relativeName, 'extends', () => findTask(reference, task.scope, name, null)).task;
206
+ // hammerkit makes the commands of a task that builds an image (see image-build.ts)
207
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(extend.schema)) {
208
+ throw new Error(`task ${task.relativeName} extends ${name}, which builds an image: such a task can't be extended`);
209
+ }
201
210
  applySchemaExtension(reference, extend);
202
211
  task.schema.shell = task.schema.shell ?? extend.schema.shell;
203
212
  task.schema.cache = task.schema.cache ?? extend.schema.cache;
@@ -239,7 +248,7 @@ function applySchemaExtension(reference, task) {
239
248
  task.extension = 'applied';
240
249
  }
241
250
  function rejectContainerPropertiesWithoutImage(task) {
242
- if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema)) {
251
+ if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema) || (0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
243
252
  return;
244
253
  }
245
254
  const schema = task.schema;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getWorkContext = exports.defaultEnvironment = void 0;
4
4
  const work_scope_1 = require("../executer/work-scope");
5
+ const work_tree_1 = require("../planner/work-tree");
5
6
  const label_values_1 = require("../executer/label-values");
6
7
  const append_work_service_1 = require("../planner/utils/append-work-service");
7
8
  const append_work_task_1 = require("../planner/utils/append-work-task");
@@ -70,6 +71,14 @@ function getWorkContext(context, scope, environment) {
70
71
  throw new Error(`no task or service named ${unknown.join(', ')}, see hammerkit ls`);
71
72
  }
72
73
  }
74
+ if (!(0, work_scope_1.isContextTaskFilter)(scope) && scope.taskNames) {
75
+ filteredWorkTree.named = scope.taskNames;
76
+ const known = new Set(tasks.map((task) => task.name));
77
+ const unknown = scope.taskNames.filter((name) => !known.has(name));
78
+ if (unknown.length > 0) {
79
+ throw new Error(`no task named ${unknown.join(', ')}, see hammerkit ls`);
80
+ }
81
+ }
73
82
  if (scope.args) {
74
83
  (0, task_arguments_1.applyArguments)({ tasks: selectedTasks, services: scope.args.services ? selectedServices : [] }, scope.args.values, scope.args.cache);
75
84
  }
@@ -89,7 +98,7 @@ function keepRequirersInScope(workTree) {
89
98
  service.requiredBy = service.requiredBy.filter((required) => inScope.has(required));
90
99
  // an init task asked for alone is what its service starts for
91
100
  const init = service.data.type === 'container-service' ? service.data.init : null;
92
- if (init && workTree.requested?.length === 1 && workTree.requested[0] === init.task.name) {
101
+ if (init && (0, work_tree_1.isAskedByName)(workTree, init.task.name)) {
93
102
  service.requiredBy.push(init.task);
94
103
  }
95
104
  }
@@ -131,6 +140,9 @@ function matchesTaskWorkScope(task, scope) {
131
140
  if (scope.serviceNames) {
132
141
  return false;
133
142
  }
143
+ if (scope.taskNames) {
144
+ return scope.taskNames.includes(task.name);
145
+ }
134
146
  if (scope.names) {
135
147
  return scope.names.includes(task.name);
136
148
  }
@@ -143,6 +155,9 @@ function matchesServiceWorkScope(service, scope) {
143
155
  if (scope.serviceNames) {
144
156
  return scope.serviceNames.includes(service.name);
145
157
  }
158
+ if (scope.taskNames) {
159
+ return false;
160
+ }
146
161
  if (scope.names) {
147
162
  return scope.names.includes(service.name);
148
163
  }
@@ -1,10 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.collectSecretCatalog = exports.emptySecretCatalog = void 0;
3
+ exports.collectSecretCatalog = exports.emptySecretCatalog = exports.declared = void 0;
4
4
  const merge_environment_variables_1 = require("../environment/merge-environment-variables");
5
5
  const replace_env_variables_1 = require("../environment/replace-env-variables");
6
6
  const units_1 = require("../utils/units");
7
7
  const DEFAULT_TIMEOUT = '30s';
8
+ // What a record of the catalog holds under a name a build file or a config gives, only when it
9
+ // was declared there: `constructor` or `toString` is no provider or account of any catalog.
10
+ function declared(record, name) {
11
+ return Object.prototype.hasOwnProperty.call(record, name) ? record[name] : undefined;
12
+ }
13
+ exports.declared = declared;
8
14
  function emptySecretCatalog() {
9
15
  return { providers: {}, accounts: {} };
10
16
  }
@@ -51,6 +57,7 @@ function collectSecretCatalog(files, environment, context, host) {
51
57
  }
52
58
  }
53
59
  if (host) {
60
+ catalog.hostConfig = host.fileName;
54
61
  // the host config has no envs of its own: `${NAME}` is read from the process
55
62
  for (const [name, provider] of Object.entries(host.secretProviders ?? {})) {
56
63
  catalog.providers[name] = toProvider(name, provider, {}, host.fileName);
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BorrowedQuotas = exports.readPoolRoom = exports.isPoolNode = exports.getBorrowedQuota = exports.getBorrowedResource = exports.BORROWED_RESOURCES = void 0;
4
+ const log_1 = require("../log");
5
+ const apply_1 = require("../kubernetes/apply");
6
+ const units_1 = require("../utils/units");
7
+ /**
8
+ * A caller's quota above its share (`backend.quota`), up to `backend.maxQuota`: the room of
9
+ * the nodes that no other caller is promised. While a run of a caller executes, the caller is
10
+ * promised its share; the room of the nodes of the pools beyond the shares of the callers with
11
+ * a run executing and the quotas of the service runs that are up is split evenly among those
12
+ * callers, each up to its `maxQuota`. A caller alone on the cluster gets all of it. The server
13
+ * works it out again when a run of a caller or a service run starts or ends, from nothing but
14
+ * which of them execute and what the nodes hold, so the same runs give the same quotas. It only
15
+ * lowers a quota and never evicts: the pods a caller runs above its new quota run on, and its
16
+ * next ones wait for room under the quota as they do under a full one.
17
+ */
18
+ // The keys of a quota a caller may borrow, by the resource of the nodes whose room they take.
19
+ // `cpu` and `memory` are `requests.cpu` and `requests.memory`, as Kubernetes reads them.
20
+ exports.BORROWED_RESOURCES = {
21
+ cpu: { requests: ['requests.cpu', 'cpu'], limits: ['limits.cpu'] },
22
+ memory: { requests: ['requests.memory', 'memory'], limits: ['limits.memory'] },
23
+ };
24
+ function getBorrowedResource(key) {
25
+ return Object.keys(exports.BORROWED_RESOURCES).find((resource) => {
26
+ const keys = [...exports.BORROWED_RESOURCES[resource].requests, ...exports.BORROWED_RESOURCES[resource].limits];
27
+ return keys.includes(key);
28
+ });
29
+ }
30
+ exports.getBorrowedResource = getBorrowedResource;
31
+ // The key of a quota that holds what the pods of a namespace request of `resource`
32
+ function requestsKey(quota, resource) {
33
+ return exports.BORROWED_RESOURCES[resource].requests.find((key) => quota[key] !== undefined);
34
+ }
35
+ /**
36
+ * The quota of each caller with a run executing: its share, and of each resource of
37
+ * `maxQuota` the part of the room `callers` share evenly beyond what is promised, up to
38
+ * `maxQuota`. Every key of a resource rises by the same part of the way from its share to its
39
+ * `maxQuota`, its limits as its requests. Without the room of the nodes, the share.
40
+ */
41
+ function getBorrowedQuota(options) {
42
+ const { quota, maxQuota } = options;
43
+ const borrowed = { ...quota };
44
+ const callers = Math.max(1, options.callers);
45
+ for (const resource of Object.keys(exports.BORROWED_RESOURCES)) {
46
+ const key = requestsKey(maxQuota, resource);
47
+ const room = options.room?.[resource];
48
+ if (!key || room === undefined) {
49
+ continue;
50
+ }
51
+ const share = (0, units_1.parseQuantity)(quota[key]) ?? 0;
52
+ const max = (0, units_1.parseQuantity)(maxQuota[key]) ?? share;
53
+ if (max <= share) {
54
+ continue;
55
+ }
56
+ const promised = callers * share +
57
+ options.serviceRuns.reduce((sum, up) => {
58
+ const of = requestsKey(up, resource);
59
+ return sum + (of ? (0, units_1.parseQuantity)(up[of]) ?? 0 : 0);
60
+ }, 0);
61
+ const part = Math.min(1, Math.max(0, (room - promised) / callers / (max - share)));
62
+ if (part === 0) {
63
+ continue;
64
+ }
65
+ for (const of of [...exports.BORROWED_RESOURCES[resource].requests, ...exports.BORROWED_RESOURCES[resource].limits]) {
66
+ if (maxQuota[of] === undefined) {
67
+ continue;
68
+ }
69
+ if (part === 1) {
70
+ borrowed[of] = maxQuota[of];
71
+ continue;
72
+ }
73
+ const from = (0, units_1.parseQuantity)(quota[of]) ?? 0;
74
+ const to = (0, units_1.parseQuantity)(maxQuota[of]) ?? from;
75
+ borrowed[of] = formatQuantity(resource, from + part * (to - from));
76
+ }
77
+ }
78
+ return borrowed;
79
+ }
80
+ exports.getBorrowedQuota = getBorrowedQuota;
81
+ // Down to a millicore and a MiB, so that a quota changes only with what it is worked out from
82
+ function formatQuantity(resource, amount) {
83
+ return resource === 'cpu' ? `${Math.floor(amount * 1000)}m` : `${Math.floor(amount / 2 ** 20)}Mi`;
84
+ }
85
+ // Whether a node is one of a pool's, where the pods of tasks and services go
86
+ function isPoolNode(node, pools) {
87
+ if (node.spec?.unschedulable) {
88
+ return false;
89
+ }
90
+ const labels = node.metadata?.labels ?? {};
91
+ return pools.some((pool) => labels['kubernetes.io/os'] === pool.platform.os &&
92
+ labels['kubernetes.io/arch'] === pool.platform.arch &&
93
+ Object.entries(pool.nodeSelector).every(([label, value]) => labels[label] === value));
94
+ }
95
+ exports.isPoolNode = isPoolNode;
96
+ // What the schedulable nodes of the pools hold together
97
+ async function readPoolRoom(instance, pools) {
98
+ const nodes = await instance.coreApi.listNode();
99
+ const room = { cpu: 0, memory: 0 };
100
+ for (const node of nodes.items.filter((candidate) => isPoolNode(candidate, pools))) {
101
+ room.cpu = (room.cpu ?? 0) + ((0, units_1.parseQuantity)(node.status?.allocatable?.cpu) ?? 0);
102
+ room.memory = (room.memory ?? 0) + ((0, units_1.parseQuantity)(node.status?.allocatable?.memory) ?? 0);
103
+ }
104
+ return room;
105
+ }
106
+ exports.readPoolRoom = readPoolRoom;
107
+ /**
108
+ * The quotas of the callers' namespaces while `backend.maxQuota` lets them borrow: which
109
+ * callers have a run executing and which service runs are up, and the quota last written to
110
+ * each namespace. Changes are worked out and written one at a time, in the order they came.
111
+ */
112
+ class BorrowedQuotas {
113
+ constructor(options) {
114
+ this.options = options;
115
+ // per caller namespace, its runs that execute
116
+ this.runs = new Map();
117
+ // per namespace of a service run that is up, its quota
118
+ this.serviceRuns = new Map();
119
+ // per caller namespace, the quota last written to it
120
+ this.written = new Map();
121
+ this.last = Promise.resolve();
122
+ }
123
+ // A run of the caller of `namespace` executes from now, until `leave`.
124
+ enter(namespace, run) {
125
+ const runs = this.runs.get(namespace) ?? new Set();
126
+ runs.add(run);
127
+ this.runs.set(namespace, runs);
128
+ }
129
+ // The run ended: the quotas are worked out again, the caller's back to its share once its
130
+ // last run ended.
131
+ leave(namespace, run) {
132
+ const runs = this.runs.get(namespace);
133
+ if (!runs?.delete(run)) {
134
+ return this.last;
135
+ }
136
+ if (runs.size === 0) {
137
+ this.runs.delete(namespace);
138
+ }
139
+ return this.apply();
140
+ }
141
+ // A service run is up, with the quota of its namespace, until `serviceRunEnded`.
142
+ serviceRun(namespace, quota) {
143
+ this.serviceRuns.set(namespace, quota ?? {});
144
+ return this.apply();
145
+ }
146
+ serviceRunEnded(namespace) {
147
+ if (!this.serviceRuns.delete(namespace)) {
148
+ return this.last;
149
+ }
150
+ return this.apply();
151
+ }
152
+ // The quotas as they are now, written where they changed; the quota of `own` (the namespace
153
+ // of a run that starts, which it is written into before its tasks run) also when it did
154
+ // not, since the server may have made the namespace since. Writing to `own` fails the call,
155
+ // writing to another caller's namespace is logged.
156
+ apply(own) {
157
+ const next = this.last.then(() => this.write(own));
158
+ this.last = next.catch(() => undefined);
159
+ return next;
160
+ }
161
+ async write(own) {
162
+ const room = await this.options.room().then((room) => {
163
+ this.roomProblem = undefined;
164
+ return room;
165
+ }, (e) => {
166
+ const problem = (0, log_1.getErrorMessage)(e);
167
+ if (problem !== this.roomProblem) {
168
+ this.roomProblem = problem;
169
+ this.options.log?.(`callers borrow no quota, the nodes could not be read: ${problem}`);
170
+ }
171
+ return undefined;
172
+ });
173
+ const callers = [...this.runs.keys()];
174
+ const borrowed = getBorrowedQuota({
175
+ quota: this.options.quota,
176
+ maxQuota: this.options.maxQuota,
177
+ callers: callers.length,
178
+ serviceRuns: [...this.serviceRuns.values()],
179
+ room,
180
+ });
181
+ // those that give back first, then those that borrow
182
+ const quotas = [
183
+ ...[...this.written.keys()]
184
+ .filter((namespace) => !this.runs.has(namespace))
185
+ .map((namespace) => [namespace, this.options.quota]),
186
+ ...callers.map((namespace) => [namespace, borrowed]),
187
+ ];
188
+ for (const [namespace, quota] of quotas) {
189
+ const text = JSON.stringify(quota);
190
+ if (namespace !== own && this.written.get(namespace) === text) {
191
+ continue;
192
+ }
193
+ try {
194
+ await this.options.write(namespace, quota);
195
+ this.written.set(namespace, text);
196
+ }
197
+ catch (e) {
198
+ if (namespace === own) {
199
+ throw e;
200
+ }
201
+ this.written.delete(namespace);
202
+ if ((0, apply_1.statusCodeOf)(e) !== 404) {
203
+ this.options.log?.(`the quota of ${namespace} could not be changed: ${(0, log_1.getErrorMessage)(e)}`);
204
+ }
205
+ }
206
+ }
207
+ // a caller back at its share needs nothing written until it borrows again
208
+ for (const namespace of [...this.written.keys()]) {
209
+ if (!this.runs.has(namespace)) {
210
+ this.written.delete(namespace);
211
+ }
212
+ }
213
+ }
214
+ }
215
+ exports.BorrowedQuotas = BorrowedQuotas;
216
+ //# sourceMappingURL=borrowed-quota.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.KubernetesCapacity = exports.cachedCapacity = exports.parseQuantity = void 0;
3
+ exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.KubernetesCapacity = exports.getQuotaResources = exports.cachedCapacity = exports.parseQuantity = void 0;
4
4
  const os_1 = require("os");
5
5
  const log_1 = require("../log");
6
6
  const apply_1 = require("../kubernetes/apply");
@@ -71,6 +71,16 @@ function briefly(e, what) {
71
71
  }
72
72
  return what === 'nodes' ? 'nodes not readable' : 'metrics not readable';
73
73
  }
74
+ // The CPU and memory pods may request under a quota, if it limits them
75
+ function getQuotaResources(hard) {
76
+ const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
77
+ const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
78
+ if (cpu === undefined && memory === undefined) {
79
+ return undefined;
80
+ }
81
+ return { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
82
+ }
83
+ exports.getQuotaResources = getQuotaResources;
74
84
  const ENDED = ['Succeeded', 'Failed'];
75
85
  // On Kubernetes: per namespace of the server, its pods' requests, its quota and its usage.
76
86
  class KubernetesCapacity {
@@ -162,11 +172,13 @@ class KubernetesCapacity {
162
172
  name: this.options.quotaName,
163
173
  namespace,
164
174
  });
165
- const hard = quota.spec?.hard ?? {};
166
- const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
167
- const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
168
- if (cpu !== undefined || memory !== undefined) {
169
- group.quota = { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
175
+ const resources = getQuotaResources(quota.spec?.hard ?? {});
176
+ if (resources) {
177
+ group.quota = resources;
178
+ const share = this.options.share;
179
+ if (kind === 'caller' && share && (share.cpu !== resources.cpu || share.memory !== resources.memory)) {
180
+ group.share = share;
181
+ }
170
182
  }
171
183
  }
172
184
  catch (e) {
@@ -8,8 +8,9 @@ const http_1 = require("./http");
8
8
  const oauth_1 = require("./oauth");
9
9
  const policy_1 = require("./policy");
10
10
  const overview_1 = require("./overview");
11
- // Approving and publishing take a sign-in of the last minutes: the groups of a session are
12
- // those of its sign-in, and somebody taken out of a group must not decide for hours.
11
+ // Approving, publishing and retrying a run take a sign-in of the last minutes: the groups of a
12
+ // session are those of its sign-in, and somebody taken out of a group must not decide, nor
13
+ // start runs with the accounts the group gave them, for hours.
13
14
  exports.DECIDE_WITHIN_MS = 15 * 60000;
14
15
  const RUN = 'run_[A-Za-z0-9_-]{16}';
15
16
  const SANDBOX = 'sbx_[A-Za-z0-9_-]{16}';
@@ -43,8 +44,9 @@ const READS = [
43
44
  const ACTIONS = [`runs/${RUN}/(cancel|extend|wake)`].map(path);
44
45
  // what the delete buttons remove: a sandbox of the person's
45
46
  const REMOVALS = [`sandboxes/${SANDBOX}`].map(path);
46
- // what needs a recent sign-in
47
+ // what needs a recent sign-in: deciding, and starting a run with the person's accounts
47
48
  const DECISIONS = [`approvals/${RUN}/(approve|reject)`, `proposals/${HASH}/(approve|reject)`].map(path);
49
+ const STARTS = [`runs/${RUN}/retry`].map(path);
48
50
  exports.HEADERS = {
49
51
  'cache-control': 'no-store',
50
52
  'x-robots-tag': 'noindex',
@@ -116,7 +118,8 @@ async function api(context, principal, viewer, now, req, res, url) {
116
118
  const target = url.pathname.slice('/api'.length);
117
119
  const read = READS.some((pattern) => pattern.test(target));
118
120
  const action = ACTIONS.some((pattern) => pattern.test(target));
119
- const decision = DECISIONS.some((pattern) => pattern.test(target));
121
+ const start = STARTS.some((pattern) => pattern.test(target));
122
+ const decision = start || DECISIONS.some((pattern) => pattern.test(target));
120
123
  const removal = REMOVALS.some((pattern) => pattern.test(target));
121
124
  if (!read && !action && !decision && !removal) {
122
125
  return (0, http_1.send)(res, 404, { error: 'not found' });
@@ -139,7 +142,7 @@ async function api(context, principal, viewer, now, req, res, url) {
139
142
  // an API token is new; a sign-in in the browser has to be of the last minutes to decide
140
143
  if (decision && context.signedInAt !== undefined && now - context.signedInAt > exports.DECIDE_WITHIN_MS) {
141
144
  return (0, http_1.send)(res, 403, {
142
- error: `approving and rejecting take a sign-in of the last ${exports.DECIDE_WITHIN_MS / 60000} minutes`,
145
+ error: `${start ? 'retrying a run takes' : 'approving and rejecting take'} a sign-in of the last ${exports.DECIDE_WITHIN_MS / 60000} minutes`,
143
146
  signInAgain: true,
144
147
  });
145
148
  }