hammerkit 2.0.0-next.1 → 2.0.0-next.11

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 (64) 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-backend.js +9 -3
  41. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  42. package/dist/server/oauth.js +16 -1
  43. package/dist/server/overview.js +80 -11
  44. package/dist/server/plan.js +16 -3
  45. package/dist/server/policy.js +9 -3
  46. package/dist/server/run-worker.js +47 -6
  47. package/dist/server/runs.js +74 -6
  48. package/dist/server/sandbox-files.js +107 -16
  49. package/dist/server/sandbox-patch.js +43 -17
  50. package/dist/server/sandboxes.js +57 -23
  51. package/dist/server/server-config.js +4 -1
  52. package/dist/server/server.js +45 -10
  53. package/dist/server/service-runs.js +8 -1
  54. package/dist/server/sources.js +68 -11
  55. package/dist/server/timings.js +23 -3
  56. package/dist/utils/buffer-context.js +30 -20
  57. package/dist/utils/limit.js +30 -0
  58. package/dist/utils/read-lines.js +65 -0
  59. package/dist/utils/units.js +36 -1
  60. package/dist/utils/web-links.js +34 -0
  61. package/package.json +1 -1
  62. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  63. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  64. package/dist/dashboard/favicon.svg +0 -1
@@ -1,11 +1,14 @@
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
14
  function getRestoreTarget(work, path,
@@ -16,14 +19,28 @@ stateDir) {
16
19
  exports.getRestoreTarget = getRestoreTarget;
17
20
  async function restoreKubernetesData(work, kubernetes, instance, environment, path,
18
21
  // the kept claim of the work holds what an earlier run left, which goes first; on a
19
- // service run, the outputs go into the folder of `stateKey` (see getStateFilesDir)
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
20
25
  options = {}) {
21
26
  const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes, options.stateKey);
22
27
  const stateDir = kubernetes.server?.serviceRun ? (0, volumes_1.getItemFilesDir)(work, options.stateKey) : undefined;
23
- await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'write', async (name) => {
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) => {
24
38
  if (options.reset) {
25
39
  await (0, ensure_persistent_data_1.clearClaim)(instance, kubernetes, work, name);
26
40
  }
41
+ if (stateDir && options.otherStates) {
42
+ await (0, ensure_persistent_data_1.clearStateFiles)(instance, kubernetes, work, name, stateDir, options.otherStates);
43
+ }
27
44
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path)) {
28
45
  if (!(await environment.file.exists(generatedArchive.filename))) {
29
46
  continue;
@@ -32,7 +49,13 @@ options = {}) {
32
49
  // a claim made for this run (a server removes the claims of a run when it
33
50
  // ends) does not have the directory of the output yet
34
51
  let failure = null;
35
- 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) => {
36
59
  work.status.write('debug', `upload ${generatedArchive.filename} to ${name}: ${status.status}`);
37
60
  if (status.status !== 'Success') {
38
61
  failure = status.message ?? status.reason ?? 'unknown';
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.storeKubernetesData = void 0;
4
+ const path_1 = require("path");
4
5
  const log_1 = require("../log");
5
6
  const event_cache_1 = require("../executer/event-cache");
6
7
  const volumes_1 = require("./volumes");
@@ -10,10 +11,20 @@ async function storeKubernetesData(work, kubernetes, instance, environment, path
10
11
  // getStateFilesDir)
11
12
  stateKey) {
12
13
  const persistence = await (0, volumes_1.getKubernetesPersistence)(work, kubernetes, stateKey);
13
- await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'read', async (name) => {
14
+ // a run stopped while the pod waits for room under the quota
15
+ const { signal } = environment.abortCtrl;
16
+ // an output that is a file is mounted as one: its archive holds it by its name, as on Docker
17
+ const files = new Set(work.data.type === 'container-task'
18
+ ? work.data.generates
19
+ .filter((generate) => generate.isFile && !generate.inherited)
20
+ .map((generate) => generate.path)
21
+ : []);
22
+ await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'read', signal, async (name) => {
14
23
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path)) {
15
24
  const writerStream = environment.file.createWriteStream(generatedArchive.filename);
16
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', ['tar', 'zcf', '-', '-C', generatedArchive.path, '.'], writerStream, process.stderr, null, false, (status) => {
25
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', files.has(generatedArchive.path)
26
+ ? ['tar', 'zcf', '-', '-C', path_1.posix.dirname(generatedArchive.path), path_1.posix.basename(generatedArchive.path)]
27
+ : ['tar', 'zcf', '-', '-C', generatedArchive.path, '.'], writerStream, process.stderr, null, false, (status) => {
17
28
  work.status.write('debug', `archive ${generatedArchive.path} of ${name}: ${status}`);
18
29
  writerStream.close();
19
30
  });
@@ -59,6 +59,7 @@ stateKey) {
59
59
  sources: [],
60
60
  mounts: [],
61
61
  initCommands: [],
62
+ files: [],
62
63
  };
63
64
  const workspace = kubernetes.server?.workspace;
64
65
  for (const mount of work.data.mounts) {
@@ -68,20 +69,23 @@ stateKey) {
68
69
  }
69
70
  appendVolume(work, persistence, mount.containerPath, mount.localPath, mount.isFile, true, kubernetes, mounted, own);
70
71
  }
72
+ // its deps' src too, uploaded into its own claim: a container task sees them as it does on
73
+ // docker (a tsc -b of a project that references another reads the other's tsconfig)
71
74
  for (const src of work.data.src) {
72
- if (src.inherited) {
73
- continue;
74
- }
75
75
  if (workspace &&
76
76
  appendWorkspaceMount(workspace, persistence, src.absolutePath, src.absolutePath, src.isFile, false)) {
77
77
  continue;
78
78
  }
79
- appendVolume(work, persistence, src.absolutePath, src.absolutePath, src.isFile, true, kubernetes, mounted, own); // TODO matcher
79
+ appendVolume(work, persistence, src.absolutePath, src.absolutePath, src.isFile, true, kubernetes, mounted, own, src.inherited ? (0, claim_layout_1.getInheritedSourceSubPath)(work, src.absolutePath) : undefined); // TODO matcher
80
80
  }
81
81
  if (work.data.type === 'container-task') {
82
82
  for (const generate of work.data.generates) {
83
- appendVolume(generate.inherited ?? work, persistence, generate.path, null, false, !!generate.inherited, kubernetes, dirOf(generate.inherited ?? work));
83
+ const subPath = appendVolume(generate.inherited ?? work, persistence, generate.path, null, generate.isFile, !!generate.inherited, kubernetes, dirOf(generate.inherited ?? work));
84
+ if (generate.isFile && !generate.inherited) {
85
+ persistence.files.push(subPath);
86
+ }
84
87
  }
88
+ persistence.files.push(...getNestedMountPlaces(persistence, getVolumeName(work, kubernetes)));
85
89
  }
86
90
  else {
87
91
  for (const volume of work.data.volumes) {
@@ -93,14 +97,36 @@ stateKey) {
93
97
  return persistence;
94
98
  }
95
99
  exports.getKubernetesPersistence = getKubernetesPersistence;
100
+ // The places in the claim `claim` of the paths mounted inside a folder that is mounted read
101
+ // only from it: an output of a task inside a folder of its src (pkg/coverage/lcov.info with a
102
+ // src pkg). The container runtime makes the place of a mount where it isn't there, which it
103
+ // can't in a folder mounted read only, and the pod fails to start (exit 128). Each is in the
104
+ // claim's folder of the read-only path, a folder ending in `/`, or a file.
105
+ function getNestedMountPlaces(persistence, claim) {
106
+ const own = persistence.mounts.filter((m) => !m.workspace);
107
+ const folders = own.filter((m) => m.mount.name === claim && m.mount.readOnly && m.cwd === m.mount.mountPath && m.mount.subPath);
108
+ const places = [];
109
+ for (const mount of own) {
110
+ const parent = folders
111
+ .filter((folder) => folder !== mount && mount.mount.mountPath.startsWith(`${folder.mount.mountPath}/`))
112
+ .sort((a, b) => b.mount.mountPath.length - a.mount.mountPath.length)[0];
113
+ if (!parent) {
114
+ continue;
115
+ }
116
+ const place = `${parent.mount.subPath}/${mount.mount.mountPath.slice(parent.mount.mountPath.length + 1)}`;
117
+ places.push(mount.cwd === mount.mount.mountPath ? `${place}/` : place);
118
+ }
119
+ return places;
120
+ }
96
121
  function appendVolume(sourceWork, persistence, containerPath, localPath, isFile, readOnly, kubernetes,
97
122
  // the folder of the state of `sourceWork` the path is in, see getStateFilesDir
98
123
  stateDir,
99
124
  // the folder its upload goes to, when it is not the one the path is mounted from (a
100
125
  // service that watches its files, see syncLiveFiles)
101
- uploadDir = stateDir) {
126
+ uploadDir = stateDir,
127
+ // where it goes in the claim, when not where getClaimSubPath puts it
128
+ claimPath = (0, claim_layout_1.getClaimSubPath)(sourceWork, containerPath)) {
102
129
  const volumeName = getVolumeName(sourceWork, kubernetes);
103
- const claimPath = (0, claim_layout_1.getClaimSubPath)(sourceWork, containerPath);
104
130
  const subPath = (stateDir ? `${stateDir}/` : '') + claimPath;
105
131
  const existVolume = persistence.volumes.some((v) => v.name === volumeName);
106
132
  if (!existVolume) {
@@ -134,6 +160,7 @@ uploadDir = stateDir) {
134
160
  stateKey: '', // TODO
135
161
  });
136
162
  }
163
+ return subPath;
137
164
  }
138
165
  exports.appendVolume = appendVolume;
139
166
  /**
@@ -1,17 +1,60 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateChecksum = void 0;
3
+ exports.calculateChecksum = exports.racyWindow = void 0;
4
4
  const crypto_1 = require("crypto");
5
+ // The checksums a process computed, by the file context and path: every task of a run hashes
6
+ // the sources of the tasks it depends on too, so most files are asked for many times
7
+ const known = new WeakMap();
8
+ // A file written again soon after it was hashed, with the same size, keeps its times on a
9
+ // file system whose timestamps are coarser than that: a checksum of a file changed within
10
+ // the window before it was hashed is not kept. Whole seconds are taken for a file system
11
+ // that has no more (FAT, ext3, HFS+), else the window is short.
12
+ function racyWindow(stats) {
13
+ return stats.lastModified % 1000 === 0 && stats.identity.changed % 1000 === 0 ? 2000 : 50;
14
+ }
15
+ exports.racyWindow = racyWindow;
5
16
  // Hashes the raw bytes: decoding to text first would map every invalid UTF-8
6
17
  // sequence to U+FFFD, so two different binary files could share a checksum.
7
18
  // For UTF-8 text the result is unchanged. sha256, which nobody can make two files share:
8
19
  // a cache hit is also what a verified check counts (check-key.ts).
9
- async function calculateChecksum(environment, path) {
20
+ //
21
+ // With the `stats` of the file, the checksum is reused while the file stays the same file:
22
+ // the same modification and change time, size and inode. A write changes its times, a
23
+ // replacement (a checkout, a rename over it) its inode.
24
+ async function calculateChecksum(environment, path, stats) {
25
+ const identity = stats?.identity;
26
+ if (!identity) {
27
+ return hashFile(environment, path);
28
+ }
29
+ let files = known.get(environment.file);
30
+ if (!files) {
31
+ files = new Map();
32
+ known.set(environment.file, files);
33
+ }
34
+ const cached = files.get(path);
35
+ if (cached &&
36
+ cached.lastModified === stats.lastModified &&
37
+ cached.size === identity.size &&
38
+ cached.changed === identity.changed &&
39
+ cached.inode === identity.inode) {
40
+ return cached.checksum;
41
+ }
42
+ const hashedAt = Date.now();
43
+ const checksum = await hashFile(environment, path);
44
+ if (hashedAt - Math.max(stats.lastModified, identity.changed) > racyWindow({ ...stats, identity })) {
45
+ files.set(path, { lastModified: stats.lastModified, ...identity, checksum });
46
+ }
47
+ else {
48
+ files.delete(path);
49
+ }
50
+ return checksum;
51
+ }
52
+ exports.calculateChecksum = calculateChecksum;
53
+ async function hashFile(environment, path) {
10
54
  const hash = (0, crypto_1.createHash)('sha256');
11
55
  for await (const chunk of environment.file.readStream(path)) {
12
56
  hash.update(chunk);
13
57
  }
14
58
  return hash.digest('hex');
15
59
  }
16
- exports.calculateChecksum = calculateChecksum;
17
60
  //# sourceMappingURL=calculate-checksum.js.map
@@ -15,9 +15,11 @@ const check_key_1 = require("./check-key");
15
15
  * nodes) is the server's, and a result counts for the server it passed on. The secrets'
16
16
  * providers and accounts are the server's too, and no part of a key, so any is taken here.
17
17
  */
18
- async function getCheckKeys(entry, environment, scope) {
18
+ async function getCheckKeys(entry, environment, scope,
19
+ // on a server: the build files are read from the published files and work on the source
20
+ directory) {
19
21
  const keyed = { ...environment, hosted: { catalog: anyCatalog(), localTasksInContainers: true } };
20
- const { ctx, scope: parsed } = await (0, schema_parser_1.createParseContext)(entry, keyed);
22
+ const { ctx, scope: parsed } = await (0, schema_parser_1.createParseContext)(entry, keyed, { directory });
21
23
  const workTree = (0, work_scope_parser_1.getWorkContext)(await (0, reference_parser_1.parseReferences)(ctx, parsed, keyed), scope, keyed);
22
24
  const memo = new Map();
23
25
  const keys = {};
@@ -5,55 +5,67 @@ const calculate_checksum_1 = require("./calculate-checksum");
5
5
  const path_1 = require("path");
6
6
  const crypto_1 = require("crypto");
7
7
  const promises_1 = require("fs/promises");
8
+ const limit_1 = require("../utils/limit");
8
9
  function isExcluded(path, excluded) {
9
10
  return excluded.some((excludedPath) => path === excludedPath || path.startsWith(excludedPath + path_1.sep));
10
11
  }
11
- async function addWorkCacheStats(result, cwd, path, matcher, context, root, excluded) {
12
+ // What the walk does at once: a stat, a listing or a checksum of a file each. Awaited one
13
+ // after the other, a walk of a thousand files spent most of its time waiting for the disk.
14
+ const WALK_CONCURRENCY = 32;
15
+ async function addWorkCacheStats(result, cwd, path, matcher, context, root, excluded, limit = (0, limit_1.createLimit)(WALK_CONCURRENCY)) {
12
16
  if (isExcluded(path, excluded)) {
13
17
  return 0;
14
18
  }
19
+ // the slot is held for what this path needs of the disk, not while its children are walked
20
+ const visited = await limit(() => visitPath(cwd, path, matcher, context, root));
21
+ if (visited.type === 'file') {
22
+ // '/'-separated on every OS, so a Windows host keys a container task like Linux
23
+ result.files[visited.key] = { lastModified: visited.lastModified, checksum: visited.checksum };
24
+ return 1;
25
+ }
26
+ if (visited.type === 'directory') {
27
+ const counts = await Promise.all(visited.files.map((file) => addWorkCacheStats(result, cwd, (0, path_1.join)(path, file), matcher, context, false, excluded, limit)));
28
+ return counts.reduce((sum, count) => sum + count, 0);
29
+ }
30
+ return 0;
31
+ }
32
+ async function visitPath(cwd, path, matcher, context, root) {
33
+ const key = (0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep);
15
34
  // On a server the files were written by a commit or a task: a link is a source as it is,
16
35
  // its target, and never followed. A `**` would walk `x -> /` through the server's disk.
17
36
  if (context.hosted) {
18
37
  const link = await (0, promises_1.lstat)(path).catch(() => undefined);
19
38
  if (link?.isSymbolicLink()) {
20
39
  if (!matcher(path)) {
21
- return 0;
40
+ return { type: 'none' };
22
41
  }
23
42
  const checksum = (0, crypto_1.createHash)('sha256')
24
43
  .update(`link:${await (0, promises_1.readlink)(path)}`)
25
44
  .digest('hex');
26
- result.files[(0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep)] = { lastModified: link.mtimeMs, checksum };
27
- return 1;
45
+ return { type: 'file', key, lastModified: link.mtimeMs, checksum };
28
46
  }
29
47
  }
30
48
  const exists = await context.file.exists(path);
31
49
  if (!exists) {
32
- return 0;
50
+ return { type: 'none' };
33
51
  }
34
52
  const stats = await context.file.stats(path);
35
53
  if (stats.type === 'file') {
36
54
  if (!matcher(path)) {
37
- return 0;
55
+ return { type: 'none' };
38
56
  }
39
- const checksum = await (0, calculate_checksum_1.calculateChecksum)(context, path);
40
- // '/'-separated on every OS, so a Windows host keys a container task like Linux
41
- result.files[(0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep)] = { lastModified: stats.lastModified, checksum };
42
- return 1;
57
+ const checksum = await (0, calculate_checksum_1.calculateChecksum)(context, path, stats);
58
+ return { type: 'file', key, lastModified: stats.lastModified, checksum };
43
59
  }
44
60
  else if (stats.type === 'directory') {
45
61
  // A glob such as src/**/*.ts never matches a directory itself, so a
46
62
  // directory is walked when files inside it could match.
47
63
  if (!root && !matcher(path, true)) {
48
- return 0;
49
- }
50
- let matched = 0;
51
- for (const file of await context.file.listFiles(path)) {
52
- matched += await addWorkCacheStats(result, cwd, (0, path_1.join)(path, file), matcher, context, false, excluded);
64
+ return { type: 'none' };
53
65
  }
54
- return matched;
66
+ return { type: 'directory', files: await context.file.listFiles(path) };
55
67
  }
56
- return 0;
68
+ return { type: 'none' };
57
69
  }
58
70
  async function getWorkCacheStats(work, environment) {
59
71
  return (await collectSourceStats(work, environment, [])).stats;
@@ -66,14 +78,14 @@ async function collectSourceStats(work, environment, excluded) {
66
78
  created: new Date(),
67
79
  files: {},
68
80
  };
69
- const unmatched = [];
70
- for (const src of work.src) {
81
+ // one limit for all its srcs, which are walked at once: an inherited src is often a large
82
+ // part of what a task hashes
83
+ const limit = (0, limit_1.createLimit)(WALK_CONCURRENCY);
84
+ const matches = await Promise.all(work.src.map((src) => {
71
85
  const matcher = (file, partial) => src.matcher(file, work.cwd, partial);
72
- const matched = await addWorkCacheStats(result, work.cwd, src.absolutePath, matcher, environment, true, excluded);
73
- if (matched === 0 && !src.inherited && !isExcluded(src.absolutePath, excluded)) {
74
- unmatched.push(src);
75
- }
76
- }
86
+ return addWorkCacheStats(result, work.cwd, src.absolutePath, matcher, environment, true, excluded, limit);
87
+ }));
88
+ const unmatched = work.src.filter((src, index) => matches[index] === 0 && !src.inherited && !isExcluded(src.absolutePath, excluded));
77
89
  return { stats: result, unmatched };
78
90
  }
79
91
  // The source stats of a task or service, leaving out everything its (transitive)
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.read = exports.write = void 0;
3
+ exports.readSized = exports.read = exports.write = void 0;
4
4
  const yaml_1 = require("yaml");
5
5
  async function write(filename, content, context) {
6
6
  await context.file.writeFile(filename, (0, yaml_1.stringify)(content));
7
7
  }
8
8
  exports.write = write;
9
9
  async function read(fileName, context) {
10
+ return (await readSized(fileName, context)).value;
11
+ }
12
+ exports.read = read;
13
+ // The parsed file and the bytes it took.
14
+ async function readSized(fileName, context) {
10
15
  context.status.context({ type: 'cli', name: 'hammerkit' }).write('debug', `read ${fileName} build file`);
11
16
  let content;
12
17
  try {
@@ -16,7 +21,7 @@ async function read(fileName, context) {
16
21
  throw new Error(`unable to read ${fileName}`);
17
22
  }
18
23
  try {
19
- return (0, yaml_1.parse)(content);
24
+ return { value: (0, yaml_1.parse)(content), bytes: Buffer.byteLength(content, 'utf8') };
20
25
  }
21
26
  catch (e) {
22
27
  if (e instanceof Error) {
@@ -27,5 +32,5 @@ async function read(fileName, context) {
27
32
  }
28
33
  }
29
34
  }
30
- exports.read = read;
35
+ exports.readSized = readSized;
31
36
  //# sourceMappingURL=read-build-file.js.map
@@ -5,11 +5,27 @@ function templateValue(value, envs) {
5
5
  if (!value || !envs) {
6
6
  return value;
7
7
  }
8
- let result = value;
9
- for (const [key, envValue] of Object.entries(envs.variables)) {
10
- result = result.replace(new RegExp(`\\$\\{${key}\\}|\\$${key}`, 'gi'), envValue);
8
+ // A name is matched as the text it is, in any case; when two names match the same `$`, the
9
+ // one listed first wins. One pass over the value: a value put in is not read again.
10
+ const names = Object.keys(envs.variables).filter((name) => name.length > 0);
11
+ if (names.length === 0) {
12
+ return value;
13
+ }
14
+ const values = new Map();
15
+ for (const name of names) {
16
+ const key = name.toLowerCase();
17
+ if (!values.has(key)) {
18
+ values.set(key, envs.variables[name]);
19
+ }
11
20
  }
12
- return result;
21
+ const alternatives = names.map(escapeRegExp).join('|');
22
+ const pattern = new RegExp(`\\$\\{(${alternatives})\\}|\\$(${alternatives})`, 'gi');
23
+ return value.replace(pattern, (match, braced, bare) => {
24
+ return values.get((braced ?? bare ?? '').toLowerCase()) ?? match;
25
+ });
13
26
  }
14
27
  exports.templateValue = templateValue;
28
+ function escapeRegExp(text) {
29
+ return text.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&');
30
+ }
15
31
  //# sourceMappingURL=template-value.js.map
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readExecutions = exports.clearExecutions = exports.recordExecution = void 0;
4
+ // kept by the task, not its item: the runtime and the scheduler hold copies of the item
5
+ const executions = new WeakMap();
6
+ function recordExecution(task, startedAt, finishedAt) {
7
+ if (Number.isNaN(startedAt.getTime()) || Number.isNaN(finishedAt.getTime()) || finishedAt < startedAt) {
8
+ return;
9
+ }
10
+ let list = executions.get(task);
11
+ if (!list) {
12
+ list = [];
13
+ executions.set(task, list);
14
+ }
15
+ list.push({ startedAt, finishedAt });
16
+ }
17
+ exports.recordExecution = recordExecution;
18
+ // a task that runs again (watch) starts with none
19
+ function clearExecutions(task) {
20
+ executions.delete(task);
21
+ }
22
+ exports.clearExecutions = clearExecutions;
23
+ function readExecutions(task) {
24
+ return executions.get(task) ?? [];
25
+ }
26
+ exports.readExecutions = readExecutions;
27
+ //# sourceMappingURL=work-item-executions.js.map
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = void 0;
6
+ exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = exports.recordJobExecution = void 0;
7
7
  const abort_1 = require("../executer/abort");
8
8
  const kubernetes_service_1 = require("../executer/kubernetes-service");
9
9
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
@@ -12,6 +12,7 @@ const apply_1 = require("../kubernetes/apply");
12
12
  const ensure_kubernetes_service_exists_1 = require("../kubernetes/ensure-kubernetes-service-exists");
13
13
  const ensure_kubernetes_deployment_exists_1 = require("../kubernetes/ensure-kubernetes-deployment-exists");
14
14
  const follow_pod_logs_1 = require("../kubernetes/follow-pod-logs");
15
+ const work_item_executions_1 = require("./work-item-executions");
15
16
  const service_definition_1 = require("./service-definition");
16
17
  const ensure_namespace_1 = require("../kubernetes/ensure-namespace");
17
18
  const ensure_persistent_data_1 = require("../kubernetes/ensure-persistent-data");
@@ -62,32 +63,17 @@ async function getJobPod(instance, kubernetes, job) {
62
63
  .sort((a, b) => (a.metadata?.creationTimestamp?.toISOString() ?? '').localeCompare(b.metadata?.creationTimestamp?.toISOString() ?? ''))
63
64
  .pop();
64
65
  }
65
- // a task's log is kept to this, the run's own cap is smaller
66
- const MAX_JOB_LOG_BYTES = 4 * 1024 * 1024;
67
- // What the command printed, as the task's output: read from the cluster once the Job
68
- // has ended. Without a pod (it never started) there is nothing to say.
69
- async function writeJobLogs(instance, kubernetes, task, job, container) {
70
- try {
71
- const pod = await getJobPod(instance, kubernetes, job);
72
- if (!pod?.metadata?.name) {
73
- return;
74
- }
75
- const log = await instance.coreApi.readNamespacedPodLog({
76
- name: pod.metadata.name,
77
- namespace: kubernetes.namespace,
78
- container,
79
- limitBytes: MAX_JOB_LOG_BYTES,
80
- });
81
- for (const line of String(log ?? '').split(/\r?\n/)) {
82
- if (line.length > 0) {
83
- task.status.console('stdout', line);
84
- }
85
- }
86
- }
87
- catch (e) {
88
- task.status.write('debug', `the log of ${job} could not be read: ${(0, log_1.getErrorMessage)(e)}`);
66
+ // When the command of a Job ran, as its container says: what the task spent before it (the
67
+ // pod scheduled, the image pulled, the init containers) and after it is not the command's.
68
+ async function recordJobExecution(instance, kubernetes, task, job, container) {
69
+ const pod = await getJobPod(instance, kubernetes, job).catch(() => undefined);
70
+ const status = pod?.status?.containerStatuses?.find((s) => s.name === container);
71
+ const terminated = status?.state?.terminated ?? status?.lastState?.terminated;
72
+ if (terminated?.startedAt && terminated.finishedAt) {
73
+ (0, work_item_executions_1.recordExecution)(task, new Date(terminated.startedAt), new Date(terminated.finishedAt));
89
74
  }
90
75
  }
76
+ exports.recordJobExecution = recordJobExecution;
91
77
  // the command of a Job exited with this code, as a crash on docker or a host
92
78
  class JobCrash extends Error {
93
79
  constructor(exitCode) {
@@ -170,6 +156,9 @@ function kubernetesTaskRuntime(task, kubernetes) {
170
156
  // on a server that keeps them, the task's claim stays after the run with the state of its
171
157
  // outputs, and the next run of the same source mounts them as they are (see kept-claims)
172
158
  const kept = (0, kept_claims_1.isKeptClaim)(task, kubernetes);
159
+ // on a service run, the claim names the last state whose folder is whole (see
160
+ // rememberedClaimState): a wake or a move at that state mounts it without an upload
161
+ const remembers = kept || !!kubernetes.server?.serviceRun;
173
162
  const claim = (0, volumes_1.getVolumeName)(task, kubernetes);
174
163
  return {
175
164
  initialize() {
@@ -182,6 +171,21 @@ function kubernetesTaskRuntime(task, kubernetes) {
182
171
  stateKey &&
183
172
  (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has((0, volumes_1.getStateFilesDir)(stateKey))) {
184
173
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
174
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
175
+ return;
176
+ }
177
+ if (remembers && !kept) {
178
+ // the folder of the state is written now: until it is whole, the claim names no state
179
+ // (a restore without a state key says none, and the next run uploads again)
180
+ await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim);
181
+ await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path, {
182
+ stateKey,
183
+ // the folders of other states no pod of the run mounts go, as before a Job
184
+ ...(stateKey ? { otherStates: await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim) } : {}),
185
+ });
186
+ if (stateKey) {
187
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
188
+ }
185
189
  return;
186
190
  }
187
191
  if (!kept) {
@@ -231,11 +235,14 @@ function kubernetesTaskRuntime(task, kubernetes) {
231
235
  try {
232
236
  if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
233
237
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
238
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
234
239
  return;
235
240
  }
236
241
  // the task writes to it now: what it holds stops being the outputs of a state, and
237
- // goes, as a new claim would hold nothing
238
- const reset = kept && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
242
+ // goes, as a new claim would hold nothing (on a service run, the folders of other
243
+ // states that no pod mounts go)
244
+ const forgotten = remembers && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
245
+ const reset = kept && forgotten;
239
246
  await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset, files });
240
247
  }
241
248
  catch (e) {
@@ -373,24 +380,36 @@ function kubernetesTaskRuntime(task, kubernetes) {
373
380
  };
374
381
  try {
375
382
  const pod = await (0, apply_1.apply)(instance, spec);
376
- if (!pod.status?.succeeded) {
377
- try {
378
- await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort);
379
- }
380
- catch (e) {
381
- if (!(e instanceof abort_1.AbortError)) {
382
- await writeJobLogs(instance, kubernetes, task, podName, container);
383
- const failure = await describeFailedJob(instance, kubernetes, task.name, podName, container, inJob);
384
- if (failure?.type === 'crash') {
385
- throw new JobCrash(failure.exitCode);
383
+ // what the command prints, while it prints it; the last lines once the pod ended
384
+ const logs = (0, follow_pod_logs_1.followPodLogs)(instance, kubernetes.namespace, `job-name=${podName}`, container, (line) => task.status.console('stdout', line), { onError: (text) => task.status.write('debug', text) });
385
+ try {
386
+ if (!pod.status?.succeeded) {
387
+ try {
388
+ await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
389
+ onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
+ timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
+ });
392
+ }
393
+ catch (e) {
394
+ if (!(e instanceof abort_1.AbortError)) {
395
+ await logs.settle();
396
+ await recordJobExecution(instance, kubernetes, task.data, podName, container);
397
+ const failure = await describeFailedJob(instance, kubernetes, task.name, podName, container, inJob);
398
+ if (failure?.type === 'crash') {
399
+ throw new JobCrash(failure.exitCode);
400
+ }
401
+ throw new Error(failure?.message ?? (0, log_1.getErrorMessage)(e));
386
402
  }
387
- throw new Error(failure?.message ?? (0, log_1.getErrorMessage)(e));
403
+ throw e;
388
404
  }
389
- throw e;
390
405
  }
406
+ await logs.settle();
407
+ }
408
+ finally {
409
+ logs.stop();
391
410
  }
392
- await writeJobLogs(instance, kubernetes, task, podName, container);
393
411
  task.status.write('debug', 'pod completed');
412
+ await recordJobExecution(instance, kubernetes, task.data, podName, container);
394
413
  // its init containers are done with the credentials
395
414
  await (0, job_secrets_1.removeJobCredentials)(instance, kubernetes, task);
396
415
  if (i < task.data.cmds.length) {
@@ -415,7 +434,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
415
434
  }
416
435
  // the finished job stays for its state, the values it read need not
417
436
  await removeTaskSecrets(instance, kubernetes, task);
418
- if (kept) {
437
+ if (remembers) {
419
438
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
420
439
  }
421
440
  }
@@ -471,6 +490,15 @@ function kubernetesTaskRuntime(task, kubernetes) {
471
490
  // the server removes the Jobs of a run at its end, the claim says
472
491
  return (0, kept_claims_1.useClaimState)(instance, kubernetes, claim);
473
492
  }
493
+ if (remembers) {
494
+ // a service run that sleeps loses its Jobs but keeps its claims, the claim says. One
495
+ // that names no state is being written (or was, and that failed): the folder of the
496
+ // state of an earlier Job may be gone. Only a task without a claim goes by its Jobs.
497
+ const remembered = await (0, kept_claims_1.rememberedClaimState)(instance, kubernetes, claim);
498
+ if (remembered !== undefined) {
499
+ return remembered;
500
+ }
501
+ }
474
502
  const jobs = await instance.batchApi.listNamespacedJob({
475
503
  namespace: kubernetes.namespace,
476
504
  labelSelector: (0, resources_1.getItemSelector)(task, kubernetes),