hammerkit 2.0.0-next.9 → 2.0.0
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.
- package/build.schema.json +228 -63
- package/dist/cache/backends/registry/registry-client.js +8 -2
- package/dist/cache/explain.js +5 -0
- package/dist/cache/last-resolved.js +11 -0
- package/dist/cli.js +4 -1
- package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
- package/dist/dashboard/assets/index-BndChMep.css +2 -0
- package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
- package/dist/dashboard/index.html +2 -2
- package/dist/docker/item-network.js +51 -18
- package/dist/docker/package.js +85 -76
- package/dist/docker/server-tools.js +96 -0
- package/dist/docker/stream.js +15 -7
- package/dist/environment/replace-env-variables.js +1 -1
- package/dist/environment/run-source-envs.js +18 -0
- package/dist/executer/check-container-binds.js +158 -0
- package/dist/executer/docker-service.js +42 -3
- package/dist/executer/docker-task.js +33 -6
- package/dist/executer/execute-command.js +9 -15
- package/dist/executer/execute-work-task.js +11 -1
- package/dist/executer/execute-work-tree.js +2 -1
- package/dist/executer/execution-steps.js +6 -2
- package/dist/executer/get-container-binds.js +2 -0
- package/dist/executer/print-container-options.js +10 -10
- package/dist/executer/process-manager.js +84 -5
- package/dist/executer/scheduler/state-key.js +19 -1
- package/dist/executer/task-priority.js +131 -0
- package/dist/file/stat-beneath.js +66 -0
- package/dist/file/within-root.js +13 -4
- package/dist/harness/connect.js +1 -6
- package/dist/harness/mcp-command.js +1 -1
- package/dist/harness/sandbox-client.js +39 -4
- package/dist/harness/service-tools.js +2 -2
- package/dist/kubernetes/await-running-state.js +42 -26
- package/dist/kubernetes/ensure-persistent-data.js +22 -7
- package/dist/kubernetes/network-gate.js +74 -11
- package/dist/kubernetes/network-policy.js +32 -10
- package/dist/kubernetes/remove-stale-items.js +15 -2
- package/dist/kubernetes/restore-kubernetes-data.js +3 -2
- package/dist/kubernetes/sandbox-runner.js +3 -4
- package/dist/kubernetes/store-kubernetes-data.js +3 -2
- package/dist/kubernetes/transfer-tools.js +66 -0
- package/dist/kubernetes/volumes.js +52 -10
- package/dist/optimizer/check-key.js +7 -0
- package/dist/optimizer/check-keys.js +19 -5
- package/dist/optimizer/get-work-cache-stats.js +19 -7
- package/dist/optimizer/work-task-cache-description.js +42 -8
- package/dist/planner/image-build.js +172 -0
- package/dist/planner/utils/append-work-dependencies.js +14 -1
- package/dist/planner/utils/append-work-service.js +1 -1
- package/dist/planner/utils/append-work-task.js +51 -1
- package/dist/planner/utils/assert-item-paths.js +6 -7
- package/dist/planner/utils/dependency-outputs.js +18 -0
- package/dist/planner/work-runtime-docker.js +48 -50
- package/dist/planner/work-runtime-kubernetes.js +1 -0
- package/dist/planner/work-runtime-local.js +3 -7
- package/dist/planner/work-secret.js +135 -13
- package/dist/planner/work-tree.js +10 -0
- package/dist/remote/collect-bundle.js +9 -1
- package/dist/remote/host-config.js +49 -3
- package/dist/remote/location.js +5 -5
- package/dist/remote/remote-commands.js +12 -14
- package/dist/remote/remote-work-commands.js +20 -8
- package/dist/schema/build-file-image-build-schema.js +77 -0
- package/dist/schema/build-file-task-schema.js +9 -2
- package/dist/schema/reference-parser.js +10 -1
- package/dist/schema/work-scope-parser.js +16 -1
- package/dist/secrets/secret-catalog.js +8 -1
- package/dist/server/dashboard.js +8 -5
- package/dist/server/executor.js +58 -35
- package/dist/server/kubernetes-backend.js +29 -4
- package/dist/server/overview.js +20 -2
- package/dist/server/plan.js +31 -3
- package/dist/server/policy.js +14 -7
- package/dist/server/repo-access.js +4 -3
- package/dist/server/run-environment.js +5 -2
- package/dist/server/run-plan.js +18 -6
- package/dist/server/run-retry.js +57 -0
- package/dist/server/run-source-environment.js +39 -0
- package/dist/server/run-worker.js +38 -9
- package/dist/server/runs.js +59 -1
- package/dist/server/sandbox-files.js +232 -39
- package/dist/server/server-config.js +24 -4
- package/dist/server/server.js +107 -12
- package/dist/server/service-runs.js +42 -4
- package/dist/utils/line-splitter.js +52 -0
- package/dist/utils/tar.js +51 -1
- package/package.json +1 -1
- package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.recordTaskDuration = exports.readTaskDurations = exports.getDurationFile = exports.getTaskPriority = void 0;
|
|
4
|
+
const crypto_1 = require("crypto");
|
|
5
|
+
const path_1 = require("path");
|
|
6
|
+
const work_item_1 = require("../planner/work-item");
|
|
7
|
+
const work_task_1 = require("../planner/work-task");
|
|
8
|
+
const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
|
|
9
|
+
const get_cache_directory_1 = require("../optimizer/get-cache-directory");
|
|
10
|
+
const log_1 = require("../log");
|
|
11
|
+
// how many of its last durations a task keeps on this machine, the median of which it is
|
|
12
|
+
// expected to take
|
|
13
|
+
const KEPT_DURATIONS = 5;
|
|
14
|
+
/**
|
|
15
|
+
* The priority of a task waiting for a place to run: the time from its start until the end
|
|
16
|
+
* of the longest chain of what waits for it, its own expected duration and that of each
|
|
17
|
+
* task after it. A task on the longest chain of the run starts first, so a long chain does
|
|
18
|
+
* not wait behind short ones that could just as well run later.
|
|
19
|
+
*
|
|
20
|
+
* Expected durations come from past runs. A task without any counts as the median of the
|
|
21
|
+
* others; when none has one, every task counts 1 and the chain is counted in tasks. A task
|
|
22
|
+
* that runs nothing (it only groups others), and one that completed already (it was taken
|
|
23
|
+
* from the cache), count 0. A service counts 0 itself and carries on the chains of the
|
|
24
|
+
* tasks that need it.
|
|
25
|
+
*/
|
|
26
|
+
function getTaskPriority(workTree, durations) {
|
|
27
|
+
const items = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree), ...(0, plan_work_tasks_1.iterateWorkServices)(workTree)];
|
|
28
|
+
const dependents = new Map();
|
|
29
|
+
const add = (on, dependent) => {
|
|
30
|
+
const list = dependents.get(on) ?? [];
|
|
31
|
+
if (!list.includes(dependent)) {
|
|
32
|
+
list.push(dependent);
|
|
33
|
+
}
|
|
34
|
+
dependents.set(on, list);
|
|
35
|
+
};
|
|
36
|
+
for (const item of items) {
|
|
37
|
+
for (const dep of item.deps) {
|
|
38
|
+
add(dep, item);
|
|
39
|
+
}
|
|
40
|
+
for (const need of item.needs) {
|
|
41
|
+
add(need.service, item);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const known = items
|
|
45
|
+
.filter((item) => (0, work_item_1.isWorkTaskItem)(item) && durations[item.name] !== undefined)
|
|
46
|
+
.map((item) => durations[item.name])
|
|
47
|
+
.sort((a, b) => a - b);
|
|
48
|
+
const fallback = known.length > 0 ? known[Math.floor((known.length - 1) / 2)] : 1;
|
|
49
|
+
const cost = (item) => {
|
|
50
|
+
if (!(0, work_item_1.isWorkTaskItem)(item)) {
|
|
51
|
+
return 0;
|
|
52
|
+
}
|
|
53
|
+
const state = item.state?.current;
|
|
54
|
+
if (state?.type === 'completed' || (0, work_task_1.isAggregateTask)(item.data)) {
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
return durations[item.name] ?? fallback;
|
|
58
|
+
};
|
|
59
|
+
// a memo holds for one pick: what completed since the last one counts 0 now
|
|
60
|
+
return (item, memo = new Map()) => {
|
|
61
|
+
const chain = (current, path) => {
|
|
62
|
+
const cached = memo.get(current);
|
|
63
|
+
if (cached !== undefined) {
|
|
64
|
+
return cached;
|
|
65
|
+
}
|
|
66
|
+
// a loop is refused before a run starts, this only keeps the walk finite
|
|
67
|
+
if (path.has(current)) {
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
path.add(current);
|
|
71
|
+
let longest = 0;
|
|
72
|
+
for (const dependent of dependents.get(current) ?? []) {
|
|
73
|
+
longest = Math.max(longest, chain(dependent, path));
|
|
74
|
+
}
|
|
75
|
+
path.delete(current);
|
|
76
|
+
const value = cost(current) + longest;
|
|
77
|
+
memo.set(current, value);
|
|
78
|
+
return value;
|
|
79
|
+
};
|
|
80
|
+
return chain(item, new Set());
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
exports.getTaskPriority = getTaskPriority;
|
|
84
|
+
// Where a task keeps its last durations on this machine: below hammerkit's directory, by
|
|
85
|
+
// the directory of its build file and its name.
|
|
86
|
+
function getDurationFile(task) {
|
|
87
|
+
const key = (0, crypto_1.createHash)('sha1').update(`${task.data.cwd}\0${task.name}`).digest('hex');
|
|
88
|
+
return (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'durations', `${key}.json`);
|
|
89
|
+
}
|
|
90
|
+
exports.getDurationFile = getDurationFile;
|
|
91
|
+
async function readKept(environment, task) {
|
|
92
|
+
const file = getDurationFile(task);
|
|
93
|
+
try {
|
|
94
|
+
if (!(await environment.file.exists(file))) {
|
|
95
|
+
return [];
|
|
96
|
+
}
|
|
97
|
+
const parsed = JSON.parse(await environment.file.read(file));
|
|
98
|
+
return Array.isArray(parsed?.durations)
|
|
99
|
+
? parsed.durations.filter((value) => typeof value === 'number' && value >= 0)
|
|
100
|
+
: [];
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
// What the tasks of a run took the last times they ran on this machine.
|
|
107
|
+
async function readTaskDurations(workTree, environment) {
|
|
108
|
+
const durations = {};
|
|
109
|
+
await Promise.all([...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].map(async (task) => {
|
|
110
|
+
const kept = await readKept(environment, task);
|
|
111
|
+
if (kept.length > 0) {
|
|
112
|
+
const sorted = [...kept].sort((a, b) => a - b);
|
|
113
|
+
durations[task.name] = sorted[Math.floor((sorted.length - 1) / 2)];
|
|
114
|
+
}
|
|
115
|
+
}));
|
|
116
|
+
return durations;
|
|
117
|
+
}
|
|
118
|
+
exports.readTaskDurations = readTaskDurations;
|
|
119
|
+
// Keep what a task took, once it ran to its end. Best effort: a run never fails over it.
|
|
120
|
+
async function recordTaskDuration(environment, task, duration) {
|
|
121
|
+
try {
|
|
122
|
+
const kept = [...(await readKept(environment, task)), Math.max(0, Math.round(duration))].slice(-KEPT_DURATIONS);
|
|
123
|
+
await environment.file.createDirectory((0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'durations'));
|
|
124
|
+
await environment.file.writeFile(getDurationFile(task), JSON.stringify({ durations: kept }));
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
task.status.write('debug', `${task.name} could not keep how long it took: ${(0, log_1.getErrorMessage)(e)}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
exports.recordTaskDuration = recordTaskDuration;
|
|
131
|
+
//# sourceMappingURL=task-priority.js.map
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.statBeneath = void 0;
|
|
4
|
+
const fs_1 = require("fs");
|
|
5
|
+
const promises_1 = require("fs/promises");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
/**
|
|
8
|
+
* What `path`, inside `root`, is: its device and inode, reached from the root one name at a
|
|
9
|
+
* time without following a link. On Linux each folder is opened with O_NOFOLLOW through the
|
|
10
|
+
* descriptor of the one above (/proc/self/fd/<n>/<name>), and the last name is looked at
|
|
11
|
+
* (lstat) through the descriptor of its folder, so a folder swapped for a link at any moment
|
|
12
|
+
* is either refused or not looked at: the answer is never what a link led to.
|
|
13
|
+
* Elsewhere (a machine of a developer) the names are checked for links, then the path read.
|
|
14
|
+
* Throws when the path leaves the root, goes through a link, or can not be opened.
|
|
15
|
+
*/
|
|
16
|
+
async function statBeneath(root, path) {
|
|
17
|
+
const inside = (0, path_1.relative)(root, path);
|
|
18
|
+
if (inside === '..' || inside.startsWith(`..${path_1.sep}`) || (0, path_1.isAbsolute)(inside)) {
|
|
19
|
+
throw new Error(`${path} is outside of ${root}`);
|
|
20
|
+
}
|
|
21
|
+
const parts = inside === '' ? [] : inside.split(path_1.sep);
|
|
22
|
+
if (process.platform !== 'linux') {
|
|
23
|
+
let current = root;
|
|
24
|
+
for (const part of parts) {
|
|
25
|
+
current = (0, path_1.join)(current, part);
|
|
26
|
+
if ((await (0, promises_1.lstat)(current)).isSymbolicLink()) {
|
|
27
|
+
throw new Error(`${path} goes through the symbolic link ${(0, path_1.relative)(root, current)}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return (0, promises_1.stat)(path, { bigint: true });
|
|
31
|
+
}
|
|
32
|
+
let handle = await (0, promises_1.open)(root, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY);
|
|
33
|
+
try {
|
|
34
|
+
if ((await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined)) === undefined) {
|
|
35
|
+
throw new Error(`${path} can not be checked: /proc/self/fd is not readable`);
|
|
36
|
+
}
|
|
37
|
+
// the folders on the way are opened, the last name is only looked at, from the folder
|
|
38
|
+
// above it, which is pinned by its descriptor: so a file the server may not read still
|
|
39
|
+
// has an identity
|
|
40
|
+
for (const [index, part] of parts.entries()) {
|
|
41
|
+
const through = `/proc/self/fd/${handle.fd}/${part}`;
|
|
42
|
+
if (index === parts.length - 1) {
|
|
43
|
+
const stats = await (0, promises_1.lstat)(through, { bigint: true });
|
|
44
|
+
if (stats.isSymbolicLink()) {
|
|
45
|
+
throw new Error(`${path} goes through a symbolic link at ${parts.join('/')}`);
|
|
46
|
+
}
|
|
47
|
+
return stats;
|
|
48
|
+
}
|
|
49
|
+
const next = await (0, promises_1.open)(through, fs_1.constants.O_RDONLY | fs_1.constants.O_NOFOLLOW | fs_1.constants.O_DIRECTORY).catch((e) => {
|
|
50
|
+
const code = e.code;
|
|
51
|
+
if (code === 'ELOOP' || code === 'ENOTDIR') {
|
|
52
|
+
throw new Error(`${path} goes through a symbolic link at ${parts.slice(0, index + 1).join('/')}`);
|
|
53
|
+
}
|
|
54
|
+
throw e;
|
|
55
|
+
});
|
|
56
|
+
await handle.close();
|
|
57
|
+
handle = next;
|
|
58
|
+
}
|
|
59
|
+
return await handle.stat({ bigint: true });
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
await handle.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.statBeneath = statBeneath;
|
|
66
|
+
//# sourceMappingURL=stat-beneath.js.map
|
package/dist/file/within-root.js
CHANGED
|
@@ -8,7 +8,9 @@ const path_1 = require("path");
|
|
|
8
8
|
* checkout, a sandbox), or null when it stays inside. A path may not lead out of the
|
|
9
9
|
* root, and none of its parts that exist may be a symbolic link, since docker, tar
|
|
10
10
|
* and the file system would follow it wherever it points. A part that doesn't exist
|
|
11
|
-
* yet is fine, it can't be a link until something makes it.
|
|
11
|
+
* yet is fine, it can't be a link until something makes it. A part that can't be looked
|
|
12
|
+
* at (a folder the server may not read) is not: what reads it later, a rootful docker,
|
|
13
|
+
* may well follow a link behind it.
|
|
12
14
|
*/
|
|
13
15
|
async function findRootEscape(root, path) {
|
|
14
16
|
const inside = (0, path_1.relative)((0, path_1.resolve)(root), (0, path_1.resolve)(root, path));
|
|
@@ -21,9 +23,16 @@ async function findRootEscape(root, path) {
|
|
|
21
23
|
let current = (0, path_1.resolve)(root);
|
|
22
24
|
for (const part of inside.split(path_1.sep)) {
|
|
23
25
|
current = (0, path_1.join)(current, part);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
let stats;
|
|
27
|
+
try {
|
|
28
|
+
stats = await (0, promises_1.lstat)(current);
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
const code = e.code;
|
|
32
|
+
if (code === 'ENOENT' || code === 'ENOTDIR') {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return `can not be checked for symbolic links at ${(0, path_1.relative)(root, current).split(path_1.sep).join('/')} (${code ?? e})`;
|
|
27
36
|
}
|
|
28
37
|
if (stats.isSymbolicLink()) {
|
|
29
38
|
return `goes through the symbolic link ${(0, path_1.relative)(root, current).split(path_1.sep).join('/')}`;
|
package/dist/harness/connect.js
CHANGED
|
@@ -36,12 +36,7 @@ exports.hasShell = hasShell;
|
|
|
36
36
|
*/
|
|
37
37
|
async function connectServer(environment, options) {
|
|
38
38
|
const config = await (0, host_config_1.readHostConfig)(environment);
|
|
39
|
-
const name = options.server
|
|
40
|
-
if (!name || !(0, host_config_1.hasServer)(config.servers, name)) {
|
|
41
|
-
throw new Error(options.server
|
|
42
|
-
? `server ${options.server} is not registered, add it with: hammerkit remote add ${options.server} <url> --issuer <url>`
|
|
43
|
-
: 'name a server (HAMMERKIT_SERVER or --server), or set a default with: hammerkit remote use <name>');
|
|
44
|
-
}
|
|
39
|
+
const name = (0, host_config_1.chooseServer)(config, options.server || undefined, 'with HAMMERKIT_SERVER or --server');
|
|
45
40
|
if (!options.build) {
|
|
46
41
|
throw new Error('name the published version of the build file whose tasks run on the sandbox by its hash (HAMMERKIT_BUILD or --build), as hammerkit remote publish printed it');
|
|
47
42
|
}
|
|
@@ -25,7 +25,7 @@ function registerMcpCommand(remote, environment, input = process.stdin) {
|
|
|
25
25
|
remote
|
|
26
26
|
.command('mcp')
|
|
27
27
|
.description('serve the files, shell and tasks of a sandbox on a server as MCP tools over stdio (experimental)')
|
|
28
|
-
.addOption(new commander_1.Option('--server <name>', 'registered server (default: hammerkit remote use)').env('HAMMERKIT_SERVER'))
|
|
28
|
+
.addOption(new commander_1.Option('--server <name>', 'registered server (default: hammerkit remote use, or the only registered server)').env('HAMMERKIT_SERVER'))
|
|
29
29
|
.addOption(new commander_1.Option('--sandbox <id>', 'a sandbox of yours on the server').env('HAMMERKIT_SANDBOX'))
|
|
30
30
|
.addOption(new commander_1.Option('--repo <repo>', 'create a sandbox of this repository').env('HAMMERKIT_REPO'))
|
|
31
31
|
.addOption(new commander_1.Option('--ref <ref>', 'at this branch').env('HAMMERKIT_REF'))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = void 0;
|
|
3
|
+
exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
|
|
4
4
|
const path_1 = require("path");
|
|
5
5
|
const token_source_1 = require("../remote/token-source");
|
|
6
6
|
// a write carries up to 32 MiB
|
|
@@ -9,6 +9,9 @@ const TIMEOUT_MS = 60000;
|
|
|
9
9
|
const POLL_WAIT = '1s';
|
|
10
10
|
// a cancelled run waits this long for the server to take the cancel, before it gives up
|
|
11
11
|
const CANCEL_WAIT_MS = 10000;
|
|
12
|
+
// what is read of a page of an endpoint: an app can answer with any amount, and only
|
|
13
|
+
// the start of it is shown
|
|
14
|
+
exports.MAX_ENDPOINT_BYTES = 256 * 1024;
|
|
12
15
|
class SandboxClientError extends Error {
|
|
13
16
|
constructor(message, status) {
|
|
14
17
|
super(message);
|
|
@@ -213,9 +216,10 @@ class SandboxClient {
|
|
|
213
216
|
}
|
|
214
217
|
/**
|
|
215
218
|
* A page of an endpoint of a service run, as the caller sees it: only at an address the
|
|
216
|
-
* server gave the run, so the token goes to the server and nowhere else.
|
|
219
|
+
* server gave the run, so the token goes to the server and nowhere else. At most
|
|
220
|
+
* `maxBytes` of the body are read, `truncated` tells when there was more.
|
|
217
221
|
*/
|
|
218
|
-
async fetchEndpoint(id, path, service, signal) {
|
|
222
|
+
async fetchEndpoint(id, path, service, signal, maxBytes = exports.MAX_ENDPOINT_BYTES) {
|
|
219
223
|
const run = await this.getRun(id);
|
|
220
224
|
const endpoint = run.up?.endpoints.find((candidate) => service === undefined || candidate.service === service);
|
|
221
225
|
if (!endpoint) {
|
|
@@ -232,11 +236,13 @@ class SandboxClient {
|
|
|
232
236
|
redirect: 'manual',
|
|
233
237
|
signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]),
|
|
234
238
|
});
|
|
239
|
+
const { text, truncated } = await readTextUpTo(response, maxBytes);
|
|
235
240
|
return {
|
|
236
241
|
url: url.toString(),
|
|
237
242
|
status: response.status,
|
|
238
243
|
type: response.headers.get('content-type') ?? '',
|
|
239
|
-
body:
|
|
244
|
+
body: text,
|
|
245
|
+
truncated,
|
|
240
246
|
};
|
|
241
247
|
}
|
|
242
248
|
/**
|
|
@@ -305,6 +311,35 @@ function oneAtATime() {
|
|
|
305
311
|
};
|
|
306
312
|
}
|
|
307
313
|
exports.oneAtATime = oneAtATime;
|
|
314
|
+
// The body of an answer as text, read up to `maxBytes` and then cancelled, so a page
|
|
315
|
+
// of any size takes no more memory than that. A character cut at the limit is left out.
|
|
316
|
+
async function readTextUpTo(response, maxBytes) {
|
|
317
|
+
if (!response.body) {
|
|
318
|
+
return { text: '', truncated: false };
|
|
319
|
+
}
|
|
320
|
+
const reader = response.body.getReader();
|
|
321
|
+
const decoder = new TextDecoder();
|
|
322
|
+
let text = '';
|
|
323
|
+
let read = 0;
|
|
324
|
+
try {
|
|
325
|
+
for (;;) {
|
|
326
|
+
const { done, value } = await reader.read();
|
|
327
|
+
if (done) {
|
|
328
|
+
return { text: text + decoder.decode(), truncated: false };
|
|
329
|
+
}
|
|
330
|
+
const room = maxBytes - read;
|
|
331
|
+
if (value.byteLength > room) {
|
|
332
|
+
return { text: text + decoder.decode(value.subarray(0, room), { stream: true }), truncated: true };
|
|
333
|
+
}
|
|
334
|
+
read += value.byteLength;
|
|
335
|
+
text += decoder.decode(value, { stream: true });
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
await reader.cancel().catch(() => undefined);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
exports.readTextUpTo = readTextUpTo;
|
|
308
343
|
// a run that is over, its state does not change any more
|
|
309
344
|
exports.FINAL_RUN_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
|
|
310
345
|
async function submitRun(connection, request) {
|
|
@@ -120,8 +120,8 @@ exports.SERVICE_TOOLS = [
|
|
|
120
120
|
required: ['run', 'path'],
|
|
121
121
|
async call(client, args, signal) {
|
|
122
122
|
const page = await client.fetchEndpoint(args.run, args.path, args.service || undefined, signal);
|
|
123
|
-
const body = page.body.length > MAX_PAGE_CHARS
|
|
124
|
-
? `${page.body.slice(0, MAX_PAGE_CHARS)}\n… (${page.body.length} characters, the first ${MAX_PAGE_CHARS} shown)`
|
|
123
|
+
const body = page.truncated || page.body.length > MAX_PAGE_CHARS
|
|
124
|
+
? `${page.body.slice(0, MAX_PAGE_CHARS)}\n… (${page.truncated ? 'more than ' : ''}${page.body.length} characters, the first ${Math.min(MAX_PAGE_CHARS, page.body.length)} shown)`
|
|
125
125
|
: page.body;
|
|
126
126
|
return [`GET ${page.url}: ${page.status}${page.type ? ` (${page.type})` : ''}`, '', body].join('\n');
|
|
127
127
|
},
|
|
@@ -33,38 +33,54 @@ async function awaitJobCompletion(instance, env, name, abort, pollInterval = 100
|
|
|
33
33
|
: null;
|
|
34
34
|
// when the job last had a pod: a refusal before it is not one of the pod it waits for now
|
|
35
35
|
let hadPod = 0;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const job = await instance.batchApi.readNamespacedJobStatus({ name, namespace: env.namespace });
|
|
42
|
-
const status = job.status;
|
|
43
|
-
if (status?.succeeded) {
|
|
44
|
-
return;
|
|
36
|
+
let refused = false;
|
|
37
|
+
const tell = (now) => {
|
|
38
|
+
if (now !== refused) {
|
|
39
|
+
refused = now;
|
|
40
|
+
quota?.onRefused?.(now);
|
|
45
41
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
42
|
+
};
|
|
43
|
+
try {
|
|
44
|
+
return await pollJob();
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
tell(false);
|
|
48
|
+
}
|
|
49
|
+
async function pollJob() {
|
|
50
|
+
for (;;) {
|
|
51
|
+
if (abort.aborted) {
|
|
52
|
+
await deleteJob(instance, env, name);
|
|
53
|
+
throw new abort_1.AbortError();
|
|
54
54
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
const job = await instance.batchApi.readNamespacedJobStatus({ name, namespace: env.namespace });
|
|
56
|
+
const status = job.status;
|
|
57
|
+
if (status?.succeeded) {
|
|
58
|
+
return;
|
|
58
59
|
}
|
|
59
|
-
|
|
60
|
-
|
|
60
|
+
const failed = status?.conditions?.find((c) => c.type === 'Failed' && c.status === 'True');
|
|
61
|
+
if (failed) {
|
|
62
|
+
throw new Error(`job ${name} failed: ${failed.message ?? failed.reason ?? 'unknown reason'}`);
|
|
61
63
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
64
|
+
if (wait) {
|
|
65
|
+
let refusal = null;
|
|
66
|
+
if (status?.active || status?.ready) {
|
|
67
|
+
hadPod = Date.now();
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
// the job controller can't make the pod: no pod to wait on, only its events say why
|
|
71
|
+
refusal = await readJobRefusal(instance, env, name, job, hadPod);
|
|
72
|
+
}
|
|
73
|
+
tell(refusal !== null);
|
|
74
|
+
try {
|
|
75
|
+
await wait.check(refusal);
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
await deleteJob(instance, env, name);
|
|
79
|
+
throw e;
|
|
80
|
+
}
|
|
65
81
|
}
|
|
82
|
+
await sleep(pollInterval, abort);
|
|
66
83
|
}
|
|
67
|
-
await sleep(pollInterval, abort);
|
|
68
84
|
}
|
|
69
85
|
}
|
|
70
86
|
exports.awaitJobCompletion = awaitJobCompletion;
|
|
@@ -17,6 +17,8 @@ const ensure_kubernetes_persistent_volume_claim_exists_1 = require("./ensure-kub
|
|
|
17
17
|
const stream_1 = require("stream");
|
|
18
18
|
const job_placement_1 = require("./job-placement");
|
|
19
19
|
const assert_item_paths_1 = require("../planner/utils/assert-item-paths");
|
|
20
|
+
const transfer_tools_1 = require("./transfer-tools");
|
|
21
|
+
const network_policy_1 = require("./network-policy");
|
|
20
22
|
// A previous run that crashed between creating an upload/download pod and its
|
|
21
23
|
// `finally` cleanup leaves a pod behind under the same deterministic name. apply()
|
|
22
24
|
// would then patch that stale pod in place — and if it is stuck in a terminal
|
|
@@ -102,6 +104,12 @@ signal, fn) {
|
|
|
102
104
|
}
|
|
103
105
|
return array;
|
|
104
106
|
}, []);
|
|
107
|
+
// its tools are in a folder of their own, which no output may be in or over: it would
|
|
108
|
+
// replace them with what the task wrote
|
|
109
|
+
const overTools = mounts.find((mount) => (0, transfer_tools_1.isTransferToolsPath)(mount.mountPath));
|
|
110
|
+
if (overTools) {
|
|
111
|
+
throw new Error(`${service.name}: an output can not be at ${overTools.mountPath}, ${transfer_tools_1.TRANSFER_TOOLS_PATH} is the folder of hammerkit's tools`);
|
|
112
|
+
}
|
|
105
113
|
// only the claims it mounts: one of a dep it doesn't read would only bind where it goes
|
|
106
114
|
const volumes = persistence.volumes.filter((volume) => mounts.some((mount) => mount.name === volume.name));
|
|
107
115
|
// Guarantee the claims exist right before scheduling the pod that mounts
|
|
@@ -123,7 +131,12 @@ signal, fn) {
|
|
|
123
131
|
metadata: {
|
|
124
132
|
namespace: env.namespace,
|
|
125
133
|
name,
|
|
126
|
-
labels: {
|
|
134
|
+
labels: {
|
|
135
|
+
...(serving ? (0, job_placement_1.getRunLabels)(env) : (0, resources_1.getItemLabels)(service, env)),
|
|
136
|
+
...claims.labels,
|
|
137
|
+
// on a server it reaches nothing and nothing reaches it (see getNamespacePolicies)
|
|
138
|
+
...(env.server ? (0, network_policy_1.getTransferNetworkLabels)() : {}),
|
|
139
|
+
},
|
|
127
140
|
annotations: {
|
|
128
141
|
'hammerkit.dev/version': (0, version_1.getVersion)(),
|
|
129
142
|
},
|
|
@@ -138,18 +151,20 @@ signal, fn) {
|
|
|
138
151
|
...(0, job_placement_1.getPodPlacement)(env.server, 'pool' in service.data ? service.data.pool : undefined),
|
|
139
152
|
}
|
|
140
153
|
: {}),
|
|
154
|
+
initContainers: [(0, transfer_tools_1.getTransferToolsInitContainer)()],
|
|
141
155
|
containers: [
|
|
142
156
|
{
|
|
143
157
|
name: 'volume',
|
|
144
|
-
image:
|
|
145
|
-
command: ['sh'],
|
|
158
|
+
image: transfer_tools_1.HELPER_TOOLS_IMAGE,
|
|
159
|
+
command: (0, transfer_tools_1.inTransferPod)(['sh']),
|
|
146
160
|
tty: true,
|
|
147
|
-
|
|
161
|
+
env: transfer_tools_1.TRANSFER_TOOLS_ENV,
|
|
162
|
+
volumeMounts: [...mounts, transfer_tools_1.TRANSFER_TOOLS_MOUNT],
|
|
148
163
|
resources: exports.TRANSFER_POD_RESOURCES,
|
|
149
164
|
...(0, job_placement_1.getContainerSecurity)(env),
|
|
150
165
|
},
|
|
151
166
|
],
|
|
152
|
-
volumes,
|
|
167
|
+
volumes: [...volumes, ...transfer_tools_1.TRANSFER_TOOLS_VOLUMES],
|
|
153
168
|
},
|
|
154
169
|
};
|
|
155
170
|
service.status.write('debug', `create pod ${name}`);
|
|
@@ -194,7 +209,7 @@ exports.clearClaim = clearClaim;
|
|
|
194
209
|
// Runs `command` in the upload pod `pod`: what failed, or null when it went well
|
|
195
210
|
async function execInPod(instance, env, pod, command) {
|
|
196
211
|
let failure = null;
|
|
197
|
-
const res = await instance.exec.exec(env.namespace, pod, 'volume', command, process.stdout, process.stderr, null, false, (status) => {
|
|
212
|
+
const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(command), process.stdout, process.stderr, null, false, (status) => {
|
|
198
213
|
if (status.status !== 'Success') {
|
|
199
214
|
failure = status.message ?? status.reason ?? 'unknown';
|
|
200
215
|
}
|
|
@@ -457,7 +472,7 @@ options = {}) {
|
|
|
457
472
|
const data = packSource(source);
|
|
458
473
|
service.status.write('info', `upload ${source.localPath}`);
|
|
459
474
|
const targetPath = `/dev/hammerkit/${service.id()}`;
|
|
460
|
-
const res = await instance.exec.exec(env.namespace, name, 'volume', ['tar', 'xf', '-', '-C', targetPath], process.stdout, process.stderr, data, false, (status) => {
|
|
475
|
+
const res = await instance.exec.exec(env.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)(['tar', 'xf', '-', '-C', targetPath]), process.stdout, process.stderr, data, false, (status) => {
|
|
461
476
|
service.status.write('debug', `upload ${source.localPath} to ${name}: ${status}`);
|
|
462
477
|
});
|
|
463
478
|
await new Promise((resolve, reject) => {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getNetworkGateContainer = exports.HELPER_SECURITY_CONTEXT = exports.NETWORK_GATE_SCRIPT = exports.NETWORK_GATE_CONTAINER = exports.NETWORK_GATE_TIMEOUT_MS = void 0;
|
|
3
|
+
exports.getOpenNetworkGate = exports.OPEN_NETWORK_GATE_SETTING = exports.METADATA_ADDRESS = exports.getNetworkGateContainer = exports.HELPER_SECURITY_CONTEXT = exports.NETWORK_GATE_SCRIPT = exports.NETWORK_GATE_CONTAINER = exports.NETWORK_GATE_TIMEOUT_MS = void 0;
|
|
4
|
+
const net_1 = require("net");
|
|
4
5
|
const egress_proxy_1 = require("../network/egress-proxy");
|
|
5
6
|
// Some network plugins (kind's kindnet among them) enforce a NetworkPolicy a
|
|
6
7
|
// moment after a pod started, so a limited pod's first connections could
|
|
@@ -8,6 +9,9 @@ const egress_proxy_1 = require("../network/egress-proxy");
|
|
|
8
9
|
// the pod no longer reaches the cluster DNS, which the policy of every limited
|
|
9
10
|
// item denies, so the item's own containers start only once the policy holds.
|
|
10
11
|
// A policy that never takes hold fails the pod instead of running it open.
|
|
12
|
+
// A pod with an open network on a server is limited too, by the policy of its
|
|
13
|
+
// namespace, which denies it the cloud's metadata address among others: its gate
|
|
14
|
+
// waits until that address is out of reach instead (see getOpenNetworkGate).
|
|
11
15
|
// A script for `node -e` in the proxy's image, like the proxy.
|
|
12
16
|
exports.NETWORK_GATE_TIMEOUT_MS = 60000;
|
|
13
17
|
// the name of the gate's init container
|
|
@@ -20,23 +24,30 @@ const resolvConf = process.env.HAMMERKIT_GATE_RESOLV_CONF || '/etc/resolv.conf'
|
|
|
20
24
|
const port = parseInt(process.env.HAMMERKIT_GATE_PORT || '53', 10)
|
|
21
25
|
const deadline = Date.now() + parseInt(process.env.HAMMERKIT_GATE_TIMEOUT_MS || '${exports.NETWORK_GATE_TIMEOUT_MS}', 10)
|
|
22
26
|
function fail(message) {
|
|
27
|
+
if (process.env.HAMMERKIT_GATE_HINT) {
|
|
28
|
+
message += ' (' + process.env.HAMMERKIT_GATE_HINT + ')'
|
|
29
|
+
}
|
|
23
30
|
process.stderr.write('hammerkit: ' + message + '\\n')
|
|
24
31
|
try {
|
|
25
32
|
fs.writeFileSync('/dev/termination-log', 'hammerkit: ' + message)
|
|
26
33
|
} catch (e) {}
|
|
27
34
|
process.exit(1)
|
|
28
35
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
+
const probeMs = parseInt(process.env.HAMMERKIT_GATE_PROBE_MS || '2000', 10)
|
|
37
|
+
let nameserver = process.env.HAMMERKIT_GATE_HOST
|
|
38
|
+
if (!nameserver) {
|
|
39
|
+
let conf = ''
|
|
40
|
+
try {
|
|
41
|
+
conf = fs.readFileSync(resolvConf, 'utf8')
|
|
42
|
+
} catch (e) {}
|
|
43
|
+
const match = /^nameserver\\s+(\\S+)/m.exec(conf)
|
|
44
|
+
if (!match) {
|
|
45
|
+
fail('the pod has no cluster DNS, so its network policy can not be checked')
|
|
46
|
+
}
|
|
47
|
+
nameserver = match[1]
|
|
36
48
|
}
|
|
37
|
-
const nameserver = match[1]
|
|
38
49
|
function attempt() {
|
|
39
|
-
const socket = net.connect({ host: nameserver, port, timeout:
|
|
50
|
+
const socket = net.connect({ host: nameserver, port, timeout: probeMs })
|
|
40
51
|
socket.once('connect', () => {
|
|
41
52
|
socket.destroy()
|
|
42
53
|
if (Date.now() > deadline) {
|
|
@@ -58,14 +69,66 @@ exports.HELPER_SECURITY_CONTEXT = {
|
|
|
58
69
|
readOnlyRootFilesystem: true,
|
|
59
70
|
capabilities: { drop: ['ALL'] },
|
|
60
71
|
};
|
|
61
|
-
|
|
72
|
+
// how long the gate of an open pod waits for an answer of its target: a link-local
|
|
73
|
+
// address answers at once, when it is reached at all
|
|
74
|
+
const OPEN_GATE_PROBE_MS = 1000;
|
|
75
|
+
// `target`: the address of an open pod's gate (getOpenNetworkGate); without it, the
|
|
76
|
+
// cluster DNS a limited pod is denied
|
|
77
|
+
function getNetworkGateContainer(target) {
|
|
62
78
|
return {
|
|
63
79
|
name: exports.NETWORK_GATE_CONTAINER,
|
|
64
80
|
image: egress_proxy_1.EGRESS_PROXY_IMAGE,
|
|
65
81
|
command: ['node', '-e', exports.NETWORK_GATE_SCRIPT],
|
|
82
|
+
...(target
|
|
83
|
+
? {
|
|
84
|
+
env: [
|
|
85
|
+
{ name: 'HAMMERKIT_GATE_HOST', value: target.host },
|
|
86
|
+
{ name: 'HAMMERKIT_GATE_PORT', value: `${target.port}` },
|
|
87
|
+
{ name: 'HAMMERKIT_GATE_PROBE_MS', value: `${OPEN_GATE_PROBE_MS}` },
|
|
88
|
+
{
|
|
89
|
+
name: 'HAMMERKIT_GATE_HINT',
|
|
90
|
+
value: `the server's ${exports.OPEN_NETWORK_GATE_SETTING} points this wait at another address ` +
|
|
91
|
+
'the namespace denies, or turns it off with false',
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
}
|
|
95
|
+
: {}),
|
|
66
96
|
securityContext: exports.HELPER_SECURITY_CONTEXT,
|
|
67
97
|
resources: { limits: { memory: '64Mi' } },
|
|
68
98
|
};
|
|
69
99
|
}
|
|
70
100
|
exports.getNetworkGateContainer = getNetworkGateContainer;
|
|
101
|
+
// The metadata endpoint of the clouds, which hands out the node's identity
|
|
102
|
+
exports.METADATA_ADDRESS = '169.254.169.254';
|
|
103
|
+
// the setting of the server that turns the gate of open pods off or points it elsewhere
|
|
104
|
+
exports.OPEN_NETWORK_GATE_SETTING = 'backend.openNetworkGate';
|
|
105
|
+
/**
|
|
106
|
+
* The gate of the pods with an open network on a server: they wait until they no longer
|
|
107
|
+
* reach an address the policy of their namespace denies them, by default the metadata
|
|
108
|
+
* endpoint (`backend.deniedEgress` covers it). The operator points it elsewhere, or turns
|
|
109
|
+
* it off with `false` (`backend.openNetworkGate`). None when the operator did not state that
|
|
110
|
+
* the cluster enforces NetworkPolicy, or when the address isn't denied or is allowed: the
|
|
111
|
+
* gate would never open.
|
|
112
|
+
*/
|
|
113
|
+
function getOpenNetworkGate(backend) {
|
|
114
|
+
if (backend.networkPolicy !== 'enforced' || backend.openNetworkGate === false) {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
const target = backend.openNetworkGate ?? { host: exports.METADATA_ADDRESS, port: 80 };
|
|
118
|
+
const covers = (ranges) => {
|
|
119
|
+
const list = new net_1.BlockList();
|
|
120
|
+
for (const range of ranges) {
|
|
121
|
+
const [address, prefix] = range.split('/');
|
|
122
|
+
if ((0, net_1.isIPv4)(address)) {
|
|
123
|
+
list.addSubnet(address, prefix === undefined ? 32 : parseInt(prefix, 10), 'ipv4');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return list.check(target.host, 'ipv4');
|
|
127
|
+
};
|
|
128
|
+
if (!covers(backend.deniedEgress) || covers(backend.allowedEgress)) {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
return target;
|
|
132
|
+
}
|
|
133
|
+
exports.getOpenNetworkGate = getOpenNetworkGate;
|
|
71
134
|
//# sourceMappingURL=network-gate.js.map
|