hammerkit 2.1.0 → 2.2.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 (97) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/docker/item-network.js +6 -5
  8. package/dist/docker/remove-orphaned-containers.js +5 -4
  9. package/dist/environment/replace-env-variables.js +8 -5
  10. package/dist/environment/run-source-envs.js +2 -1
  11. package/dist/executer/archive-task-entry.js +1 -1
  12. package/dist/executer/check-readiness.js +8 -4
  13. package/dist/executer/docker-healthcheck.js +73 -0
  14. package/dist/executer/docker-service.js +21 -15
  15. package/dist/executer/event-cache.js +5 -1
  16. package/dist/executer/runner-commands.js +36 -0
  17. package/dist/file/get-file-context.js +4 -7
  18. package/dist/harness/connect.js +12 -8
  19. package/dist/harness/reconnect.js +141 -0
  20. package/dist/harness/sandbox-client.js +241 -33
  21. package/dist/harness/service-tools.js +11 -2
  22. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  23. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  24. package/dist/kubernetes/follow-pod-logs.js +8 -5
  25. package/dist/kubernetes/kept-claims.js +38 -14
  26. package/dist/kubernetes/sandbox-runner.js +526 -156
  27. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  28. package/dist/kubernetes/sync-changes.js +463 -0
  29. package/dist/kubernetes/volumes.js +23 -1
  30. package/dist/network/healthcheck-request.js +38 -0
  31. package/dist/optimizer/get-work-cache-stats.js +7 -0
  32. package/dist/optimizer/work-task-cache-description.js +5 -3
  33. package/dist/planner/image-build.js +5 -0
  34. package/dist/planner/service-definition.js +2 -1
  35. package/dist/planner/utils/append-work-service.js +12 -4
  36. package/dist/planner/utils/dependency-outputs.js +7 -6
  37. package/dist/planner/validate.js +41 -0
  38. package/dist/planner/work-healthcheck.js +23 -2
  39. package/dist/planner/work-item-status.js +12 -2
  40. package/dist/planner/work-runtime-aggregate.js +1 -0
  41. package/dist/planner/work-runtime-docker.js +33 -6
  42. package/dist/planner/work-runtime-kubernetes.js +313 -70
  43. package/dist/planner/work-runtime-local.js +8 -4
  44. package/dist/planner/work-secret.js +33 -11
  45. package/dist/planner/work-service-id.js +30 -6
  46. package/dist/planner/work-service.js +2 -2
  47. package/dist/program.js +19 -1
  48. package/dist/remote/annotations.js +8 -2
  49. package/dist/remote/bundle.js +6 -8
  50. package/dist/remote/device-login.js +4 -1
  51. package/dist/remote/remote-commands.js +16 -7
  52. package/dist/remote/remote-status.js +1 -1
  53. package/dist/remote/remote-work-commands.js +220 -68
  54. package/dist/remote/server-client.js +38 -40
  55. package/dist/schema/build-file-base-task-schema.js +16 -1
  56. package/dist/schema/build-file-image-build-schema.js +5 -8
  57. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  58. package/dist/schema/reference-parser.js +108 -43
  59. package/dist/schema/work-scope-parser.js +8 -0
  60. package/dist/secrets/prefetch-secrets.js +20 -1
  61. package/dist/server/artifacts-api.js +56 -0
  62. package/dist/server/borrowed-quota.js +216 -0
  63. package/dist/server/capacity.js +18 -6
  64. package/dist/server/definitions-api.js +62 -8
  65. package/dist/server/executor.js +117 -30
  66. package/dist/server/http.js +4 -1
  67. package/dist/server/keep-artifacts.js +230 -0
  68. package/dist/server/kubernetes-backend.js +292 -79
  69. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  70. package/dist/server/overview.js +73 -9
  71. package/dist/server/paging.js +167 -0
  72. package/dist/server/plan.js +16 -1
  73. package/dist/server/run-access.js +24 -0
  74. package/dist/server/run-artifacts.js +171 -0
  75. package/dist/server/run-logs.js +25 -1
  76. package/dist/server/run-request.js +11 -0
  77. package/dist/server/run-source-environment.js +1 -1
  78. package/dist/server/run-worker.js +267 -33
  79. package/dist/server/runs.js +531 -105
  80. package/dist/server/sandbox-files-api.js +27 -12
  81. package/dist/server/sandbox-files.js +12 -10
  82. package/dist/server/sandbox-follow.js +54 -0
  83. package/dist/server/sandbox-pod.js +1 -1
  84. package/dist/server/sandbox-storage.js +38 -1
  85. package/dist/server/sandbox-sync.js +392 -0
  86. package/dist/server/sandboxes-api.js +116 -19
  87. package/dist/server/sandboxes.js +38 -3
  88. package/dist/server/server-config.js +73 -2
  89. package/dist/server/server.js +169 -38
  90. package/dist/server/task-order.js +56 -0
  91. package/dist/utils/project-path.js +20 -0
  92. package/dist/utils/tar-files.js +52 -0
  93. package/dist/utils/tar.js +37 -1
  94. package/package.json +1 -1
  95. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  96. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  97. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -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) {
@@ -9,6 +9,7 @@ const run_plan_1 = require("./run-plan");
9
9
  const oauth_1 = require("./oauth");
10
10
  const policy_1 = require("./policy");
11
11
  const proposals_1 = require("./proposals");
12
+ const paging_1 = require("./paging");
12
13
  // A bundle is JSON text with escapes, so the body may be somewhat larger than the files.
13
14
  const MAX_PUBLISH_BYTES = bundle_1.MAX_BUNDLE_BYTES * 2;
14
15
  /**
@@ -19,7 +20,11 @@ const MAX_PUBLISH_BYTES = bundle_1.MAX_BUNDLE_BYTES * 2;
19
20
  * Beside entry and files the body may carry
20
21
  * `annotations`, which are not part of the hash
21
22
  * GET /v1/definitions the versions, newest first; `?<key>=<value>`
22
- * keeps the ones with those annotations
23
+ * keeps the ones with those annotations (a key
24
+ * repeated, with any of its values), `q` the ones
25
+ * with the text; `limit` and `cursor` page them,
26
+ * `values=<key>` answers the values of an
27
+ * annotation (paging.ts)
23
28
  * GET /v1/definitions/<hash> one version, with `arguments`: per task null when
24
29
  * a run of it may pass arguments, else why not
25
30
  * GET /v1/definitions/<hash>/files its files
@@ -67,13 +72,15 @@ async function handleDefinitions(config, store, proposals, log, principal, req,
67
72
  return true;
68
73
  }
69
74
  if (hash === undefined) {
70
- const wanted = [...url.searchParams.entries()];
71
- (0, http_1.send)(res, 200, {
72
- definitions: store
73
- .list()
74
- .filter((version) => wanted.every(([key, value]) => version.annotations?.[key] === value))
75
- .map(toSummary),
76
- });
75
+ try {
76
+ listDefinitions(store, url.searchParams, res);
77
+ }
78
+ catch (e) {
79
+ if (!(e instanceof paging_1.ListParamError)) {
80
+ throw e;
81
+ }
82
+ (0, http_1.send)(res, 400, { error: e.message });
83
+ }
77
84
  return true;
78
85
  }
79
86
  const found = store.find(hash);
@@ -91,6 +98,53 @@ async function handleDefinitions(config, store, proposals, log, principal, req,
91
98
  return true;
92
99
  }
93
100
  exports.handleDefinitions = handleDefinitions;
101
+ // the parameters of the list that are not annotations to filter by
102
+ const LIST_PARAMS = ['q', 'limit', 'cursor', 'values', 'search'];
103
+ // GET /v1/definitions: the versions with the annotations and the text asked for, a page of
104
+ // them, or the values of an annotation.
105
+ function listDefinitions(store, params, res) {
106
+ const wanted = new Map();
107
+ for (const [key, value] of params) {
108
+ if (!LIST_PARAMS.includes(key)) {
109
+ wanted.set(key, [...(wanted.get(key) ?? []), value]);
110
+ }
111
+ }
112
+ const text = (0, paging_1.readText)(params);
113
+ // any annotation has values, those of a key no version has are none
114
+ const asked = params.get('values');
115
+ if (asked !== null && !bundle_1.ANNOTATION_KEY_PATTERN.test(asked)) {
116
+ throw new paging_1.ListParamError('values: the key of an annotation');
117
+ }
118
+ const values = asked !== null ? (0, paging_1.parseValues)(params, [asked]) : undefined;
119
+ const page = values ? undefined : (0, paging_1.parsePage)(params);
120
+ const found = (except) => store
121
+ .list()
122
+ .filter((version) => [...wanted].every(([key, accepted]) => key === except || accepted.includes(version.annotations?.[key] ?? '\0')) &&
123
+ (!text ||
124
+ (0, paging_1.hasText)([
125
+ version.hash,
126
+ version.entry,
127
+ version.publishedBy.sub,
128
+ ...Object.values(version.annotations ?? {}),
129
+ ...version.tasks,
130
+ ...version.services,
131
+ ], text)));
132
+ if (values) {
133
+ // the values an annotation has, counted over the versions the other filters let through
134
+ const key = values.field;
135
+ const counted = (0, paging_1.countValues)(found(key), (version) => (version.annotations?.[key] !== undefined ? [version.annotations[key]] : []), values);
136
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('values', counted));
137
+ return;
138
+ }
139
+ const listed = found();
140
+ if (!page) {
141
+ (0, http_1.send)(res, 200, { definitions: listed.map(toSummary) });
142
+ return;
143
+ }
144
+ const key = (version) => [version.publishedAt, version.hash];
145
+ const answered = (0, paging_1.pageByKey)((0, paging_1.newestFirst)(listed, key), page, key);
146
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('definitions', { ...answered, items: answered.items.map(toSummary) }));
147
+ }
94
148
  // What the list shows of a version: who published it and when, and what it runs as.
95
149
  function toSummary(version) {
96
150
  const { hash, entry, publishedAt, publishedBy, approvedBy, annotations, tasks, services, accounts, yanked } = version;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostExecutor = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
3
+ exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const checks_1 = require("./checks");
@@ -10,10 +10,12 @@ const path_1 = require("path");
10
10
  const readline_1 = require("readline");
11
11
  const resolve_git_source_1 = require("../includes/resolve-git-source");
12
12
  const git_checkout_1 = require("./git-checkout");
13
+ const runs_1 = require("./runs");
13
14
  const run_plan_1 = require("./run-plan");
14
15
  const work_network_1 = require("../planner/work-network");
15
16
  const execute_docker_1 = require("../executer/execute-docker");
16
17
  const run_source_environment_1 = require("./run-source-environment");
18
+ const run_artifacts_1 = require("./run-artifacts");
17
19
  // `.git` as a file system may read it: any case, and a name Windows reads without its
18
20
  // trailing dots and spaces, or by its short name
19
21
  function isGitDirectory(segment) {
@@ -21,8 +23,12 @@ function isGitDirectory(segment) {
21
23
  return name === '.git' || name === 'git~1';
22
24
  }
23
25
  // A cancelled run gets this long to stop its tasks and remove its containers, after that
24
- // its process is killed
26
+ // its process is killed. A server without a store waits for it on close (CLOSE_TIMEOUT in
27
+ // runs.ts bounds only a server that detaches its runs)
25
28
  const STOP_GRACE_MS = 15000;
29
+ // A run the server leaves to the next one gets this long to stop its tasks on this machine: the
30
+ // rest of what CLOSE_TIMEOUT gives it is for its execution to end (its directory, its volumes)
31
+ const DETACH_GRACE_MS = runs_1.CLOSE_TIMEOUT - 5000;
26
32
  // what is kept of the error output of a process that died without saying why
27
33
  const MAX_STDERR = 2 * 1024;
28
34
  /**
@@ -120,11 +126,52 @@ exports.removeServiceRunVolumes = removeServiceRunVolumes;
120
126
  * nothing else. The cache is shared by the runs of the same source, a task is keyed by
121
127
  * its definition and sources and not by where they are.
122
128
  */
129
+ /**
130
+ * What a line the worker of a run wrote on its standard output does: the message it carries goes
131
+ * to the matching handler (a `sync-failed` one is told with the run's id). A line that is not a
132
+ * message is not the run's, and is left alone.
133
+ */
134
+ function relayWorkerLine(line, runId, relay) {
135
+ try {
136
+ const message = JSON.parse(line);
137
+ if (message.kind === 'event') {
138
+ relay.emit(message.event);
139
+ }
140
+ else if (message.kind === 'up') {
141
+ relay.up?.(message.targets);
142
+ }
143
+ else if (message.kind === 'sync-failed') {
144
+ relay.syncFailed?.(runId);
145
+ }
146
+ else if (message.kind === 'result') {
147
+ relay.result(message);
148
+ }
149
+ }
150
+ catch {
151
+ // not ours: whatever else the process prints is not an event of the run
152
+ }
153
+ }
154
+ exports.relayWorkerLine = relayWorkerLine;
123
155
  class HostExecutor {
124
156
  constructor(options) {
125
157
  this.options = options;
126
158
  // the directories of the executions that run now
127
159
  this.directories = new Set();
160
+ // the processes of the runs that run now, by run id, while they take input
161
+ this.children = new Map();
162
+ }
163
+ /**
164
+ * Hands the changed files of a sandbox to the process of a service run that is up here, which
165
+ * syncs them into its services (see run-worker). The archive goes in the line itself, so
166
+ * nothing is staged on this server. False when no process of the run runs here.
167
+ */
168
+ syncChildFiles(runId, changes) {
169
+ const child = this.children.get(runId);
170
+ if (!child?.stdin) {
171
+ return false;
172
+ }
173
+ child.stdin.write(`sync ${JSON.stringify({ ...changes, archive: changes.archive.toString('base64') })}\n`);
174
+ return true;
128
175
  }
129
176
  // the docker daemon the runs' services are on, as their processes reach it
130
177
  docker() {
@@ -212,6 +259,17 @@ class HostExecutor {
212
259
  if (refused) {
213
260
  throw new Error(refused);
214
261
  }
262
+ // the outputs of a run are not handed out when anything reads a credential, or when the
263
+ // local tasks of this host could write them: then the run keeps none and says why
264
+ const wanted = context.artifacts && !run.up ? context.artifacts : undefined;
265
+ const noArtifacts = wanted ? this.artifactsRefusal(planned.plan) : null;
266
+ const artifacts = noArtifacts ? undefined : wanted;
267
+ if (wanted && noArtifacts) {
268
+ const manifest = { refused: noArtifacts, outputs: [], left: [] };
269
+ await (0, promises_1.mkdir)(wanted.directory, { recursive: true });
270
+ await (0, promises_1.writeFile)((0, path_1.join)(wanted.directory, run_artifacts_1.ARTIFACTS_MANIFEST), JSON.stringify(manifest));
271
+ context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `keeps no outputs: ${noArtifacts}` });
272
+ }
215
273
  const abortCtrl = new AbortController();
216
274
  const abort = () => abortCtrl.abort();
217
275
  if (context.signal.aborted) {
@@ -239,12 +297,21 @@ class HostExecutor {
239
297
  // does a run that was approved: what was approved is those files, and the sandbox has
240
298
  // more (its ignored files, node_modules, outputs), which its owner and their runs write
241
299
  // while the run waits and runs.
242
- const copied = source.type === 'sandbox' && (source.check || (run.approvals?.length ?? 0) > 0);
300
+ // A service run from a sandbox on a cluster gets a copy of the files too: its pods mount no
301
+ // claim of the sandbox, and the files of later edits reach it by a move (RunRegistry.follow)
302
+ const approved = (run.approvals?.length ?? 0) > 0;
303
+ const onCluster = !!run.up && !!this.options.placement;
304
+ const copied = source.type === 'sandbox' && (source.check || approved || onCluster);
243
305
  // (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
244
306
  if (source.type === 'sandbox' && copied) {
245
- const { registry, network } = sandboxes;
246
- const what = source.check ? 'the check' : 'the approved run';
247
- if (!source.check) {
307
+ const { registry, network, started } = sandboxes;
308
+ const kind = source.check ? 'check' : approved ? 'approved run' : 'service run';
309
+ if (onCluster) {
310
+ // before the copy: a change from here on is one the services have not got
311
+ await started?.(run);
312
+ }
313
+ const what = `the ${kind}`;
314
+ if (!source.check && approved) {
248
315
  // what was approved is what runs: the files may have changed since, by a run
249
316
  // before this one on the sandbox (the copy checks it again, under the sandbox's lock)
250
317
  const state = await registry.state(source.id, abortCtrl.signal);
@@ -266,7 +333,7 @@ class HostExecutor {
266
333
  type: 'log',
267
334
  task: 'hammerkit',
268
335
  stream: 'stdout',
269
- text: `${source.check ? 'check' : 'approved run'} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
336
+ text: `${kind} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
270
337
  });
271
338
  // the tasks see the published build files in place of the sandbox's own
272
339
  await this.writeBundle(work, bundle.files);
@@ -346,22 +413,30 @@ class HostExecutor {
346
413
  volumeScope: volumeScope(run, this.options.directory),
347
414
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
415
  ...(context.durations ? { durations: context.durations } : {}),
416
+ // the commands it started in a sandbox's runner; the logs of its pods go in the
417
+ // cluster's environment (KubernetesExecutor)
418
+ ...(context.resumed?.outputs ? { resumed: { outputs: context.resumed.outputs } } : {}),
419
+ ...(artifacts ? { artifacts } : {}),
349
420
  catalog: planning.environment.hosted?.catalog,
350
421
  ...(run.up
351
422
  ? {
352
423
  up: {
353
424
  services: run.up.services,
354
425
  endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
426
+ ...(run.up.restart ? { restart: run.up.restart } : {}),
355
427
  },
356
428
  }
357
429
  : {}),
358
430
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
359
431
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
360
- }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal);
432
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed, run.id);
361
433
  }
362
434
  finally {
363
435
  if (placement && placed) {
364
- await placement.release(run, context);
436
+ // a run that resumes with the next server finds its Jobs and services where they are
437
+ if (!(0, runs_1.isDetached)(context)) {
438
+ await placement.release(run, context);
439
+ }
365
440
  }
366
441
  else if (run.up && !context.keep?.()) {
367
442
  // the services are gone with the process, their volumes stay only while the run sleeps
@@ -372,6 +447,9 @@ class HostExecutor {
372
447
  finally {
373
448
  context.signal.removeEventListener('abort', abort);
374
449
  attachment?.release?.();
450
+ if (run.up && this.options.placement) {
451
+ await sandboxes?.ended?.(run);
452
+ }
375
453
  await this.removeRunDirectory(run, root, context);
376
454
  this.directories.delete(root);
377
455
  if (source.type === 'sandbox') {
@@ -380,6 +458,10 @@ class HostExecutor {
380
458
  }
381
459
  }
382
460
  }
461
+ // why a run keeps none of its outputs: a credential its tasks read, or local tasks on this host
462
+ artifactsRefusal(plan) {
463
+ return this.options.localTasksOnHost ? run_artifacts_1.LOCAL_TASKS_REFUSAL : (0, run_artifacts_1.refuseArtifacts)(plan);
464
+ }
383
465
  directoryOf(run) {
384
466
  for (let execution = 1;; execution++) {
385
467
  const root = (0, path_1.join)(this.options.directory, execution === 1 ? run.id : `${run.id}-${execution}`);
@@ -428,7 +510,10 @@ class HostExecutor {
428
510
  // engine stops its tasks and removes its containers; a signal on Windows would end the
429
511
  // process at once and leave its tasks running in the directory of the run. The process is
430
512
  // killed if it has not stopped after the grace period.
431
- runInProcess(command, input, cwd, env, context, signal) {
513
+ // A run that the server leaves to the next one (RunContext.detached) and whose tasks are on
514
+ // a cluster: the process is killed at once, so its Jobs and services stay. One whose tasks
515
+ // are on this machine stops them as a cancel does, in less time.
516
+ runInProcess(command, input, cwd, env, context, signal, onCluster, runId) {
432
517
  return new Promise((resolvePromise, reject) => {
433
518
  const child = (0, child_process_1.spawn)(command[0], command.slice(1), {
434
519
  cwd,
@@ -439,16 +524,23 @@ class HostExecutor {
439
524
  child.stdin.on('error', () => undefined);
440
525
  // the run first, so a cancel comes after it; kept open, it is how a cancel reaches the process
441
526
  child.stdin.write(`${JSON.stringify(input)}\n`);
527
+ this.children.set(runId, child);
442
528
  let result;
443
529
  let stderr = '';
444
530
  let killTimer;
445
531
  const stop = () => {
532
+ const detaching = (0, runs_1.isDetached)(context);
533
+ if (detaching && onCluster) {
534
+ child.kill('SIGKILL');
535
+ return;
536
+ }
446
537
  child.stdin.write('cancel\n', (e) => {
447
538
  if (e) {
448
539
  child.kill();
449
540
  }
450
541
  });
451
- killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopGraceMs ?? STOP_GRACE_MS);
542
+ const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
543
+ killTimer = setTimeout(() => child.kill('SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
452
544
  killTimer.unref();
453
545
  };
454
546
  if (signal.aborted) {
@@ -457,25 +549,17 @@ class HostExecutor {
457
549
  else {
458
550
  signal.addEventListener('abort', stop, { once: true });
459
551
  }
460
- (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => {
461
- try {
462
- const message = JSON.parse(line);
463
- if (message.kind === 'event') {
464
- context.emit(message.event);
465
- }
466
- else if (message.kind === 'up') {
467
- context.up?.(message.targets);
468
- }
469
- else if (message.kind === 'result') {
470
- result = message;
471
- // nothing left to tell the process
472
- child.stdin.end();
473
- }
474
- }
475
- catch {
476
- // not ours: whatever else the process prints is not an event of the run
477
- }
478
- });
552
+ (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => relayWorkerLine(line, runId, {
553
+ emit: (event) => context.emit(event),
554
+ up: (targets) => context.up?.(targets),
555
+ syncFailed: (id) => this.options.sandboxes?.syncFailed?.(id),
556
+ result: (message) => {
557
+ result = message;
558
+ // nothing left to tell the process
559
+ this.children.delete(runId);
560
+ child.stdin.end();
561
+ },
562
+ }));
479
563
  child.stderr.on('data', (chunk) => {
480
564
  stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR);
481
565
  });
@@ -487,6 +571,9 @@ class HostExecutor {
487
571
  child.on('close', (code, killed) => {
488
572
  signal.removeEventListener('abort', stop);
489
573
  clearTimeout(killTimer);
574
+ if (this.children.get(runId) === child) {
575
+ this.children.delete(runId);
576
+ }
490
577
  if (result?.ok) {
491
578
  resolvePromise();
492
579
  }
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readJson = exports.MAX_BODY_BYTES = exports.HttpError = exports.send = void 0;
3
+ exports.readJson = exports.MAX_BODY_BYTES = exports.HttpError = exports.send = exports.RETRY_HEADER = void 0;
4
+ // Set to `safe` on an answer to a request the server took nothing of, such as a submit while it
5
+ // shuts down: a client may send it again, also a request it never sends twice otherwise.
6
+ exports.RETRY_HEADER = 'hammerkit-retry';
4
7
  function send(res, status, body, headers = {}) {
5
8
  res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers });
6
9
  res.end(JSON.stringify(body));