hammerkit 2.0.0-next.1 → 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 (63) hide show
  1. package/dist/cache/explain.js +7 -5
  2. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  3. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  4. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  5. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  6. package/dist/dashboard/index.html +3 -3
  7. package/dist/dashboard/logo.png +0 -0
  8. package/dist/executer/docker-task.js +3 -0
  9. package/dist/executer/execute-work-task.js +3 -1
  10. package/dist/executer/local-task.js +3 -0
  11. package/dist/executer/scheduler/enqueue-next.js +6 -1
  12. package/dist/executer/scheduler/state-key.js +71 -34
  13. package/dist/executer/watch-loop.js +18 -5
  14. package/dist/file/get-file-context.js +5 -1
  15. package/dist/kubernetes/await-running-state.js +69 -5
  16. package/dist/kubernetes/claim-layout.js +10 -1
  17. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  18. package/dist/kubernetes/ensure-persistent-data.js +108 -20
  19. package/dist/kubernetes/follow-pod-logs.js +128 -29
  20. package/dist/kubernetes/kept-claims.js +16 -1
  21. package/dist/kubernetes/network-policy.js +4 -4
  22. package/dist/kubernetes/quota-wait.js +97 -0
  23. package/dist/kubernetes/restore-kubernetes-data.js +27 -4
  24. package/dist/kubernetes/store-kubernetes-data.js +13 -2
  25. package/dist/kubernetes/volumes.js +34 -7
  26. package/dist/optimizer/calculate-checksum.js +46 -3
  27. package/dist/optimizer/check-keys.js +4 -2
  28. package/dist/optimizer/get-work-cache-stats.js +36 -24
  29. package/dist/parser/read-build-file.js +8 -3
  30. package/dist/planner/utils/template-value.js +20 -4
  31. package/dist/planner/work-item-executions.js +27 -0
  32. package/dist/planner/work-runtime-kubernetes.js +69 -41
  33. package/dist/remote/host-config.js +1 -1
  34. package/dist/remote/remote-work-commands.js +14 -5
  35. package/dist/schema/schema-parser.js +46 -2
  36. package/dist/server/capacity.js +71 -41
  37. package/dist/server/dashboard.js +27 -9
  38. package/dist/server/endpoints.js +10 -1
  39. package/dist/server/executor.js +65 -34
  40. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  41. package/dist/server/oauth.js +16 -1
  42. package/dist/server/overview.js +80 -11
  43. package/dist/server/plan.js +16 -3
  44. package/dist/server/policy.js +9 -3
  45. package/dist/server/run-worker.js +47 -6
  46. package/dist/server/runs.js +74 -6
  47. package/dist/server/sandbox-files.js +107 -16
  48. package/dist/server/sandbox-patch.js +43 -17
  49. package/dist/server/sandboxes.js +57 -23
  50. package/dist/server/server-config.js +4 -1
  51. package/dist/server/server.js +45 -10
  52. package/dist/server/service-runs.js +8 -1
  53. package/dist/server/sources.js +68 -11
  54. package/dist/server/timings.js +23 -3
  55. package/dist/utils/buffer-context.js +30 -20
  56. package/dist/utils/limit.js +30 -0
  57. package/dist/utils/read-lines.js +65 -0
  58. package/dist/utils/units.js +36 -1
  59. package/dist/utils/web-links.js +34 -0
  60. package/package.json +1 -1
  61. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  62. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  63. package/dist/dashboard/favicon.svg +0 -1
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensurePersistentData = exports.packSource = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = void 0;
3
+ exports.ensurePersistentData = exports.packSource = exports.clearStateFiles = exports.ENSURE_OUTPUT_FILES = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = exports.applyWithinQuota = exports.QUOTA_TIMEOUT = exports.TRANSFER_POD_RESOURCES = void 0;
4
+ const quota_wait_1 = require("./quota-wait");
5
+ Object.defineProperty(exports, "QUOTA_TIMEOUT", { enumerable: true, get: function () { return quota_wait_1.QUOTA_TIMEOUT; } });
4
6
  const volumes_1 = require("./volumes");
5
7
  const apply_1 = require("./apply");
6
8
  const path_1 = require("path");
@@ -8,6 +10,7 @@ const tar_1 = require("../utils/tar");
8
10
  const resources_1 = require("./resources");
9
11
  const await_running_state_1 = require("./await-running-state");
10
12
  const sleep_1 = require("../utils/sleep");
13
+ const abort_1 = require("../executer/abort");
11
14
  const version_1 = require("../version");
12
15
  const log_1 = require("../log");
13
16
  const ensure_kubernetes_persistent_volume_claim_exists_1 = require("./ensure-kubernetes-persistent-volume-claim-exists");
@@ -42,7 +45,41 @@ async function removeStalePod(instance, namespace, name) {
42
45
  await (0, sleep_1.sleep)(500);
43
46
  }
44
47
  }
45
- async function getPodForPersistence(instance, env, service, persistence, type, fn) {
48
+ // What the pod that copies files into and out of a claim gets: tar and find, through
49
+ // exec. Without its own, the default limit of the namespace is taken, which is sized for
50
+ // tasks (4Gi on a server), and a run's quota then has no room for the pods of its tasks.
51
+ exports.TRANSFER_POD_RESOURCES = {
52
+ requests: { cpu: '50m', memory: '64Mi' },
53
+ limits: { memory: '512Mi' },
54
+ };
55
+ // A Job waits for room under a full quota, a pod is refused: so a transfer pod is
56
+ // created again until the pods of the tasks it runs beside are done and make room
57
+ async function applyWithinQuota(instance, podSpec, service, timeout = quota_wait_1.QUOTA_TIMEOUT, pollInterval = 2000,
58
+ // a run stopped while it waits: it stops waiting
59
+ signal) {
60
+ const deadline = Date.now() + timeout;
61
+ for (let waiting = false;; waiting = true) {
62
+ if (signal) {
63
+ (0, abort_1.checkForAbort)(signal);
64
+ }
65
+ try {
66
+ return await (0, apply_1.apply)(instance, podSpec);
67
+ }
68
+ catch (e) {
69
+ if ((0, apply_1.statusCodeOf)(e) !== 403 || !/exceeded quota/i.test((0, log_1.getErrorMessage)(e)) || Date.now() >= deadline) {
70
+ throw e;
71
+ }
72
+ if (!waiting) {
73
+ service.status.write('info', `wait for room under the quota of ${podSpec.metadata.namespace}`);
74
+ }
75
+ await (0, sleep_1.sleep)(pollInterval);
76
+ }
77
+ }
78
+ }
79
+ exports.applyWithinQuota = applyWithinQuota;
80
+ async function getPodForPersistence(instance, env, service, persistence, type,
81
+ // stops a wait for room under the quota
82
+ signal, fn) {
46
83
  if (persistence.volumes.length === 0) {
47
84
  return;
48
85
  }
@@ -50,7 +87,11 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
50
87
  // and takes no upload
51
88
  const own = persistence.mounts.filter((m) => !m.workspace);
52
89
  const mounts = type === 'read'
53
- ? own.map((m) => m.mount)
90
+ ? // what a task stores are its outputs, which it mounts writable: its src and the
91
+ // outputs of its deps are not mounted, so an output inside a folder of its src
92
+ // (pkg/coverage/lcov.info) has a place in the pod even when the claim holds no src,
93
+ // after a restore into a new claim
94
+ own.filter((m) => service.data.type !== 'container-task' || !m.mount.readOnly).map((m) => m.mount)
54
95
  : own.reduce((array, v) => {
55
96
  if (!array.some((i) => i.name === v.mount.name)) {
56
97
  array.push({
@@ -61,11 +102,13 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
61
102
  }
62
103
  return array;
63
104
  }, []);
105
+ // only the claims it mounts: one of a dep it doesn't read would only bind where it goes
106
+ const volumes = persistence.volumes.filter((volume) => mounts.some((mount) => mount.name === volume.name));
64
107
  // Guarantee the claims exist right before scheduling the pod that mounts
65
108
  // them. ensurePersistentData also creates them, but store/restore reach this
66
109
  // function directly, and a claim shared with another work item can be removed
67
110
  // concurrently — without this the pod would hang Pending on "pvc not found".
68
- for (const volume of persistence.volumes) {
111
+ for (const volume of volumes) {
69
112
  await (0, ensure_kubernetes_persistent_volume_claim_exists_1.ensureKubernetesPersistentVolumeClaimExists)(instance, env, volume, service, persistence.sizes[volume.name], persistence.kept.includes(volume.name));
70
113
  }
71
114
  const name = (0, resources_1.getResourceName)(service, env, type === 'write' ? '-upload' : '-download');
@@ -73,7 +116,7 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
73
116
  // commit): the pod is not one its Service sends to
74
117
  const serving = !!env.server?.serviceRun && service.data.type === 'container-service';
75
118
  // and on a service run, it goes where the pods that mount the same claims run
76
- const claims = env.server?.serviceRun ? (0, volumes_1.getClaimPodSpec)(persistence.volumes) : { labels: {} };
119
+ const claims = env.server?.serviceRun ? (0, volumes_1.getClaimPodSpec)(volumes) : { labels: {} };
77
120
  const podSpec = {
78
121
  kind: 'Pod',
79
122
  apiVersion: 'v1',
@@ -102,15 +145,16 @@ async function getPodForPersistence(instance, env, service, persistence, type, f
102
145
  command: ['sh'],
103
146
  tty: true,
104
147
  volumeMounts: mounts,
148
+ resources: exports.TRANSFER_POD_RESOURCES,
105
149
  ...(0, job_placement_1.getContainerSecurity)(env),
106
150
  },
107
151
  ],
108
- volumes: persistence.volumes,
152
+ volumes,
109
153
  },
110
154
  };
111
155
  service.status.write('debug', `create pod ${name}`);
112
156
  await removeStalePod(instance, env.namespace, name);
113
- const pod = await (0, apply_1.apply)(instance, podSpec);
157
+ const pod = await applyWithinQuota(instance, podSpec, service, quota_wait_1.QUOTA_TIMEOUT, 2000, signal);
114
158
  if (pod.status?.phase !== 'Running') {
115
159
  service.status.write('debug', `await running state ${name}`);
116
160
  await (0, await_running_state_1.awaitRunningState)(instance, env, name, 'Running');
@@ -273,7 +317,7 @@ exports.syncLiveFiles = syncLiveFiles;
273
317
  // its files mounts them from: a move that did not get up leaves the service at the commit
274
318
  // it was at
275
319
  async function restoreLiveFiles(instance, env, work, persistence, from) {
276
- await getPodForPersistence(instance, env, work, persistence, 'write', (pod) => syncLiveFiles(instance, env, work, persistence, pod, from));
320
+ await getPodForPersistence(instance, env, work, persistence, 'write', undefined, (pod) => syncLiveFiles(instance, env, work, persistence, pod, from));
277
321
  }
278
322
  exports.restoreLiveFiles = restoreLiveFiles;
279
323
  // Prepares the folder of a state in the claim of a work item of a service run before its
@@ -282,6 +326,58 @@ exports.restoreLiveFiles = restoreLiveFiles;
282
326
  // Returns whether the upload is needed.
283
327
  async function prepareStateFiles(instance, env, work, pod, dir, inUse) {
284
328
  const targetPath = `/dev/hammerkit/${work.id()}`;
329
+ await removeOtherStates(instance, env, pod, targetPath, dir, inUse);
330
+ if (inUse.has(dir) && !(await execInPod(instance, env, pod, ['test', '-e', `${targetPath}/${dir}/${UPLOADED}`]))) {
331
+ work.status.write('info', `the files of ${work.name} are there already`);
332
+ return false;
333
+ }
334
+ await clearStateDir(instance, env, pod, `${targetPath}/${dir}`);
335
+ return true;
336
+ }
337
+ // Makes each of `files` (paths in the claim of `work`, see KubernetesPersistence.files) an
338
+ // empty file unless it is one: Kubernetes would make a directory of a subPath that isn't
339
+ // there, and the task could not write the file. A directory there is what an earlier
340
+ // version left in a kept claim, and goes. A path ending in `/` is made a folder.
341
+ exports.ENSURE_OUTPUT_FILES = `cd "$1" || exit 1
342
+ shift
343
+ for f; do
344
+ case "$f" in */) mkdir -p "$f" || exit 1; continue ;; esac
345
+ if [ -d "$f" ] && [ ! -L "$f" ]; then rm -rf "$f" || exit 1; fi
346
+ if [ ! -e "$f" ] && [ ! -L "$f" ]; then mkdir -p "$(dirname "$f")" && : > "$f" || exit 1; fi
347
+ done`;
348
+ async function ensureOutputFiles(instance, env, work, pod, files) {
349
+ if (files.length === 0) {
350
+ return;
351
+ }
352
+ const made = await execInPod(instance, env, pod, [
353
+ 'sh',
354
+ '-c',
355
+ exports.ENSURE_OUTPUT_FILES,
356
+ 'sh',
357
+ `/dev/hammerkit/${work.id()}`,
358
+ ...files,
359
+ ]);
360
+ if (made) {
361
+ throw new Error(`unable to make the output files ${files.join(', ')} of ${work.name}: ${made}`);
362
+ }
363
+ }
364
+ // what a failed upload, restore or task left: tar does not remove files the commit does not have
365
+ async function clearStateDir(instance, env, pod, path) {
366
+ const cleared = await execInPod(instance, env, pod, ['rm', '-rf', path]);
367
+ if (cleared) {
368
+ throw new Error(`unable to clear ${path}: ${cleared}`);
369
+ }
370
+ }
371
+ // Before a restore of a service run into the folder `dir` of the claim of `work` (in its upload
372
+ // pod `pod`): the folders of the other states go but those of `inUse`, which pods of the run
373
+ // mount, and `dir` is emptied. A claim that took only restores holds one state, as after a Job.
374
+ async function clearStateFiles(instance, env, work, pod, dir, inUse) {
375
+ const targetPath = `/dev/hammerkit/${work.id()}`;
376
+ await removeOtherStates(instance, env, pod, targetPath, dir, inUse);
377
+ await clearStateDir(instance, env, pod, `${targetPath}/${dir}`);
378
+ }
379
+ exports.clearStateFiles = clearStateFiles;
380
+ async function removeOtherStates(instance, env, pod, targetPath, dir, inUse) {
285
381
  const removed = await execInPod(instance, env, pod, [
286
382
  'sh',
287
383
  '-c',
@@ -294,16 +390,6 @@ async function prepareStateFiles(instance, env, work, pod, dir, inUse) {
294
390
  if (removed) {
295
391
  throw new Error(`unable to remove the files of other commits in ${targetPath}: ${removed}`);
296
392
  }
297
- if (inUse.has(dir) && !(await execInPod(instance, env, pod, ['test', '-e', `${targetPath}/${dir}/${UPLOADED}`]))) {
298
- work.status.write('info', `the files of ${work.name} are there already`);
299
- return false;
300
- }
301
- // what a failed upload or task left: tar does not remove files the commit does not have
302
- const cleared = await execInPod(instance, env, pod, ['rm', '-rf', `${targetPath}/${dir}`]);
303
- if (cleared) {
304
- throw new Error(`unable to clear ${targetPath}/${dir}: ${cleared}`);
305
- }
306
- return true;
307
393
  }
308
394
  // The archive that uploads a source into the claim: its file or directory, at its place in
309
395
  // the claim (see getClaimSubPath) instead of under its own name
@@ -343,7 +429,7 @@ options = {}) {
343
429
  const files = persistence.volumes.some((volume) => volume.persistentVolumeClaim?.claimName === claim)
344
430
  ? options.files
345
431
  : undefined;
346
- if (persistence.sources.length === 0 && !options.reset && !files) {
432
+ if (persistence.sources.length === 0 && persistence.files.length === 0 && !options.reset && !files) {
347
433
  return;
348
434
  }
349
435
  // the folders of the states the pods of the run mount, before the upload pod mounts the claim
@@ -352,7 +438,8 @@ options = {}) {
352
438
  inUse.add(dir);
353
439
  }
354
440
  service.status.write('debug', 'start upload container');
355
- await getPodForPersistence(instance, env, service, persistence, 'write', async (name) => {
441
+ const { signal } = environment.abortCtrl;
442
+ await getPodForPersistence(instance, env, service, persistence, 'write', signal, async (name) => {
356
443
  if (options.reset) {
357
444
  await clearClaim(instance, env, service, name);
358
445
  }
@@ -392,6 +479,7 @@ options = {}) {
392
479
  }
393
480
  });
394
481
  }
482
+ await ensureOutputFiles(instance, env, service, name, persistence.files);
395
483
  if (files) {
396
484
  const dir = `/dev/hammerkit/${service.id()}/${files.dir}`;
397
485
  const marked = await execInPod(instance, env, name, [
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.followPodLogs = void 0;
3
+ exports.followPodLogs = exports.MAX_LOG_LINE_CHARS = void 0;
4
4
  const stream_1 = require("stream");
5
- const readline_1 = require("readline");
6
5
  const log_1 = require("../log");
6
+ const read_lines_1 = require("../utils/read-lines");
7
7
  // what is read of an instance of a container that already ended
8
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(?: (.*))?$/;
9
16
  /**
10
17
  * Follows the log of a container in the pods of a selector, as `docker attach` does for a
11
18
  * service on Docker: the instance that runs as it writes, and an instance that ended before
@@ -14,7 +21,12 @@ const MAX_ENDED_LOG_BYTES = 1024 * 1024;
14
21
  */
15
22
  function followPodLogs(instance, namespace, labelSelector, container, onLine, options = {}) {
16
23
  const seen = new Set();
17
- const following = [];
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();
18
30
  const reading = new Set();
19
31
  let stopped = false;
20
32
  let failed = false;
@@ -34,28 +46,91 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
34
46
  const tracked = promise.catch(fail).finally(() => reading.delete(tracked));
35
47
  reading.add(tracked);
36
48
  };
37
- const readEnded = async (pod, previous) => {
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++;
38
89
  const log = await instance.coreApi.readNamespacedPodLog({
39
90
  name: pod,
40
91
  namespace,
41
92
  container,
42
93
  previous,
94
+ timestamps: true,
43
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
+ : {}),
44
100
  });
101
+ const read = reader(position);
45
102
  for (const line of String(log ?? '').split(/\r?\n/)) {
46
103
  if (line.length > 0) {
47
- onLine(line);
104
+ read(line);
48
105
  }
49
106
  }
50
107
  };
51
- const follow = async (pod) => {
108
+ const follow = async (pod, id) => {
109
+ const position = positionOf(id);
110
+ position.reads++;
52
111
  const output = new stream_1.PassThrough();
53
- let ended = false;
54
- // the instance ended or the request broke: a restarted one is looked for at once
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
55
119
  const end = () => {
56
- if (!ended) {
57
- ended = true;
120
+ if (!over) {
121
+ over = true;
58
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
+ }
59
134
  wake();
60
135
  }
61
136
  };
@@ -64,11 +139,15 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
64
139
  end();
65
140
  }));
66
141
  output.on('end', end);
67
- (0, readline_1.createInterface)({ input: output }).on('line', (line) => onLine(line));
142
+ (0, read_lines_1.readLines)(output, exports.MAX_LOG_LINE_CHARS, reader(position));
68
143
  streaming++;
69
144
  let controller;
70
145
  try {
71
- controller = await instance.log.log(namespace, pod, container, output, { follow: true });
146
+ controller = await instance.log.log(namespace, pod, container, output, {
147
+ follow: true,
148
+ timestamps: true,
149
+ ...(position.since ? { sinceTime: position.since } : {}),
150
+ });
72
151
  }
73
152
  catch (e) {
74
153
  end();
@@ -78,7 +157,7 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
78
157
  controller.abort();
79
158
  }
80
159
  else {
81
- following.push(controller);
160
+ following.set(id, controller);
82
161
  }
83
162
  };
84
163
  const look = (pod) => {
@@ -91,22 +170,28 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
91
170
  // an instance that ended before this one, not seen while it ran: its lines go first
92
171
  let before = Promise.resolve();
93
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
+ }
94
180
  if (last && !seen.has(last)) {
95
181
  seen.add(last);
96
- before = readEnded(name, true).catch(fail);
182
+ before = readEnded(name, last, true).catch(fail);
97
183
  track(before);
98
184
  }
99
- const current = status.containerID;
100
185
  if (!current || seen.has(current)) {
101
186
  return;
102
187
  }
103
188
  if (status.state?.running) {
104
189
  seen.add(current);
105
- track(before.then(() => follow(name)));
190
+ track(before.then(() => follow(name, current)));
106
191
  }
107
192
  else if (status.state?.terminated) {
108
193
  seen.add(current);
109
- track(before.then(() => readEnded(name, false)));
194
+ track(before.then(() => readEnded(name, current, false)));
110
195
  }
111
196
  };
112
197
  const poll = async () => {
@@ -157,26 +242,40 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
157
242
  async settle() {
158
243
  await polling;
159
244
  await poll();
160
- // what follows a running instance never ends by itself
161
- const ended = [...reading];
162
- let wait;
163
- await Promise.race([
164
- Promise.all(ended),
165
- new Promise((resolve) => {
166
- wait = setTimeout(resolve, 5000);
167
- wait.unref?.();
168
- }),
169
- ]);
170
- clearTimeout(wait);
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
+ }
171
258
  },
172
259
  stop() {
173
260
  stopped = true;
174
261
  clearTimeout(timer);
175
- for (const controller of following.splice(0)) {
262
+ for (const controller of following.values()) {
176
263
  controller.abort();
177
264
  }
265
+ following.clear();
178
266
  },
179
267
  };
180
268
  }
181
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
+ }
182
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.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) {
@@ -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) {
@@ -543,7 +543,7 @@ async function removeSandboxProxies(instance, namespace, of, keep = () => false)
543
543
  const deployments = await instance.appsApi.listNamespacedDeployment({
544
544
  namespace,
545
545
  labelSelector: [
546
- `${PROXY_OF_SANDBOX_LABEL}=${of.sandbox}`,
546
+ `${exports.PROXY_OF_SANDBOX_LABEL}=${of.sandbox}`,
547
547
  ...(of.item ? [`${NETWORK_OF_LABEL}=${of.item.id()}`] : []),
548
548
  ].join(','),
549
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