hammerkit 2.0.0-next.14 → 2.0.0-next.16
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/dist/cache/last-resolved.js +11 -0
- package/dist/docker/package.js +85 -76
- package/dist/executer/docker-service.js +9 -0
- package/dist/executer/docker-task.js +2 -0
- package/dist/executer/execution-steps.js +3 -2
- package/dist/file/within-root.js +13 -4
- package/dist/harness/sandbox-client.js +39 -4
- package/dist/harness/service-tools.js +2 -2
- package/dist/planner/utils/assert-item-paths.js +6 -7
- package/dist/planner/work-runtime-docker.js +3 -4
- package/dist/planner/work-runtime-local.js +3 -7
- package/dist/remote/collect-bundle.js +9 -1
- package/dist/server/kubernetes-backend.js +5 -2
- package/dist/server/runs.js +4 -1
- package/dist/server/sandbox-files.js +232 -39
- package/dist/utils/tar.js +51 -1
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.readLastResolvedRecord = exports.writeLastResolvedRecord = exports.getLastResolvedFile = void 0;
|
|
4
4
|
const crypto_1 = require("crypto");
|
|
5
5
|
const path_1 = require("path");
|
|
6
|
+
const within_root_1 = require("../file/within-root");
|
|
6
7
|
const work_task_cache_description_1 = require("../optimizer/work-task-cache-description");
|
|
7
8
|
// Stored in the project's `.hammerkit` dir (local-first, alongside the local
|
|
8
9
|
// runtime state file) keyed by task name. The name is sanitized for the
|
|
@@ -14,8 +15,18 @@ function getLastResolvedFile(task) {
|
|
|
14
15
|
return (0, path_1.join)(task.data.cwd, '.hammerkit', 'last-resolved', `${sanitized}-${suffix}.json`);
|
|
15
16
|
}
|
|
16
17
|
exports.getLastResolvedFile = getLastResolvedFile;
|
|
18
|
+
// The record is written into the project, which a server does not own: a checkout or a
|
|
19
|
+
// sandbox whose `.hammerkit` may be a link a contributor committed or a task made, and the
|
|
20
|
+
// record would overwrite whatever it points at. A server writes none (`explain` runs where
|
|
21
|
+
// the project is), and on a machine a record that would go through a link is left out.
|
|
17
22
|
async function writeLastResolvedRecord(environment, task, record) {
|
|
23
|
+
if (environment.hosted) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
18
26
|
const file = getLastResolvedFile(task);
|
|
27
|
+
if (await (0, within_root_1.findRootEscape)(task.data.cwd, file)) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
19
30
|
await environment.file.createDirectory((0, path_1.join)(task.data.cwd, '.hammerkit', 'last-resolved'));
|
|
20
31
|
const payload = {
|
|
21
32
|
taskId: task.id(),
|
package/dist/docker/package.js
CHANGED
|
@@ -6,6 +6,7 @@ const work_item_1 = require("../planner/work-item");
|
|
|
6
6
|
const work_service_1 = require("../planner/work-service");
|
|
7
7
|
const execute_docker_1 = require("../executer/execute-docker");
|
|
8
8
|
const node_os_1 = require("node:os");
|
|
9
|
+
const promises_1 = require("node:fs/promises");
|
|
9
10
|
const path_1 = require("path");
|
|
10
11
|
const log_1 = require("../log");
|
|
11
12
|
// Default the build platform to the host architecture so a packaged image runs
|
|
@@ -32,88 +33,96 @@ async function packageWorkTree(workTree, environment, options) {
|
|
|
32
33
|
if ((0, work_item_1.isContainerWorkServiceItem)(service)) {
|
|
33
34
|
environment.console.info(`preparing files for ${service.name}`);
|
|
34
35
|
const definition = getServiceInstructions(service, options);
|
|
35
|
-
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
await environment.file.writeFile(dockerFileName, dockerFileContent);
|
|
40
|
-
environment.console.debug(`create dockerfile ${dockerFileName}`);
|
|
41
|
-
environment.console.debug(`with cwd ${definition.cwd}`);
|
|
42
|
-
const src = ['Dockerfile'];
|
|
43
|
-
for (const source of definition.sources) {
|
|
44
|
-
const path = (0, path_1.relative)(definition.cwd, source.absolutePath);
|
|
45
|
-
environment.console.debug(`copying ${source.absolutePath} to ${(0, path_1.join)(buildDir, path)}`);
|
|
46
|
-
await environment.file.copy(source.absolutePath, (0, path_1.join)(buildDir, path));
|
|
47
|
-
src.push(path);
|
|
36
|
+
// a new private directory for each build, removed afterwards
|
|
37
|
+
const buildDir = await (0, promises_1.mkdtemp)((0, path_1.join)((0, node_os_1.tmpdir)(), 'hammerkit-package-'));
|
|
38
|
+
try {
|
|
39
|
+
await packageService(docker, service, definition, buildDir, environment, options, platform, tag);
|
|
48
40
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const buildStream = await docker.buildImage({
|
|
52
|
-
src,
|
|
53
|
-
context: buildDir,
|
|
54
|
-
}, {
|
|
55
|
-
t: imageName,
|
|
56
|
-
platform,
|
|
57
|
-
abortSignal: environment.abortCtrl.signal,
|
|
58
|
-
});
|
|
59
|
-
await new Promise((resolve, reject) => {
|
|
60
|
-
docker.modem.followProgress(buildStream, (err, res) => {
|
|
61
|
-
if (err) {
|
|
62
|
-
environment.console.error((0, log_1.getErrorMessage)(err));
|
|
63
|
-
reject(err);
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
// followProgress returns every build message in `res`, so a
|
|
67
|
-
// non-empty array is normal on success. Only fail when an entry
|
|
68
|
-
// actually carries an error.
|
|
69
|
-
const failure = (res ?? []).find((i) => 'error' in i && !!i.error);
|
|
70
|
-
if (failure && 'error' in failure) {
|
|
71
|
-
const detail = failure.errorDetail?.message ?? failure.error ?? 'unknown error';
|
|
72
|
-
environment.console.error(detail);
|
|
73
|
-
reject(new Error(`build failed: ${detail}`));
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
resolve();
|
|
77
|
-
}
|
|
78
|
-
}, (res) => {
|
|
79
|
-
if (res.stream) {
|
|
80
|
-
if (res.stream === '\n') {
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
if (res.stream.endsWith('\n')) {
|
|
84
|
-
environment.console.info(res.stream.substr(0, res.stream.length - 1));
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
environment.console.info(res.stream);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
});
|
|
91
|
-
});
|
|
92
|
-
environment.console.info(`generated image ${imageName} for ${service.name}`);
|
|
93
|
-
if (options.push) {
|
|
94
|
-
environment.console.info(`pushing image ${imageName} to ${options.registry}`);
|
|
95
|
-
const img = docker.getImage(imageName);
|
|
96
|
-
const pushStream = await img.push({
|
|
97
|
-
abortSignal: environment.abortCtrl.signal,
|
|
98
|
-
authconfig: {
|
|
99
|
-
username: options.username || '',
|
|
100
|
-
password: options.password || '',
|
|
101
|
-
serveraddress: options.registry,
|
|
102
|
-
},
|
|
103
|
-
});
|
|
104
|
-
await new Promise((resolve, reject) => {
|
|
105
|
-
docker.modem.followProgress(pushStream, (err, res) => (err ? reject(err) : resolve(res)), (res) => {
|
|
106
|
-
if (res.stream) {
|
|
107
|
-
environment.console.info(res.stream);
|
|
108
|
-
}
|
|
109
|
-
});
|
|
110
|
-
});
|
|
111
|
-
environment.console.info(`pushed image ${imageName} to ${options.registry}`);
|
|
41
|
+
finally {
|
|
42
|
+
await (0, promises_1.rm)(buildDir, { recursive: true, force: true });
|
|
112
43
|
}
|
|
113
44
|
}
|
|
114
45
|
}
|
|
115
46
|
}
|
|
116
47
|
exports.packageWorkTree = packageWorkTree;
|
|
48
|
+
async function packageService(docker, service, definition, buildDir, environment, options, platform, tag) {
|
|
49
|
+
const dockerFileName = (0, path_1.join)(buildDir, 'Dockerfile');
|
|
50
|
+
const dockerFileContent = definition.instructions.join('\n');
|
|
51
|
+
await environment.file.writeFile(dockerFileName, dockerFileContent);
|
|
52
|
+
environment.console.debug(`create dockerfile ${dockerFileName}`);
|
|
53
|
+
environment.console.debug(`with cwd ${definition.cwd}`);
|
|
54
|
+
const src = ['Dockerfile'];
|
|
55
|
+
for (const source of definition.sources) {
|
|
56
|
+
const path = (0, path_1.relative)(definition.cwd, source.absolutePath);
|
|
57
|
+
environment.console.debug(`copying ${source.absolutePath} to ${(0, path_1.join)(buildDir, path)}`);
|
|
58
|
+
await environment.file.copy(source.absolutePath, (0, path_1.join)(buildDir, path));
|
|
59
|
+
src.push(path);
|
|
60
|
+
}
|
|
61
|
+
const imageName = `${options.registry}/${service.name}:${tag}`;
|
|
62
|
+
environment.console.info(`building image ${imageName} for ${service.name} (${platform})`);
|
|
63
|
+
const buildStream = await docker.buildImage({
|
|
64
|
+
src,
|
|
65
|
+
context: buildDir,
|
|
66
|
+
}, {
|
|
67
|
+
t: imageName,
|
|
68
|
+
platform,
|
|
69
|
+
abortSignal: environment.abortCtrl.signal,
|
|
70
|
+
});
|
|
71
|
+
await new Promise((resolve, reject) => {
|
|
72
|
+
docker.modem.followProgress(buildStream, (err, res) => {
|
|
73
|
+
if (err) {
|
|
74
|
+
environment.console.error((0, log_1.getErrorMessage)(err));
|
|
75
|
+
reject(err);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
// followProgress returns every build message in `res`, so a
|
|
79
|
+
// non-empty array is normal on success. Only fail when an entry
|
|
80
|
+
// actually carries an error.
|
|
81
|
+
const failure = (res ?? []).find((i) => 'error' in i && !!i.error);
|
|
82
|
+
if (failure && 'error' in failure) {
|
|
83
|
+
const detail = failure.errorDetail?.message ?? failure.error ?? 'unknown error';
|
|
84
|
+
environment.console.error(detail);
|
|
85
|
+
reject(new Error(`build failed: ${detail}`));
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
resolve();
|
|
89
|
+
}
|
|
90
|
+
}, (res) => {
|
|
91
|
+
if (res.stream) {
|
|
92
|
+
if (res.stream === '\n') {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (res.stream.endsWith('\n')) {
|
|
96
|
+
environment.console.info(res.stream.substr(0, res.stream.length - 1));
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
environment.console.info(res.stream);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
environment.console.info(`generated image ${imageName} for ${service.name}`);
|
|
105
|
+
if (options.push) {
|
|
106
|
+
environment.console.info(`pushing image ${imageName} to ${options.registry}`);
|
|
107
|
+
const img = docker.getImage(imageName);
|
|
108
|
+
const pushStream = await img.push({
|
|
109
|
+
abortSignal: environment.abortCtrl.signal,
|
|
110
|
+
authconfig: {
|
|
111
|
+
username: options.username || '',
|
|
112
|
+
password: options.password || '',
|
|
113
|
+
serveraddress: options.registry,
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
await new Promise((resolve, reject) => {
|
|
117
|
+
docker.modem.followProgress(pushStream, (err, res) => (err ? reject(err) : resolve(res)), (res) => {
|
|
118
|
+
if (res.stream) {
|
|
119
|
+
environment.console.info(res.stream);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
environment.console.info(`pushed image ${imageName} to ${options.registry}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
117
126
|
function getDependencySources(service, taskIds) {
|
|
118
127
|
const result = [...service.data.src.filter((s) => !s.inherited)];
|
|
119
128
|
taskIds.push(service.id());
|
|
@@ -112,7 +112,16 @@ async function dockerService(docker, item, options, environment) {
|
|
|
112
112
|
const relay = await network.connect(container);
|
|
113
113
|
const stream = await container.attach({ stream: true, stdout: true, stderr: true });
|
|
114
114
|
(0, stream_1.logStream)(item.status, stream);
|
|
115
|
+
// the engine resolves the paths it binds when the container starts: check them right before, and after
|
|
116
|
+
await (0, execution_steps_1.refuseHostLinks)(item, environment);
|
|
115
117
|
await container.start();
|
|
118
|
+
const started = container;
|
|
119
|
+
await (0, execution_steps_1.refuseHostLinks)(item, environment).catch(async (e) => {
|
|
120
|
+
// not kept, not even for a daemon
|
|
121
|
+
container = null;
|
|
122
|
+
await (0, remove_container_1.removeContainer)(started);
|
|
123
|
+
throw e;
|
|
124
|
+
});
|
|
116
125
|
const published = options.publishPorts ? await readPublishedPorts(relay ?? container, item.data.ports) : [];
|
|
117
126
|
if (!item.data.healthcheck || !options.waitForReady) {
|
|
118
127
|
options.state.set({
|
|
@@ -99,6 +99,8 @@ async function dockerTask(docker, item, environment, options) {
|
|
|
99
99
|
await (0, execution_steps_1.refuseHostLinks)(item, environment);
|
|
100
100
|
const itemNetwork = network;
|
|
101
101
|
const succeeded = await (0, using_container_1.usingContainer)(docker, item, containerOptions, async (container) => {
|
|
102
|
+
// the engine resolved the paths it binds as the container started: once more, before anything runs in it
|
|
103
|
+
await (0, execution_steps_1.refuseHostLinks)(item, environment);
|
|
102
104
|
await itemNetwork.connect(container);
|
|
103
105
|
await (0, execution_steps_1.setUserPermissions)(item, container, environment);
|
|
104
106
|
for (const generate of outputsToReset.filter((g) => !g.isFile)) {
|
|
@@ -20,8 +20,9 @@ exports.hostedRoot = hostedRoot;
|
|
|
20
20
|
* reads or writes for it, has to stay inside the run's files with no link on the way:
|
|
21
21
|
* tasks of this or an earlier run on a sandbox, or the commit of a ref, could have left
|
|
22
22
|
* one pointing anywhere on the server. The runtime checks before an item runs; this is
|
|
23
|
-
* checked again right before a container is made
|
|
24
|
-
* other tasks of the
|
|
23
|
+
* checked again right before a container is made, after it started (the engine resolves
|
|
24
|
+
* the paths it binds as it starts) and before outputs are copied, after other tasks of the
|
|
25
|
+
* run had their turn.
|
|
25
26
|
*/
|
|
26
27
|
async function refuseHostLinks(item, environment) {
|
|
27
28
|
const root = hostedRoot(environment);
|
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('/')}`;
|
|
@@ -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
|
},
|
|
@@ -11,14 +11,14 @@ const hosted_volumes_1 = require("./hosted-volumes");
|
|
|
11
11
|
* checkout it did not write either: a `src: ../..` or a link in the checkout would
|
|
12
12
|
* have the server mount or upload its own files (its credentials, other callers'
|
|
13
13
|
* caches) into a task. Checked when the run is planned and again before each item
|
|
14
|
-
* runs, since an earlier task may have left a link behind
|
|
14
|
+
* runs, since an earlier task may have left a link behind: the sources and outputs it
|
|
15
|
+
* inherits from its dependencies too, which a task after them may have swapped for a link.
|
|
15
16
|
*/
|
|
16
17
|
async function assertItemPathsWithinRoot(item, root) {
|
|
17
18
|
const data = item.data;
|
|
18
19
|
for (const source of 'src' in data ? data.src : []) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
20
|
+
const of = source.inherited ? ` of ${source.inherited.name}` : '';
|
|
21
|
+
await (0, within_root_1.assertWithinRoot)(root, source.absolutePath, `${item.name}: src ${source.source}${of}`);
|
|
22
22
|
}
|
|
23
23
|
if ((0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)) {
|
|
24
24
|
for (const mount of data.mounts) {
|
|
@@ -34,9 +34,8 @@ async function assertItemPathsWithinRoot(item, root) {
|
|
|
34
34
|
}
|
|
35
35
|
if ((0, work_task_1.isWorkTask)(data)) {
|
|
36
36
|
for (const generate of data.generates) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
}
|
|
37
|
+
const of = generate.inherited ? ` of ${generate.inherited.name}` : '';
|
|
38
|
+
await (0, within_root_1.assertWithinRoot)(root, generate.path, `${item.name}: generates ${generate.path}${of}`);
|
|
40
39
|
}
|
|
41
40
|
}
|
|
42
41
|
}
|
|
@@ -11,8 +11,7 @@ const using_container_1 = require("../docker/using-container");
|
|
|
11
11
|
const event_cache_1 = require("../executer/event-cache");
|
|
12
12
|
const get_docker_executor_1 = require("../executer/get-docker-executor");
|
|
13
13
|
const path_1 = require("path");
|
|
14
|
-
const tar_1 = require("tar");
|
|
15
|
-
const tar_2 = require("../utils/tar");
|
|
14
|
+
const tar_1 = require("../utils/tar");
|
|
16
15
|
const plan_work_volume_1 = require("./utils/plan-work-volume");
|
|
17
16
|
const work_instance_id_1 = require("./work-instance-id");
|
|
18
17
|
const stream_1 = require("stream");
|
|
@@ -174,7 +173,7 @@ async function restoreContainer(docker, environment, item, path) {
|
|
|
174
173
|
for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
|
|
175
174
|
if (onHost.has(generate.path) && (await environment.file.exists(generate.filename))) {
|
|
176
175
|
await environment.file.remove(generate.path);
|
|
177
|
-
await (0, tar_1.
|
|
176
|
+
await (0, tar_1.extractOutput)(generate.filename, (0, path_1.dirname)(generate.path), (0, path_1.basename)(generate.path), !!environment.hosted);
|
|
178
177
|
}
|
|
179
178
|
}
|
|
180
179
|
}
|
|
@@ -303,7 +302,7 @@ async function archiveContainer(docker, environment, item, path) {
|
|
|
303
302
|
for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path)) {
|
|
304
303
|
// a file output is a bind mount of a host file, so archive it from the host
|
|
305
304
|
const readable = hostFiles.has(generatedArchive.path)
|
|
306
|
-
? stream_1.Readable.from((0,
|
|
305
|
+
? stream_1.Readable.from((0, tar_1.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
|
|
307
306
|
: await container.getArchive({
|
|
308
307
|
path: generatedArchive.path,
|
|
309
308
|
});
|
|
@@ -4,8 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.getLocalWorkRuntime = exports.getStateFilename = void 0;
|
|
7
|
-
const tar_1 = require("tar");
|
|
8
|
-
const tar_2 = require("../utils/tar");
|
|
7
|
+
const tar_1 = require("../utils/tar");
|
|
9
8
|
const path_1 = require("path");
|
|
10
9
|
const local_task_1 = require("../executer/local-task");
|
|
11
10
|
const event_cache_1 = require("../executer/event-cache");
|
|
@@ -122,7 +121,7 @@ async function archiveLocal(environment, task, path) {
|
|
|
122
121
|
for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
|
|
123
122
|
await environment.file.writeStream(generatedArchive.filename,
|
|
124
123
|
// tar's stream is a Minipass stream; Readable.from adapts it to a Node one
|
|
125
|
-
stream_1.Readable.from((0,
|
|
124
|
+
stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
|
|
126
125
|
}
|
|
127
126
|
}
|
|
128
127
|
async function restoreLocal(environment, task, path) {
|
|
@@ -131,10 +130,7 @@ async function restoreLocal(environment, task, path) {
|
|
|
131
130
|
// a cache hit means exactly the stored outputs: whatever a failed or
|
|
132
131
|
// older run left in the folder goes first
|
|
133
132
|
await environment.file.remove(generate.path);
|
|
134
|
-
await (0, tar_1.
|
|
135
|
-
file: generate.filename,
|
|
136
|
-
cwd: task.cwd,
|
|
137
|
-
});
|
|
133
|
+
await (0, tar_1.extractOutput)(generate.filename, task.cwd, (0, path_1.relative)(task.cwd, generate.path), !!environment.hosted);
|
|
138
134
|
}
|
|
139
135
|
}
|
|
140
136
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.collectBundle = void 0;
|
|
4
|
+
const promises_1 = require("node:fs/promises");
|
|
4
5
|
const path_1 = require("path");
|
|
5
6
|
const resolve_git_source_1 = require("../includes/resolve-git-source");
|
|
6
7
|
const schema_parser_1 = require("../schema/schema-parser");
|
|
@@ -10,7 +11,10 @@ const bundle_1 = require("./bundle");
|
|
|
10
11
|
// The build file is read with the parser of a run, so what it pulls in is what a
|
|
11
12
|
// run would read. Git includes are not part of it (the server fetches them, at
|
|
12
13
|
// the commit they are pinned to), and neither is anything outside of the
|
|
13
|
-
// directory of the build file, which a server could not reproduce.
|
|
14
|
+
// directory of the build file, which a server could not reproduce. That holds for
|
|
15
|
+
// where a file really is too: a link to a file outside of the directory is refused
|
|
16
|
+
// rather than followed, so publishing a checkout never sends a file of this machine
|
|
17
|
+
// that the checkout only points to.
|
|
14
18
|
async function collectBundle(fileName, environment) {
|
|
15
19
|
if (!(await environment.file.exists(fileName))) {
|
|
16
20
|
throw new Error(`there is no build file at ${fileName}`);
|
|
@@ -24,11 +28,15 @@ async function collectBundle(fileName, environment) {
|
|
|
24
28
|
paths.add((0, path_1.resolve)(scope.fileName));
|
|
25
29
|
}
|
|
26
30
|
}
|
|
31
|
+
const realRoot = await (0, promises_1.realpath)(root);
|
|
27
32
|
const files = {};
|
|
28
33
|
for (const path of [...paths].sort()) {
|
|
29
34
|
if (!(0, resolve_git_source_1.isWithin)(root, path)) {
|
|
30
35
|
throw new Error(`${path} is outside of ${root}: a published build file can only include files below its own directory`);
|
|
31
36
|
}
|
|
37
|
+
if (!(0, resolve_git_source_1.isWithin)(realRoot, await (0, promises_1.realpath)(path))) {
|
|
38
|
+
throw new Error(`${path} links to a file outside of ${root}: a published build file can only include files below its own directory`);
|
|
39
|
+
}
|
|
32
40
|
files[(0, path_1.relative)(root, path).split(path_1.sep).join('/')] = await environment.file.read(path);
|
|
33
41
|
}
|
|
34
42
|
const result = bundle_1.bundleSchema.safeParse({ entry: (0, path_1.relative)(root, entryPath).split(path_1.sep).join('/'), files });
|
|
@@ -723,10 +723,13 @@ exports.getPrivilegedNamespaceProblem = getPrivilegedNamespaceProblem;
|
|
|
723
723
|
// What may mount a claim a run kept: the runs of the same branch or tag of a repository,
|
|
724
724
|
// which share its cache, so that the runs of two branches go side by side and the runs of one find what
|
|
725
725
|
// the last one left; on a sandbox the runs of that sandbox only, whose claim is on the same
|
|
726
|
-
// node or zone as the kept ones.
|
|
726
|
+
// node or zone as the kept ones. An approved run on a sandbox keeps nothing with those runs,
|
|
727
|
+
// whose outputs nobody approved, as its cache is apart from theirs: it has a scope of its own,
|
|
728
|
+
// per sandbox, so that approved runs on two sandboxes go side by side. The owner is the namespace's.
|
|
727
729
|
function getVolumeScope(run) {
|
|
728
730
|
if (run.source.type === 'sandbox' && !run.source.check) {
|
|
729
|
-
|
|
731
|
+
const id = (0, crypto_1.createHash)('sha256').update(run.source.id).digest('hex').slice(0, 24);
|
|
732
|
+
return (run.approvals?.length ?? 0) > 0 ? `approved-${id}` : `sandbox-${id}`;
|
|
730
733
|
}
|
|
731
734
|
// a ref given as a commit hash names no branch: its runs keep the repository's claims
|
|
732
735
|
if (run.source.type === 'ref' && !/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(run.source.ref)) {
|
package/dist/server/runs.js
CHANGED
|
@@ -456,7 +456,10 @@ class RunRegistry {
|
|
|
456
456
|
}
|
|
457
457
|
// The run that holds a sandbox: the oldest on it that is not over. It holds it from
|
|
458
458
|
// when it is submitted, so the files are not moved under what an approver saw. A service
|
|
459
|
-
// run that is up
|
|
459
|
+
// run that is up holds it no longer, so the agent can go on working while its services
|
|
460
|
+
// run: an approved one works on a copy of the files, any other (on a host) in the sandbox
|
|
461
|
+
// itself, which edits then write in through the directories they checked (see `write` of
|
|
462
|
+
// HostSandboxFiles).
|
|
460
463
|
holder(sandbox) {
|
|
461
464
|
return [...this.entries.values()].find((entry) => onSandbox(entry.run, sandbox) &&
|
|
462
465
|
!isFinal(entry.run.state) &&
|
|
@@ -5,6 +5,7 @@ const child_process_1 = require("child_process");
|
|
|
5
5
|
const crypto_1 = require("crypto");
|
|
6
6
|
const fs_1 = require("fs");
|
|
7
7
|
const promises_1 = require("fs/promises");
|
|
8
|
+
const os_1 = require("os");
|
|
8
9
|
const path_1 = require("path");
|
|
9
10
|
const minimatch_1 = require("minimatch");
|
|
10
11
|
const source_manifest_1 = require("../remote/source-manifest");
|
|
@@ -193,6 +194,8 @@ function fileType(stats) {
|
|
|
193
194
|
* without following a link, and on Linux the opened file is checked to be the one in the
|
|
194
195
|
* sandbox, in case a task swapped a directory for a link in between.
|
|
195
196
|
*/
|
|
197
|
+
// the ignore files ripgrep reads in the folders above the path it searches
|
|
198
|
+
const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
|
|
196
199
|
class HostSandboxFiles {
|
|
197
200
|
constructor(root, git,
|
|
198
201
|
// the environment of ripgrep: the variables runs see
|
|
@@ -301,12 +304,17 @@ class HostSandboxFiles {
|
|
|
301
304
|
}
|
|
302
305
|
}
|
|
303
306
|
// The opened file is the one in the sandbox: a task may have swapped a directory above it
|
|
304
|
-
// for a link after the names were checked. Linux names the file a descriptor is open on
|
|
305
|
-
//
|
|
307
|
+
// for a link after the names were checked. Linux names the file a descriptor is open on,
|
|
308
|
+
// and a server that can't read that (no /proc) reads nothing: a check of the path would
|
|
309
|
+
// leave a moment for a swap. Elsewhere (a machine of a developer) the path has to lead to
|
|
310
|
+
// the same file and to no link.
|
|
306
311
|
async mustBeInside(handle, absolute, path) {
|
|
307
312
|
let actual;
|
|
308
313
|
if (process.platform === 'linux') {
|
|
309
314
|
actual = await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined);
|
|
315
|
+
if (actual === undefined) {
|
|
316
|
+
throw new SandboxFileError(503, `${path} can not be read: the server can not tell which file it opened, /proc/self/fd is not readable`);
|
|
317
|
+
}
|
|
310
318
|
}
|
|
311
319
|
if (actual === undefined) {
|
|
312
320
|
const [opened, named] = await Promise.all([handle.stat(), (0, promises_1.lstat)(absolute)]);
|
|
@@ -534,7 +542,13 @@ class HostSandboxFiles {
|
|
|
534
542
|
else {
|
|
535
543
|
args.push('--count-matches', '--null');
|
|
536
544
|
}
|
|
537
|
-
|
|
545
|
+
// ripgrep follows a link in the path it is given, which a running task can swap in after
|
|
546
|
+
// the check above: it reads what was checked (see pin)
|
|
547
|
+
const target = await this.pin(path);
|
|
548
|
+
if (target.stdin) {
|
|
549
|
+
args.push('--with-filename');
|
|
550
|
+
}
|
|
551
|
+
args.push('--regexp', query.pattern, '--', target.arg);
|
|
538
552
|
const result = { output_mode: mode, total: 0, exact: true, truncated: false, cursor: null };
|
|
539
553
|
const files = [];
|
|
540
554
|
const matches = [];
|
|
@@ -549,8 +563,11 @@ class HostSandboxFiles {
|
|
|
549
563
|
};
|
|
550
564
|
// the JSON of ripgrep names paths with the separator of the system, whatever --path-separator says
|
|
551
565
|
const clean = (file) => {
|
|
552
|
-
|
|
553
|
-
|
|
566
|
+
if (target.stdin && file === '<stdin>') {
|
|
567
|
+
return path;
|
|
568
|
+
}
|
|
569
|
+
const name = process.platform === 'win32' ? file.replace(/\\/g, '/') : file;
|
|
570
|
+
return name.startsWith('./') ? name.slice(2) : name;
|
|
554
571
|
};
|
|
555
572
|
const onRecord = (record) => {
|
|
556
573
|
if (mode === 'files_with_matches') {
|
|
@@ -577,7 +594,16 @@ class HostSandboxFiles {
|
|
|
577
594
|
...(message.type === 'context' ? { context: true } : {}),
|
|
578
595
|
})));
|
|
579
596
|
};
|
|
580
|
-
|
|
597
|
+
let ran;
|
|
598
|
+
try {
|
|
599
|
+
ran = target.skip
|
|
600
|
+
? { code: 1, stderr: '', stopped: false }
|
|
601
|
+
: await this.ripgrep(args, mode === 'files_with_matches' ? '\0' : '\n', onRecord, target);
|
|
602
|
+
}
|
|
603
|
+
finally {
|
|
604
|
+
await target.release();
|
|
605
|
+
}
|
|
606
|
+
const { code, stderr, stopped } = ran;
|
|
581
607
|
if (code === 2 && total === 0 && !stopped) {
|
|
582
608
|
throw new SandboxFileError(400, stderr.trim() || 'ripgrep failed');
|
|
583
609
|
}
|
|
@@ -596,9 +622,93 @@ class HostSandboxFiles {
|
|
|
596
622
|
}
|
|
597
623
|
return result;
|
|
598
624
|
}
|
|
625
|
+
// What ripgrep searches for a `path` of a search, so that it reads what was checked when a
|
|
626
|
+
// task swaps a link into the path meanwhile (ripgrep follows the links of the path it is
|
|
627
|
+
// given, not those it finds below it). A file is read here, through the check of what was
|
|
628
|
+
// opened, and handed to ripgrep on stdin. A directory is opened here and checked the same
|
|
629
|
+
// way; ripgrep is given the same relative path in a folder of its own where it is a link
|
|
630
|
+
// to that open directory (on Linux, /proc/<pid>/fd/<n>), next to copies of the ignore
|
|
631
|
+
// files above it, so that globs, `.gitignore` and the paths it prints are what they were.
|
|
632
|
+
// Elsewhere (a machine of a developer) a directory is searched by its name.
|
|
633
|
+
async pin(path) {
|
|
634
|
+
const none = async () => undefined;
|
|
635
|
+
if (!path) {
|
|
636
|
+
return { arg: '.', cwd: this.root, release: none };
|
|
637
|
+
}
|
|
638
|
+
const found = await this.stat(path);
|
|
639
|
+
if (found?.type === 'file') {
|
|
640
|
+
const { handle, stat } = await this.open(path);
|
|
641
|
+
if (stat.size > exports.MAX_FILE_BYTES) {
|
|
642
|
+
// as ripgrep's --max-filesize leaves it out
|
|
643
|
+
await handle.close();
|
|
644
|
+
return { arg: '-', cwd: this.root, skip: true, release: none };
|
|
645
|
+
}
|
|
646
|
+
const stdin = handle.createReadStream();
|
|
647
|
+
return { arg: '-', cwd: this.root, stdin, release: async () => void stdin.destroy() };
|
|
648
|
+
}
|
|
649
|
+
if (process.platform !== 'linux') {
|
|
650
|
+
return { arg: path, cwd: this.root, release: none };
|
|
651
|
+
}
|
|
652
|
+
const absolute = this.absolute(path);
|
|
653
|
+
const handle = await (0, promises_1.open)(absolute, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | fs_1.constants.O_NOFOLLOW).catch((e) => {
|
|
654
|
+
if (e.code === 'ELOOP' || e.code === 'ENOTDIR') {
|
|
655
|
+
throw new SandboxFileError(409, `${path} changed while it was searched, search again`);
|
|
656
|
+
}
|
|
657
|
+
throw e;
|
|
658
|
+
});
|
|
659
|
+
let folder;
|
|
660
|
+
try {
|
|
661
|
+
await this.mustBeInside(handle, absolute, path);
|
|
662
|
+
folder = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-search-'));
|
|
663
|
+
const parts = path.split('/');
|
|
664
|
+
for (let depth = 0; depth < parts.length; depth++) {
|
|
665
|
+
const above = parts.slice(0, depth).join('/');
|
|
666
|
+
await (0, promises_1.mkdir)((0, path_1.join)(folder, ...parts.slice(0, depth)), { recursive: true });
|
|
667
|
+
for (const name of IGNORE_FILES) {
|
|
668
|
+
const file = above ? `${above}/${name}` : name;
|
|
669
|
+
const content = await this.ignoreFile(file);
|
|
670
|
+
if (content !== undefined) {
|
|
671
|
+
await (0, promises_1.writeFile)((0, path_1.join)(folder, ...parts.slice(0, depth), name), content);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
await (0, promises_1.symlink)(`/proc/${process.pid}/fd/${handle.fd}`, (0, path_1.join)(folder, ...parts));
|
|
676
|
+
}
|
|
677
|
+
catch (e) {
|
|
678
|
+
await handle.close();
|
|
679
|
+
if (folder) {
|
|
680
|
+
await (0, promises_1.rm)(folder, { recursive: true, force: true });
|
|
681
|
+
}
|
|
682
|
+
throw e;
|
|
683
|
+
}
|
|
684
|
+
const pinned = folder;
|
|
685
|
+
return {
|
|
686
|
+
arg: path,
|
|
687
|
+
cwd: pinned,
|
|
688
|
+
release: async () => {
|
|
689
|
+
await (0, promises_1.rm)(pinned, { recursive: true, force: true });
|
|
690
|
+
await handle.close();
|
|
691
|
+
},
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
// An ignore file above the path of a search, read as any file is; none when there is none
|
|
695
|
+
// or it can not be read as a file
|
|
696
|
+
async ignoreFile(path) {
|
|
697
|
+
const found = await this.stat(path);
|
|
698
|
+
if (found?.type !== 'file' || found.size > exports.MAX_FILE_BYTES) {
|
|
699
|
+
return undefined;
|
|
700
|
+
}
|
|
701
|
+
const { handle, stat } = await this.open(path);
|
|
702
|
+
try {
|
|
703
|
+
return await readOpened(handle, stat.size);
|
|
704
|
+
}
|
|
705
|
+
finally {
|
|
706
|
+
await handle.close();
|
|
707
|
+
}
|
|
708
|
+
}
|
|
599
709
|
// Runs ripgrep in the files and hands each record of its output to `onRecord`, which
|
|
600
710
|
// answers whether to read on.
|
|
601
|
-
ripgrep(args, separator, onRecord) {
|
|
711
|
+
ripgrep(args, separator, onRecord, target = { cwd: this.root }) {
|
|
602
712
|
const env = {};
|
|
603
713
|
for (const [key, value] of Object.entries(this.env)) {
|
|
604
714
|
if (value !== undefined && !key.toUpperCase().startsWith('RIPGREP_')) {
|
|
@@ -607,11 +717,20 @@ class HostSandboxFiles {
|
|
|
607
717
|
}
|
|
608
718
|
return new Promise((resolve, reject) => {
|
|
609
719
|
const child = (0, child_process_1.spawn)('rg', args, {
|
|
610
|
-
cwd:
|
|
720
|
+
cwd: target.cwd,
|
|
611
721
|
env,
|
|
612
|
-
stdio: ['
|
|
722
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
613
723
|
signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
|
|
614
724
|
});
|
|
725
|
+
// ripgrep stops reading when it is stopped or has seen enough
|
|
726
|
+
child.stdin.on('error', () => undefined);
|
|
727
|
+
if (target.stdin) {
|
|
728
|
+
target.stdin.on('error', () => child.stdin.destroy());
|
|
729
|
+
target.stdin.pipe(child.stdin);
|
|
730
|
+
}
|
|
731
|
+
else {
|
|
732
|
+
child.stdin.end();
|
|
733
|
+
}
|
|
615
734
|
let stopped = false;
|
|
616
735
|
let buffered = '';
|
|
617
736
|
let stderr = '';
|
|
@@ -797,50 +916,124 @@ class HostSandboxFiles {
|
|
|
797
916
|
return state.content;
|
|
798
917
|
}
|
|
799
918
|
// Writes the changes: what a path held is moved aside first, and put back when a later
|
|
800
|
-
// write fails.
|
|
919
|
+
// write fails. Each name is written in the directory above it, opened from the root name
|
|
920
|
+
// by name (see `folder`), so what a task swaps in meanwhile leads no write out of the files.
|
|
801
921
|
async write(changes) {
|
|
802
922
|
const backups = [];
|
|
803
923
|
const written = [];
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
924
|
+
const folders = new Map();
|
|
925
|
+
const folderOf = async (path, create) => {
|
|
926
|
+
const key = (0, path_1.dirname)(path);
|
|
927
|
+
let folder = folders.get(key);
|
|
928
|
+
if (!folder) {
|
|
929
|
+
folder = await this.folder(path, create);
|
|
930
|
+
folders.set(key, folder);
|
|
931
|
+
}
|
|
932
|
+
return folder;
|
|
933
|
+
};
|
|
808
934
|
try {
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
935
|
+
// the directories above every path are still the ones the edits were planned in
|
|
936
|
+
for (const [path] of changes) {
|
|
937
|
+
await this.sameParents(path);
|
|
938
|
+
}
|
|
939
|
+
try {
|
|
940
|
+
for (const [path, before] of changes) {
|
|
941
|
+
if (before.kind === 'file' || before.kind === 'link') {
|
|
942
|
+
const folder = await folderOf(path, false);
|
|
943
|
+
const name = (0, path_1.basename)(path);
|
|
944
|
+
const backup = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.bak`;
|
|
945
|
+
await (0, promises_1.rename)(folder.at(name), folder.at(backup));
|
|
946
|
+
backups.push([folder, name, backup]);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
for (const [path, before, after] of [...changes].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
|
|
950
|
+
if (after.kind !== 'file') {
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
const folder = await folderOf(path, true);
|
|
954
|
+
const name = (0, path_1.basename)(path);
|
|
955
|
+
const temporary = `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`;
|
|
956
|
+
const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
|
|
957
|
+
const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
|
|
958
|
+
const flags = fs_1.constants.O_WRONLY | fs_1.constants.O_CREAT | fs_1.constants.O_EXCL | (fs_1.constants.O_NOFOLLOW ?? 0);
|
|
959
|
+
const handle = await (0, promises_1.open)(folder.at(temporary), flags, mode);
|
|
960
|
+
try {
|
|
961
|
+
await handle.writeFile(after.content ?? Buffer.alloc(0));
|
|
962
|
+
await handle.chmod(mode);
|
|
963
|
+
}
|
|
964
|
+
finally {
|
|
965
|
+
await handle.close();
|
|
966
|
+
}
|
|
967
|
+
await (0, promises_1.rename)(folder.at(temporary), folder.at(name));
|
|
968
|
+
written.push([folder, name]);
|
|
815
969
|
}
|
|
816
970
|
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
971
|
+
catch (e) {
|
|
972
|
+
for (const [folder, name] of written.reverse()) {
|
|
973
|
+
await (0, promises_1.rm)(folder.at(name), { force: true });
|
|
820
974
|
}
|
|
975
|
+
for (const [folder, name, backup] of backups.reverse()) {
|
|
976
|
+
await (0, promises_1.rename)(folder.at(backup), folder.at(name)).catch(() => undefined);
|
|
977
|
+
}
|
|
978
|
+
throw e;
|
|
979
|
+
}
|
|
980
|
+
for (const [folder, , backup] of backups) {
|
|
981
|
+
await (0, promises_1.rm)(folder.at(backup), { force: true });
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
finally {
|
|
985
|
+
for (const folder of folders.values()) {
|
|
986
|
+
await folder.release();
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
// The directory above `path`, made where it is missing and `create` is set. On Linux it is
|
|
991
|
+
// opened from the root name by name, never through a link, and its names are reached
|
|
992
|
+
// through the open descriptor (/proc/self/fd/<n>/<name>): a directory a task swaps for a link
|
|
993
|
+
// after the checks leads no write out of the files. A server on Linux that can not read
|
|
994
|
+
// /proc writes nothing. Elsewhere (a machine of a developer) the names are checked on the way.
|
|
995
|
+
async folder(path, create) {
|
|
996
|
+
const parts = path.split('/').slice(0, -1);
|
|
997
|
+
if (process.platform !== 'linux') {
|
|
998
|
+
if (create) {
|
|
821
999
|
await this.makeParents(path);
|
|
822
|
-
const absolute = this.absolute(path);
|
|
823
|
-
const temporary = (0, path_1.join)((0, path_1.dirname)(absolute), `.hammerkit-${(0, crypto_1.randomBytes)(6).toString('hex')}.tmp`);
|
|
824
|
-
const base = before.kind === 'file' ? before.mode ?? 0o644 : 0o644;
|
|
825
|
-
const mode = after.exec ? base | ((base & 0o444) >> 2) | 0o100 : base & ~0o111;
|
|
826
|
-
await (0, promises_1.writeFile)(temporary, after.content ?? Buffer.alloc(0), { flag: 'wx', mode });
|
|
827
|
-
await (0, promises_1.chmod)(temporary, mode);
|
|
828
|
-
await (0, promises_1.rename)(temporary, absolute);
|
|
829
|
-
written.push(absolute);
|
|
830
1000
|
}
|
|
1001
|
+
const absolute = (0, path_1.dirname)(this.absolute(path));
|
|
1002
|
+
return { at: (name) => (0, path_1.join)(absolute, name), release: async () => undefined };
|
|
831
1003
|
}
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
1004
|
+
let handle = await (0, promises_1.open)(this.root, fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY);
|
|
1005
|
+
try {
|
|
1006
|
+
if ((await (0, promises_1.readlink)(`/proc/self/fd/${handle.fd}`).catch(() => undefined)) === undefined) {
|
|
1007
|
+
throw new SandboxFileError(503, `${path} can not be written: the server can not reach a directory it opened, /proc/self/fd is not readable`);
|
|
835
1008
|
}
|
|
836
|
-
|
|
837
|
-
|
|
1009
|
+
const flags = fs_1.constants.O_RDONLY | fs_1.constants.O_DIRECTORY | (fs_1.constants.O_NOFOLLOW ?? 0);
|
|
1010
|
+
for (const part of parts) {
|
|
1011
|
+
const at = `/proc/self/fd/${handle.fd}/${part}`;
|
|
1012
|
+
const next = await (0, promises_1.open)(at, flags).catch(async (e) => {
|
|
1013
|
+
if (create && isNotFound(e)) {
|
|
1014
|
+
await (0, promises_1.mkdir)(at).catch((made) => {
|
|
1015
|
+
if (made.code !== 'EEXIST') {
|
|
1016
|
+
throw made;
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
return (0, promises_1.open)(at, flags);
|
|
1020
|
+
}
|
|
1021
|
+
throw e;
|
|
1022
|
+
});
|
|
1023
|
+
await handle.close();
|
|
1024
|
+
handle = next;
|
|
838
1025
|
}
|
|
839
|
-
throw e;
|
|
840
1026
|
}
|
|
841
|
-
|
|
842
|
-
await (
|
|
1027
|
+
catch (e) {
|
|
1028
|
+
await handle.close().catch(() => undefined);
|
|
1029
|
+
const code = e.code;
|
|
1030
|
+
if (code === 'ELOOP' || code === 'ENOTDIR' || code === 'ENOENT') {
|
|
1031
|
+
throw new SandboxFileError(409, `${parts.join('/')} is not a directory any more`);
|
|
1032
|
+
}
|
|
1033
|
+
throw e;
|
|
843
1034
|
}
|
|
1035
|
+
const opened = handle;
|
|
1036
|
+
return { at: (name) => `/proc/self/fd/${opened.fd}/${name}`, release: () => opened.close() };
|
|
844
1037
|
}
|
|
845
1038
|
async sameParents(path) {
|
|
846
1039
|
const parts = path.split('/');
|
package/dist/utils/tar.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.packArchive = void 0;
|
|
3
|
+
exports.onlyBelow = exports.extractOutput = exports.packArchive = void 0;
|
|
4
4
|
const tar_1 = require("tar");
|
|
5
|
+
const path_1 = require("path");
|
|
5
6
|
function packArchive(options, files) {
|
|
6
7
|
return (0, tar_1.create)({ ...options, jobs: 1, linkCache: new ExactLinkCache() }, files);
|
|
7
8
|
}
|
|
@@ -33,4 +34,53 @@ const NOT_PACKED = '\0';
|
|
|
33
34
|
function isExact(key) {
|
|
34
35
|
return key.split(':').every((part) => Number.isSafeInteger(Number(part)));
|
|
35
36
|
}
|
|
37
|
+
// Extracts the archive of one output (a path relative to `cwd`) into `cwd`. An archive
|
|
38
|
+
// comes from a cache another run, or whoever writes to the cache backend, filled, so only
|
|
39
|
+
// entries of that output are taken: one beside it (another output, a source of the task, a
|
|
40
|
+
// build file) would otherwise be written over the project. A hard link is taken only to a
|
|
41
|
+
// file of the output (packArchive stores one to a file outside as its content). A symbolic
|
|
42
|
+
// link may point out of the output on a machine (a node_modules links its workspace
|
|
43
|
+
// packages); on a server, which did not write the archive, it is left out.
|
|
44
|
+
async function extractOutput(file, cwd, output, hosted) {
|
|
45
|
+
const below = onlyBelow(output);
|
|
46
|
+
await (0, tar_1.extract)({
|
|
47
|
+
file,
|
|
48
|
+
cwd,
|
|
49
|
+
filter: (path, entry) => {
|
|
50
|
+
if (!below(path)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
const read = entry;
|
|
54
|
+
if (read.type === 'Link') {
|
|
55
|
+
return below(read.linkpath ?? '');
|
|
56
|
+
}
|
|
57
|
+
if (read.type === 'SymbolicLink' && hosted) {
|
|
58
|
+
const target = read.linkpath ?? '';
|
|
59
|
+
return !path_1.posix.isAbsolute(target) && below(path_1.posix.join(path_1.posix.dirname(normalizeEntry(path)), target));
|
|
60
|
+
}
|
|
61
|
+
return true;
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
exports.extractOutput = extractOutput;
|
|
66
|
+
// Whether an entry of an archive is the output (a path relative to where the archive is
|
|
67
|
+
// extracted) or below it.
|
|
68
|
+
function onlyBelow(output) {
|
|
69
|
+
const own = normalizeEntry(output);
|
|
70
|
+
return (path) => {
|
|
71
|
+
const entry = normalizeEntry(path);
|
|
72
|
+
if (own === '.') {
|
|
73
|
+
// the output is the folder the archive is extracted in
|
|
74
|
+
return entry !== '..' && !entry.startsWith('../') && !path_1.posix.isAbsolute(entry);
|
|
75
|
+
}
|
|
76
|
+
return entry === own || entry.startsWith(`${own}/`);
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
exports.onlyBelow = onlyBelow;
|
|
80
|
+
function normalizeEntry(path) {
|
|
81
|
+
return path_1.posix
|
|
82
|
+
.normalize(path.replace(/\\/g, '/'))
|
|
83
|
+
.replace(/^(\.\/)+/, '')
|
|
84
|
+
.replace(/\/+$/, '');
|
|
85
|
+
}
|
|
36
86
|
//# sourceMappingURL=tar.js.map
|
package/package.json
CHANGED