hammerkit 2.0.0-next.2 → 2.0.0-next.21

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 (112) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/index-DRSwIRXd.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +31 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +35 -14
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +100 -13
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-retry.js +57 -0
  91. package/dist/server/run-source-environment.js +39 -0
  92. package/dist/server/run-worker.js +71 -9
  93. package/dist/server/runs.js +133 -7
  94. package/dist/server/sandbox-files.js +339 -55
  95. package/dist/server/sandbox-patch.js +43 -17
  96. package/dist/server/sandboxes.js +57 -23
  97. package/dist/server/server-config.js +28 -5
  98. package/dist/server/server.js +150 -20
  99. package/dist/server/service-runs.js +50 -5
  100. package/dist/server/sources.js +68 -11
  101. package/dist/server/timings.js +23 -3
  102. package/dist/utils/buffer-context.js +30 -20
  103. package/dist/utils/limit.js +30 -0
  104. package/dist/utils/line-splitter.js +52 -0
  105. package/dist/utils/read-lines.js +65 -0
  106. package/dist/utils/tar.js +51 -1
  107. package/dist/utils/units.js +36 -1
  108. package/dist/utils/web-links.js +34 -0
  109. package/package.json +1 -1
  110. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  111. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  112. package/dist/dashboard/favicon.svg +0 -1
@@ -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,
@@ -519,16 +519,25 @@ function registerWorkCommands(remote, context) {
519
519
  .command('tasks [server]')
520
520
  .description('show what the past runs of each task took, over the runs the server keeps: how often it ran, failed and came from the cache, the median and 90th percentile of its time, and how long its runs waited for a place')
521
521
  .addOption(new commander_1.Option('--mine', 'only your runs'))
522
+ .addOption(new commander_1.Option('--since <when>', 'only the runs created since then: back from now, such as 24h or 7d, or a time'))
523
+ .addOption(new commander_1.Option('--until <when>', 'only the runs created until then: back from now, or a time'))
522
524
  .addOption(new commander_1.Option('--json', 'print it as the server answers it'))
523
525
  .action(guarded('Remote tasks was not successful', async (name, options) => {
524
526
  const { name: serverName, server, token } = await connect(name);
525
- const { tasks } = (await (0, server_client_1.callServer)(server, token, 'GET', `/v1/tasks?scope=${options.mine ? 'mine' : 'visible'}`)).body;
527
+ const query = new URLSearchParams({ scope: options.mine ? 'mine' : 'visible' });
528
+ if (options.since) {
529
+ query.set('since', options.since);
530
+ }
531
+ if (options.until) {
532
+ query.set('until', options.until);
533
+ }
534
+ const { tasks } = (await (0, server_client_1.callServer)(server, token, 'GET', `/v1/tasks?${query}`)).body;
526
535
  if (options.json) {
527
536
  environment.stdout.write(`${JSON.stringify(tasks, null, 2)}\n`);
528
537
  return;
529
538
  }
530
539
  if (tasks.length === 0) {
531
- environment.stdout.write(`${serverName}: no task ran in the runs it keeps\n`);
540
+ environment.stdout.write(`${serverName}: no task ran in the runs it keeps${options.since || options.until ? ' of that period' : ''}\n`);
532
541
  return;
533
542
  }
534
543
  for (const line of (0, remote_status_1.describeTaskStats)(tasks)) {
@@ -674,11 +683,23 @@ function registerWorkCommands(remote, context) {
674
683
  const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/cancel`)).body;
675
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`);
676
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
+ }));
677
698
  remote
678
699
  .command('verify <tasks...>')
679
700
  .description('check that the server already passed tasks for the files checked out here, without running them; ' +
680
701
  'exits 1 at once for any it did not')
681
- .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'))
682
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'))
683
704
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
684
705
  .action(guarded('Remote verify was not successful', async (tasks, options) => {
@@ -700,7 +721,7 @@ function registerWorkCommands(remote, context) {
700
721
  keys.push({ task, key: found.key });
701
722
  }
702
723
  }
703
- const { name: serverName, server, token } = await connect(options.server);
724
+ const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
704
725
  const answer = keys.length > 0
705
726
  ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
706
727
  : { body: { checks: [] } };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.appendBuildFile = exports.createParseContext = void 0;
3
+ exports.appendBuildFile = exports.MAX_BUILD_FILE_ITEMS = exports.MAX_BUILD_FILE_BYTES = exports.MAX_INCLUDE_INPUT_BYTES = exports.MAX_BUILD_FILES = exports.MAX_INCLUDE_DEPTH = exports.createParseContext = void 0;
4
4
  const build_file_schema_1 = require("./build-file-schema");
5
5
  const read_build_file_1 = require("../parser/read-build-file");
6
6
  const path_1 = require("path");
@@ -20,6 +20,17 @@ async function createParseContext(fileName, environment, options) {
20
20
  return { ctx, scope };
21
21
  }
22
22
  exports.createParseContext = createParseContext;
23
+ // How deep includes and references may nest, how many build files one parse may read (a
24
+ // file included with other inputs counts again), and how large the inputs one include
25
+ // passes on may be. A file that includes itself with inputs that change each time ends at
26
+ // these instead of reading on without end.
27
+ exports.MAX_INCLUDE_DEPTH = 32;
28
+ exports.MAX_BUILD_FILES = 1000;
29
+ exports.MAX_INCLUDE_INPUT_BYTES = 64 * 1024;
30
+ // What the build files of one parse may take together, and how many tasks and services they
31
+ // may declare, a file included again counted again.
32
+ exports.MAX_BUILD_FILE_BYTES = 16 * 1024 * 1024;
33
+ exports.MAX_BUILD_FILE_ITEMS = 10000;
23
34
  async function appendBuildFile(cwd, ctx, environment, fileName, namePrefix, remote, inputs,
24
35
  // on a server: the file is included with `publish: false`, or below such an include
25
36
  leftOut = false) {
@@ -30,12 +41,26 @@ leftOut = false) {
30
41
  if (ctx.files[key]) {
31
42
  return ctx.files[key];
32
43
  }
33
- const input = await (0, read_build_file_1.read)(fileName, environment);
44
+ if (namePrefix.length > exports.MAX_INCLUDE_DEPTH) {
45
+ throw new Error(`${relativeName} (${fileName}) is included ${namePrefix.length} levels deep, at most ${exports.MAX_INCLUDE_DEPTH} are read`);
46
+ }
47
+ if (Object.keys(ctx.files).length >= exports.MAX_BUILD_FILES) {
48
+ throw new Error(`${relativeName} (${fileName}): the build file includes more than ${exports.MAX_BUILD_FILES} files, counting a file included with other inputs again`);
49
+ }
50
+ if (inputs && Buffer.byteLength(JSON.stringify(inputs), 'utf8') > exports.MAX_INCLUDE_INPUT_BYTES) {
51
+ throw new Error(`${relativeName} (${fileName}): the inputs passed to it take more than ${exports.MAX_INCLUDE_INPUT_BYTES} bytes`);
52
+ }
53
+ const input = await readCounted(ctx, fileName, environment, relativeName);
34
54
  (0, removed_properties_1.assertNoRemovedProperties)(input, fileName);
35
55
  const result = await build_file_schema_1.buildFileSchema.safeParseAsync(input);
36
56
  if (!result.success) {
37
57
  throw new parse_error_1.ParseError(result.error, fileName);
38
58
  }
59
+ const read = readOf(ctx);
60
+ read.items += Object.keys(result.data.tasks ?? {}).length + Object.keys(result.data.services ?? {}).length;
61
+ if (read.items > exports.MAX_BUILD_FILE_ITEMS) {
62
+ throw new Error(`${relativeName} (${fileName}): the build file declares more than ${exports.MAX_BUILD_FILE_ITEMS} tasks and services, counting a file included with other inputs again`);
63
+ }
39
64
  const scope = {
40
65
  fileName,
41
66
  cwd,
@@ -77,6 +102,25 @@ leftOut = false) {
77
102
  return scope;
78
103
  }
79
104
  exports.appendBuildFile = appendBuildFile;
105
+ // A build file, parsed once per parse and counted each time it is read.
106
+ async function readCounted(ctx, fileName, environment, relativeName) {
107
+ const read = readOf(ctx);
108
+ let parsed = read.parsed.get(fileName);
109
+ if (!parsed) {
110
+ parsed = await (0, read_build_file_1.readSized)(fileName, environment);
111
+ read.parsed.set(fileName, parsed);
112
+ }
113
+ read.bytes += parsed.bytes;
114
+ if (read.bytes > exports.MAX_BUILD_FILE_BYTES) {
115
+ throw new Error(`${relativeName} (${fileName}): the build file includes more than ${exports.MAX_BUILD_FILE_BYTES} bytes of build files, counting a file included with other inputs again`);
116
+ }
117
+ // every scope gets a value of its own
118
+ return structuredClone(parsed.value);
119
+ }
120
+ function readOf(ctx) {
121
+ ctx.read ?? (ctx.read = { bytes: 0, items: 0, parsed: new Map() });
122
+ return ctx.read;
123
+ }
80
124
  // The scope of a git source a server does not fetch, see ParseScope.notFetched
81
125
  function notFetched(cwd, namePrefix, include) {
82
126
  return {
@@ -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);
@@ -4,41 +4,11 @@ exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.Kubern
4
4
  const os_1 = require("os");
5
5
  const log_1 = require("../log");
6
6
  const apply_1 = require("../kubernetes/apply");
7
- const UNITS = {
8
- n: 1e-9,
9
- u: 1e-6,
10
- m: 1e-3,
11
- '': 1,
12
- k: 1e3,
13
- K: 1e3,
14
- M: 1e6,
15
- G: 1e9,
16
- T: 1e12,
17
- P: 1e15,
18
- E: 1e18,
19
- Ki: 1024,
20
- Mi: 1024 ** 2,
21
- Gi: 1024 ** 3,
22
- Ti: 1024 ** 4,
23
- Pi: 1024 ** 5,
24
- Ei: 1024 ** 6,
25
- };
26
- // A quantity of Kubernetes (`250m`, `1.5`, `512Mi`, `12345678n`, `1e3`), as a number.
27
- function parseQuantity(value) {
28
- if (value === undefined) {
29
- return undefined;
30
- }
31
- if (typeof value === 'number') {
32
- return value;
33
- }
34
- const match = /^([+-]?[0-9.]+(?:[eE][+-]?\d+)?)([a-zA-Z]*)$/.exec(value.trim());
35
- if (!match || !(match[2] in UNITS)) {
36
- return undefined;
37
- }
38
- const number = Number(match[1]);
39
- return Number.isFinite(number) ? number * UNITS[match[2]] : undefined;
40
- }
41
- exports.parseQuantity = parseQuantity;
7
+ const job_placement_1 = require("../kubernetes/job-placement");
8
+ const volumes_1 = require("../kubernetes/volumes");
9
+ const network_policy_1 = require("../kubernetes/network-policy");
10
+ const units_1 = require("../utils/units");
11
+ Object.defineProperty(exports, "parseQuantity", { enumerable: true, get: function () { return units_1.parseQuantity; } });
42
12
  function add(into, cpu, memory) {
43
13
  if (cpu !== undefined) {
44
14
  into.cpu = (into.cpu ?? 0) + cpu;
@@ -90,6 +60,17 @@ function why(what, e, rule) {
90
60
  }
91
61
  return `${what}: ${(0, log_1.getErrorMessage)(e)}`;
92
62
  }
63
+ // `why`, in a few words
64
+ function briefly(e, what) {
65
+ const code = (0, apply_1.statusCodeOf)(e);
66
+ if (code === 403) {
67
+ return what === 'nodes' ? 'may not list nodes' : 'may not read metrics';
68
+ }
69
+ if (code === 404 && what === 'metrics') {
70
+ return 'no metrics API';
71
+ }
72
+ return what === 'nodes' ? 'nodes not readable' : 'metrics not readable';
73
+ }
93
74
  const ENDED = ['Succeeded', 'Failed'];
94
75
  // On Kubernetes: per namespace of the server, its pods' requests, its quota and its usage.
95
76
  class KubernetesCapacity {
@@ -107,6 +88,37 @@ class KubernetesCapacity {
107
88
  catch (e) {
108
89
  problems.push(why('the namespaces of the server', e));
109
90
  }
91
+ const unknown = {};
92
+ // the runs by the value of their label, and what the pods of each run or sandbox take
93
+ const byLabel = new Map(runs.map((run) => [(0, job_placement_1.getRunLabelValue)(run.id), run]));
94
+ const uses = new Map();
95
+ const useOf = (namespace, labels, owner) => {
96
+ const run = byLabel.get(labels?.[job_placement_1.RUN_LABEL] ?? '');
97
+ const sandbox = labels?.[volumes_1.SANDBOX_LABEL] ?? labels?.[network_policy_1.PROXY_OF_SANDBOX_LABEL];
98
+ const key = run ? `run ${run.id}` : sandbox ? `sandbox ${sandbox}` : `other ${namespace}`;
99
+ let use = uses.get(key);
100
+ if (!use) {
101
+ use = run
102
+ ? {
103
+ kind: 'run',
104
+ run: run.id,
105
+ tasks: run.tasks,
106
+ ...(run.up ? { up: { name: run.up.name, services: run.up.services } } : {}),
107
+ repo: run.source.type === 'upload' ? 'an upload' : run.source.repo,
108
+ owner: { iss: run.owner.iss, sub: run.owner.sub, ...(run.owner.name ? { name: run.owner.name } : {}) },
109
+ pods: 0,
110
+ requested: { cpu: 0, memory: 0 },
111
+ }
112
+ : {
113
+ kind: sandbox ? 'sandbox' : 'other',
114
+ ...(owner ? { owner } : {}),
115
+ pods: 0,
116
+ requested: { cpu: 0, memory: 0 },
117
+ };
118
+ uses.set(key, use);
119
+ }
120
+ return use;
121
+ };
110
122
  const said = new Set();
111
123
  const once = (text) => {
112
124
  if (!said.has(text)) {
@@ -123,6 +135,8 @@ class KubernetesCapacity {
123
135
  // a namespace whose pods could be listed and that has none asks for nothing
124
136
  requested: { cpu: 0, memory: 0 },
125
137
  };
138
+ // the use of each pod that runs, by its name
139
+ const usesOfPods = new Map();
126
140
  try {
127
141
  const pods = await this.instance.coreApi.listNamespacedPod({ namespace });
128
142
  for (const pod of pods.items) {
@@ -130,9 +144,13 @@ class KubernetesCapacity {
130
144
  continue;
131
145
  }
132
146
  group.pods++;
147
+ const use = useOf(namespace, pod.metadata?.labels, group.owner);
148
+ usesOfPods.set(pod.metadata?.name ?? '', use);
149
+ use.pods++;
133
150
  for (const container of pod.spec?.containers ?? []) {
134
151
  const requests = container.resources?.requests ?? {};
135
- add(group.requested, parseQuantity(requests.cpu) ?? 0, parseQuantity(requests.memory) ?? 0);
152
+ add(group.requested, (0, units_1.parseQuantity)(requests.cpu) ?? 0, (0, units_1.parseQuantity)(requests.memory) ?? 0);
153
+ add(use.requested, (0, units_1.parseQuantity)(requests.cpu) ?? 0, (0, units_1.parseQuantity)(requests.memory) ?? 0);
136
154
  }
137
155
  }
138
156
  }
@@ -145,8 +163,8 @@ class KubernetesCapacity {
145
163
  namespace,
146
164
  });
147
165
  const hard = quota.spec?.hard ?? {};
148
- const cpu = parseQuantity(hard['requests.cpu'] ?? hard.cpu);
149
- const memory = parseQuantity(hard['requests.memory'] ?? hard.memory);
166
+ const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
167
+ const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
150
168
  if (cpu !== undefined || memory !== undefined) {
151
169
  group.quota = { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
152
170
  }
@@ -162,13 +180,19 @@ class KubernetesCapacity {
162
180
  const metrics = await this.instance.metrics.getPodMetrics(namespace);
163
181
  const used = { cpu: 0, memory: 0 };
164
182
  for (const pod of metrics.items) {
183
+ const use = usesOfPods.get(pod.metadata?.name ?? '');
165
184
  for (const container of pod.containers) {
166
- add(used, parseQuantity(container.usage.cpu), parseQuantity(container.usage.memory));
185
+ add(used, (0, units_1.parseQuantity)(container.usage.cpu), (0, units_1.parseQuantity)(container.usage.memory));
186
+ if (use) {
187
+ use.used ?? (use.used = { cpu: 0, memory: 0 });
188
+ add(use.used, (0, units_1.parseQuantity)(container.usage.cpu), (0, units_1.parseQuantity)(container.usage.memory));
189
+ }
167
190
  }
168
191
  }
169
192
  group.used = used;
170
193
  }
171
194
  catch (e) {
195
+ unknown.used ?? (unknown.used = briefly(e, 'metrics'));
172
196
  once(why('what the pods use (metrics)', e, 'list on pods.metrics.k8s.io in them (runRole, see the backend docs)'));
173
197
  }
174
198
  }
@@ -191,7 +215,7 @@ class KubernetesCapacity {
191
215
  const allocatable = {};
192
216
  for (const node of nodes.items) {
193
217
  const of = node.status?.allocatable ?? {};
194
- add(allocatable, parseQuantity(of.cpu), parseQuantity(of.memory));
218
+ add(allocatable, (0, units_1.parseQuantity)(of.cpu), (0, units_1.parseQuantity)(of.memory));
195
219
  }
196
220
  machines = { count: nodes.items.length, allocatable };
197
221
  if (this.instance.metrics) {
@@ -199,16 +223,18 @@ class KubernetesCapacity {
199
223
  const metrics = await this.instance.metrics.getNodeMetrics();
200
224
  const nodesUsed = {};
201
225
  for (const node of metrics.items) {
202
- add(nodesUsed, parseQuantity(node.usage.cpu), parseQuantity(node.usage.memory));
226
+ add(nodesUsed, (0, units_1.parseQuantity)(node.usage.cpu), (0, units_1.parseQuantity)(node.usage.memory));
203
227
  }
204
228
  machines.used = nodesUsed;
205
229
  }
206
230
  catch (e) {
231
+ unknown.used ?? (unknown.used = briefly(e, 'metrics'));
207
232
  once(why('what the nodes use (metrics)', e, 'list on nodes.metrics.k8s.io (see the backend docs)'));
208
233
  }
209
234
  }
210
235
  }
211
236
  catch (e) {
237
+ unknown.total = briefly(e, 'nodes');
212
238
  // listing nodes is optional, and many clusters do not let a workload do it
213
239
  if ((0, apply_1.statusCodeOf)(e) === 403) {
214
240
  once('the nodes: not shown, the server may not list nodes (optional, see the backend docs)');
@@ -223,7 +249,11 @@ class KubernetesCapacity {
223
249
  ...(machines ? { machines } : {}),
224
250
  runs: total,
225
251
  groups,
252
+ uses: [...uses.values()].sort((a, b) => (b.used?.cpu ?? 0) - (a.used?.cpu ?? 0) ||
253
+ (b.requested.cpu ?? 0) - (a.requested.cpu ?? 0) ||
254
+ (b.requested.memory ?? 0) - (a.requested.memory ?? 0)),
226
255
  problems,
256
+ ...(Object.keys(unknown).length > 0 ? { unknown } : {}),
227
257
  };
228
258
  }
229
259
  }
@@ -5,12 +5,15 @@ const crypto_1 = require("crypto");
5
5
  const promises_1 = require("fs/promises");
6
6
  const path_1 = require("path");
7
7
  const http_1 = require("./http");
8
+ const oauth_1 = require("./oauth");
8
9
  const policy_1 = require("./policy");
9
10
  const overview_1 = require("./overview");
10
- // Approving and publishing take a sign-in of the last minutes: the groups of a session are
11
- // 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.
12
14
  exports.DECIDE_WITHIN_MS = 15 * 60000;
13
15
  const RUN = 'run_[A-Za-z0-9_-]{16}';
16
+ const SANDBOX = 'sbx_[A-Za-z0-9_-]{16}';
14
17
  // a hash of a build file version, checked by the API
15
18
  const HASH = '[A-Za-z0-9:_-]{1,200}';
16
19
  const path = (pattern) => new RegExp(`^/v1/${pattern}$`);
@@ -28,11 +31,22 @@ const READS = [
28
31
  'proposals',
29
32
  `proposals/${HASH}`,
30
33
  `proposals/${HASH}/files`,
34
+ // the build files, and the page of the version a task or run ran
35
+ 'definitions',
36
+ `definitions/${HASH}`,
37
+ `definitions/${HASH}/files`,
38
+ // the person's sandboxes and what changed in them; not their files, nothing that writes
39
+ 'sandboxes',
40
+ `sandboxes/${SANDBOX}`,
41
+ `sandboxes/${SANDBOX}/changes`,
31
42
  ].map(path);
32
43
  // what the buttons do
33
- const ACTIONS = [`runs/${RUN}/(cancel|extend)`].map(path);
34
- // what needs a recent sign-in
44
+ const ACTIONS = [`runs/${RUN}/(cancel|extend|wake)`].map(path);
45
+ // what the delete buttons remove: a sandbox of the person's
46
+ const REMOVALS = [`sandboxes/${SANDBOX}`].map(path);
47
+ // what needs a recent sign-in: deciding, and starting a run with the person's accounts
35
48
  const DECISIONS = [`approvals/${RUN}/(approve|reject)`, `proposals/${HASH}/(approve|reject)`].map(path);
49
+ const STARTS = [`runs/${RUN}/retry`].map(path);
36
50
  exports.HEADERS = {
37
51
  'cache-control': 'no-store',
38
52
  'x-robots-tag': 'noindex',
@@ -52,8 +66,8 @@ const TYPES = {
52
66
  };
53
67
  async function handleDashboard(context, principal, req, res, url) {
54
68
  const now = context.now ?? Date.now;
55
- const grant = (0, policy_1.getGrant)(context.config.entitlements, principal);
56
- const viewer = { principal, grant, activity: context.config.runs.activity === 'everyone' };
69
+ const viewer = (0, overview_1.getViewer)(context.config, principal);
70
+ const { grant } = viewer;
57
71
  const pathname = url.pathname;
58
72
  for (const [name, value] of Object.entries(exports.HEADERS)) {
59
73
  res.setHeader(name, value);
@@ -78,9 +92,11 @@ async function api(context, principal, viewer, now, req, res, url) {
78
92
  if (method !== 'GET') {
79
93
  return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
80
94
  }
95
+ const name = (0, oauth_1.displayName)(principal);
81
96
  const session = {
82
97
  iss: principal.iss,
83
98
  sub: principal.sub,
99
+ ...(name ? { name } : {}),
84
100
  observe: grant.observe,
85
101
  seesOthers: grant.observe || (0, overview_1.seesActivity)(viewer),
86
102
  publishes: (0, policy_1.mayPublish)(grant),
@@ -102,16 +118,21 @@ async function api(context, principal, viewer, now, req, res, url) {
102
118
  const target = url.pathname.slice('/api'.length);
103
119
  const read = READS.some((pattern) => pattern.test(target));
104
120
  const action = ACTIONS.some((pattern) => pattern.test(target));
105
- const decision = DECISIONS.some((pattern) => pattern.test(target));
106
- if (!read && !action && !decision) {
121
+ const start = STARTS.some((pattern) => pattern.test(target));
122
+ const decision = start || DECISIONS.some((pattern) => pattern.test(target));
123
+ const removal = REMOVALS.some((pattern) => pattern.test(target));
124
+ if (!read && !action && !decision && !removal) {
107
125
  return (0, http_1.send)(res, 404, { error: 'not found' });
108
126
  }
127
+ const allow = [read ? 'GET' : '', action || decision ? 'POST' : '', removal ? 'DELETE' : '']
128
+ .filter(Boolean)
129
+ .join(', ');
109
130
  if (method === 'GET' || method === 'HEAD') {
110
131
  if (!read) {
111
- return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
132
+ return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow });
112
133
  }
113
134
  }
114
- else if (method === 'POST' && (action || decision)) {
135
+ else if ((method === 'POST' && (action || decision)) || (method === 'DELETE' && removal)) {
115
136
  // a page of another site can not set the header, nor read the token
116
137
  const given = Buffer.from(String(req.headers['x-hammerkit-csrf'] ?? ''));
117
138
  const expected = Buffer.from(csrf);
@@ -121,14 +142,14 @@ async function api(context, principal, viewer, now, req, res, url) {
121
142
  // an API token is new; a sign-in in the browser has to be of the last minutes to decide
122
143
  if (decision && context.signedInAt !== undefined && now - context.signedInAt > exports.DECIDE_WITHIN_MS) {
123
144
  return (0, http_1.send)(res, 403, {
124
- 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`,
125
146
  signInAgain: true,
126
147
  });
127
148
  }
128
149
  context.log(`dashboard ${method} ${target} iss=${principal.iss} sub=${principal.sub}`);
129
150
  }
130
151
  else {
131
- return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: read ? 'GET' : 'POST' });
152
+ return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow });
132
153
  }
133
154
  const forwarded = new URL(`${target}${url.search}`, 'http://localhost');
134
155
  return context.api(principal, req, res, forwarded);
@@ -165,8 +186,8 @@ async function asset(context, req, res, pathname) {
165
186
  const root = context.assets ?? (0, path_1.join)(__dirname, '..', 'dashboard');
166
187
  const file = /^\/assets\/[A-Za-z0-9_-][A-Za-z0-9._-]{0,200}$/.test(pathname)
167
188
  ? pathname.slice(1)
168
- : pathname === '/favicon.svg'
169
- ? 'favicon.svg'
189
+ : pathname === '/logo.png'
190
+ ? 'logo.png'
170
191
  : pathname.startsWith('/assets/') || pathname.startsWith('/.')
171
192
  ? undefined
172
193
  : 'index.html';
@@ -285,7 +285,15 @@ class EndpointGateway {
285
285
  return null;
286
286
  }
287
287
  const session = this.readSession(label, req.headers.cookie);
288
- return session ? { iss: session.iss, sub: session.sub, groups: session.groups, claims: session.claims } : null;
288
+ return session
289
+ ? {
290
+ iss: session.iss,
291
+ sub: session.sub,
292
+ groups: session.groups,
293
+ claims: session.claims,
294
+ ...(session.name ? { name: session.name } : {}),
295
+ }
296
+ : null;
289
297
  }
290
298
  // Whether the browser sends the request for another page than the endpoint's own: an
291
299
  // upgrade from another origin, or a request a page of another site makes (a frame too),
@@ -652,6 +660,7 @@ ${run.state === 'up'
652
660
  host: label,
653
661
  iss: issued.principal.iss,
654
662
  sub: issued.principal.sub,
663
+ ...((0, oauth_1.displayName)(issued.principal) ? { name: (0, oauth_1.displayName)(issued.principal) } : {}),
655
664
  groups: issued.principal.groups,
656
665
  claims: this.matchedClaims(issued.principal),
657
666
  exp,