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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.followPodLogs = exports.MAX_LOG_LINE_CHARS = void 0;
4
+ const stream_1 = require("stream");
5
+ const log_1 = require("../log");
6
+ const read_lines_1 = require("../utils/read-lines");
7
+ // what is read of an instance of a container that already ended
8
+ const MAX_ENDED_LOG_BYTES = 1024 * 1024;
9
+ // how often in a row the log of one instance is read again after its reading broke off at once
10
+ const MAX_READS = 20;
11
+ // the most of one line of a followed log that is held, its timestamp included
12
+ exports.MAX_LOG_LINE_CHARS = 64 * 1024;
13
+ // `timestamps: true` puts the time a line was written before it (RFC3339 with up to nine
14
+ // digits of a second), which says where a log that broke off got to
15
+ const TIMESTAMPED = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z(?: (.*))?$/;
16
+ /**
17
+ * Follows the log of a container in the pods of a selector, as `docker attach` does for a
18
+ * service on Docker: the instance that runs as it writes, and an instance that ended before
19
+ * it was seen (one that crashed and was restarted) once, from its start. Each instance is
20
+ * read once, by its container id.
21
+ */
22
+ function followPodLogs(instance, namespace, labelSelector, container, onLine, options = {}) {
23
+ const seen = new Set();
24
+ const positions = new Map();
25
+ // the logs followed now, resolved when they end
26
+ const streams = new Map();
27
+ const following = new Map();
28
+ // the instances that ended, by the last look
29
+ const ended = new Set();
30
+ const reading = new Set();
31
+ let stopped = false;
32
+ let failed = false;
33
+ let timer;
34
+ let polling = Promise.resolve();
35
+ let busy = false;
36
+ let again = false;
37
+ // the logs followed now, which end when their instance does
38
+ let streaming = 0;
39
+ const fail = (e) => {
40
+ if (!failed && !stopped) {
41
+ failed = true;
42
+ options.onError?.(`the log of ${container} could not be read: ${(0, log_1.getErrorMessage)(e)}`);
43
+ }
44
+ };
45
+ const track = (promise) => {
46
+ const tracked = promise.catch(fail).finally(() => reading.delete(tracked));
47
+ reading.add(tracked);
48
+ };
49
+ const positionOf = (id) => {
50
+ let position = positions.get(id);
51
+ if (!position) {
52
+ position = { at: null, since: null, count: 0, reads: 0 };
53
+ positions.set(id, position);
54
+ }
55
+ return position;
56
+ };
57
+ // a reader of the log of one instance from where it got to: the lines read before, again
58
+ // at the start of a log read since their second, are passed over
59
+ const reader = (position) => {
60
+ const from = position.at;
61
+ const skip = position.count;
62
+ let atFrom = 0;
63
+ return (raw) => {
64
+ const match = TIMESTAMPED.exec(raw);
65
+ if (!match) {
66
+ onLine(raw);
67
+ return;
68
+ }
69
+ const at = `${match[1]}.${(match[2] ?? '').padEnd(9, '0')}`;
70
+ if (from !== null && at <= from) {
71
+ if (at < from || ++atFrom <= skip) {
72
+ return;
73
+ }
74
+ }
75
+ if (at === position.at) {
76
+ position.count++;
77
+ }
78
+ else {
79
+ position.at = at;
80
+ position.since = `${match[1]}Z`;
81
+ position.count = 1;
82
+ }
83
+ onLine(match[3] ?? '');
84
+ };
85
+ };
86
+ const readEnded = async (pod, id, previous) => {
87
+ const position = positionOf(id);
88
+ position.reads++;
89
+ const log = await instance.coreApi.readNamespacedPodLog({
90
+ name: pod,
91
+ namespace,
92
+ container,
93
+ previous,
94
+ timestamps: true,
95
+ limitBytes: MAX_ENDED_LOG_BYTES,
96
+ // this call takes no sinceTime: a minute more than since then, for clocks that differ
97
+ ...(position.since
98
+ ? { sinceSeconds: Math.max(1, Math.ceil((Date.now() - Date.parse(position.since)) / 1000) + 60) }
99
+ : {}),
100
+ });
101
+ const read = reader(position);
102
+ for (const line of String(log ?? '').split(/\r?\n/)) {
103
+ if (line.length > 0) {
104
+ read(line);
105
+ }
106
+ }
107
+ };
108
+ const follow = async (pod, id) => {
109
+ const position = positionOf(id);
110
+ position.reads++;
111
+ const output = new stream_1.PassThrough();
112
+ const started = Date.now();
113
+ let over = false;
114
+ let done = () => undefined;
115
+ const stream = new Promise((resolve) => (done = resolve));
116
+ streams.set(id, stream);
117
+ // the instance ended or the request broke: it is looked at again at once, a restarted
118
+ // one followed, and what this one wrote after the break read from where it got to
119
+ const end = () => {
120
+ if (!over) {
121
+ over = true;
122
+ streaming--;
123
+ // a follow that lasted is cut now and then (a quiet stretch, a proxy): only reads
124
+ // that break off at once count against the limit
125
+ if (Date.now() - started >= 10000) {
126
+ position.reads = 0;
127
+ }
128
+ streams.delete(id);
129
+ following.delete(id);
130
+ done();
131
+ if (!stopped && position.reads < MAX_READS) {
132
+ seen.delete(id);
133
+ }
134
+ wake();
135
+ }
136
+ };
137
+ // stop() aborts the request, which errors the stream the client pipes in here
138
+ output.on('pipe', (source) => source.on('error', () => {
139
+ end();
140
+ }));
141
+ output.on('end', end);
142
+ (0, read_lines_1.readLines)(output, exports.MAX_LOG_LINE_CHARS, reader(position));
143
+ streaming++;
144
+ let controller;
145
+ try {
146
+ controller = await instance.log.log(namespace, pod, container, output, {
147
+ follow: true,
148
+ timestamps: true,
149
+ ...(position.since ? { sinceTime: position.since } : {}),
150
+ });
151
+ }
152
+ catch (e) {
153
+ end();
154
+ throw e;
155
+ }
156
+ if (stopped) {
157
+ controller.abort();
158
+ }
159
+ else {
160
+ following.set(id, controller);
161
+ }
162
+ };
163
+ const look = (pod) => {
164
+ const name = pod.metadata?.name;
165
+ const status = pod.status?.containerStatuses?.find((s) => s.name === container);
166
+ // a pod that goes is of a Deployment before this one, or of a rollout that replaced it
167
+ if (!name || !status || pod.metadata?.deletionTimestamp) {
168
+ return;
169
+ }
170
+ // an instance that ended before this one, not seen while it ran: its lines go first
171
+ let before = Promise.resolve();
172
+ const last = status.lastState?.terminated?.containerID;
173
+ const current = status.containerID;
174
+ if (last) {
175
+ ended.add(last);
176
+ }
177
+ if (current && status.state?.terminated) {
178
+ ended.add(current);
179
+ }
180
+ if (last && !seen.has(last)) {
181
+ seen.add(last);
182
+ before = readEnded(name, last, true).catch(fail);
183
+ track(before);
184
+ }
185
+ if (!current || seen.has(current)) {
186
+ return;
187
+ }
188
+ if (status.state?.running) {
189
+ seen.add(current);
190
+ track(before.then(() => follow(name, current)));
191
+ }
192
+ else if (status.state?.terminated) {
193
+ seen.add(current);
194
+ track(before.then(() => readEnded(name, current, false)));
195
+ }
196
+ };
197
+ const poll = async () => {
198
+ try {
199
+ const pods = await instance.coreApi.listNamespacedPod({ namespace, labelSelector });
200
+ if (!stopped) {
201
+ pods.items.forEach(look);
202
+ }
203
+ }
204
+ catch (e) {
205
+ fail(e);
206
+ }
207
+ };
208
+ const loop = () => {
209
+ if (stopped) {
210
+ return;
211
+ }
212
+ busy = true;
213
+ polling = poll().finally(() => {
214
+ busy = false;
215
+ if (stopped) {
216
+ return;
217
+ }
218
+ if (again) {
219
+ again = false;
220
+ loop();
221
+ return;
222
+ }
223
+ const interval = streaming > 0 ? options.followingInterval ?? 15000 : options.pollInterval ?? 1000;
224
+ timer = setTimeout(loop, interval);
225
+ timer.unref?.();
226
+ });
227
+ };
228
+ // looks now, not at the next interval
229
+ function wake() {
230
+ if (stopped) {
231
+ return;
232
+ }
233
+ if (busy) {
234
+ again = true;
235
+ return;
236
+ }
237
+ clearTimeout(timer);
238
+ loop();
239
+ }
240
+ loop();
241
+ return {
242
+ async settle() {
243
+ await polling;
244
+ await poll();
245
+ // what follows an instance that ended ends by itself once it has read all there is
246
+ const endedStreams = () => [...streams].filter(([id]) => ended.has(id));
247
+ await within(Promise.all([...reading, ...endedStreams().map(([, stream]) => stream)]), 5000);
248
+ // one still going after that is cut, and read from where it got to
249
+ const cut = endedStreams();
250
+ if (cut.length > 0) {
251
+ for (const [id] of cut) {
252
+ following.get(id)?.abort();
253
+ }
254
+ await within(Promise.all(cut.map(([, stream]) => stream)), 1000);
255
+ await poll();
256
+ await within(Promise.all([...reading]), 5000);
257
+ }
258
+ },
259
+ stop() {
260
+ stopped = true;
261
+ clearTimeout(timer);
262
+ for (const controller of following.values()) {
263
+ controller.abort();
264
+ }
265
+ following.clear();
266
+ },
267
+ };
268
+ }
269
+ exports.followPodLogs = followPodLogs;
270
+ async function within(promise, ms) {
271
+ let wait;
272
+ await Promise.race([
273
+ promise,
274
+ new Promise((resolve) => {
275
+ wait = setTimeout(resolve, ms);
276
+ wait.unref?.();
277
+ }),
278
+ ]);
279
+ clearTimeout(wait);
280
+ }
281
+ //# sourceMappingURL=follow-pod-logs.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getContainerSecurity = exports.getRunLabels = exports.getRunLabelValue = exports.RUN_LABEL = exports.getPodPlacement = exports.placeOnPool = exports.getNodeArch = exports.runInToolImage = exports.getLocalTaskPool = void 0;
3
+ exports.getPodRuntimeClass = exports.getContainerSecurity = exports.getRunLabels = exports.getRunLabelValue = exports.RUN_LABEL = exports.getPodPlacement = exports.placeOnPool = exports.getNodeArch = exports.runInToolImage = exports.getLocalTaskPool = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  /**
6
6
  * The pool a local task runs on: the first that offers its platform. A pool says
@@ -34,6 +34,7 @@ function runInToolImage(task, server, platform) {
34
34
  user: null,
35
35
  mounts: [],
36
36
  volumeSize: null,
37
+ capAdd: [],
37
38
  pool: pool.name,
38
39
  arch: getNodeArch(pool),
39
40
  };
@@ -82,18 +83,41 @@ exports.getRunLabels = getRunLabels;
82
83
  /**
83
84
  * What a container of a run may do on a server, where it shares nodes with the pods of
84
85
  * other callers: no privilege escalation (setuid binaries such as sudo), no raw sockets
85
- * (spoofing on a bridge network) and the runtime's seccomp profile.
86
+ * (spoofing on a bridge network) and the runtime's seccomp profile. The capabilities a
87
+ * task adds (`capAdd`) come on top, in the sandbox of getPodRuntimeClass on a server.
86
88
  */
87
- function getContainerSecurity(kubernetes) {
88
- return kubernetes.server
89
- ? {
90
- securityContext: {
91
- allowPrivilegeEscalation: false,
92
- capabilities: { drop: ['NET_RAW'] },
93
- seccompProfile: { type: 'RuntimeDefault' },
94
- },
95
- }
96
- : {};
89
+ function getContainerSecurity(kubernetes, capAdd = []) {
90
+ const add = capAdd.length > 0 ? { add: [...capAdd] } : {};
91
+ if (!kubernetes.server) {
92
+ return capAdd.length > 0 ? { securityContext: { capabilities: add } } : {};
93
+ }
94
+ const drop = capAdd.includes('NET_RAW') ? {} : { drop: ['NET_RAW'] };
95
+ return {
96
+ securityContext: {
97
+ allowPrivilegeEscalation: false,
98
+ capabilities: { ...drop, ...add },
99
+ seccompProfile: { type: 'RuntimeDefault' },
100
+ },
101
+ };
97
102
  }
98
103
  exports.getContainerSecurity = getContainerSecurity;
104
+ /**
105
+ * The RuntimeClass of the pod of a task that adds capabilities on a server: the sandbox the
106
+ * operator named (`backend.capabilities.runtimeClass`), so the capabilities hold in its own
107
+ * kernel and never in the node's. Elsewhere the cluster is the build file's own.
108
+ */
109
+ function getPodRuntimeClass(task, kubernetes) {
110
+ if (task.capAdd.length === 0 || !kubernetes.server) {
111
+ return {};
112
+ }
113
+ const sandbox = kubernetes.server.capabilities;
114
+ if (!sandbox) {
115
+ throw new Error(`${task.name}: adds the capabilities ${task.capAdd.join(', ')}, which this server grants in no sandboxed runtime`);
116
+ }
117
+ if (sandbox.unavailable) {
118
+ throw new Error(`${task.name}: adds the capabilities ${task.capAdd.join(', ')}, but ${sandbox.unavailable}`);
119
+ }
120
+ return { runtimeClassName: sandbox.runtimeClass };
121
+ }
122
+ exports.getPodRuntimeClass = getPodRuntimeClass;
99
123
  //# sourceMappingURL=job-placement.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.evictKeptClaims = exports.sweepKeptClaims = exports.expireKeptClaims = exports.recordClaimState = exports.forgetClaimState = exports.useClaimState = exports.isKeptClaim = exports.getClaimName = exports.EXPIRES_ANNOTATION = exports.STATE_ANNOTATION = exports.KEPT_BY_LABEL = exports.VOLUME_SCOPE_LABEL = void 0;
3
+ exports.evictKeptClaims = exports.sweepKeptClaims = exports.expireKeptClaims = exports.recordClaimState = exports.forgetClaimState = exports.rememberedClaimState = exports.useClaimState = exports.isKeptClaim = exports.getClaimName = exports.EXPIRES_ANNOTATION = exports.STATE_ANNOTATION = exports.KEPT_BY_LABEL = exports.VOLUME_SCOPE_LABEL = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const apply_1 = require("./apply");
6
6
  const sleep_1 = require("../utils/sleep");
@@ -98,6 +98,21 @@ async function annotate(instance, namespace, name, annotations) {
98
98
  throw e;
99
99
  }
100
100
  }
101
+ // The state key of the outputs whose folder is whole in the claim of a task of a service run
102
+ // (see getStateFilesDir), null when it names none (also while the claim is being removed),
103
+ // undefined when there is no claim. The run's namespace is its own, and only the run writes
104
+ // to the claim: it forgets the state before it writes, records it after.
105
+ async function rememberedClaimState(instance, kubernetes, name) {
106
+ const claim = await readClaim(instance, kubernetes.namespace, name);
107
+ if (!claim) {
108
+ return undefined;
109
+ }
110
+ if (claim.metadata?.deletionTimestamp) {
111
+ return null;
112
+ }
113
+ return claim.metadata?.annotations?.[exports.STATE_ANNOTATION] ?? null;
114
+ }
115
+ exports.rememberedClaimState = rememberedClaimState;
101
116
  // Before a task writes to its kept claim: the outputs in it stop being those of a state.
102
117
  // Whether the claim was there, with what an earlier run left in it.
103
118
  function forgetClaimState(instance, kubernetes, name) {
@@ -24,6 +24,7 @@ function createKubernetesInstances(kubernetes) {
24
24
  return {
25
25
  objectApi,
26
26
  log: new client_node_1.Log(kc),
27
+ metrics: new client_node_1.Metrics(kc),
27
28
  exec,
28
29
  appsApi,
29
30
  coreApi,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeSandboxProxies = exports.getProxyReadinessScript = exports.removeAllKubernetesItemNetworks = exports.releaseKubernetesItemNetwork = exports.awaitPodsEnded = exports.removeKubernetesItemNetwork = exports.ensureKubernetesItemNetwork = exports.buildProxyPolicy = exports.buildNetworkPolicy = exports.getNetworkPolicyName = exports.getSandboxProxy = exports.getProxyName = exports.getNetworkLabels = exports.NETWORK_PROXY = exports.NETWORK_LIMITED = exports.NETWORK_LABEL = exports.RUN_LABEL = void 0;
3
+ exports.removeSandboxProxies = exports.getProxyReadinessScript = exports.removeAllKubernetesItemNetworks = exports.releaseKubernetesItemNetwork = exports.awaitPodsEnded = exports.removeKubernetesItemNetwork = exports.ensureKubernetesItemNetwork = exports.buildProxyPolicy = exports.buildNetworkPolicy = exports.getNetworkPolicyName = exports.getSandboxProxy = exports.getProxyName = exports.getNetworkLabels = exports.NETWORK_PROXY = exports.NETWORK_LIMITED = exports.NETWORK_LABEL = exports.PROXY_OF_SANDBOX_LABEL = exports.RUN_LABEL = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const stream_1 = require("stream");
6
6
  const readline_1 = require("readline");
@@ -21,7 +21,7 @@ const resources_1 = require("./resources");
21
21
  const PROXY_LABEL = 'hammerkit.dev/proxy-for';
22
22
  const NETWORK_OF_LABEL = 'hammerkit.dev/network-of';
23
23
  // on the proxy of a task on a sandbox: the sandbox, whose pod of files it stays with
24
- const PROXY_OF_SANDBOX_LABEL = 'hammerkit.dev/proxy-of-sandbox';
24
+ exports.PROXY_OF_SANDBOX_LABEL = 'hammerkit.dev/proxy-of-sandbox';
25
25
  const PROXY_READY_TIMEOUT_MS = 60000;
26
26
  // the token of the endpoints of secret providers, in a Secret named like the proxy
27
27
  const SECRET_TOKEN_KEY = 'token';
@@ -77,7 +77,7 @@ exports.getSandboxProxy = getSandboxProxy;
77
77
  function getProxyLabels(env, item, proxy) {
78
78
  return {
79
79
  [NETWORK_OF_LABEL]: item.id(),
80
- ...(proxy.sandbox ? { [PROXY_OF_SANDBOX_LABEL]: proxy.sandbox.label } : (0, job_placement_1.getRunLabels)(env)),
80
+ ...(proxy.sandbox ? { [exports.PROXY_OF_SANDBOX_LABEL]: proxy.sandbox.label } : (0, job_placement_1.getRunLabels)(env)),
81
81
  };
82
82
  }
83
83
  function getNetworkPolicyName(item, scope) {
@@ -129,7 +129,8 @@ function buildNetworkPolicy(env, item, network, scope, proxy = getRunProxy(item,
129
129
  namespace: env.namespace,
130
130
  name: getNetworkPolicyName(item, scope),
131
131
  annotations: { 'hammerkit.dev/version': (0, version_1.getVersion)() },
132
- labels: { [NETWORK_OF_LABEL]: item.id(), ...(0, job_placement_1.getRunLabels)(env) },
132
+ labels: { [NETWORK_OF_LABEL]: item.id(), ...(scope.owners ? {} : (0, job_placement_1.getRunLabels)(env)) },
133
+ ...(scope.owners ? { ownerReferences: scope.owners } : {}),
133
134
  },
134
135
  spec: {
135
136
  podSelector: { matchLabels: getItemPodLabels(item, scope) },
@@ -542,7 +543,7 @@ async function removeSandboxProxies(instance, namespace, of, keep = () => false)
542
543
  const deployments = await instance.appsApi.listNamespacedDeployment({
543
544
  namespace,
544
545
  labelSelector: [
545
- `${PROXY_OF_SANDBOX_LABEL}=${of.sandbox}`,
546
+ `${exports.PROXY_OF_SANDBOX_LABEL}=${of.sandbox}`,
546
547
  ...(of.item ? [`${NETWORK_OF_LABEL}=${of.item.id()}`] : []),
547
548
  ].join(','),
548
549
  });
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QuotaWait = exports.exceedsQuota = exports.getQuotaRefusal = exports.QUOTA_TIMEOUT = void 0;
4
+ const units_1 = require("../utils/units");
5
+ // How long a pod the quota of its namespace refuses waits for room before what needs it fails:
6
+ // a transfer pod in any case, a task's or service's only when no pod that will end holds the
7
+ // room (see QuotaWait)
8
+ exports.QUOTA_TIMEOUT = 10 * 60 * 1000;
9
+ // What a refusal of the quota of the namespace says, from where it starts: `exceeded quota:
10
+ // hammerkit, requested: limits.memory=4Gi, used: limits.memory=24Gi, limited: limits.memory=26Gi`
11
+ function getQuotaRefusal(message) {
12
+ const index = message ? message.search(/exceeded quota/i) : -1;
13
+ return message && index >= 0 ? message.slice(index) : null;
14
+ }
15
+ exports.getQuotaRefusal = getQuotaRefusal;
16
+ // A pod that asks for more of a resource than the quota allows at all never fits.
17
+ function exceedsQuota(refusal) {
18
+ const requested = readAmounts(/requested: (\S+?)(?:,\s|$)/.exec(refusal)?.[1]);
19
+ const limited = readAmounts(/limited: (\S+?)(?:,\s|$)/.exec(refusal)?.[1]);
20
+ return [...requested].some(([resource, amount]) => {
21
+ const limit = limited.get(resource);
22
+ return limit !== undefined && amount > limit;
23
+ });
24
+ }
25
+ exports.exceedsQuota = exceedsQuota;
26
+ // `limits.memory=4Gi,requests.cpu=1` → limits.memory 4Gi, requests.cpu 1
27
+ function readAmounts(list = '') {
28
+ const amounts = new Map();
29
+ for (const entry of list.split(',')) {
30
+ const [resource, value] = entry.split('=');
31
+ const amount = (0, units_1.parseQuantity)(value);
32
+ if (resource && amount !== undefined) {
33
+ amounts.set(resource, amount);
34
+ }
35
+ }
36
+ return amounts;
37
+ }
38
+ // A pod that will end and free its room: one of a Job (a task) or a pod of its own (the copy of
39
+ // a task's files). The pods of a Deployment (a service) stay as long as what needs them.
40
+ function willEnd(pod) {
41
+ if (pod.metadata?.deletionTimestamp || (pod.status?.phase !== 'Pending' && pod.status?.phase !== 'Running')) {
42
+ return false;
43
+ }
44
+ return !(pod.metadata?.ownerReferences ?? []).some((owner) => owner.kind === 'ReplicaSet');
45
+ }
46
+ /**
47
+ * The wait of a pod the quota of its namespace refuses. It is told what the quota refused,
48
+ * fails at once when the pod asks for more than the quota allows at all, and after `timeout`
49
+ * goes on waiting only while a pod that will end (a task's, another run's) holds room in the
50
+ * namespace: when only services hold it, they wait for what waits for them, and it fails.
51
+ */
52
+ class QuotaWait {
53
+ constructor(instance, env, options) {
54
+ this.instance = instance;
55
+ this.env = env;
56
+ this.options = options;
57
+ this.since = null;
58
+ this.told = '';
59
+ }
60
+ // Called on each poll with what the quota refused now, or null when nothing is refused.
61
+ async check(refusal) {
62
+ const now = this.options.now ?? Date.now;
63
+ if (!refusal) {
64
+ this.since = null;
65
+ return;
66
+ }
67
+ if (refusal !== this.told) {
68
+ this.told = refusal;
69
+ this.options.onWaiting?.(`waits for room under the quota of the namespace: ${refusal}`);
70
+ }
71
+ if (exceedsQuota(refusal)) {
72
+ throw new Error(`${this.options.subject} asks for more than the quota of the namespace allows: ${refusal}`);
73
+ }
74
+ this.since = this.since ?? now();
75
+ if (now() - this.since < this.options.timeout) {
76
+ return;
77
+ }
78
+ if (await this.othersWillEnd()) {
79
+ // checked again after another `timeout`
80
+ this.since = now();
81
+ return;
82
+ }
83
+ throw new Error(`${this.options.subject} did not fit the quota of the namespace within ${Math.round(this.options.timeout / 60000)} minutes, and only services hold its room: ${refusal}`);
84
+ }
85
+ async othersWillEnd() {
86
+ try {
87
+ const pods = await this.instance.coreApi.listNamespacedPod({ namespace: this.env.namespace });
88
+ return pods.items.some(willEnd);
89
+ }
90
+ catch {
91
+ // what it can not see may still end
92
+ return true;
93
+ }
94
+ }
95
+ }
96
+ exports.QuotaWait = QuotaWait;
97
+ //# sourceMappingURL=quota-wait.js.map
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getStaleItemSelector = exports.removeStaleItems = void 0;
4
+ const job_placement_1 = require("./job-placement");
5
+ const resources_1 = require("./resources");
6
+ const apply_1 = require("./apply");
7
+ /**
8
+ * What a service run made for items it has no more, once it moved to another commit: the
9
+ * Deployment, Service, Secret, policies and Jobs of a service or task whose id changed (a new
10
+ * image, other volumes). Their claims stay, with the namespace of the run.
11
+ */
12
+ async function removeStaleItems(instance, env, ids) {
13
+ if (!env.server) {
14
+ return;
15
+ }
16
+ const namespace = env.namespace;
17
+ const labelSelector = getStaleItemSelector(env.server.run, ids);
18
+ const selector = { namespace, labelSelector };
19
+ await instance.appsApi.deleteCollectionNamespacedDeployment({ ...selector, propagationPolicy: 'Background' });
20
+ await instance.batchApi.deleteCollectionNamespacedJob({ ...selector, propagationPolicy: 'Background' });
21
+ await instance.coreApi.deleteCollectionNamespacedService(selector);
22
+ await instance.coreApi.deleteCollectionNamespacedSecret(selector);
23
+ const policies = await instance.objectApi.list('networking.k8s.io/v1', 'NetworkPolicy', namespace, undefined, undefined, undefined, undefined, labelSelector);
24
+ for (const policy of policies.items) {
25
+ const metadata = { name: policy.metadata?.name, namespace };
26
+ await instance.objectApi
27
+ .delete({ apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata })
28
+ .catch((e) => {
29
+ if ((0, apply_1.statusCodeOf)(e) !== 404) {
30
+ throw e;
31
+ }
32
+ });
33
+ }
34
+ }
35
+ exports.removeStaleItems = removeStaleItems;
36
+ // the objects of the run's items but those of `ids`
37
+ function getStaleItemSelector(run, ids) {
38
+ const current = [...new Set(ids)].sort();
39
+ return [
40
+ `${job_placement_1.RUN_LABEL}=${(0, job_placement_1.getRunLabelValue)(run)}`,
41
+ resources_1.ID_LABEL,
42
+ ...(current.length > 0 ? [`${resources_1.ID_LABEL} notin (${current.join(',')})`] : []),
43
+ ].join(',');
44
+ }
45
+ exports.getStaleItemSelector = getStaleItemSelector;
46
+ //# sourceMappingURL=remove-stale-items.js.map
@@ -1,34 +1,61 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.restoreKubernetesData = exports.getRestoreTarget = void 0;
3
+ exports.restoreKubernetesData = exports.getRestoreTarget = exports.RESTORE_FILE = void 0;
4
4
  const event_cache_1 = require("../executer/event-cache");
5
5
  const log_1 = require("../log");
6
6
  const volumes_1 = require("./volumes");
7
7
  const ensure_persistent_data_1 = require("./ensure-persistent-data");
8
8
  const claim_layout_1 = require("./claim-layout");
9
+ // Unpacks the archive of an output that is a file to `$1`: by its content, since the name in
10
+ // the archive is the file's and the one in the claim may carry a hash (see getClaimSubPath)
11
+ exports.RESTORE_FILE = 'mkdir -p "$(dirname "$1")" && rm -rf "$1" && tar xzf - -O > "$1"';
9
12
  // Where the upload pod (which mounts the work's claim at /dev/hammerkit/<id>) unpacks the
10
13
  // archive of an output: the output's place in the claim, which its mount reads
11
- function getRestoreTarget(work, path) {
12
- return `/dev/hammerkit/${work.id()}/${(0, claim_layout_1.getClaimSubPath)(work, path)}`;
14
+ function getRestoreTarget(work, path,
15
+ // the folder of the state on a service run, see getStateFilesDir
16
+ stateDir) {
17
+ return `/dev/hammerkit/${work.id()}/${stateDir ? `${stateDir}/` : ''}${(0, claim_layout_1.getClaimSubPath)(work, path)}`;
13
18
  }
14
19
  exports.getRestoreTarget = getRestoreTarget;
15
20
  async function restoreKubernetesData(work, kubernetes, instance, environment, path,
16
- // the kept claim of the work holds what an earlier run left, which goes first
21
+ // the kept claim of the work holds what an earlier run left, which goes first; on a
22
+ // service run, the outputs go into the folder of `stateKey` (see getStateFilesDir);
23
+ // `otherStates`: the folders of the other states go but these (the ones pods of the run
24
+ // mount), and the folder of `stateKey` is emptied first
17
25
  options = {}) {
18
- const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes);
19
- await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'write', async (name) => {
26
+ const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes, options.stateKey);
27
+ const stateDir = kubernetes.server?.serviceRun ? (0, volumes_1.getItemFilesDir)(work, options.stateKey) : undefined;
28
+ // an output that is a file: its archive holds it alone (see storeKubernetesData), and it
29
+ // takes the place of whatever is at its path in the claim
30
+ const files = new Set(work.data.type === 'container-task'
31
+ ? work.data.generates
32
+ .filter((generate) => generate.isFile && !generate.inherited)
33
+ .map((generate) => generate.path)
34
+ : []);
35
+ // a run stopped while the pod waits for room under the quota
36
+ const { signal } = environment.abortCtrl;
37
+ await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'write', signal, async (name) => {
20
38
  if (options.reset) {
21
39
  await (0, ensure_persistent_data_1.clearClaim)(instance, kubernetes, work, name);
22
40
  }
41
+ if (stateDir && options.otherStates) {
42
+ await (0, ensure_persistent_data_1.clearStateFiles)(instance, kubernetes, work, name, stateDir, options.otherStates);
43
+ }
23
44
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path)) {
24
45
  if (!(await environment.file.exists(generatedArchive.filename))) {
25
46
  continue;
26
47
  }
27
- const targetPath = getRestoreTarget(work, generatedArchive.path);
48
+ const targetPath = getRestoreTarget(work, generatedArchive.path, stateDir);
28
49
  // a claim made for this run (a server removes the claims of a run when it
29
50
  // ends) does not have the directory of the output yet
30
51
  let failure = null;
31
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', ['sh', '-c', 'mkdir -p "$1" && tar xzf - -C "$1"', 'sh', targetPath], process.stdout, process.stderr, environment.file.readStream(generatedArchive.filename), false, (status) => {
52
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', [
53
+ 'sh',
54
+ '-c',
55
+ files.has(generatedArchive.path) ? exports.RESTORE_FILE : 'mkdir -p "$1" && tar xzf - -C "$1"',
56
+ 'sh',
57
+ targetPath,
58
+ ], process.stdout, process.stderr, environment.file.readStream(generatedArchive.filename), false, (status) => {
32
59
  work.status.write('debug', `upload ${generatedArchive.filename} to ${name}: ${status.status}`);
33
60
  if (status.status !== 'Success') {
34
61
  failure = status.message ?? status.reason ?? 'unknown';