@ship.zone/runner 3.0.0 → 5.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/.smartconfig.json +19 -1
- package/changelog.md +61 -0
- package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
- package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +4 -4
- package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
- package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +4 -4
- package/dist_ts/00_commitinfo_data.js +3 -3
- package/dist_ts/api-client.d.ts +2 -1
- package/dist_ts/api-client.js +10 -2
- package/dist_ts/artifact-manager.js +1 -1
- package/dist_ts/attempt-state.js +1 -1
- package/dist_ts/cache-manager.js +1 -1
- package/dist_ts/cli-entry.js +17 -3
- package/dist_ts/cli.d.ts +7 -0
- package/dist_ts/cli.js +155 -35
- package/dist_ts/config.js +75 -22
- package/dist_ts/egress-proxy.d.ts +99 -0
- package/dist_ts/egress-proxy.js +607 -0
- package/dist_ts/errors.js +1 -1
- package/dist_ts/filesystem.js +1 -1
- package/dist_ts/index.d.ts +5 -1
- package/dist_ts/index.js +6 -2
- package/dist_ts/interfaces.d.ts +85 -31
- package/dist_ts/interfaces.js +1 -1
- package/dist_ts/log-sender.js +1 -1
- package/dist_ts/microvm-executor.d.ts +90 -0
- package/dist_ts/microvm-executor.js +1078 -0
- package/dist_ts/node-version.d.ts +11 -0
- package/dist_ts/node-version.js +43 -0
- package/dist_ts/npm-grants.d.ts +9 -0
- package/dist_ts/npm-grants.js +44 -0
- package/dist_ts/oci-registry.d.ts +73 -0
- package/dist_ts/oci-registry.js +508 -0
- package/dist_ts/plugins.d.ts +6 -2
- package/dist_ts/plugins.js +7 -3
- package/dist_ts/protocol-validator.d.ts +3 -5
- package/dist_ts/protocol-validator.js +27 -51
- package/dist_ts/redactor.js +1 -1
- package/dist_ts/registration-state.js +1 -1
- package/dist_ts/runner.d.ts +5 -5
- package/dist_ts/runner.js +47 -22
- package/dist_ts/source-workspace.js +1 -1
- package/dist_ts/spec-version.js +1 -1
- package/dist_ts/staging-scavenger.js +1 -1
- package/dist_ts/state-owner.js +4 -2
- package/dist_ts/transfer-archive.js +1 -1
- package/dist_ts/validation.js +1 -1
- package/dist_ts/vsock-protocol.d.ts +130 -0
- package/dist_ts/vsock-protocol.js +336 -0
- package/dist_ts/wire-schema.js +1 -1
- package/package.json +19 -15
- package/readme.md +106 -108
- package/rust/Cargo.lock +1 -0
- package/rust/Cargo.toml +2 -1
- package/rust/src/cpio.rs +147 -0
- package/rust/src/extfs.rs +747 -0
- package/rust/src/guest.rs +2411 -0
- package/rust/src/lib.rs +41 -0
- package/rust/src/main.rs +6 -1
- package/rust/src/oci_tar.rs +842 -0
- package/ts/00_commitinfo_data.ts +2 -2
- package/ts/api-client.ts +19 -1
- package/ts/cli-entry.ts +15 -2
- package/ts/cli.ts +172 -40
- package/ts/config.ts +100 -25
- package/ts/egress-proxy.ts +649 -0
- package/ts/index.ts +5 -1
- package/ts/interfaces.ts +97 -30
- package/ts/microvm-executor.ts +1310 -0
- package/ts/node-version.ts +49 -0
- package/ts/npm-grants.ts +49 -0
- package/ts/oci-registry.ts +649 -0
- package/ts/plugins.ts +6 -2
- package/ts/protocol-validator.ts +29 -58
- package/ts/runner.ts +48 -21
- package/ts/state-owner.ts +8 -1
- package/ts/vsock-protocol.ts +437 -0
- package/dist_ts/oci-executor.d.ts +0 -155
- package/dist_ts/oci-executor.js +0 -2238
- package/ts/oci-executor.ts +0 -2989
package/ts/oci-executor.ts
DELETED
|
@@ -1,2989 +0,0 @@
|
|
|
1
|
-
import * as plugins from './plugins.js';
|
|
2
|
-
import { ConfigurationError, ProtocolError, ResourceCleanupError, RunnerError } from './errors.js';
|
|
3
|
-
import {
|
|
4
|
-
createNewWriteFlags,
|
|
5
|
-
isAlreadyExists,
|
|
6
|
-
isNotFound,
|
|
7
|
-
lstatIfPresent,
|
|
8
|
-
makeTempDir,
|
|
9
|
-
readBoundedRegularFile,
|
|
10
|
-
removePath,
|
|
11
|
-
sameFileIdentity,
|
|
12
|
-
sha256Hex,
|
|
13
|
-
syncDirectory,
|
|
14
|
-
withOpenFile,
|
|
15
|
-
writeAll,
|
|
16
|
-
} from './filesystem.js';
|
|
17
|
-
import {
|
|
18
|
-
ensurePrivateStateDirectory,
|
|
19
|
-
resolvePackagedWorkspaceHelperPath,
|
|
20
|
-
type RunnerStateOwner,
|
|
21
|
-
workspaceHelperMaximumBytes,
|
|
22
|
-
} from './state-owner.js';
|
|
23
|
-
import type {
|
|
24
|
-
ICompiledStep,
|
|
25
|
-
IExecutionContext,
|
|
26
|
-
IExecutionResult,
|
|
27
|
-
IJobExecutor,
|
|
28
|
-
IOciExecutorConfig,
|
|
29
|
-
IOciJobLease,
|
|
30
|
-
IOciRuntimeFacts,
|
|
31
|
-
IPreparedOciLease,
|
|
32
|
-
IPrepareOciLeaseContext,
|
|
33
|
-
IRunnerConfig,
|
|
34
|
-
IRuntimeWorkspaceExporter,
|
|
35
|
-
IWorkspaceExport,
|
|
36
|
-
IWorkspaceExportRequest,
|
|
37
|
-
TExecutionStopReason,
|
|
38
|
-
TOciArchitecture,
|
|
39
|
-
TOciHelperTarget,
|
|
40
|
-
} from './interfaces.js';
|
|
41
|
-
import { utf8Length, validateEnvironmentName, validateIdentifier } from './validation.js';
|
|
42
|
-
|
|
43
|
-
const { join, resolve } = plugins.path;
|
|
44
|
-
|
|
45
|
-
const runtimeEnvironmentNames = [
|
|
46
|
-
'CONTAINER_CONNECTION',
|
|
47
|
-
'CONTAINER_HOST',
|
|
48
|
-
'DOCKER_CONFIG',
|
|
49
|
-
'DOCKER_CONTEXT',
|
|
50
|
-
'DOCKER_HOST',
|
|
51
|
-
'HOME',
|
|
52
|
-
'PATH',
|
|
53
|
-
'REGISTRY_AUTH_FILE',
|
|
54
|
-
'XDG_CONFIG_HOME',
|
|
55
|
-
'XDG_DATA_HOME',
|
|
56
|
-
'XDG_RUNTIME_DIR',
|
|
57
|
-
] as const;
|
|
58
|
-
|
|
59
|
-
const managedLabel = 'ship.zone.runner.managed';
|
|
60
|
-
const runnerLabel = 'ship.zone.runner.id';
|
|
61
|
-
const sessionLabel = 'ship.zone.runner.session';
|
|
62
|
-
const attemptLabel = 'ship.zone.runner.attempt';
|
|
63
|
-
const runtimeProbeLabel = 'ship.zone.runner.runtime-probe';
|
|
64
|
-
const runtimeProbeOwnerLabel = 'ship.zone.runner.runtime-probe-owner';
|
|
65
|
-
const helperContainerPath = '/runnerworkspace';
|
|
66
|
-
const maximumRuntimeOutputBytes = 1024 * 1024;
|
|
67
|
-
const runtimeCommandTimeoutMs = 30_000;
|
|
68
|
-
const runtimeTerminationGraceMs = 5_000;
|
|
69
|
-
const helperMemoryBytes = 256 * 1024 * 1024;
|
|
70
|
-
const helperPids = 64;
|
|
71
|
-
const helperCpus = 1;
|
|
72
|
-
const probeVolumeBytes = 8 * 1024 * 1024;
|
|
73
|
-
const probeVolumeEntries = 64;
|
|
74
|
-
const maximumCommandArguments = 128;
|
|
75
|
-
const maximumCommandArgumentBytes = 16 * 1024;
|
|
76
|
-
const maximumCommandBytes = 128 * 1024;
|
|
77
|
-
const maximumWorkspaceHelperErrorBytes = 512;
|
|
78
|
-
const hostTmpfsProbeMaximumAgeMs = 60 * 60 * 1000;
|
|
79
|
-
const runtimeProbeVolumeMaximumAgeMs = 60 * 60 * 1000;
|
|
80
|
-
const runtimeProbeOwnerIdPattern = /^[a-f0-9]{32}$/;
|
|
81
|
-
const hostTmpfsProbeNamePattern = /^shipzone-ci-probe-([a-f0-9]{32})-[a-f0-9]{16}$/;
|
|
82
|
-
const runtimeProbeVolumeNamePattern = /^shipzone-ci-volume-[a-f0-9]{32}$/;
|
|
83
|
-
const workspaceHelperDirectoryName = 'workspace-helpers';
|
|
84
|
-
/** The advisory lock file of runner 2.x, replaced by the state owner lock and removed on sight. */
|
|
85
|
-
const legacyWorkspaceHelperLockName = '.workspace-helper.lock';
|
|
86
|
-
const runtimeProbeOwnerMarkerPrefix = '.runtime-probe-owner_';
|
|
87
|
-
const runtimeProbeOwnerMarkerPattern = /^\.runtime-probe-owner_([a-f0-9]{32})$/;
|
|
88
|
-
const workspaceHelperExecutableMode = 0o755;
|
|
89
|
-
const workspaceHelperRetainedFinalCount = 8;
|
|
90
|
-
const workspaceHelperTemporaryMaximumBytes = 8 * workspaceHelperMaximumBytes;
|
|
91
|
-
const workspaceHelperTemporaryMaximumCount = 8;
|
|
92
|
-
const workspaceHelperTemporaryMaximumAgeMs = 60 * 60 * 1000;
|
|
93
|
-
const workspaceHelperFinalNamePattern = /^runnerworkspace_linux_(?:amd64|arm64)_musl_[a-f0-9]{64}$/;
|
|
94
|
-
const workspaceHelperTemporaryNamePattern =
|
|
95
|
-
/^\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.workspace-helper\.tmp$/;
|
|
96
|
-
|
|
97
|
-
export const workspaceHelperReserveBytes = 1024 * 1024;
|
|
98
|
-
export const workspaceFixedInodes = 3;
|
|
99
|
-
|
|
100
|
-
export interface IOciRuntimeCommandRequest {
|
|
101
|
-
executable: string;
|
|
102
|
-
args: string[];
|
|
103
|
-
environment: Record<string, string>;
|
|
104
|
-
timeoutMs: number;
|
|
105
|
-
signal?: AbortSignal;
|
|
106
|
-
maximumOutputBytes?: number;
|
|
107
|
-
onOutput?: (stream: 'stdout' | 'stderr', chunk: Uint8Array) => Promise<void>;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
export interface IOciRuntimeCommandResult {
|
|
111
|
-
success: boolean;
|
|
112
|
-
code: number;
|
|
113
|
-
stdout: Uint8Array;
|
|
114
|
-
stderr: Uint8Array;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export type TOciRuntimeCommandRunner = (
|
|
118
|
-
request: IOciRuntimeCommandRequest,
|
|
119
|
-
) => Promise<IOciRuntimeCommandResult>;
|
|
120
|
-
|
|
121
|
-
export interface IRuntimeMakeTempOptions {
|
|
122
|
-
dir?: string;
|
|
123
|
-
prefix?: string;
|
|
124
|
-
suffix?: string;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
export interface IRuntimeRemoveOptions {
|
|
128
|
-
recursive?: boolean;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export interface IRuntimeDirectoryEntry {
|
|
132
|
-
name: string;
|
|
133
|
-
isFile: boolean;
|
|
134
|
-
isDirectory: boolean;
|
|
135
|
-
isSymlink: boolean;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
export interface IRuntimeFileInfo {
|
|
139
|
-
isDirectory: boolean;
|
|
140
|
-
isSymlink: boolean;
|
|
141
|
-
uid: number | null;
|
|
142
|
-
mtime: Date | null;
|
|
143
|
-
dev: number | null;
|
|
144
|
-
ino: number | null;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export interface IOciExecutorDependencies {
|
|
148
|
-
commandRunner?: TOciRuntimeCommandRunner;
|
|
149
|
-
runtimeEnvironment?: Record<string, string>;
|
|
150
|
-
resolveHelperPath?: (target: TOciHelperTarget) => Promise<string>;
|
|
151
|
-
probeTmpfs?: (helperPath: string) => Promise<number>;
|
|
152
|
-
randomId?: () => string;
|
|
153
|
-
now?: () => number;
|
|
154
|
-
makeTempDir?: (options: IRuntimeMakeTempOptions) => Promise<string>;
|
|
155
|
-
chmod?: (path: string, mode: number) => Promise<void>;
|
|
156
|
-
remove?: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export interface IHostTmpfsProbeScavengerDependencies {
|
|
160
|
-
getUid?: () => number | undefined;
|
|
161
|
-
now?: () => number;
|
|
162
|
-
readDir?: (path: string) => AsyncIterable<IRuntimeDirectoryEntry>;
|
|
163
|
-
lstat?: (path: string) => Promise<IRuntimeFileInfo>;
|
|
164
|
-
remove?: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
export interface IWorkspaceVolumeLimits {
|
|
168
|
-
blockSize: number;
|
|
169
|
-
logicalBytes: number;
|
|
170
|
-
maximumEntries: number;
|
|
171
|
-
reserveBytes: number;
|
|
172
|
-
sizeBytes: number;
|
|
173
|
-
inodeLimit: number;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export interface IOciRunCommand {
|
|
177
|
-
args: string[];
|
|
178
|
-
environment: Record<string, string>;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
export interface IOciStepCommandInput {
|
|
182
|
-
runnerId: string;
|
|
183
|
-
sessionId: string;
|
|
184
|
-
lease: IOciJobLease;
|
|
185
|
-
step: ICompiledStep;
|
|
186
|
-
containerName: string;
|
|
187
|
-
volumeName: string;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
export interface IOciHelperCommandInput {
|
|
191
|
-
runnerId: string;
|
|
192
|
-
sessionId: string;
|
|
193
|
-
attemptId: string;
|
|
194
|
-
containerName: string;
|
|
195
|
-
image: string;
|
|
196
|
-
helperPath: string;
|
|
197
|
-
command: string[];
|
|
198
|
-
volumeName?: string;
|
|
199
|
-
sourcePath?: string;
|
|
200
|
-
destinationPath?: string;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
interface IContainerState {
|
|
204
|
-
exitCode: number;
|
|
205
|
-
oomKilled: boolean;
|
|
206
|
-
error: string;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
interface ICounts {
|
|
210
|
-
bytes: number;
|
|
211
|
-
entries: number;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
interface IFilesystemCapacity {
|
|
215
|
-
availableBlocks: number;
|
|
216
|
-
availableInodes: number;
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
interface IImageInspection {
|
|
220
|
-
os: string;
|
|
221
|
-
architecture: string;
|
|
222
|
-
repoDigests: string[];
|
|
223
|
-
digest?: string;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
class WorkspaceResourceError extends RunnerError {
|
|
227
|
-
constructor(message: string, options?: ErrorOptions) {
|
|
228
|
-
super(message, options);
|
|
229
|
-
this.name = 'WorkspaceResourceError';
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
234
|
-
typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
235
|
-
|
|
236
|
-
const field = (record: Record<string, unknown>, ...names: string[]): unknown => {
|
|
237
|
-
for (const name of names) {
|
|
238
|
-
if (Object.hasOwn(record, name)) return record[name];
|
|
239
|
-
}
|
|
240
|
-
return undefined;
|
|
241
|
-
};
|
|
242
|
-
|
|
243
|
-
const readRuntimeEnvironment = (): Record<string, string> => {
|
|
244
|
-
const environment: Record<string, string> = {};
|
|
245
|
-
for (const name of runtimeEnvironmentNames) {
|
|
246
|
-
const value = process.env[name];
|
|
247
|
-
if (value !== undefined) environment[name] = value;
|
|
248
|
-
}
|
|
249
|
-
return environment;
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
const concatChunks = (chunks: Uint8Array[], total: number): Uint8Array => {
|
|
253
|
-
const output = new Uint8Array(total);
|
|
254
|
-
let offset = 0;
|
|
255
|
-
for (const chunk of chunks) {
|
|
256
|
-
output.set(chunk, offset);
|
|
257
|
-
offset += chunk.byteLength;
|
|
258
|
-
}
|
|
259
|
-
return output;
|
|
260
|
-
};
|
|
261
|
-
|
|
262
|
-
const consumeCommandStream = async (
|
|
263
|
-
stream: plugins.stream.Readable,
|
|
264
|
-
streamName: 'stdout' | 'stderr',
|
|
265
|
-
maximumBytes: number,
|
|
266
|
-
onOutput?: IOciRuntimeCommandRequest['onOutput'],
|
|
267
|
-
): Promise<Uint8Array> => {
|
|
268
|
-
const chunks: Uint8Array[] = [];
|
|
269
|
-
let total = 0;
|
|
270
|
-
for await (const value of stream as AsyncIterable<Buffer>) {
|
|
271
|
-
const chunk = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
272
|
-
if (onOutput) {
|
|
273
|
-
await onOutput(streamName, chunk);
|
|
274
|
-
continue;
|
|
275
|
-
}
|
|
276
|
-
total += chunk.byteLength;
|
|
277
|
-
if (total > maximumBytes) {
|
|
278
|
-
// Leaving the loop destroys the stream, which closes the pipe.
|
|
279
|
-
throw new RunnerError('OCI runtime output exceeded the configured limit');
|
|
280
|
-
}
|
|
281
|
-
chunks.push(chunk);
|
|
282
|
-
}
|
|
283
|
-
return onOutput ? new Uint8Array() : concatChunks(chunks, total);
|
|
284
|
-
};
|
|
285
|
-
|
|
286
|
-
const withTimeout = async <T>(
|
|
287
|
-
promise: Promise<T>,
|
|
288
|
-
timeoutMs: number,
|
|
289
|
-
message: string,
|
|
290
|
-
): Promise<T> => {
|
|
291
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
292
|
-
const timeout = new Promise<never>((_resolve, reject) => {
|
|
293
|
-
timer = setTimeout(() => reject(new RunnerError(message)), timeoutMs);
|
|
294
|
-
});
|
|
295
|
-
try {
|
|
296
|
-
return await Promise.race([promise, timeout]);
|
|
297
|
-
} finally {
|
|
298
|
-
if (timer !== undefined) clearTimeout(timer);
|
|
299
|
-
}
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
interface IChildExit {
|
|
303
|
-
code: number;
|
|
304
|
-
success: boolean;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/** Resolves when the child has exited, or when it could not be started at all. */
|
|
308
|
-
const childExit = (child: plugins.childProcess.ChildProcess): Promise<IChildExit> =>
|
|
309
|
-
new Promise((resolvePromise, rejectPromise) => {
|
|
310
|
-
child.once('exit', (code, signal) => {
|
|
311
|
-
const signalNumber = signal ? plugins.os.constants.signals[signal] : undefined;
|
|
312
|
-
const exitCode = code ?? (signalNumber === undefined ? 1 : 128 + signalNumber);
|
|
313
|
-
resolvePromise({ code: exitCode, success: code === 0 });
|
|
314
|
-
});
|
|
315
|
-
child.once('error', (error) => {
|
|
316
|
-
if (child.pid === undefined) rejectPromise(error);
|
|
317
|
-
});
|
|
318
|
-
});
|
|
319
|
-
|
|
320
|
-
const terminateChild = async (
|
|
321
|
-
child: plugins.childProcess.ChildProcess,
|
|
322
|
-
exited: Promise<unknown>,
|
|
323
|
-
): Promise<void> => {
|
|
324
|
-
const status = exited.then(() => undefined, () => undefined);
|
|
325
|
-
child.kill('SIGTERM');
|
|
326
|
-
try {
|
|
327
|
-
await withTimeout(status, runtimeTerminationGraceMs, 'OCI runtime process ignored SIGTERM');
|
|
328
|
-
return;
|
|
329
|
-
} catch {
|
|
330
|
-
// Escalate below.
|
|
331
|
-
}
|
|
332
|
-
child.kill('SIGKILL');
|
|
333
|
-
await withTimeout(status, runtimeTerminationGraceMs, 'OCI runtime process ignored SIGKILL');
|
|
334
|
-
};
|
|
335
|
-
|
|
336
|
-
const defaultCommandRunner: TOciRuntimeCommandRunner = async (request) => {
|
|
337
|
-
// An explicit `env` replaces the runner's environment: the command sees only the given names.
|
|
338
|
-
const child = plugins.childProcess.spawn(request.executable, request.args, {
|
|
339
|
-
env: request.environment,
|
|
340
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
341
|
-
});
|
|
342
|
-
const exited = childExit(child);
|
|
343
|
-
const maximumBytes = request.maximumOutputBytes ?? maximumRuntimeOutputBytes;
|
|
344
|
-
const stdout = consumeCommandStream(child.stdout!, 'stdout', maximumBytes, request.onOutput);
|
|
345
|
-
const stderr = consumeCommandStream(child.stderr!, 'stderr', maximumBytes, request.onOutput);
|
|
346
|
-
const output = Promise.all([exited, stdout, stderr]);
|
|
347
|
-
let abortListener: (() => void) | undefined;
|
|
348
|
-
const aborted = new Promise<never>((_resolve, reject) => {
|
|
349
|
-
abortListener = () => reject(request.signal?.reason ?? new RunnerError('Command aborted'));
|
|
350
|
-
request.signal?.addEventListener('abort', abortListener, { once: true });
|
|
351
|
-
if (request.signal?.aborted) abortListener();
|
|
352
|
-
});
|
|
353
|
-
try {
|
|
354
|
-
const [status, commandStdout, commandStderr] = await withTimeout(
|
|
355
|
-
request.signal ? Promise.race([output, aborted]) : output,
|
|
356
|
-
request.timeoutMs,
|
|
357
|
-
`Command timed out: ${request.args[0] ?? request.executable}`,
|
|
358
|
-
);
|
|
359
|
-
return {
|
|
360
|
-
success: status.success,
|
|
361
|
-
code: status.code,
|
|
362
|
-
stdout: commandStdout,
|
|
363
|
-
stderr: commandStderr,
|
|
364
|
-
};
|
|
365
|
-
} catch (error) {
|
|
366
|
-
const cleanupErrors: unknown[] = [];
|
|
367
|
-
try {
|
|
368
|
-
await terminateChild(child, exited);
|
|
369
|
-
} catch (cleanupError) {
|
|
370
|
-
cleanupErrors.push(cleanupError);
|
|
371
|
-
}
|
|
372
|
-
try {
|
|
373
|
-
await withTimeout(
|
|
374
|
-
Promise.allSettled([exited, stdout, stderr]),
|
|
375
|
-
runtimeTerminationGraceMs,
|
|
376
|
-
'OCI runtime resources did not close after termination',
|
|
377
|
-
);
|
|
378
|
-
} catch (cleanupError) {
|
|
379
|
-
cleanupErrors.push(cleanupError);
|
|
380
|
-
}
|
|
381
|
-
if (cleanupErrors.length > 0) {
|
|
382
|
-
throw new ResourceCleanupError('OCI runtime process cleanup failed', [
|
|
383
|
-
error,
|
|
384
|
-
...cleanupErrors,
|
|
385
|
-
]);
|
|
386
|
-
}
|
|
387
|
-
throw error;
|
|
388
|
-
} finally {
|
|
389
|
-
if (abortListener) request.signal?.removeEventListener('abort', abortListener);
|
|
390
|
-
}
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
const requireSuccess = (result: IOciRuntimeCommandResult, message: string): void => {
|
|
394
|
-
if (!result.success) throw new RunnerError(message);
|
|
395
|
-
};
|
|
396
|
-
|
|
397
|
-
const decode = (value: Uint8Array): string => new TextDecoder().decode(value).trim();
|
|
398
|
-
|
|
399
|
-
async function* readRuntimeDirectory(path: string): AsyncIterable<IRuntimeDirectoryEntry> {
|
|
400
|
-
for (const entry of await plugins.fs.readdir(path, { withFileTypes: true })) {
|
|
401
|
-
yield {
|
|
402
|
-
name: entry.name,
|
|
403
|
-
isFile: entry.isFile(),
|
|
404
|
-
isDirectory: entry.isDirectory(),
|
|
405
|
-
isSymlink: entry.isSymbolicLink(),
|
|
406
|
-
};
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
const lstatRuntimeFile = async (path: string): Promise<IRuntimeFileInfo> => {
|
|
411
|
-
const stat = await plugins.fs.lstat(path);
|
|
412
|
-
return {
|
|
413
|
-
isDirectory: stat.isDirectory(),
|
|
414
|
-
isSymlink: stat.isSymbolicLink(),
|
|
415
|
-
uid: stat.uid,
|
|
416
|
-
mtime: stat.mtime,
|
|
417
|
-
dev: stat.dev,
|
|
418
|
-
ino: stat.ino,
|
|
419
|
-
};
|
|
420
|
-
};
|
|
421
|
-
|
|
422
|
-
export const scavengeHostTmpfsProbes = async (
|
|
423
|
-
directory = '/dev/shm',
|
|
424
|
-
dependencies: IHostTmpfsProbeScavengerDependencies = {},
|
|
425
|
-
runtimeProbeOwnerId?: string,
|
|
426
|
-
): Promise<void> => {
|
|
427
|
-
if (!runtimeProbeOwnerId || !runtimeProbeOwnerIdPattern.test(runtimeProbeOwnerId)) {
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
let uid: number | null | undefined;
|
|
431
|
-
try {
|
|
432
|
-
uid = dependencies.getUid ? dependencies.getUid() : process.getuid?.();
|
|
433
|
-
} catch {
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
if (uid === undefined || uid === null || !Number.isSafeInteger(uid) || uid < 0) return;
|
|
437
|
-
|
|
438
|
-
const now = dependencies.now ?? Date.now;
|
|
439
|
-
const readDir = dependencies.readDir ?? readRuntimeDirectory;
|
|
440
|
-
const lstat = dependencies.lstat ?? lstatRuntimeFile;
|
|
441
|
-
const remove = dependencies.remove ?? ((path, options) => removePath(path, options));
|
|
442
|
-
const isEligible = (stat: IRuntimeFileInfo): boolean =>
|
|
443
|
-
stat.isDirectory && !stat.isSymlink && stat.uid === uid && stat.mtime !== null &&
|
|
444
|
-
now() - stat.mtime.getTime() > hostTmpfsProbeMaximumAgeMs;
|
|
445
|
-
|
|
446
|
-
for await (const entry of readDir(directory)) {
|
|
447
|
-
if (hostTmpfsProbeNamePattern.exec(entry.name)?.[1] !== runtimeProbeOwnerId) continue;
|
|
448
|
-
const path = join(directory, entry.name);
|
|
449
|
-
let initial: IRuntimeFileInfo;
|
|
450
|
-
try {
|
|
451
|
-
initial = await lstat(path);
|
|
452
|
-
} catch (error) {
|
|
453
|
-
if (isNotFound(error)) continue;
|
|
454
|
-
throw error;
|
|
455
|
-
}
|
|
456
|
-
if (!isEligible(initial) || initial.dev === null || initial.ino === null) continue;
|
|
457
|
-
let current: IRuntimeFileInfo;
|
|
458
|
-
try {
|
|
459
|
-
current = await lstat(path);
|
|
460
|
-
} catch (error) {
|
|
461
|
-
if (isNotFound(error)) continue;
|
|
462
|
-
throw error;
|
|
463
|
-
}
|
|
464
|
-
if (
|
|
465
|
-
!isEligible(current) || current.dev !== initial.dev || current.ino !== initial.ino
|
|
466
|
-
) continue;
|
|
467
|
-
try {
|
|
468
|
-
await remove(path, { recursive: true });
|
|
469
|
-
} catch (error) {
|
|
470
|
-
if (!isNotFound(error)) {
|
|
471
|
-
throw new ResourceCleanupError(`Unable to remove stale host tmpfs probe ${path}`, [error]);
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
};
|
|
476
|
-
|
|
477
|
-
const parseJson = (value: Uint8Array, message: string): unknown => {
|
|
478
|
-
try {
|
|
479
|
-
return JSON.parse(decode(value));
|
|
480
|
-
} catch (error) {
|
|
481
|
-
throw new RunnerError(message, { cause: error });
|
|
482
|
-
}
|
|
483
|
-
};
|
|
484
|
-
|
|
485
|
-
const firstObject = (value: unknown, message: string): Record<string, unknown> => {
|
|
486
|
-
const candidate = Array.isArray(value) ? value[0] : value;
|
|
487
|
-
if (!isRecord(candidate)) throw new RunnerError(message);
|
|
488
|
-
return candidate;
|
|
489
|
-
};
|
|
490
|
-
|
|
491
|
-
const positiveSafeInteger = (value: number, fieldName: string): number => {
|
|
492
|
-
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
493
|
-
throw new ProtocolError(`${fieldName} must be a positive safe integer`);
|
|
494
|
-
}
|
|
495
|
-
return value;
|
|
496
|
-
};
|
|
497
|
-
|
|
498
|
-
const nonNegativeSafeInteger = (value: number, fieldName: string): number => {
|
|
499
|
-
if (!Number.isSafeInteger(value) || value < 0) {
|
|
500
|
-
throw new ProtocolError(`${fieldName} must be a non-negative safe integer`);
|
|
501
|
-
}
|
|
502
|
-
return value;
|
|
503
|
-
};
|
|
504
|
-
|
|
505
|
-
const checkedAdd = (left: number, right: number, message: string): number => {
|
|
506
|
-
const result = left + right;
|
|
507
|
-
if (!Number.isSafeInteger(result)) throw new ProtocolError(message);
|
|
508
|
-
return result;
|
|
509
|
-
};
|
|
510
|
-
|
|
511
|
-
const checkedMultiply = (left: number, right: number, message: string): number => {
|
|
512
|
-
const result = left * right;
|
|
513
|
-
if (!Number.isSafeInteger(result)) throw new ProtocolError(message);
|
|
514
|
-
return result;
|
|
515
|
-
};
|
|
516
|
-
|
|
517
|
-
const roundUp = (value: number, blockSize: number): number => {
|
|
518
|
-
const blocks = Math.ceil(value / blockSize);
|
|
519
|
-
return checkedMultiply(blocks, blockSize, 'Workspace volume size overflow');
|
|
520
|
-
};
|
|
521
|
-
|
|
522
|
-
export const calculateWorkspaceVolumeLimits = (
|
|
523
|
-
logicalBytes: number,
|
|
524
|
-
maximumEntries: number,
|
|
525
|
-
blockSize: number,
|
|
526
|
-
): IWorkspaceVolumeLimits => {
|
|
527
|
-
nonNegativeSafeInteger(logicalBytes, 'Workspace byte limit');
|
|
528
|
-
positiveSafeInteger(maximumEntries, 'Workspace entry limit');
|
|
529
|
-
positiveSafeInteger(blockSize, 'Workspace block size');
|
|
530
|
-
const roundedLogicalBytes = roundUp(logicalBytes, blockSize);
|
|
531
|
-
const entryRoundingBytes = checkedMultiply(
|
|
532
|
-
maximumEntries,
|
|
533
|
-
blockSize,
|
|
534
|
-
'Workspace entry allocation size overflow',
|
|
535
|
-
);
|
|
536
|
-
const sizeBytes = checkedAdd(
|
|
537
|
-
checkedAdd(roundedLogicalBytes, entryRoundingBytes, 'Workspace volume size overflow'),
|
|
538
|
-
workspaceHelperReserveBytes,
|
|
539
|
-
'Workspace volume size overflow',
|
|
540
|
-
);
|
|
541
|
-
return Object.freeze({
|
|
542
|
-
blockSize,
|
|
543
|
-
logicalBytes,
|
|
544
|
-
maximumEntries,
|
|
545
|
-
reserveBytes: workspaceHelperReserveBytes,
|
|
546
|
-
sizeBytes,
|
|
547
|
-
inodeLimit: checkedAdd(
|
|
548
|
-
maximumEntries,
|
|
549
|
-
workspaceFixedInodes,
|
|
550
|
-
'Workspace inode limit overflow',
|
|
551
|
-
),
|
|
552
|
-
});
|
|
553
|
-
};
|
|
554
|
-
|
|
555
|
-
const parseContainerUser = (value: string): { uid: number; gid: number } => {
|
|
556
|
-
const match = /^([1-9][0-9]*)(?::([1-9][0-9]*))?$/.exec(value);
|
|
557
|
-
if (!match) throw new RunnerError('OCI containerUser must be a numeric non-root UID[:GID]');
|
|
558
|
-
const uid = Number(match[1]);
|
|
559
|
-
const gid = Number(match[2] ?? match[1]);
|
|
560
|
-
if (
|
|
561
|
-
!Number.isSafeInteger(uid) || !Number.isSafeInteger(gid) || uid > 4_294_967_294 ||
|
|
562
|
-
gid > 4_294_967_294
|
|
563
|
-
) {
|
|
564
|
-
throw new RunnerError('OCI containerUser is outside the supported numeric range');
|
|
565
|
-
}
|
|
566
|
-
return { uid, gid };
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
const validateImage = (image: string): string => {
|
|
570
|
-
if (
|
|
571
|
-
image.length > 1024 ||
|
|
572
|
-
image.startsWith('-') ||
|
|
573
|
-
!/^[^\s@]+@sha256:[a-f0-9]{64}$/.test(image)
|
|
574
|
-
) {
|
|
575
|
-
throw new ProtocolError('Job image must be pinned by a lowercase SHA-256 digest');
|
|
576
|
-
}
|
|
577
|
-
return image;
|
|
578
|
-
};
|
|
579
|
-
|
|
580
|
-
const validateWorkingDirectory = (value: string | undefined): string => {
|
|
581
|
-
const workingDirectory = value ?? '/workspace';
|
|
582
|
-
if (
|
|
583
|
-
workingDirectory.length > 256 ||
|
|
584
|
-
!/^\/[A-Za-z0-9._/-]+$/.test(workingDirectory)
|
|
585
|
-
) {
|
|
586
|
-
throw new ProtocolError('Job working directory is invalid');
|
|
587
|
-
}
|
|
588
|
-
return workingDirectory;
|
|
589
|
-
};
|
|
590
|
-
|
|
591
|
-
const validateStepCommand = (command: string[]): void => {
|
|
592
|
-
if (command.length === 0 || command.length > maximumCommandArguments) {
|
|
593
|
-
throw new ProtocolError('Compiled step command has an invalid argument count');
|
|
594
|
-
}
|
|
595
|
-
let totalBytes = 0;
|
|
596
|
-
for (const argument of command) {
|
|
597
|
-
const argumentBytes = utf8Length(argument);
|
|
598
|
-
if (
|
|
599
|
-
!argument || argument.includes('\0') || argumentBytes > maximumCommandArgumentBytes
|
|
600
|
-
) {
|
|
601
|
-
throw new ProtocolError('Compiled step command argument is invalid');
|
|
602
|
-
}
|
|
603
|
-
totalBytes = checkedAdd(totalBytes, argumentBytes, 'Compiled step command size overflow');
|
|
604
|
-
}
|
|
605
|
-
if (totalBytes > maximumCommandBytes) {
|
|
606
|
-
throw new ProtocolError('Compiled step command exceeds the total byte limit');
|
|
607
|
-
}
|
|
608
|
-
};
|
|
609
|
-
|
|
610
|
-
const validateGeneratedName = (value: string, kind: 'container' | 'volume'): string => {
|
|
611
|
-
const pattern = kind === 'container'
|
|
612
|
-
? /^shipzone-ci-(?:helper|probe|step)-[a-f0-9]{32}$/
|
|
613
|
-
: /^shipzone-ci-volume-[a-f0-9]{32}$/;
|
|
614
|
-
if (!pattern.test(value)) throw new ProtocolError(`Runner generated an invalid OCI ${kind} name`);
|
|
615
|
-
return value;
|
|
616
|
-
};
|
|
617
|
-
|
|
618
|
-
const validateHostMountPath = (path: string, name: string): string => {
|
|
619
|
-
if (!path.startsWith('/') || path.includes(',') || path.includes('\0') || path.includes('\n')) {
|
|
620
|
-
throw new RunnerError(`${name} is incompatible with an OCI bind mount`);
|
|
621
|
-
}
|
|
622
|
-
return path;
|
|
623
|
-
};
|
|
624
|
-
|
|
625
|
-
interface IStepResources {
|
|
626
|
-
memoryBytes: number;
|
|
627
|
-
cpus: number;
|
|
628
|
-
pids: number;
|
|
629
|
-
sharedMemoryBytes: number;
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
/**
|
|
633
|
-
* Resolves the attempt's resource ceilings: the job's declared values, or the runner defaults for
|
|
634
|
-
* omitted values, each bounded by the runner maximum it advertises.
|
|
635
|
-
*/
|
|
636
|
-
const validateResources = (config: IRunnerConfig, lease: IOciJobLease): IStepResources => {
|
|
637
|
-
const bounded = (
|
|
638
|
-
requested: number | undefined,
|
|
639
|
-
fallback: number,
|
|
640
|
-
maximum: number,
|
|
641
|
-
name: string,
|
|
642
|
-
integer = false,
|
|
643
|
-
): number => {
|
|
644
|
-
const value = requested ?? fallback;
|
|
645
|
-
if (
|
|
646
|
-
!Number.isFinite(value) || value <= 0 || value > maximum ||
|
|
647
|
-
(integer && !Number.isInteger(value))
|
|
648
|
-
) {
|
|
649
|
-
throw new ProtocolError(`Job ${name} exceeds runner policy`);
|
|
650
|
-
}
|
|
651
|
-
return value;
|
|
652
|
-
};
|
|
653
|
-
return {
|
|
654
|
-
memoryBytes: bounded(
|
|
655
|
-
lease.job.resources?.memoryBytes,
|
|
656
|
-
config.oci.defaultMemoryBytes,
|
|
657
|
-
config.oci.maximumMemoryBytes,
|
|
658
|
-
'memory limit',
|
|
659
|
-
true,
|
|
660
|
-
),
|
|
661
|
-
cpus: bounded(
|
|
662
|
-
lease.job.resources?.cpus,
|
|
663
|
-
config.oci.defaultCpus,
|
|
664
|
-
config.oci.maximumCpus,
|
|
665
|
-
'CPU limit',
|
|
666
|
-
),
|
|
667
|
-
pids: bounded(
|
|
668
|
-
lease.job.resources?.pids,
|
|
669
|
-
config.oci.defaultPids,
|
|
670
|
-
config.oci.maximumPids,
|
|
671
|
-
'PID limit',
|
|
672
|
-
true,
|
|
673
|
-
),
|
|
674
|
-
sharedMemoryBytes: bounded(
|
|
675
|
-
lease.job.resources?.sharedMemoryBytes,
|
|
676
|
-
config.oci.defaultSharedMemoryBytes,
|
|
677
|
-
config.oci.maximumSharedMemoryBytes,
|
|
678
|
-
'shared memory limit',
|
|
679
|
-
true,
|
|
680
|
-
),
|
|
681
|
-
};
|
|
682
|
-
};
|
|
683
|
-
|
|
684
|
-
/**
|
|
685
|
-
* The only network mode this executor enforces: `none` gives every step container a new network
|
|
686
|
-
* namespace whose only interface is loopback, private to that container.
|
|
687
|
-
*/
|
|
688
|
-
const requireNoNetwork = (config: IRunnerConfig, lease: IOciJobLease): 'none' => {
|
|
689
|
-
const mode: string = lease.job.network.mode;
|
|
690
|
-
if (mode !== 'none' || !config.oci.allowedNetworks.includes('none')) {
|
|
691
|
-
throw new ProtocolError(`Job network ${mode} is not enforced by this runner`);
|
|
692
|
-
}
|
|
693
|
-
return 'none';
|
|
694
|
-
};
|
|
695
|
-
|
|
696
|
-
const labels = (
|
|
697
|
-
runnerId: string,
|
|
698
|
-
sessionId: string,
|
|
699
|
-
attemptId: string,
|
|
700
|
-
): string[] => [
|
|
701
|
-
'--label',
|
|
702
|
-
`${managedLabel}=true`,
|
|
703
|
-
'--label',
|
|
704
|
-
`${runnerLabel}=${runnerId}`,
|
|
705
|
-
'--label',
|
|
706
|
-
`${sessionLabel}=${sessionId}`,
|
|
707
|
-
'--label',
|
|
708
|
-
`${attemptLabel}=${attemptId}`,
|
|
709
|
-
];
|
|
710
|
-
|
|
711
|
-
const isolatedContainerArgs = (
|
|
712
|
-
config: IRunnerConfig,
|
|
713
|
-
input: {
|
|
714
|
-
runnerId: string;
|
|
715
|
-
sessionId: string;
|
|
716
|
-
attemptId: string;
|
|
717
|
-
containerName: string;
|
|
718
|
-
user: string;
|
|
719
|
-
network: 'none';
|
|
720
|
-
workdir: string;
|
|
721
|
-
memoryBytes: number;
|
|
722
|
-
cpus: number;
|
|
723
|
-
pids: number;
|
|
724
|
-
},
|
|
725
|
-
): string[] => [
|
|
726
|
-
'create',
|
|
727
|
-
'--name',
|
|
728
|
-
validateGeneratedName(input.containerName, 'container'),
|
|
729
|
-
...labels(input.runnerId, input.sessionId, input.attemptId),
|
|
730
|
-
'--read-only',
|
|
731
|
-
'--cap-drop',
|
|
732
|
-
'ALL',
|
|
733
|
-
'--security-opt',
|
|
734
|
-
'no-new-privileges:true',
|
|
735
|
-
'--ipc',
|
|
736
|
-
'private',
|
|
737
|
-
'--network',
|
|
738
|
-
input.network,
|
|
739
|
-
'--user',
|
|
740
|
-
input.user,
|
|
741
|
-
'--workdir',
|
|
742
|
-
input.workdir,
|
|
743
|
-
'--pids-limit',
|
|
744
|
-
String(input.pids),
|
|
745
|
-
'--memory',
|
|
746
|
-
String(input.memoryBytes),
|
|
747
|
-
'--memory-swap',
|
|
748
|
-
String(
|
|
749
|
-
config.oci.runtime === 'docker'
|
|
750
|
-
? input.memoryBytes
|
|
751
|
-
: checkedAdd(input.memoryBytes, 4096, 'OCI memory and swap limit overflow'),
|
|
752
|
-
),
|
|
753
|
-
'--cpus',
|
|
754
|
-
String(input.cpus),
|
|
755
|
-
'--ulimit',
|
|
756
|
-
'core=0:0',
|
|
757
|
-
'--ulimit',
|
|
758
|
-
'nofile=4096:4096',
|
|
759
|
-
'--tmpfs',
|
|
760
|
-
`/tmp:rw,noexec,nosuid,nodev,size=${config.oci.temporarySizeBytes}`,
|
|
761
|
-
'--no-healthcheck',
|
|
762
|
-
'--pull=never',
|
|
763
|
-
];
|
|
764
|
-
|
|
765
|
-
const collectStepEnvironment = (
|
|
766
|
-
config: IRunnerConfig,
|
|
767
|
-
input: IOciStepCommandInput,
|
|
768
|
-
): Record<string, string> => {
|
|
769
|
-
const environment: Record<string, string> = {};
|
|
770
|
-
const names = [
|
|
771
|
-
...Object.keys(input.step.environment),
|
|
772
|
-
...Object.keys(input.lease.job.secrets),
|
|
773
|
-
];
|
|
774
|
-
if (new Set(names).size !== names.length) {
|
|
775
|
-
throw new ProtocolError('Step environment and secret targets must be unique');
|
|
776
|
-
}
|
|
777
|
-
if (names.length > config.maximumEnvironmentVariables) {
|
|
778
|
-
throw new ProtocolError('Step has too many environment variables');
|
|
779
|
-
}
|
|
780
|
-
let secretBytes = 0;
|
|
781
|
-
for (
|
|
782
|
-
const [name, value, secret] of [
|
|
783
|
-
...Object.entries(input.step.environment).map(([name, value]) =>
|
|
784
|
-
[name, value, false] as const
|
|
785
|
-
),
|
|
786
|
-
...Object.entries(input.lease.job.secrets).map(([name, value]) =>
|
|
787
|
-
[name, value, true] as const
|
|
788
|
-
),
|
|
789
|
-
]
|
|
790
|
-
) {
|
|
791
|
-
validateEnvironmentName(name);
|
|
792
|
-
if (value.includes('\0') || utf8Length(value) > config.maximumEnvironmentValueBytes) {
|
|
793
|
-
throw new ProtocolError(`Environment value for ${name} exceeds runner policy`);
|
|
794
|
-
}
|
|
795
|
-
if (secret) secretBytes += utf8Length(value);
|
|
796
|
-
environment[name] = value;
|
|
797
|
-
}
|
|
798
|
-
if (secretBytes > config.maximumSecretBytes) {
|
|
799
|
-
throw new ProtocolError('Job secrets exceed runner policy');
|
|
800
|
-
}
|
|
801
|
-
return environment;
|
|
802
|
-
};
|
|
803
|
-
|
|
804
|
-
export const buildOciRunCommand = (
|
|
805
|
-
config: IRunnerConfig,
|
|
806
|
-
input: IOciStepCommandInput,
|
|
807
|
-
): IOciRunCommand => {
|
|
808
|
-
validateIdentifier(input.runnerId, 'runnerId');
|
|
809
|
-
validateIdentifier(input.sessionId, 'sessionId');
|
|
810
|
-
validateIdentifier(input.lease.jobId, 'jobId');
|
|
811
|
-
validateIdentifier(input.lease.attemptId, 'attemptId');
|
|
812
|
-
validateGeneratedName(input.containerName, 'container');
|
|
813
|
-
validateGeneratedName(input.volumeName, 'volume');
|
|
814
|
-
validateImage(input.lease.job.execution.image);
|
|
815
|
-
validateStepCommand(input.step.command);
|
|
816
|
-
const network = requireNoNetwork(config, input.lease);
|
|
817
|
-
const { sharedMemoryBytes, ...resources } = validateResources(config, input.lease);
|
|
818
|
-
const environment = collectStepEnvironment(config, input);
|
|
819
|
-
const volumeMountOptions = config.oci.runtime === 'docker'
|
|
820
|
-
? 'volume-subpath=workspace,volume-nocopy'
|
|
821
|
-
: 'subpath=/workspace';
|
|
822
|
-
const args = isolatedContainerArgs(config, {
|
|
823
|
-
runnerId: input.runnerId,
|
|
824
|
-
sessionId: input.sessionId,
|
|
825
|
-
attemptId: input.lease.attemptId,
|
|
826
|
-
containerName: input.containerName,
|
|
827
|
-
user: config.oci.containerUser,
|
|
828
|
-
network,
|
|
829
|
-
workdir: validateWorkingDirectory(input.lease.job.execution.workingDirectory),
|
|
830
|
-
...resources,
|
|
831
|
-
});
|
|
832
|
-
args.push(
|
|
833
|
-
'--shm-size',
|
|
834
|
-
String(sharedMemoryBytes),
|
|
835
|
-
'--mount',
|
|
836
|
-
`type=volume,source=${input.volumeName},target=/workspace,${volumeMountOptions}`,
|
|
837
|
-
);
|
|
838
|
-
for (const name of Object.keys(environment).sort()) args.push('--env', name);
|
|
839
|
-
args.push(input.lease.job.execution.image, ...input.step.command);
|
|
840
|
-
return { args, environment };
|
|
841
|
-
};
|
|
842
|
-
|
|
843
|
-
const validateLeasePolicy = (
|
|
844
|
-
config: IRunnerConfig,
|
|
845
|
-
context: Pick<IPrepareOciLeaseContext, 'runnerId' | 'sessionId' | 'lease'>,
|
|
846
|
-
): void => {
|
|
847
|
-
parseContainerUser(config.oci.containerUser);
|
|
848
|
-
validateImage(context.lease.job.execution.image);
|
|
849
|
-
validateWorkingDirectory(context.lease.job.execution.workingDirectory);
|
|
850
|
-
requireNoNetwork(config, context.lease);
|
|
851
|
-
if (
|
|
852
|
-
!Number.isSafeInteger(context.lease.job.timeoutMs) ||
|
|
853
|
-
context.lease.job.timeoutMs <= 0 ||
|
|
854
|
-
context.lease.job.timeoutMs > config.oci.maximumTimeoutMs
|
|
855
|
-
) {
|
|
856
|
-
throw new ProtocolError('Job timeout exceeds runner policy');
|
|
857
|
-
}
|
|
858
|
-
const workspaceBytes = context.lease.job.requirements.limits.maximumWorkspaceBytes;
|
|
859
|
-
const workspaceEntries = context.lease.job.requirements.limits.maximumWorkspaceEntries;
|
|
860
|
-
nonNegativeSafeInteger(workspaceBytes, 'Workspace byte limit');
|
|
861
|
-
positiveSafeInteger(workspaceEntries, 'Workspace entry limit');
|
|
862
|
-
if (
|
|
863
|
-
workspaceBytes > config.oci.workspaceSizeBytes ||
|
|
864
|
-
workspaceEntries > config.maximumWorkspaceEntries
|
|
865
|
-
) {
|
|
866
|
-
throw new ProtocolError('Job workspace limits exceed runner policy');
|
|
867
|
-
}
|
|
868
|
-
validateResources(config, context.lease);
|
|
869
|
-
if (context.lease.job.steps.length === 0) {
|
|
870
|
-
throw new ProtocolError('Compiled job must contain at least one step');
|
|
871
|
-
}
|
|
872
|
-
for (const step of context.lease.job.steps) {
|
|
873
|
-
buildOciRunCommand(config, {
|
|
874
|
-
runnerId: context.runnerId,
|
|
875
|
-
sessionId: context.sessionId,
|
|
876
|
-
lease: context.lease,
|
|
877
|
-
step,
|
|
878
|
-
containerName: `shipzone-ci-step-${'0'.repeat(32)}`,
|
|
879
|
-
volumeName: `shipzone-ci-volume-${'0'.repeat(32)}`,
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
};
|
|
883
|
-
|
|
884
|
-
export const buildOciHelperCreateCommand = (
|
|
885
|
-
config: IRunnerConfig,
|
|
886
|
-
input: IOciHelperCommandInput,
|
|
887
|
-
): string[] => {
|
|
888
|
-
validateIdentifier(input.runnerId, 'runnerId');
|
|
889
|
-
validateIdentifier(input.sessionId, 'sessionId');
|
|
890
|
-
validateIdentifier(input.attemptId, 'attemptId');
|
|
891
|
-
validateGeneratedName(input.containerName, 'container');
|
|
892
|
-
validateImage(input.image);
|
|
893
|
-
validateHostMountPath(input.helperPath, 'Workspace helper path');
|
|
894
|
-
if (input.command.length === 0 || input.command.some((argument) => argument.includes('\0'))) {
|
|
895
|
-
throw new ProtocolError('Workspace helper command is invalid');
|
|
896
|
-
}
|
|
897
|
-
const args = isolatedContainerArgs(config, {
|
|
898
|
-
runnerId: input.runnerId,
|
|
899
|
-
sessionId: input.sessionId,
|
|
900
|
-
attemptId: input.attemptId,
|
|
901
|
-
containerName: input.containerName,
|
|
902
|
-
user: '0',
|
|
903
|
-
network: 'none',
|
|
904
|
-
workdir: '/',
|
|
905
|
-
memoryBytes: Math.min(config.oci.defaultMemoryBytes, helperMemoryBytes),
|
|
906
|
-
cpus: Math.min(config.oci.defaultCpus, helperCpus),
|
|
907
|
-
pids: Math.min(config.oci.defaultPids, helperPids),
|
|
908
|
-
});
|
|
909
|
-
args.push(
|
|
910
|
-
'--entrypoint',
|
|
911
|
-
helperContainerPath,
|
|
912
|
-
'--mount',
|
|
913
|
-
`type=bind,source=${input.helperPath},target=${helperContainerPath},readonly`,
|
|
914
|
-
);
|
|
915
|
-
if (input.volumeName) {
|
|
916
|
-
validateGeneratedName(input.volumeName, 'volume');
|
|
917
|
-
const noCopy = config.oci.runtime === 'docker' ? ',volume-nocopy' : '';
|
|
918
|
-
args.push(
|
|
919
|
-
'--mount',
|
|
920
|
-
`type=volume,source=${input.volumeName},target=/volume${noCopy}`,
|
|
921
|
-
);
|
|
922
|
-
}
|
|
923
|
-
if (input.sourcePath) {
|
|
924
|
-
validateHostMountPath(input.sourcePath, 'Workspace import path');
|
|
925
|
-
args.push(
|
|
926
|
-
'--mount',
|
|
927
|
-
`type=bind,source=${input.sourcePath},target=/staging,readonly`,
|
|
928
|
-
);
|
|
929
|
-
}
|
|
930
|
-
if (input.destinationPath) {
|
|
931
|
-
validateHostMountPath(input.destinationPath, 'Workspace export path');
|
|
932
|
-
args.push(
|
|
933
|
-
'--mount',
|
|
934
|
-
`type=bind,source=${input.destinationPath},target=/export`,
|
|
935
|
-
);
|
|
936
|
-
}
|
|
937
|
-
const operation = input.command[0];
|
|
938
|
-
if (['reserve', 'import', 'measure', 'filesystem', 'export'].includes(operation)) {
|
|
939
|
-
args.push('--cap-add', 'DAC_OVERRIDE');
|
|
940
|
-
}
|
|
941
|
-
if (['reserve', 'import', 'export'].includes(operation)) {
|
|
942
|
-
args.push('--cap-add', 'CHOWN');
|
|
943
|
-
}
|
|
944
|
-
args.push(input.image, ...input.command);
|
|
945
|
-
return args;
|
|
946
|
-
};
|
|
947
|
-
|
|
948
|
-
const mapArchitecture = (
|
|
949
|
-
value: string,
|
|
950
|
-
): { architecture: TOciArchitecture; helperTarget: TOciHelperTarget } => {
|
|
951
|
-
switch (value.toLowerCase()) {
|
|
952
|
-
case 'amd64':
|
|
953
|
-
case 'x86_64':
|
|
954
|
-
return { architecture: 'amd64', helperTarget: 'linux_amd64' };
|
|
955
|
-
case 'arm64':
|
|
956
|
-
case 'aarch64':
|
|
957
|
-
return { architecture: 'arm64', helperTarget: 'linux_arm64' };
|
|
958
|
-
default:
|
|
959
|
-
throw new RunnerError(`Unsupported OCI engine architecture: ${value}`);
|
|
960
|
-
}
|
|
961
|
-
};
|
|
962
|
-
|
|
963
|
-
const sha256File = async (path: string): Promise<string> =>
|
|
964
|
-
sha256Hex(
|
|
965
|
-
(await readBoundedRegularFile(path, workspaceHelperMaximumBytes, 'Workspace helper')).bytes,
|
|
966
|
-
);
|
|
967
|
-
|
|
968
|
-
const safeSelections = (selections: string[]): string[] => {
|
|
969
|
-
if (selections.length === 0 || selections.length > 32) {
|
|
970
|
-
throw new ProtocolError('Workspace export must select between 1 and 32 paths');
|
|
971
|
-
}
|
|
972
|
-
const result = selections.map((selection) => {
|
|
973
|
-
const segments = selection.split('/');
|
|
974
|
-
if (
|
|
975
|
-
!selection ||
|
|
976
|
-
selection.length > 1024 ||
|
|
977
|
-
selection.startsWith('/') ||
|
|
978
|
-
selection.includes('\\') ||
|
|
979
|
-
selection.includes('\0') ||
|
|
980
|
-
segments.some((segment) => !segment || segment === '.' || segment === '..')
|
|
981
|
-
) {
|
|
982
|
-
throw new ProtocolError('Workspace export selection is not a safe relative path');
|
|
983
|
-
}
|
|
984
|
-
return selection;
|
|
985
|
-
}).sort();
|
|
986
|
-
if (new Set(result).size !== result.length) {
|
|
987
|
-
throw new ProtocolError('Workspace export selections must be unique');
|
|
988
|
-
}
|
|
989
|
-
for (const selection of result) {
|
|
990
|
-
if (result.some((other) => other !== selection && selection.startsWith(`${other}/`))) {
|
|
991
|
-
throw new ProtocolError('Workspace export selections must not overlap');
|
|
992
|
-
}
|
|
993
|
-
}
|
|
994
|
-
return result;
|
|
995
|
-
};
|
|
996
|
-
|
|
997
|
-
const isStopReason = (value: unknown): value is TExecutionStopReason =>
|
|
998
|
-
typeof value === 'string' && [
|
|
999
|
-
'job_canceled',
|
|
1000
|
-
'lease_lost',
|
|
1001
|
-
'lease_expired',
|
|
1002
|
-
'runner_shutdown',
|
|
1003
|
-
'job_timeout',
|
|
1004
|
-
'log_delivery_failed',
|
|
1005
|
-
'resource_limit',
|
|
1006
|
-
].includes(value);
|
|
1007
|
-
|
|
1008
|
-
class PreparedOciLease implements IPreparedOciLease {
|
|
1009
|
-
private active = true;
|
|
1010
|
-
|
|
1011
|
-
constructor(
|
|
1012
|
-
readonly preparationId: string,
|
|
1013
|
-
readonly attemptId: string,
|
|
1014
|
-
readonly image: string,
|
|
1015
|
-
readonly imageArchitecture: TOciArchitecture,
|
|
1016
|
-
private readonly onCleanup: () => void,
|
|
1017
|
-
) {}
|
|
1018
|
-
|
|
1019
|
-
consume(): void {
|
|
1020
|
-
if (!this.active) throw new RunnerError('OCI lease preparation is no longer active');
|
|
1021
|
-
this.active = false;
|
|
1022
|
-
this.onCleanup();
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
cleanup(): Promise<void> {
|
|
1026
|
-
if (this.active) {
|
|
1027
|
-
this.active = false;
|
|
1028
|
-
this.onCleanup();
|
|
1029
|
-
}
|
|
1030
|
-
return Promise.resolve();
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
export class OciExecutor implements IJobExecutor {
|
|
1035
|
-
private readonly runtimeEnvironment: Record<string, string>;
|
|
1036
|
-
private readonly commandRunner: TOciRuntimeCommandRunner;
|
|
1037
|
-
private readonly randomId: () => string;
|
|
1038
|
-
private readonly now: () => number;
|
|
1039
|
-
private readonly resolveHelperPathImplementation: (target: TOciHelperTarget) => Promise<string>;
|
|
1040
|
-
private readonly probeTmpfsImplementation: (
|
|
1041
|
-
helperPath: string,
|
|
1042
|
-
runtimeProbeOwnerId: string,
|
|
1043
|
-
) => Promise<number>;
|
|
1044
|
-
private readonly makeTempDir: (options: IRuntimeMakeTempOptions) => Promise<string>;
|
|
1045
|
-
private readonly chmod: (path: string, mode: number) => Promise<void>;
|
|
1046
|
-
private readonly remove: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
|
|
1047
|
-
private runtimeFacts?: IOciRuntimeFacts;
|
|
1048
|
-
private readonly preparedLeases = new Map<string, PreparedOciLease>();
|
|
1049
|
-
|
|
1050
|
-
/**
|
|
1051
|
-
* @param stateOwner Ownership of `config.stateDirectory`, where the executor keeps its workspace
|
|
1052
|
-
* helpers, runtime probe owner marker and workspace exports.
|
|
1053
|
-
*/
|
|
1054
|
-
constructor(
|
|
1055
|
-
private readonly config: IRunnerConfig,
|
|
1056
|
-
private readonly stateOwner: RunnerStateOwner,
|
|
1057
|
-
dependencies: IOciExecutorDependencies = {},
|
|
1058
|
-
) {
|
|
1059
|
-
if (plugins.path.resolve(config.stateDirectory) !== stateOwner.stateDirectory) {
|
|
1060
|
-
throw new ConfigurationError('OCI executor state owner does not own the configured state');
|
|
1061
|
-
}
|
|
1062
|
-
this.commandRunner = dependencies.commandRunner ?? defaultCommandRunner;
|
|
1063
|
-
this.runtimeEnvironment = dependencies.runtimeEnvironment
|
|
1064
|
-
? { ...dependencies.runtimeEnvironment }
|
|
1065
|
-
: readRuntimeEnvironment();
|
|
1066
|
-
this.randomId = dependencies.randomId ??
|
|
1067
|
-
(() => plugins.crypto.randomUUID().replaceAll('-', ''));
|
|
1068
|
-
this.now = dependencies.now ?? Date.now;
|
|
1069
|
-
this.resolveHelperPathImplementation = dependencies.resolveHelperPath ??
|
|
1070
|
-
((target) => this.resolvePackagedHelper(target));
|
|
1071
|
-
this.probeTmpfsImplementation = dependencies.probeTmpfs
|
|
1072
|
-
? (path) => dependencies.probeTmpfs!(path)
|
|
1073
|
-
: (path, runtimeProbeOwnerId) => this.probeHostTmpfs(path, runtimeProbeOwnerId);
|
|
1074
|
-
this.makeTempDir = dependencies.makeTempDir ?? ((options) => makeTempDir(options));
|
|
1075
|
-
this.chmod = dependencies.chmod ?? ((path, mode) => plugins.fs.chmod(path, mode));
|
|
1076
|
-
this.remove = dependencies.remove ?? ((path, options) => removePath(path, options));
|
|
1077
|
-
parseContainerUser(config.oci.containerUser);
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
async verifyRuntime(): Promise<IOciRuntimeFacts> {
|
|
1081
|
-
if (this.runtimeFacts) return this.runtimeFacts;
|
|
1082
|
-
const runtime = this.config.oci.runtime;
|
|
1083
|
-
let endpoint: string;
|
|
1084
|
-
let os: string;
|
|
1085
|
-
let architectureValue: string;
|
|
1086
|
-
let rootless: boolean;
|
|
1087
|
-
|
|
1088
|
-
if (runtime === 'docker') {
|
|
1089
|
-
const contextNameResult = await this.runRuntime(['context', 'show']);
|
|
1090
|
-
requireSuccess(contextNameResult, 'Unable to determine the active Docker context');
|
|
1091
|
-
const contextName = decode(contextNameResult.stdout);
|
|
1092
|
-
if (!contextName) throw new RunnerError('Docker did not report an active context');
|
|
1093
|
-
const contextResult = await this.runRuntime(['context', 'inspect', contextName]);
|
|
1094
|
-
requireSuccess(contextResult, 'Unable to inspect the active Docker context');
|
|
1095
|
-
const context = firstObject(
|
|
1096
|
-
parseJson(contextResult.stdout, 'Docker context inspection was not valid JSON'),
|
|
1097
|
-
'Docker context inspection was empty',
|
|
1098
|
-
);
|
|
1099
|
-
const endpoints = field(context, 'Endpoints', 'endpoints');
|
|
1100
|
-
const dockerEndpoint = isRecord(endpoints) ? field(endpoints, 'docker', 'Docker') : undefined;
|
|
1101
|
-
const contextHost = isRecord(dockerEndpoint)
|
|
1102
|
-
? field(dockerEndpoint, 'Host', 'host')
|
|
1103
|
-
: undefined;
|
|
1104
|
-
if (typeof contextHost !== 'string' || !contextHost.startsWith('unix://')) {
|
|
1105
|
-
throw new RunnerError('Remote Docker contexts are not supported');
|
|
1106
|
-
}
|
|
1107
|
-
const environmentHost = this.runtimeEnvironment.DOCKER_HOST;
|
|
1108
|
-
if (environmentHost !== undefined && !environmentHost.startsWith('unix://')) {
|
|
1109
|
-
throw new RunnerError('Remote Docker endpoints are not supported');
|
|
1110
|
-
}
|
|
1111
|
-
endpoint = environmentHost ?? contextHost;
|
|
1112
|
-
const infoResult = await this.runRuntime(['info', '--format', 'json']);
|
|
1113
|
-
requireSuccess(infoResult, 'Unable to inspect the Docker engine');
|
|
1114
|
-
const info = firstObject(
|
|
1115
|
-
parseJson(infoResult.stdout, 'Docker info was not valid JSON'),
|
|
1116
|
-
'Docker info was empty',
|
|
1117
|
-
);
|
|
1118
|
-
os = String(field(info, 'OSType', 'OsType', 'osType') ?? '');
|
|
1119
|
-
architectureValue = String(field(info, 'Architecture', 'architecture') ?? '');
|
|
1120
|
-
const securityOptions = field(info, 'SecurityOptions', 'securityOptions');
|
|
1121
|
-
rootless = Array.isArray(securityOptions) &&
|
|
1122
|
-
securityOptions.some((entry) =>
|
|
1123
|
-
typeof entry === 'string' && entry.toLowerCase().includes('rootless')
|
|
1124
|
-
);
|
|
1125
|
-
} else {
|
|
1126
|
-
const connectionsResult = await this.runRuntime([
|
|
1127
|
-
'system',
|
|
1128
|
-
'connection',
|
|
1129
|
-
'list',
|
|
1130
|
-
'--format',
|
|
1131
|
-
'json',
|
|
1132
|
-
]);
|
|
1133
|
-
requireSuccess(connectionsResult, 'Unable to inspect Podman system connections');
|
|
1134
|
-
const connectionsValue = parseJson(
|
|
1135
|
-
connectionsResult.stdout,
|
|
1136
|
-
'Podman connection list was not valid JSON',
|
|
1137
|
-
);
|
|
1138
|
-
const connections = Array.isArray(connectionsValue) ? connectionsValue.filter(isRecord) : [];
|
|
1139
|
-
const selectedConnection = this.runtimeEnvironment.CONTAINER_CONNECTION;
|
|
1140
|
-
const selected = selectedConnection
|
|
1141
|
-
? connections.find((entry) => field(entry, 'Name', 'name') === selectedConnection)
|
|
1142
|
-
: undefined;
|
|
1143
|
-
if (selectedConnection && !selected) {
|
|
1144
|
-
throw new RunnerError('Active Podman system connection was not found');
|
|
1145
|
-
}
|
|
1146
|
-
const defaultConnection = connections.find((entry) =>
|
|
1147
|
-
field(entry, 'Default', 'default') === true
|
|
1148
|
-
);
|
|
1149
|
-
const environmentHost = this.runtimeEnvironment.CONTAINER_HOST;
|
|
1150
|
-
const selectedUri = selected ? field(selected, 'URI', 'Uri', 'uri') : undefined;
|
|
1151
|
-
const defaultUri = defaultConnection
|
|
1152
|
-
? field(defaultConnection, 'URI', 'Uri', 'uri')
|
|
1153
|
-
: undefined;
|
|
1154
|
-
for (const candidate of [environmentHost, selectedUri]) {
|
|
1155
|
-
if (
|
|
1156
|
-
candidate !== undefined &&
|
|
1157
|
-
(typeof candidate !== 'string' || !candidate.startsWith('unix://'))
|
|
1158
|
-
) {
|
|
1159
|
-
throw new RunnerError('Remote Podman endpoints are not supported');
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
const infoResult = await this.runRuntime(['info', '--format', 'json']);
|
|
1163
|
-
requireSuccess(infoResult, 'Unable to inspect the Podman engine');
|
|
1164
|
-
const info = firstObject(
|
|
1165
|
-
parseJson(infoResult.stdout, 'Podman info was not valid JSON'),
|
|
1166
|
-
'Podman info was empty',
|
|
1167
|
-
);
|
|
1168
|
-
const host = field(info, 'host', 'Host');
|
|
1169
|
-
if (!isRecord(host)) throw new RunnerError('Podman info omitted host details');
|
|
1170
|
-
const serviceIsRemote = field(host, 'serviceIsRemote', 'ServiceIsRemote') === true;
|
|
1171
|
-
const security = field(host, 'security', 'Security');
|
|
1172
|
-
rootless = isRecord(security) && field(security, 'rootless', 'Rootless') === true;
|
|
1173
|
-
os = String(field(host, 'os', 'Os') ?? '');
|
|
1174
|
-
architectureValue = String(field(host, 'arch', 'Arch') ?? '');
|
|
1175
|
-
const remoteSocket = field(host, 'remoteSocket', 'RemoteSocket');
|
|
1176
|
-
const socketPath = isRecord(remoteSocket) ? field(remoteSocket, 'path', 'Path') : undefined;
|
|
1177
|
-
const connectionUri = typeof selectedUri === 'string'
|
|
1178
|
-
? selectedUri
|
|
1179
|
-
: typeof defaultUri === 'string'
|
|
1180
|
-
? defaultUri
|
|
1181
|
-
: undefined;
|
|
1182
|
-
endpoint = environmentHost ?? (serviceIsRemote ? connectionUri : undefined) ??
|
|
1183
|
-
(typeof socketPath === 'string' ? `unix://${socketPath}` : '');
|
|
1184
|
-
if (!endpoint.startsWith('unix://')) {
|
|
1185
|
-
throw new RunnerError('Remote Podman endpoints are not supported');
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
if (os.toLowerCase() !== 'linux') throw new RunnerError('OCI runner requires a Linux engine');
|
|
1190
|
-
if (this.config.oci.requireRootless && !rootless) {
|
|
1191
|
-
throw new RunnerError('Runner policy requires a rootless OCI engine');
|
|
1192
|
-
}
|
|
1193
|
-
const architecture = mapArchitecture(architectureValue);
|
|
1194
|
-
const helperSourcePath = await this.resolveHelperPathImplementation(architecture.helperTarget);
|
|
1195
|
-
const helperPath = await this.materializeWorkspaceHelper(
|
|
1196
|
-
helperSourcePath,
|
|
1197
|
-
architecture.helperTarget,
|
|
1198
|
-
);
|
|
1199
|
-
const runtimeProbeOwnerId = await this.ensureRuntimeProbeOwner();
|
|
1200
|
-
const helperStat = await plugins.fs.stat(helperPath).catch((error) => {
|
|
1201
|
-
throw new RunnerError('Workspace helper is unavailable', { cause: error });
|
|
1202
|
-
});
|
|
1203
|
-
if (!helperStat.isFile() || (helperStat.mode & 0o111) === 0) {
|
|
1204
|
-
throw new RunnerError('Workspace helper is not an executable regular file');
|
|
1205
|
-
}
|
|
1206
|
-
const hostProbe = await this.runHostHelper(helperPath, ['probe']);
|
|
1207
|
-
requireSuccess(hostProbe, 'Workspace helper host probe failed');
|
|
1208
|
-
const hostProbeValue = firstObject(
|
|
1209
|
-
parseJson(hostProbe.stdout, 'Workspace helper host probe was not valid JSON'),
|
|
1210
|
-
'Workspace helper host probe was empty',
|
|
1211
|
-
);
|
|
1212
|
-
if (field(hostProbeValue, 'os') !== 'linux') {
|
|
1213
|
-
throw new RunnerError('Workspace helper does not target Linux');
|
|
1214
|
-
}
|
|
1215
|
-
const helperArchitecture = mapArchitecture(String(field(hostProbeValue, 'architecture') ?? ''));
|
|
1216
|
-
if (helperArchitecture.helperTarget !== architecture.helperTarget) {
|
|
1217
|
-
throw new RunnerError('Workspace helper architecture does not match the OCI engine');
|
|
1218
|
-
}
|
|
1219
|
-
const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath, runtimeProbeOwnerId);
|
|
1220
|
-
await this.reconcileRuntimeProbeVolumes(runtimeProbeOwnerId);
|
|
1221
|
-
await this.probeRuntimeVolume(workspaceBlockSize, runtimeProbeOwnerId);
|
|
1222
|
-
const facts: IOciRuntimeFacts = {
|
|
1223
|
-
runtime,
|
|
1224
|
-
endpoint,
|
|
1225
|
-
rootless,
|
|
1226
|
-
os: 'linux',
|
|
1227
|
-
architecture: architecture.architecture,
|
|
1228
|
-
helperTarget: architecture.helperTarget,
|
|
1229
|
-
helperPath,
|
|
1230
|
-
helperSha256: await sha256File(helperPath),
|
|
1231
|
-
workspaceBlockSize: positiveSafeInteger(workspaceBlockSize, 'Workspace block size'),
|
|
1232
|
-
};
|
|
1233
|
-
this.runtimeFacts = Object.freeze(facts);
|
|
1234
|
-
return this.runtimeFacts;
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
async prepareLease(context: IPrepareOciLeaseContext): Promise<IPreparedOciLease> {
|
|
1238
|
-
const facts = this.requireRuntimeFacts();
|
|
1239
|
-
this.validateLeaseIdentity(context.runnerId, context.sessionId, context.lease);
|
|
1240
|
-
validateLeasePolicy(this.config, context);
|
|
1241
|
-
if (context.signal.aborted) throw context.signal.reason;
|
|
1242
|
-
const image = context.lease.job.execution.image;
|
|
1243
|
-
let inspectionResult = await this.runRuntime(['image', 'inspect', image]);
|
|
1244
|
-
if (!inspectionResult.success) {
|
|
1245
|
-
const pullResult = await this.runRuntime(
|
|
1246
|
-
['pull', image],
|
|
1247
|
-
runtimeCommandTimeoutMs,
|
|
1248
|
-
context.signal,
|
|
1249
|
-
);
|
|
1250
|
-
requireSuccess(pullResult, 'Unable to pull the digest-pinned job image');
|
|
1251
|
-
inspectionResult = await this.runRuntime(['image', 'inspect', image]);
|
|
1252
|
-
}
|
|
1253
|
-
requireSuccess(inspectionResult, 'Unable to inspect the digest-pinned job image');
|
|
1254
|
-
const inspection = this.parseImageInspection(inspectionResult.stdout);
|
|
1255
|
-
const requestedDigest = image.slice(image.indexOf('@') + 1);
|
|
1256
|
-
if (
|
|
1257
|
-
!inspection.repoDigests.some((entry) => entry.endsWith(`@${requestedDigest}`)) &&
|
|
1258
|
-
inspection.digest !== requestedDigest
|
|
1259
|
-
) {
|
|
1260
|
-
throw new RunnerError('Local image does not match the requested manifest digest');
|
|
1261
|
-
}
|
|
1262
|
-
if (inspection.os.toLowerCase() !== 'linux') {
|
|
1263
|
-
throw new RunnerError('Job image does not target Linux');
|
|
1264
|
-
}
|
|
1265
|
-
const imageArchitecture = mapArchitecture(inspection.architecture).architecture;
|
|
1266
|
-
if (imageArchitecture !== facts.architecture) {
|
|
1267
|
-
throw new RunnerError('Job image architecture does not match the OCI engine');
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
const probeName = this.createResourceName('probe');
|
|
1271
|
-
const probeCommand = buildOciHelperCreateCommand(this.config, {
|
|
1272
|
-
runnerId: context.runnerId,
|
|
1273
|
-
sessionId: context.sessionId,
|
|
1274
|
-
attemptId: context.lease.attemptId,
|
|
1275
|
-
containerName: probeName,
|
|
1276
|
-
image,
|
|
1277
|
-
helperPath: facts.helperPath,
|
|
1278
|
-
command: ['probe'],
|
|
1279
|
-
});
|
|
1280
|
-
const output = await this.runInertContainer(
|
|
1281
|
-
probeName,
|
|
1282
|
-
probeCommand,
|
|
1283
|
-
context.signal,
|
|
1284
|
-
undefined,
|
|
1285
|
-
undefined,
|
|
1286
|
-
);
|
|
1287
|
-
const probe = firstObject(
|
|
1288
|
-
parseJson(output, 'Workspace helper image probe was not valid JSON'),
|
|
1289
|
-
'Workspace helper image probe was empty',
|
|
1290
|
-
);
|
|
1291
|
-
if (
|
|
1292
|
-
field(probe, 'os') !== 'linux' ||
|
|
1293
|
-
mapArchitecture(String(field(probe, 'architecture') ?? '')).architecture !==
|
|
1294
|
-
facts.architecture
|
|
1295
|
-
) {
|
|
1296
|
-
throw new RunnerError('Workspace helper image probe did not match verified runtime facts');
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
const preparationId = this.randomHex();
|
|
1300
|
-
const prepared = new PreparedOciLease(
|
|
1301
|
-
preparationId,
|
|
1302
|
-
context.lease.attemptId,
|
|
1303
|
-
image,
|
|
1304
|
-
imageArchitecture,
|
|
1305
|
-
() => this.preparedLeases.delete(preparationId),
|
|
1306
|
-
);
|
|
1307
|
-
this.preparedLeases.set(preparationId, prepared);
|
|
1308
|
-
return prepared;
|
|
1309
|
-
}
|
|
1310
|
-
|
|
1311
|
-
async reconcileOrphans(runnerId: string, currentSessionId: string): Promise<void> {
|
|
1312
|
-
validateIdentifier(runnerId, 'runnerId');
|
|
1313
|
-
validateIdentifier(currentSessionId, 'sessionId');
|
|
1314
|
-
const containers = await this.runRuntime([
|
|
1315
|
-
'ps',
|
|
1316
|
-
'--all',
|
|
1317
|
-
'--filter',
|
|
1318
|
-
`label=${managedLabel}=true`,
|
|
1319
|
-
'--filter',
|
|
1320
|
-
`label=${runnerLabel}=${runnerId}`,
|
|
1321
|
-
'--format',
|
|
1322
|
-
`{{.Names}}|{{.Label "${sessionLabel}"}}`,
|
|
1323
|
-
]);
|
|
1324
|
-
requireSuccess(containers, 'Unable to enumerate orphan OCI containers');
|
|
1325
|
-
for (const line of decode(containers.stdout).split('\n').filter(Boolean)) {
|
|
1326
|
-
const [name, sessionId] = line.split('|', 2);
|
|
1327
|
-
if (
|
|
1328
|
-
/^shipzone-ci-(?:helper|probe|step)-[a-f0-9]{32}$/.test(name) &&
|
|
1329
|
-
sessionId !== currentSessionId
|
|
1330
|
-
) {
|
|
1331
|
-
await this.stopAndRemoveContainer(name);
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
const volumes = await this.runRuntime([
|
|
1335
|
-
'volume',
|
|
1336
|
-
'ls',
|
|
1337
|
-
'--filter',
|
|
1338
|
-
`label=${managedLabel}=true`,
|
|
1339
|
-
'--filter',
|
|
1340
|
-
`label=${runnerLabel}=${runnerId}`,
|
|
1341
|
-
'--format',
|
|
1342
|
-
`{{.Name}}|{{.Label "${sessionLabel}"}}`,
|
|
1343
|
-
]);
|
|
1344
|
-
requireSuccess(volumes, 'Unable to enumerate orphan OCI volumes');
|
|
1345
|
-
for (const line of decode(volumes.stdout).split('\n').filter(Boolean)) {
|
|
1346
|
-
const [name, sessionId] = line.split('|', 2);
|
|
1347
|
-
if (/^shipzone-ci-volume-[a-f0-9]{32}$/.test(name) && sessionId !== currentSessionId) {
|
|
1348
|
-
await this.removeVolume(name);
|
|
1349
|
-
}
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
async execute(context: IExecutionContext): Promise<IExecutionResult> {
|
|
1354
|
-
const facts = this.requireRuntimeFacts();
|
|
1355
|
-
this.validateLeaseIdentity(context.runnerId, context.sessionId, context.lease);
|
|
1356
|
-
validateLeasePolicy(this.config, context);
|
|
1357
|
-
const prepared = this.preparedLeases.get(context.preparedLease.preparationId);
|
|
1358
|
-
if (
|
|
1359
|
-
!prepared ||
|
|
1360
|
-
prepared !== context.preparedLease ||
|
|
1361
|
-
prepared.attemptId !== context.lease.attemptId ||
|
|
1362
|
-
prepared.image !== context.lease.job.execution.image
|
|
1363
|
-
) {
|
|
1364
|
-
throw new RunnerError('Execution requires a matching active OCI lease preparation');
|
|
1365
|
-
}
|
|
1366
|
-
prepared.consume();
|
|
1367
|
-
if (context.signal.aborted) {
|
|
1368
|
-
return {
|
|
1369
|
-
exitCode: null,
|
|
1370
|
-
stopReason: isStopReason(context.signal.reason) ? context.signal.reason : 'runner_shutdown',
|
|
1371
|
-
};
|
|
1372
|
-
}
|
|
1373
|
-
const workspaceBytes = context.lease.job.requirements.limits.maximumWorkspaceBytes;
|
|
1374
|
-
const workspaceEntries = context.lease.job.requirements.limits.maximumWorkspaceEntries;
|
|
1375
|
-
validateHostMountPath(context.workspacePath, 'Attempt staging workspace');
|
|
1376
|
-
const volumeLimits = calculateWorkspaceVolumeLimits(
|
|
1377
|
-
workspaceBytes,
|
|
1378
|
-
workspaceEntries,
|
|
1379
|
-
facts.workspaceBlockSize,
|
|
1380
|
-
);
|
|
1381
|
-
const volumeName = this.createResourceName('volume');
|
|
1382
|
-
const activeContainers = new Set<string>();
|
|
1383
|
-
const lifetimeContainers = new Set<string>();
|
|
1384
|
-
const exportPaths = new Set<string>();
|
|
1385
|
-
if (!Number.isSafeInteger(context.timeoutMs) || context.timeoutMs < 0) {
|
|
1386
|
-
throw new RunnerError('Execution requires a non-negative remaining attempt timeout');
|
|
1387
|
-
}
|
|
1388
|
-
const deadline = this.now() + context.timeoutMs;
|
|
1389
|
-
let stopReason: TExecutionStopReason | undefined;
|
|
1390
|
-
let activeContainer: string | undefined;
|
|
1391
|
-
const stopPromises = new Map<string, Promise<void>>();
|
|
1392
|
-
let volumePossiblyExists = false;
|
|
1393
|
-
let handedOff = false;
|
|
1394
|
-
let setupComplete = false;
|
|
1395
|
-
|
|
1396
|
-
const terminationDeadline = (): number | undefined => context.terminationDeadline?.();
|
|
1397
|
-
const trackStop = (name: string): Promise<void> => {
|
|
1398
|
-
let promise = stopPromises.get(name);
|
|
1399
|
-
if (!promise) {
|
|
1400
|
-
promise = this.stopContainer(name, terminationDeadline, context.signal);
|
|
1401
|
-
stopPromises.set(name, promise);
|
|
1402
|
-
void promise.catch(() => undefined);
|
|
1403
|
-
}
|
|
1404
|
-
return promise;
|
|
1405
|
-
};
|
|
1406
|
-
const awaitStops = async (): Promise<void> => {
|
|
1407
|
-
const settled = await Promise.allSettled(stopPromises.values());
|
|
1408
|
-
const errors = settled.flatMap((result) =>
|
|
1409
|
-
result.status === 'rejected' ? [result.reason] : []
|
|
1410
|
-
);
|
|
1411
|
-
if (errors.length) {
|
|
1412
|
-
throw new AggregateError(errors, 'Unable to stop OCI execution containers');
|
|
1413
|
-
}
|
|
1414
|
-
};
|
|
1415
|
-
const stopActive = (reason: TExecutionStopReason): void => {
|
|
1416
|
-
stopReason ??= reason;
|
|
1417
|
-
const name = activeContainer;
|
|
1418
|
-
if (name) trackStop(name);
|
|
1419
|
-
};
|
|
1420
|
-
const abortListener = (): void =>
|
|
1421
|
-
stopActive(isStopReason(context.signal.reason) ? context.signal.reason : 'runner_shutdown');
|
|
1422
|
-
context.signal.addEventListener('abort', abortListener, { once: true });
|
|
1423
|
-
const timeout = setTimeout(() => stopActive('job_timeout'), context.timeoutMs);
|
|
1424
|
-
const setActive = (name: string | undefined): boolean => {
|
|
1425
|
-
activeContainer = name;
|
|
1426
|
-
if (name && stopReason) stopActive(stopReason);
|
|
1427
|
-
return stopReason !== undefined;
|
|
1428
|
-
};
|
|
1429
|
-
const commandTimeout = (): number =>
|
|
1430
|
-
Math.max(1, Math.min(runtimeCommandTimeoutMs, deadline - this.now()));
|
|
1431
|
-
const remainingJobTimeout = (): number => Math.max(1, deadline - this.now() + 5_000);
|
|
1432
|
-
|
|
1433
|
-
const cleanupVolume = async (): Promise<void> => {
|
|
1434
|
-
const errors: unknown[] = [];
|
|
1435
|
-
for (const name of [...activeContainers, ...lifetimeContainers]) {
|
|
1436
|
-
await this.stopAndRemoveContainer(name, terminationDeadline, context.signal).then(
|
|
1437
|
-
() => {
|
|
1438
|
-
activeContainers.delete(name);
|
|
1439
|
-
lifetimeContainers.delete(name);
|
|
1440
|
-
},
|
|
1441
|
-
(error) => errors.push(error),
|
|
1442
|
-
);
|
|
1443
|
-
}
|
|
1444
|
-
for (const path of [...exportPaths]) {
|
|
1445
|
-
await this.removePath(path).then(
|
|
1446
|
-
() => exportPaths.delete(path),
|
|
1447
|
-
(error) => errors.push(error),
|
|
1448
|
-
);
|
|
1449
|
-
}
|
|
1450
|
-
if (volumePossiblyExists) {
|
|
1451
|
-
await this.removeVolume(volumeName).then(
|
|
1452
|
-
() => {
|
|
1453
|
-
volumePossiblyExists = false;
|
|
1454
|
-
},
|
|
1455
|
-
(error) => errors.push(error),
|
|
1456
|
-
);
|
|
1457
|
-
}
|
|
1458
|
-
if (errors.length) {
|
|
1459
|
-
throw new ResourceCleanupError('Unable to clean OCI workspace resources', errors);
|
|
1460
|
-
}
|
|
1461
|
-
};
|
|
1462
|
-
|
|
1463
|
-
let workspaceClosed = false;
|
|
1464
|
-
const exportSelected = async (request: IWorkspaceExportRequest): Promise<IWorkspaceExport> => {
|
|
1465
|
-
if (workspaceClosed) throw new RunnerError('Runtime workspace has already been cleaned');
|
|
1466
|
-
const selections = safeSelections(request.selections);
|
|
1467
|
-
nonNegativeSafeInteger(request.maximumBytes, 'Workspace export byte limit');
|
|
1468
|
-
positiveSafeInteger(request.maximumEntries, 'Workspace export entry limit');
|
|
1469
|
-
if (request.maximumBytes > workspaceBytes || request.maximumEntries > workspaceEntries) {
|
|
1470
|
-
throw new ProtocolError('Workspace export limits exceed the accepted workspace limits');
|
|
1471
|
-
}
|
|
1472
|
-
if (request.signal?.aborted) throw request.signal.reason;
|
|
1473
|
-
this.stateOwner.assertHeld();
|
|
1474
|
-
const root = join(this.stateOwner.stateDirectory, 'workspace-exports');
|
|
1475
|
-
await plugins.fs.mkdir(root, { recursive: true, mode: 0o700 });
|
|
1476
|
-
const path = await this.makeTempDir({ dir: root, prefix: `${context.lease.attemptId}-` });
|
|
1477
|
-
exportPaths.add(path);
|
|
1478
|
-
let exportCleaned = false;
|
|
1479
|
-
let exportCleanup: Promise<void> | undefined;
|
|
1480
|
-
const cleanup = (): Promise<void> => {
|
|
1481
|
-
if (exportCleaned) return Promise.resolve();
|
|
1482
|
-
exportCleanup ??= this.removePath(path).then(
|
|
1483
|
-
() => {
|
|
1484
|
-
exportCleaned = true;
|
|
1485
|
-
exportPaths.delete(path);
|
|
1486
|
-
},
|
|
1487
|
-
(error) => {
|
|
1488
|
-
exportCleanup = undefined;
|
|
1489
|
-
throw error;
|
|
1490
|
-
},
|
|
1491
|
-
);
|
|
1492
|
-
return exportCleanup;
|
|
1493
|
-
};
|
|
1494
|
-
try {
|
|
1495
|
-
await this.chmod(path, 0o700);
|
|
1496
|
-
const name = this.createResourceName('helper');
|
|
1497
|
-
const helperCommand = buildOciHelperCreateCommand(this.config, {
|
|
1498
|
-
runnerId: context.runnerId,
|
|
1499
|
-
sessionId: context.sessionId,
|
|
1500
|
-
attemptId: context.lease.attemptId,
|
|
1501
|
-
containerName: name,
|
|
1502
|
-
image: prepared.image,
|
|
1503
|
-
helperPath: facts.helperPath,
|
|
1504
|
-
volumeName,
|
|
1505
|
-
destinationPath: path,
|
|
1506
|
-
command: [
|
|
1507
|
-
'export',
|
|
1508
|
-
'--workspace',
|
|
1509
|
-
'/volume/workspace',
|
|
1510
|
-
'--destination',
|
|
1511
|
-
'/export',
|
|
1512
|
-
...selections.flatMap((selection) => ['--selection', selection]),
|
|
1513
|
-
'--maximum-bytes',
|
|
1514
|
-
String(request.maximumBytes),
|
|
1515
|
-
'--maximum-entries',
|
|
1516
|
-
String(request.maximumEntries),
|
|
1517
|
-
],
|
|
1518
|
-
});
|
|
1519
|
-
const output = await this.runInertContainer(
|
|
1520
|
-
name,
|
|
1521
|
-
helperCommand,
|
|
1522
|
-
request.signal,
|
|
1523
|
-
activeContainers,
|
|
1524
|
-
terminationDeadline,
|
|
1525
|
-
);
|
|
1526
|
-
const counts = this.parseCounts(output, 'Workspace export helper');
|
|
1527
|
-
return {
|
|
1528
|
-
path,
|
|
1529
|
-
metadata: { logicalBytes: counts.bytes, entryCount: counts.entries },
|
|
1530
|
-
cleanup,
|
|
1531
|
-
};
|
|
1532
|
-
} catch (error) {
|
|
1533
|
-
try {
|
|
1534
|
-
await cleanup();
|
|
1535
|
-
} catch (cleanupError) {
|
|
1536
|
-
throw new ResourceCleanupError(
|
|
1537
|
-
'Workspace export and cleanup both failed',
|
|
1538
|
-
[error, cleanupError],
|
|
1539
|
-
);
|
|
1540
|
-
}
|
|
1541
|
-
throw error;
|
|
1542
|
-
}
|
|
1543
|
-
};
|
|
1544
|
-
|
|
1545
|
-
let lifetimeCleanup: Promise<void> | undefined;
|
|
1546
|
-
const workspace: IRuntimeWorkspaceExporter = {
|
|
1547
|
-
exportSelected,
|
|
1548
|
-
cleanup: () => {
|
|
1549
|
-
workspaceClosed = true;
|
|
1550
|
-
lifetimeCleanup ??= cleanupVolume().catch((error) => {
|
|
1551
|
-
lifetimeCleanup = undefined;
|
|
1552
|
-
throw error;
|
|
1553
|
-
});
|
|
1554
|
-
return lifetimeCleanup;
|
|
1555
|
-
},
|
|
1556
|
-
};
|
|
1557
|
-
const result = (
|
|
1558
|
-
exitCode: number | null,
|
|
1559
|
-
reason?: TExecutionStopReason,
|
|
1560
|
-
): IExecutionResult => {
|
|
1561
|
-
handedOff = true;
|
|
1562
|
-
return { exitCode, ...(reason ? { stopReason: reason } : {}), workspace };
|
|
1563
|
-
};
|
|
1564
|
-
|
|
1565
|
-
let executionResult: IExecutionResult | undefined;
|
|
1566
|
-
let executionError: unknown;
|
|
1567
|
-
let hasExecutionError = false;
|
|
1568
|
-
try {
|
|
1569
|
-
executionResult = await (async (): Promise<IExecutionResult> => {
|
|
1570
|
-
volumePossiblyExists = true;
|
|
1571
|
-
const createVolume = await this.runRuntime(
|
|
1572
|
-
this.volumeCreateArgs(
|
|
1573
|
-
volumeName,
|
|
1574
|
-
volumeLimits,
|
|
1575
|
-
context.runnerId,
|
|
1576
|
-
context.sessionId,
|
|
1577
|
-
context.lease.attemptId,
|
|
1578
|
-
),
|
|
1579
|
-
commandTimeout(),
|
|
1580
|
-
);
|
|
1581
|
-
requireSuccess(createVolume, 'Unable to create the attempt tmpfs volume');
|
|
1582
|
-
|
|
1583
|
-
await this.startVolumeHolder(
|
|
1584
|
-
context,
|
|
1585
|
-
prepared.image,
|
|
1586
|
-
facts.helperPath,
|
|
1587
|
-
volumeName,
|
|
1588
|
-
lifetimeContainers,
|
|
1589
|
-
commandTimeout,
|
|
1590
|
-
);
|
|
1591
|
-
|
|
1592
|
-
await this.runWorkspaceHelper(
|
|
1593
|
-
context,
|
|
1594
|
-
prepared.image,
|
|
1595
|
-
facts.helperPath,
|
|
1596
|
-
volumeName,
|
|
1597
|
-
(() => {
|
|
1598
|
-
const { uid, gid } = parseContainerUser(this.config.oci.containerUser);
|
|
1599
|
-
return [
|
|
1600
|
-
'reserve',
|
|
1601
|
-
'--volume',
|
|
1602
|
-
'/volume',
|
|
1603
|
-
'--workspace-bytes',
|
|
1604
|
-
String(workspaceBytes),
|
|
1605
|
-
'--workspace-entries',
|
|
1606
|
-
String(workspaceEntries),
|
|
1607
|
-
'--reserve-bytes',
|
|
1608
|
-
String(workspaceHelperReserveBytes),
|
|
1609
|
-
'--workspace-uid',
|
|
1610
|
-
String(uid),
|
|
1611
|
-
'--workspace-gid',
|
|
1612
|
-
String(gid),
|
|
1613
|
-
];
|
|
1614
|
-
})(),
|
|
1615
|
-
activeContainers,
|
|
1616
|
-
setActive,
|
|
1617
|
-
commandTimeout,
|
|
1618
|
-
);
|
|
1619
|
-
await this.runWorkspaceHelper(
|
|
1620
|
-
context,
|
|
1621
|
-
prepared.image,
|
|
1622
|
-
facts.helperPath,
|
|
1623
|
-
volumeName,
|
|
1624
|
-
(() => {
|
|
1625
|
-
const { uid, gid } = parseContainerUser(this.config.oci.containerUser);
|
|
1626
|
-
return [
|
|
1627
|
-
'import',
|
|
1628
|
-
'--source',
|
|
1629
|
-
'/staging',
|
|
1630
|
-
'--workspace',
|
|
1631
|
-
'/volume/workspace',
|
|
1632
|
-
'--maximum-bytes',
|
|
1633
|
-
String(workspaceBytes),
|
|
1634
|
-
'--maximum-entries',
|
|
1635
|
-
String(workspaceEntries),
|
|
1636
|
-
'--destination-uid',
|
|
1637
|
-
String(uid),
|
|
1638
|
-
'--destination-gid',
|
|
1639
|
-
String(gid),
|
|
1640
|
-
];
|
|
1641
|
-
})(),
|
|
1642
|
-
activeContainers,
|
|
1643
|
-
setActive,
|
|
1644
|
-
commandTimeout,
|
|
1645
|
-
context.workspacePath,
|
|
1646
|
-
);
|
|
1647
|
-
setupComplete = true;
|
|
1648
|
-
|
|
1649
|
-
for (const step of context.lease.job.steps) {
|
|
1650
|
-
if (stopReason) return result(null, stopReason);
|
|
1651
|
-
await this.measureWorkspace(
|
|
1652
|
-
context,
|
|
1653
|
-
prepared.image,
|
|
1654
|
-
facts.helperPath,
|
|
1655
|
-
volumeName,
|
|
1656
|
-
workspaceBytes,
|
|
1657
|
-
workspaceEntries,
|
|
1658
|
-
activeContainers,
|
|
1659
|
-
setActive,
|
|
1660
|
-
commandTimeout,
|
|
1661
|
-
);
|
|
1662
|
-
if (stopReason) return result(null, stopReason);
|
|
1663
|
-
const name = this.createResourceName('step');
|
|
1664
|
-
const command = buildOciRunCommand(this.config, {
|
|
1665
|
-
runnerId: context.runnerId,
|
|
1666
|
-
sessionId: context.sessionId,
|
|
1667
|
-
lease: context.lease,
|
|
1668
|
-
step,
|
|
1669
|
-
containerName: name,
|
|
1670
|
-
volumeName,
|
|
1671
|
-
});
|
|
1672
|
-
let state: IContainerState;
|
|
1673
|
-
try {
|
|
1674
|
-
state = await this.runStepContainer(
|
|
1675
|
-
name,
|
|
1676
|
-
command,
|
|
1677
|
-
context,
|
|
1678
|
-
activeContainers,
|
|
1679
|
-
commandTimeout,
|
|
1680
|
-
remainingJobTimeout,
|
|
1681
|
-
setActive,
|
|
1682
|
-
() => {
|
|
1683
|
-
stopReason ??= 'log_delivery_failed';
|
|
1684
|
-
return trackStop(name);
|
|
1685
|
-
},
|
|
1686
|
-
);
|
|
1687
|
-
} finally {
|
|
1688
|
-
setActive(undefined);
|
|
1689
|
-
}
|
|
1690
|
-
await awaitStops();
|
|
1691
|
-
if (stopReason) return result(null, stopReason);
|
|
1692
|
-
try {
|
|
1693
|
-
await this.measureWorkspace(
|
|
1694
|
-
context,
|
|
1695
|
-
prepared.image,
|
|
1696
|
-
facts.helperPath,
|
|
1697
|
-
volumeName,
|
|
1698
|
-
workspaceBytes,
|
|
1699
|
-
workspaceEntries,
|
|
1700
|
-
activeContainers,
|
|
1701
|
-
setActive,
|
|
1702
|
-
commandTimeout,
|
|
1703
|
-
);
|
|
1704
|
-
} catch (error) {
|
|
1705
|
-
if (error instanceof ResourceCleanupError) throw error;
|
|
1706
|
-
if (stopReason) return result(null, stopReason);
|
|
1707
|
-
if (error instanceof WorkspaceResourceError) return result(null, 'resource_limit');
|
|
1708
|
-
throw error;
|
|
1709
|
-
}
|
|
1710
|
-
if (stopReason) return result(null, stopReason);
|
|
1711
|
-
const capacity = await this.readWorkspaceCapacity(
|
|
1712
|
-
context,
|
|
1713
|
-
prepared.image,
|
|
1714
|
-
facts.helperPath,
|
|
1715
|
-
volumeName,
|
|
1716
|
-
activeContainers,
|
|
1717
|
-
setActive,
|
|
1718
|
-
commandTimeout,
|
|
1719
|
-
);
|
|
1720
|
-
if (
|
|
1721
|
-
state.oomKilled ||
|
|
1722
|
-
state.error ||
|
|
1723
|
-
capacity.availableBlocks === 0 ||
|
|
1724
|
-
capacity.availableInodes === 0
|
|
1725
|
-
) {
|
|
1726
|
-
return result(null, 'resource_limit');
|
|
1727
|
-
}
|
|
1728
|
-
if (state.exitCode !== 0) return result(state.exitCode);
|
|
1729
|
-
}
|
|
1730
|
-
return result(0);
|
|
1731
|
-
})();
|
|
1732
|
-
} catch (error) {
|
|
1733
|
-
if (error instanceof ResourceCleanupError) {
|
|
1734
|
-
executionError = error;
|
|
1735
|
-
hasExecutionError = true;
|
|
1736
|
-
} else if (stopReason && setupComplete) {
|
|
1737
|
-
executionResult = result(null, stopReason);
|
|
1738
|
-
} else {
|
|
1739
|
-
executionError = error;
|
|
1740
|
-
hasExecutionError = true;
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
clearTimeout(timeout);
|
|
1744
|
-
context.signal.removeEventListener('abort', abortListener);
|
|
1745
|
-
const stopErrors: unknown[] = [];
|
|
1746
|
-
await awaitStops().catch((error) => stopErrors.push(error));
|
|
1747
|
-
const cleanupErrors: unknown[] = [];
|
|
1748
|
-
if (handedOff) {
|
|
1749
|
-
for (const name of [...activeContainers]) {
|
|
1750
|
-
await this.stopAndRemoveContainer(name, terminationDeadline, context.signal).then(
|
|
1751
|
-
() => activeContainers.delete(name),
|
|
1752
|
-
(error) => cleanupErrors.push(error),
|
|
1753
|
-
);
|
|
1754
|
-
}
|
|
1755
|
-
} else {
|
|
1756
|
-
await cleanupVolume().catch((error) => cleanupErrors.push(error));
|
|
1757
|
-
}
|
|
1758
|
-
if (cleanupErrors.length) {
|
|
1759
|
-
throw new ResourceCleanupError(
|
|
1760
|
-
hasExecutionError
|
|
1761
|
-
? 'OCI execution setup and cleanup both failed'
|
|
1762
|
-
: handedOff
|
|
1763
|
-
? 'Unable to clean OCI execution containers'
|
|
1764
|
-
: 'Unable to clean OCI workspace resources',
|
|
1765
|
-
[
|
|
1766
|
-
...(hasExecutionError ? [executionError] : []),
|
|
1767
|
-
...stopErrors,
|
|
1768
|
-
...cleanupErrors,
|
|
1769
|
-
],
|
|
1770
|
-
);
|
|
1771
|
-
}
|
|
1772
|
-
if (hasExecutionError) throw executionError;
|
|
1773
|
-
if (!executionResult) throw new RunnerError('OCI execution produced no result');
|
|
1774
|
-
return executionResult;
|
|
1775
|
-
}
|
|
1776
|
-
|
|
1777
|
-
private requireRuntimeFacts(): IOciRuntimeFacts {
|
|
1778
|
-
if (!this.runtimeFacts) {
|
|
1779
|
-
throw new RunnerError('OCI runtime must be verified before preparing or executing work');
|
|
1780
|
-
}
|
|
1781
|
-
return this.runtimeFacts;
|
|
1782
|
-
}
|
|
1783
|
-
|
|
1784
|
-
private validateLeaseIdentity(runnerId: string, sessionId: string, lease: IOciJobLease): void {
|
|
1785
|
-
validateIdentifier(runnerId, 'runnerId');
|
|
1786
|
-
validateIdentifier(sessionId, 'sessionId');
|
|
1787
|
-
validateIdentifier(lease.jobId, 'jobId');
|
|
1788
|
-
validateIdentifier(lease.attemptId, 'attemptId');
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
|
-
private async resolvePackagedHelper(target: TOciHelperTarget): Promise<string> {
|
|
1792
|
-
return await plugins.fs.realpath(
|
|
1793
|
-
this.config.oci.workspaceHelperPath ?? await resolvePackagedWorkspaceHelperPath(target),
|
|
1794
|
-
);
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
private async materializeWorkspaceHelper(
|
|
1798
|
-
sourcePathArg: string,
|
|
1799
|
-
targetArg: TOciHelperTarget,
|
|
1800
|
-
): Promise<string> {
|
|
1801
|
-
const sourcePath = await plugins.fs.realpath(sourcePathArg).catch((error) => {
|
|
1802
|
-
throw new RunnerError('Workspace helper source is unavailable', { cause: error });
|
|
1803
|
-
});
|
|
1804
|
-
const sourceBytes = (
|
|
1805
|
-
await readBoundedRegularFile(
|
|
1806
|
-
sourcePath,
|
|
1807
|
-
workspaceHelperMaximumBytes,
|
|
1808
|
-
'Workspace helper source',
|
|
1809
|
-
)
|
|
1810
|
-
).bytes;
|
|
1811
|
-
const sourceDigest = sha256Hex(sourceBytes);
|
|
1812
|
-
const destinationName = `runnerworkspace_${targetArg}_musl_${sourceDigest}`;
|
|
1813
|
-
return await this.stateOwner.serialize(async () => {
|
|
1814
|
-
const helperDirectory = await this.ensureWorkspaceHelperDirectory();
|
|
1815
|
-
const destinationPath = join(helperDirectory, destinationName);
|
|
1816
|
-
const temporaryUsage = await this.scavengeWorkspaceHelpers(
|
|
1817
|
-
helperDirectory,
|
|
1818
|
-
destinationName,
|
|
1819
|
-
sourceDigest,
|
|
1820
|
-
);
|
|
1821
|
-
if (await lstatIfPresent(destinationPath)) {
|
|
1822
|
-
await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
|
|
1823
|
-
return await plugins.fs.realpath(destinationPath);
|
|
1824
|
-
}
|
|
1825
|
-
if (
|
|
1826
|
-
temporaryUsage.count >= workspaceHelperTemporaryMaximumCount ||
|
|
1827
|
-
temporaryUsage.bytes > workspaceHelperTemporaryMaximumBytes - sourceBytes.byteLength
|
|
1828
|
-
) {
|
|
1829
|
-
throw new RunnerError('Workspace helper temporary storage limit is exhausted');
|
|
1830
|
-
}
|
|
1831
|
-
|
|
1832
|
-
const temporaryPath = join(
|
|
1833
|
-
helperDirectory,
|
|
1834
|
-
`.${plugins.crypto.randomUUID()}.workspace-helper.tmp`,
|
|
1835
|
-
);
|
|
1836
|
-
try {
|
|
1837
|
-
await withOpenFile(
|
|
1838
|
-
temporaryPath,
|
|
1839
|
-
createNewWriteFlags,
|
|
1840
|
-
0o600,
|
|
1841
|
-
async (openedFile) => {
|
|
1842
|
-
await writeAll(openedFile, sourceBytes, 'Workspace helper write made no progress');
|
|
1843
|
-
await openedFile.sync();
|
|
1844
|
-
},
|
|
1845
|
-
'Workspace helper write and close failed',
|
|
1846
|
-
);
|
|
1847
|
-
await this.validateMaterializedWorkspaceHelper(temporaryPath, sourceDigest, true);
|
|
1848
|
-
try {
|
|
1849
|
-
await plugins.fs.link(temporaryPath, destinationPath);
|
|
1850
|
-
} catch (error) {
|
|
1851
|
-
if (!isAlreadyExists(error)) throw error;
|
|
1852
|
-
await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
|
|
1853
|
-
}
|
|
1854
|
-
await removePath(temporaryPath);
|
|
1855
|
-
await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
|
|
1856
|
-
await this.syncDirectory(helperDirectory);
|
|
1857
|
-
return await plugins.fs.realpath(destinationPath);
|
|
1858
|
-
} catch (error) {
|
|
1859
|
-
try {
|
|
1860
|
-
await removePath(temporaryPath);
|
|
1861
|
-
} catch (cleanupError) {
|
|
1862
|
-
if (!isNotFound(cleanupError)) {
|
|
1863
|
-
throw new ResourceCleanupError('Workspace helper setup and cleanup failed', [
|
|
1864
|
-
error,
|
|
1865
|
-
cleanupError,
|
|
1866
|
-
]);
|
|
1867
|
-
}
|
|
1868
|
-
}
|
|
1869
|
-
throw error;
|
|
1870
|
-
}
|
|
1871
|
-
});
|
|
1872
|
-
}
|
|
1873
|
-
|
|
1874
|
-
private async ensureWorkspaceHelperDirectory(): Promise<string> {
|
|
1875
|
-
this.stateOwner.assertHeld();
|
|
1876
|
-
const stateRoot = await ensurePrivateStateDirectory(this.stateOwner.stateDirectory);
|
|
1877
|
-
|
|
1878
|
-
const helperDirectory = join(stateRoot, workspaceHelperDirectoryName);
|
|
1879
|
-
try {
|
|
1880
|
-
await plugins.fs.mkdir(helperDirectory, { mode: 0o700 });
|
|
1881
|
-
} catch (error) {
|
|
1882
|
-
if (!isAlreadyExists(error)) throw error;
|
|
1883
|
-
}
|
|
1884
|
-
const helperStat = await plugins.fs.lstat(helperDirectory);
|
|
1885
|
-
if (!helperStat.isDirectory() || helperStat.isSymbolicLink()) {
|
|
1886
|
-
throw new RunnerError('Workspace helper directory must be a real directory');
|
|
1887
|
-
}
|
|
1888
|
-
await plugins.fs.chmod(helperDirectory, 0o700);
|
|
1889
|
-
const privateStat = await plugins.fs.lstat(helperDirectory);
|
|
1890
|
-
if (
|
|
1891
|
-
!privateStat.isDirectory() || privateStat.isSymbolicLink() ||
|
|
1892
|
-
(privateStat.mode & 0o777) !== 0o700
|
|
1893
|
-
) {
|
|
1894
|
-
throw new RunnerError('Workspace helper directory permissions are not private');
|
|
1895
|
-
}
|
|
1896
|
-
await this.syncDirectory(stateRoot);
|
|
1897
|
-
return await plugins.fs.realpath(helperDirectory);
|
|
1898
|
-
}
|
|
1899
|
-
|
|
1900
|
-
private ensureRuntimeProbeOwner(): Promise<string> {
|
|
1901
|
-
return this.stateOwner.runtimeProbeOwnerId(async () => {
|
|
1902
|
-
const helperDirectory = await this.ensureWorkspaceHelperDirectory();
|
|
1903
|
-
const markers: Array<{ name: string; ownerId: string }> = [];
|
|
1904
|
-
for (const name of await plugins.fs.readdir(helperDirectory)) {
|
|
1905
|
-
if (!name.startsWith(runtimeProbeOwnerMarkerPrefix)) continue;
|
|
1906
|
-
const match = runtimeProbeOwnerMarkerPattern.exec(name);
|
|
1907
|
-
if (!match) throw new RunnerError('Runtime probe owner marker name is invalid');
|
|
1908
|
-
markers.push({ name, ownerId: match[1] });
|
|
1909
|
-
}
|
|
1910
|
-
if (markers.length > 1) {
|
|
1911
|
-
throw new RunnerError('Runner state contains multiple runtime probe owner markers');
|
|
1912
|
-
}
|
|
1913
|
-
if (markers.length === 1) {
|
|
1914
|
-
const marker = markers[0];
|
|
1915
|
-
await this.validateRuntimeProbeOwnerMarker(join(helperDirectory, marker.name));
|
|
1916
|
-
return marker.ownerId;
|
|
1917
|
-
}
|
|
1918
|
-
|
|
1919
|
-
const ownerId = this.randomHex();
|
|
1920
|
-
const markerPath = join(
|
|
1921
|
-
helperDirectory,
|
|
1922
|
-
`${runtimeProbeOwnerMarkerPrefix}${ownerId}`,
|
|
1923
|
-
);
|
|
1924
|
-
await withOpenFile(
|
|
1925
|
-
markerPath,
|
|
1926
|
-
'wx+',
|
|
1927
|
-
0o600,
|
|
1928
|
-
async (openedMarkerFile) => await openedMarkerFile.sync(),
|
|
1929
|
-
'Runtime probe owner marker sync and close failed',
|
|
1930
|
-
);
|
|
1931
|
-
await this.validateRuntimeProbeOwnerMarker(markerPath);
|
|
1932
|
-
await this.syncDirectory(helperDirectory);
|
|
1933
|
-
return ownerId;
|
|
1934
|
-
});
|
|
1935
|
-
}
|
|
1936
|
-
|
|
1937
|
-
private async validateRuntimeProbeOwnerMarker(pathArg: string): Promise<void> {
|
|
1938
|
-
const before = await plugins.fs.lstat(pathArg);
|
|
1939
|
-
if (
|
|
1940
|
-
!before.isFile() || before.isSymbolicLink() || before.size !== 0 || before.nlink !== 1 ||
|
|
1941
|
-
(before.mode & 0o7777) !== 0o600
|
|
1942
|
-
) {
|
|
1943
|
-
throw new RunnerError('Runtime probe owner marker must be a private single-link file');
|
|
1944
|
-
}
|
|
1945
|
-
await withOpenFile(
|
|
1946
|
-
pathArg,
|
|
1947
|
-
'r',
|
|
1948
|
-
undefined,
|
|
1949
|
-
async (openedMarkerFile) => {
|
|
1950
|
-
const descriptorStat = await openedMarkerFile.stat();
|
|
1951
|
-
const current = await plugins.fs.lstat(pathArg);
|
|
1952
|
-
if (
|
|
1953
|
-
!descriptorStat.isFile() || !current.isFile() || current.isSymbolicLink() ||
|
|
1954
|
-
!sameFileIdentity(before, descriptorStat) || !sameFileIdentity(before, current) ||
|
|
1955
|
-
descriptorStat.nlink !== 1 || current.nlink !== 1 ||
|
|
1956
|
-
(current.mode & 0o7777) !== 0o600
|
|
1957
|
-
) {
|
|
1958
|
-
throw new RunnerError('Runtime probe owner marker changed during validation');
|
|
1959
|
-
}
|
|
1960
|
-
},
|
|
1961
|
-
'Runtime probe owner marker validation and close failed',
|
|
1962
|
-
);
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
private async scavengeWorkspaceHelpers(
|
|
1966
|
-
helperDirectoryArg: string,
|
|
1967
|
-
currentDestinationNameArg: string,
|
|
1968
|
-
currentDigestArg: string,
|
|
1969
|
-
): Promise<{ count: number; bytes: number }> {
|
|
1970
|
-
const finalFiles: Array<{ name: string; path: string; stat: plugins.Stats }> = [];
|
|
1971
|
-
let recentTemporaryCount = 0;
|
|
1972
|
-
let recentTemporaryBytes = 0;
|
|
1973
|
-
let removed = false;
|
|
1974
|
-
for (const name of await plugins.fs.readdir(helperDirectoryArg)) {
|
|
1975
|
-
const path = join(helperDirectoryArg, name);
|
|
1976
|
-
if (name === legacyWorkspaceHelperLockName) {
|
|
1977
|
-
const stat = await lstatIfPresent(path);
|
|
1978
|
-
if (!stat) continue;
|
|
1979
|
-
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
1980
|
-
throw new RunnerError('Legacy workspace helper lock must be a regular file');
|
|
1981
|
-
}
|
|
1982
|
-
try {
|
|
1983
|
-
await removePath(path);
|
|
1984
|
-
removed = true;
|
|
1985
|
-
} catch (error) {
|
|
1986
|
-
if (!isNotFound(error)) throw error;
|
|
1987
|
-
}
|
|
1988
|
-
continue;
|
|
1989
|
-
}
|
|
1990
|
-
if (workspaceHelperTemporaryNamePattern.test(name)) {
|
|
1991
|
-
const stat = await lstatIfPresent(path);
|
|
1992
|
-
if (!stat) continue;
|
|
1993
|
-
if (
|
|
1994
|
-
!stat.isFile() || stat.isSymbolicLink() || stat.size > workspaceHelperMaximumBytes
|
|
1995
|
-
) {
|
|
1996
|
-
throw new RunnerError('Workspace helper temporary path must be a bounded regular file');
|
|
1997
|
-
}
|
|
1998
|
-
if (
|
|
1999
|
-
await this.recoverInterruptedWorkspaceHelperPublication(
|
|
2000
|
-
path,
|
|
2001
|
-
stat,
|
|
2002
|
-
join(helperDirectoryArg, currentDestinationNameArg),
|
|
2003
|
-
currentDigestArg,
|
|
2004
|
-
)
|
|
2005
|
-
) {
|
|
2006
|
-
removed = true;
|
|
2007
|
-
continue;
|
|
2008
|
-
}
|
|
2009
|
-
if (this.now() - stat.mtime.getTime() >= workspaceHelperTemporaryMaximumAgeMs) {
|
|
2010
|
-
const currentStat = await lstatIfPresent(path);
|
|
2011
|
-
if (!currentStat) continue;
|
|
2012
|
-
if (!sameFileIdentity(stat, currentStat)) {
|
|
2013
|
-
throw new RunnerError('Workspace helper temporary path changed during cleanup');
|
|
2014
|
-
}
|
|
2015
|
-
try {
|
|
2016
|
-
await removePath(path);
|
|
2017
|
-
removed = true;
|
|
2018
|
-
} catch (error) {
|
|
2019
|
-
if (!isNotFound(error)) throw error;
|
|
2020
|
-
}
|
|
2021
|
-
continue;
|
|
2022
|
-
}
|
|
2023
|
-
recentTemporaryCount++;
|
|
2024
|
-
recentTemporaryBytes += stat.size;
|
|
2025
|
-
continue;
|
|
2026
|
-
}
|
|
2027
|
-
if (workspaceHelperFinalNamePattern.test(name)) {
|
|
2028
|
-
const stat = await lstatIfPresent(path);
|
|
2029
|
-
if (!stat) continue;
|
|
2030
|
-
if (
|
|
2031
|
-
!stat.isFile() || stat.isSymbolicLink() || stat.size < 1 ||
|
|
2032
|
-
stat.size > workspaceHelperMaximumBytes
|
|
2033
|
-
) {
|
|
2034
|
-
throw new RunnerError('Retained workspace helper must be a bounded regular file');
|
|
2035
|
-
}
|
|
2036
|
-
finalFiles.push({ name, path, stat });
|
|
2037
|
-
}
|
|
2038
|
-
}
|
|
2039
|
-
|
|
2040
|
-
finalFiles.sort((first, second) => {
|
|
2041
|
-
if (first.name === currentDestinationNameArg) return -1;
|
|
2042
|
-
if (second.name === currentDestinationNameArg) return 1;
|
|
2043
|
-
return second.stat.mtime.getTime() - first.stat.mtime.getTime() ||
|
|
2044
|
-
first.name.localeCompare(second.name);
|
|
2045
|
-
});
|
|
2046
|
-
const retainedFinalCount = finalFiles.some((entry) => entry.name === currentDestinationNameArg)
|
|
2047
|
-
? workspaceHelperRetainedFinalCount
|
|
2048
|
-
: workspaceHelperRetainedFinalCount - 1;
|
|
2049
|
-
for (const stale of finalFiles.slice(retainedFinalCount)) {
|
|
2050
|
-
const currentStat = await lstatIfPresent(stale.path);
|
|
2051
|
-
if (!currentStat) continue;
|
|
2052
|
-
if (!sameFileIdentity(stale.stat, currentStat)) {
|
|
2053
|
-
throw new RunnerError('Retained workspace helper changed during cleanup');
|
|
2054
|
-
}
|
|
2055
|
-
try {
|
|
2056
|
-
await removePath(stale.path);
|
|
2057
|
-
removed = true;
|
|
2058
|
-
} catch (error) {
|
|
2059
|
-
if (!isNotFound(error)) throw error;
|
|
2060
|
-
}
|
|
2061
|
-
}
|
|
2062
|
-
if (removed) await this.syncDirectory(helperDirectoryArg);
|
|
2063
|
-
return { count: recentTemporaryCount, bytes: recentTemporaryBytes };
|
|
2064
|
-
}
|
|
2065
|
-
|
|
2066
|
-
private async recoverInterruptedWorkspaceHelperPublication(
|
|
2067
|
-
temporaryPathArg: string,
|
|
2068
|
-
temporaryStatArg: plugins.Stats,
|
|
2069
|
-
destinationPathArg: string,
|
|
2070
|
-
expectedDigestArg: string,
|
|
2071
|
-
): Promise<boolean> {
|
|
2072
|
-
if (
|
|
2073
|
-
temporaryStatArg.nlink !== 2
|
|
2074
|
-
) {
|
|
2075
|
-
return false;
|
|
2076
|
-
}
|
|
2077
|
-
const destinationStat = await lstatIfPresent(destinationPathArg);
|
|
2078
|
-
if (!destinationStat || !sameFileIdentity(temporaryStatArg, destinationStat)) return false;
|
|
2079
|
-
if (
|
|
2080
|
-
!destinationStat.isFile() || destinationStat.isSymbolicLink() || destinationStat.size < 1 ||
|
|
2081
|
-
destinationStat.size > workspaceHelperMaximumBytes || destinationStat.nlink !== 2 ||
|
|
2082
|
-
(destinationStat.mode & 0o7777) !== workspaceHelperExecutableMode
|
|
2083
|
-
) {
|
|
2084
|
-
throw new RunnerError('Interrupted workspace helper publication is invalid');
|
|
2085
|
-
}
|
|
2086
|
-
const validated = await readBoundedRegularFile(
|
|
2087
|
-
temporaryPathArg,
|
|
2088
|
-
workspaceHelperMaximumBytes,
|
|
2089
|
-
'Interrupted workspace helper publication',
|
|
2090
|
-
);
|
|
2091
|
-
if (
|
|
2092
|
-
!sameFileIdentity(temporaryStatArg, validated.stat) || validated.stat.nlink !== 2 ||
|
|
2093
|
-
(validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode ||
|
|
2094
|
-
sha256Hex(validated.bytes) !== expectedDigestArg
|
|
2095
|
-
) {
|
|
2096
|
-
throw new RunnerError('Interrupted workspace helper publication changed during validation');
|
|
2097
|
-
}
|
|
2098
|
-
const currentTemporary = await plugins.fs.lstat(temporaryPathArg);
|
|
2099
|
-
const currentDestination = await plugins.fs.lstat(destinationPathArg);
|
|
2100
|
-
if (
|
|
2101
|
-
!sameFileIdentity(temporaryStatArg, currentTemporary) ||
|
|
2102
|
-
!sameFileIdentity(temporaryStatArg, currentDestination) ||
|
|
2103
|
-
currentTemporary.nlink !== 2 || currentDestination.nlink !== 2
|
|
2104
|
-
) {
|
|
2105
|
-
throw new RunnerError('Interrupted workspace helper publication changed before recovery');
|
|
2106
|
-
}
|
|
2107
|
-
await removePath(temporaryPathArg);
|
|
2108
|
-
const recoveredDestination = await plugins.fs.lstat(destinationPathArg);
|
|
2109
|
-
if (
|
|
2110
|
-
!sameFileIdentity(destinationStat, recoveredDestination) ||
|
|
2111
|
-
recoveredDestination.nlink !== 1 ||
|
|
2112
|
-
(recoveredDestination.mode & 0o7777) !== workspaceHelperExecutableMode
|
|
2113
|
-
) {
|
|
2114
|
-
throw new RunnerError('Interrupted workspace helper publication did not recover safely');
|
|
2115
|
-
}
|
|
2116
|
-
return true;
|
|
2117
|
-
}
|
|
2118
|
-
|
|
2119
|
-
private async validateMaterializedWorkspaceHelper(
|
|
2120
|
-
pathArg: string,
|
|
2121
|
-
expectedDigestArg: string,
|
|
2122
|
-
setExecutableModeArg = false,
|
|
2123
|
-
): Promise<void> {
|
|
2124
|
-
const before = await plugins.fs.lstat(pathArg);
|
|
2125
|
-
if (
|
|
2126
|
-
!before.isFile() || before.isSymbolicLink() || before.size < 1 ||
|
|
2127
|
-
before.size > workspaceHelperMaximumBytes ||
|
|
2128
|
-
before.nlink !== 1
|
|
2129
|
-
) {
|
|
2130
|
-
throw new RunnerError('Materialized workspace helper must be a bounded regular file');
|
|
2131
|
-
}
|
|
2132
|
-
if (setExecutableModeArg) await plugins.fs.chmod(pathArg, workspaceHelperExecutableMode);
|
|
2133
|
-
const validated = await readBoundedRegularFile(
|
|
2134
|
-
pathArg,
|
|
2135
|
-
workspaceHelperMaximumBytes,
|
|
2136
|
-
'Materialized workspace helper',
|
|
2137
|
-
);
|
|
2138
|
-
if (
|
|
2139
|
-
!sameFileIdentity(before, validated.stat) ||
|
|
2140
|
-
(validated.stat.nlink !== 1) ||
|
|
2141
|
-
((validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode)
|
|
2142
|
-
) {
|
|
2143
|
-
throw new RunnerError('Materialized workspace helper changed during validation');
|
|
2144
|
-
}
|
|
2145
|
-
const digest = sha256Hex(validated.bytes);
|
|
2146
|
-
if (digest !== expectedDigestArg) {
|
|
2147
|
-
throw new RunnerError('Materialized workspace helper digest does not match its source');
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2150
|
-
|
|
2151
|
-
private async syncDirectory(pathArg: string): Promise<void> {
|
|
2152
|
-
await syncDirectory(pathArg, 'Workspace helper directory sync and close failed');
|
|
2153
|
-
}
|
|
2154
|
-
|
|
2155
|
-
private async probeHostTmpfs(
|
|
2156
|
-
helperPath: string,
|
|
2157
|
-
runtimeProbeOwnerId: string,
|
|
2158
|
-
): Promise<number> {
|
|
2159
|
-
let path: string | undefined;
|
|
2160
|
-
let blockSize: number | undefined;
|
|
2161
|
-
let operationError: unknown;
|
|
2162
|
-
try {
|
|
2163
|
-
await scavengeHostTmpfsProbes('/dev/shm', {}, runtimeProbeOwnerId);
|
|
2164
|
-
path = await makeTempDir({
|
|
2165
|
-
dir: '/dev/shm',
|
|
2166
|
-
prefix: `shipzone-ci-probe-${runtimeProbeOwnerId}-`,
|
|
2167
|
-
});
|
|
2168
|
-
const before = await this.readFilesystemProbe(helperPath, path);
|
|
2169
|
-
const first = join(path, 'first');
|
|
2170
|
-
const second = join(path, 'second');
|
|
2171
|
-
await withOpenFile(
|
|
2172
|
-
first,
|
|
2173
|
-
createNewWriteFlags,
|
|
2174
|
-
0o600,
|
|
2175
|
-
async (file) =>
|
|
2176
|
-
await writeAll(file, new Uint8Array([1]), 'Host tmpfs probe write made no progress'),
|
|
2177
|
-
'Host tmpfs probe file close failed',
|
|
2178
|
-
);
|
|
2179
|
-
const afterFile = await this.readFilesystemProbe(helperPath, path);
|
|
2180
|
-
await plugins.fs.link(first, second);
|
|
2181
|
-
const afterLink = await this.readFilesystemProbe(helperPath, path);
|
|
2182
|
-
const firstStat = await plugins.fs.lstat(first);
|
|
2183
|
-
const secondStat = await plugins.fs.lstat(second);
|
|
2184
|
-
if (
|
|
2185
|
-
before.availableInodes - afterFile.availableInodes !== 1 ||
|
|
2186
|
-
afterFile.availableInodes - afterLink.availableInodes !== 1 ||
|
|
2187
|
-
firstStat.ino !== secondStat.ino ||
|
|
2188
|
-
firstStat.nlink < 2
|
|
2189
|
-
) {
|
|
2190
|
-
throw new RunnerError('Host tmpfs does not provide required hardlink inode accounting');
|
|
2191
|
-
}
|
|
2192
|
-
blockSize = before.blockSize;
|
|
2193
|
-
} catch (error) {
|
|
2194
|
-
operationError = error instanceof RunnerError
|
|
2195
|
-
? error
|
|
2196
|
-
: new RunnerError('Unable to verify host tmpfs semantics', { cause: error });
|
|
2197
|
-
}
|
|
2198
|
-
let cleanupError: unknown;
|
|
2199
|
-
if (path) {
|
|
2200
|
-
try {
|
|
2201
|
-
await this.removePath(path);
|
|
2202
|
-
} catch (error) {
|
|
2203
|
-
cleanupError = error;
|
|
2204
|
-
}
|
|
2205
|
-
}
|
|
2206
|
-
if (cleanupError !== undefined) {
|
|
2207
|
-
throw new ResourceCleanupError(
|
|
2208
|
-
operationError === undefined
|
|
2209
|
-
? 'Unable to clean host tmpfs probe'
|
|
2210
|
-
: 'Host tmpfs probe and cleanup both failed',
|
|
2211
|
-
[...(operationError === undefined ? [] : [operationError]), cleanupError],
|
|
2212
|
-
);
|
|
2213
|
-
}
|
|
2214
|
-
if (operationError !== undefined) throw operationError;
|
|
2215
|
-
if (blockSize === undefined) throw new RunnerError('Host tmpfs probe produced no block size');
|
|
2216
|
-
return blockSize;
|
|
2217
|
-
}
|
|
2218
|
-
|
|
2219
|
-
private async readFilesystemProbe(
|
|
2220
|
-
helperPath: string,
|
|
2221
|
-
path: string,
|
|
2222
|
-
): Promise<{ blockSize: number; availableInodes: number }> {
|
|
2223
|
-
const result = await this.runHostHelper(helperPath, ['filesystem', '--path', path]);
|
|
2224
|
-
requireSuccess(result, 'Workspace helper filesystem probe failed');
|
|
2225
|
-
const value = firstObject(
|
|
2226
|
-
parseJson(result.stdout, 'Workspace helper filesystem probe was not valid JSON'),
|
|
2227
|
-
'Workspace helper filesystem probe was empty',
|
|
2228
|
-
);
|
|
2229
|
-
const blockSize = Number(field(value, 'blockSize'));
|
|
2230
|
-
const availableInodes = Number(field(value, 'availableInodes'));
|
|
2231
|
-
positiveSafeInteger(blockSize, 'Workspace block size');
|
|
2232
|
-
nonNegativeSafeInteger(availableInodes, 'Available inode count');
|
|
2233
|
-
return { blockSize, availableInodes };
|
|
2234
|
-
}
|
|
2235
|
-
|
|
2236
|
-
private async reconcileRuntimeProbeVolumes(runtimeProbeOwnerId: string): Promise<void> {
|
|
2237
|
-
const listed = await this.runRuntime([
|
|
2238
|
-
'volume',
|
|
2239
|
-
'ls',
|
|
2240
|
-
'--filter',
|
|
2241
|
-
`label=${managedLabel}=true`,
|
|
2242
|
-
'--filter',
|
|
2243
|
-
`label=${runtimeProbeLabel}=true`,
|
|
2244
|
-
'--filter',
|
|
2245
|
-
`label=${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`,
|
|
2246
|
-
'--format',
|
|
2247
|
-
'{{.Name}}',
|
|
2248
|
-
]);
|
|
2249
|
-
requireSuccess(listed, 'Unable to enumerate OCI runtime probe volumes');
|
|
2250
|
-
for (const name of decode(listed.stdout).split('\n').filter(Boolean)) {
|
|
2251
|
-
if (!runtimeProbeVolumeNamePattern.test(name)) continue;
|
|
2252
|
-
const inspected = await this.runRuntime(['volume', 'inspect', name]);
|
|
2253
|
-
if (!inspected.success) continue;
|
|
2254
|
-
const volume = firstObject(
|
|
2255
|
-
parseJson(inspected.stdout, 'OCI runtime probe volume inspection was not valid JSON'),
|
|
2256
|
-
'OCI runtime probe volume inspection was empty',
|
|
2257
|
-
);
|
|
2258
|
-
const labelsValue = field(volume, 'Labels', 'labels');
|
|
2259
|
-
const inspectedName = field(volume, 'Name', 'name');
|
|
2260
|
-
const createdAtValue = field(volume, 'CreatedAt', 'createdAt', 'Created', 'created');
|
|
2261
|
-
if (
|
|
2262
|
-
inspectedName !== name ||
|
|
2263
|
-
!isRecord(labelsValue) ||
|
|
2264
|
-
labelsValue[managedLabel] !== 'true' ||
|
|
2265
|
-
labelsValue[runtimeProbeLabel] !== 'true' ||
|
|
2266
|
-
labelsValue[runtimeProbeOwnerLabel] !== runtimeProbeOwnerId ||
|
|
2267
|
-
typeof createdAtValue !== 'string'
|
|
2268
|
-
) {
|
|
2269
|
-
continue;
|
|
2270
|
-
}
|
|
2271
|
-
const createdAt = Date.parse(createdAtValue);
|
|
2272
|
-
const ageMs = this.now() - createdAt;
|
|
2273
|
-
if (!Number.isFinite(createdAt) || ageMs <= runtimeProbeVolumeMaximumAgeMs) continue;
|
|
2274
|
-
try {
|
|
2275
|
-
await this.removeVolume(name);
|
|
2276
|
-
} catch (error) {
|
|
2277
|
-
throw new ResourceCleanupError('Unable to clean stale OCI runtime probe volume', [error]);
|
|
2278
|
-
}
|
|
2279
|
-
}
|
|
2280
|
-
}
|
|
2281
|
-
|
|
2282
|
-
private async probeRuntimeVolume(
|
|
2283
|
-
blockSize: number,
|
|
2284
|
-
runtimeProbeOwnerId: string,
|
|
2285
|
-
): Promise<void> {
|
|
2286
|
-
const limits = calculateWorkspaceVolumeLimits(probeVolumeBytes, probeVolumeEntries, blockSize);
|
|
2287
|
-
const name = this.createResourceName('volume');
|
|
2288
|
-
let possiblyExists = false;
|
|
2289
|
-
let operationError: unknown;
|
|
2290
|
-
let hasOperationError = false;
|
|
2291
|
-
try {
|
|
2292
|
-
possiblyExists = true;
|
|
2293
|
-
const result = await this.runRuntime(
|
|
2294
|
-
this.volumeCreateArgs(
|
|
2295
|
-
name,
|
|
2296
|
-
limits,
|
|
2297
|
-
undefined,
|
|
2298
|
-
undefined,
|
|
2299
|
-
undefined,
|
|
2300
|
-
runtimeProbeOwnerId,
|
|
2301
|
-
),
|
|
2302
|
-
);
|
|
2303
|
-
requireSuccess(result, 'OCI runtime cannot create local tmpfs volumes');
|
|
2304
|
-
const inspected = await this.runRuntime(['volume', 'inspect', name]);
|
|
2305
|
-
requireSuccess(inspected, 'OCI runtime cannot inspect local tmpfs volumes');
|
|
2306
|
-
const volume = firstObject(
|
|
2307
|
-
parseJson(inspected.stdout, 'OCI volume inspection was not valid JSON'),
|
|
2308
|
-
'OCI volume inspection was empty',
|
|
2309
|
-
);
|
|
2310
|
-
if (String(field(volume, 'Driver', 'driver') ?? '') !== 'local') {
|
|
2311
|
-
throw new RunnerError('OCI runtime did not create a local volume');
|
|
2312
|
-
}
|
|
2313
|
-
const options = field(volume, 'Options', 'options');
|
|
2314
|
-
if (!isRecord(options)) throw new RunnerError('OCI runtime omitted tmpfs volume options');
|
|
2315
|
-
const type = String(field(options, 'type', 'Type') ?? '');
|
|
2316
|
-
const device = String(field(options, 'device', 'Device') ?? '');
|
|
2317
|
-
const mountOptions = String(field(options, 'o', 'O') ?? '');
|
|
2318
|
-
if (
|
|
2319
|
-
type !== 'tmpfs' ||
|
|
2320
|
-
device !== 'tmpfs' ||
|
|
2321
|
-
!mountOptions.split(',').includes('nodev') ||
|
|
2322
|
-
!mountOptions.split(',').includes('nosuid')
|
|
2323
|
-
) {
|
|
2324
|
-
throw new RunnerError('OCI runtime did not retain required tmpfs volume options');
|
|
2325
|
-
}
|
|
2326
|
-
} catch (error) {
|
|
2327
|
-
operationError = error;
|
|
2328
|
-
hasOperationError = true;
|
|
2329
|
-
}
|
|
2330
|
-
let cleanupError: unknown;
|
|
2331
|
-
if (possiblyExists) {
|
|
2332
|
-
try {
|
|
2333
|
-
await this.removeVolume(name);
|
|
2334
|
-
possiblyExists = false;
|
|
2335
|
-
} catch (error) {
|
|
2336
|
-
cleanupError = error;
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
2339
|
-
if (cleanupError !== undefined) {
|
|
2340
|
-
throw new ResourceCleanupError(
|
|
2341
|
-
hasOperationError
|
|
2342
|
-
? 'OCI runtime volume probe and cleanup both failed'
|
|
2343
|
-
: 'Unable to clean OCI runtime probe volume',
|
|
2344
|
-
[...(hasOperationError ? [operationError] : []), cleanupError],
|
|
2345
|
-
);
|
|
2346
|
-
}
|
|
2347
|
-
if (hasOperationError) throw operationError;
|
|
2348
|
-
}
|
|
2349
|
-
|
|
2350
|
-
private volumeCreateArgs(
|
|
2351
|
-
name: string,
|
|
2352
|
-
limits: IWorkspaceVolumeLimits,
|
|
2353
|
-
runnerId?: string,
|
|
2354
|
-
sessionId?: string,
|
|
2355
|
-
attemptId?: string,
|
|
2356
|
-
runtimeProbeOwnerId?: string,
|
|
2357
|
-
): string[] {
|
|
2358
|
-
validateGeneratedName(name, 'volume');
|
|
2359
|
-
const mountOptions = [
|
|
2360
|
-
`size=${limits.sizeBytes}`,
|
|
2361
|
-
`nr_inodes=${limits.inodeLimit}`,
|
|
2362
|
-
'nodev',
|
|
2363
|
-
'nosuid',
|
|
2364
|
-
'mode=0700',
|
|
2365
|
-
'uid=0',
|
|
2366
|
-
'gid=0',
|
|
2367
|
-
].join(',');
|
|
2368
|
-
const args = [
|
|
2369
|
-
'volume',
|
|
2370
|
-
'create',
|
|
2371
|
-
'--driver',
|
|
2372
|
-
'local',
|
|
2373
|
-
'--opt',
|
|
2374
|
-
'type=tmpfs',
|
|
2375
|
-
'--opt',
|
|
2376
|
-
'device=tmpfs',
|
|
2377
|
-
'--opt',
|
|
2378
|
-
`o=${mountOptions}`,
|
|
2379
|
-
];
|
|
2380
|
-
if (runnerId && sessionId && attemptId) {
|
|
2381
|
-
args.push(...labels(runnerId, sessionId, attemptId));
|
|
2382
|
-
} else if (runtimeProbeOwnerId) {
|
|
2383
|
-
if (!/^[a-f0-9]{32}$/.test(runtimeProbeOwnerId)) {
|
|
2384
|
-
throw new RunnerError('Runtime probe owner ID is invalid');
|
|
2385
|
-
}
|
|
2386
|
-
args.push(
|
|
2387
|
-
'--label',
|
|
2388
|
-
`${managedLabel}=true`,
|
|
2389
|
-
'--label',
|
|
2390
|
-
`${runtimeProbeLabel}=true`,
|
|
2391
|
-
'--label',
|
|
2392
|
-
`${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`,
|
|
2393
|
-
);
|
|
2394
|
-
}
|
|
2395
|
-
if (this.config.oci.runtime === 'podman') args.push('--opt', 'nocopy');
|
|
2396
|
-
args.push(name);
|
|
2397
|
-
return args;
|
|
2398
|
-
}
|
|
2399
|
-
|
|
2400
|
-
private parseImageInspection(output: Uint8Array): IImageInspection {
|
|
2401
|
-
const image = firstObject(
|
|
2402
|
-
parseJson(output, 'OCI image inspection was not valid JSON'),
|
|
2403
|
-
'OCI image inspection was empty',
|
|
2404
|
-
);
|
|
2405
|
-
const repoDigests = field(image, 'RepoDigests', 'repoDigests');
|
|
2406
|
-
return {
|
|
2407
|
-
os: String(field(image, 'Os', 'OS', 'os') ?? ''),
|
|
2408
|
-
architecture: String(field(image, 'Architecture', 'architecture') ?? ''),
|
|
2409
|
-
repoDigests: Array.isArray(repoDigests)
|
|
2410
|
-
? repoDigests.filter((entry): entry is string => typeof entry === 'string')
|
|
2411
|
-
: [],
|
|
2412
|
-
...(typeof field(image, 'Digest', 'digest') === 'string'
|
|
2413
|
-
? { digest: field(image, 'Digest', 'digest') as string }
|
|
2414
|
-
: {}),
|
|
2415
|
-
};
|
|
2416
|
-
}
|
|
2417
|
-
|
|
2418
|
-
private parseContainerState(output: Uint8Array): IContainerState {
|
|
2419
|
-
const inspection = firstObject(
|
|
2420
|
-
parseJson(output, 'OCI container inspection was not valid JSON'),
|
|
2421
|
-
'OCI container inspection was empty',
|
|
2422
|
-
);
|
|
2423
|
-
const state = field(inspection, 'State', 'state');
|
|
2424
|
-
if (!isRecord(state)) throw new RunnerError('OCI container inspection omitted state');
|
|
2425
|
-
const exitCode = Number(field(state, 'ExitCode', 'exitCode'));
|
|
2426
|
-
if (!Number.isInteger(exitCode)) {
|
|
2427
|
-
throw new RunnerError('OCI container reported an invalid exit code');
|
|
2428
|
-
}
|
|
2429
|
-
return {
|
|
2430
|
-
exitCode,
|
|
2431
|
-
oomKilled: field(state, 'OOMKilled', 'oomKilled') === true,
|
|
2432
|
-
error: typeof field(state, 'Error', 'error') === 'string'
|
|
2433
|
-
? String(field(state, 'Error', 'error'))
|
|
2434
|
-
: '',
|
|
2435
|
-
};
|
|
2436
|
-
}
|
|
2437
|
-
|
|
2438
|
-
private parseCounts(output: Uint8Array, name: string): ICounts {
|
|
2439
|
-
const value = firstObject(
|
|
2440
|
-
parseJson(output, `${name} output was not valid JSON`),
|
|
2441
|
-
`${name} output was empty`,
|
|
2442
|
-
);
|
|
2443
|
-
const bytes = Number(field(value, 'bytes'));
|
|
2444
|
-
const entries = Number(field(value, 'entries'));
|
|
2445
|
-
nonNegativeSafeInteger(bytes, `${name} byte count`);
|
|
2446
|
-
nonNegativeSafeInteger(entries, `${name} entry count`);
|
|
2447
|
-
return { bytes, entries };
|
|
2448
|
-
}
|
|
2449
|
-
|
|
2450
|
-
private async runHostHelper(
|
|
2451
|
-
helperPath: string,
|
|
2452
|
-
args: string[],
|
|
2453
|
-
): Promise<IOciRuntimeCommandResult> {
|
|
2454
|
-
return await this.commandRunner({
|
|
2455
|
-
executable: helperPath,
|
|
2456
|
-
args,
|
|
2457
|
-
environment: {},
|
|
2458
|
-
timeoutMs: runtimeCommandTimeoutMs,
|
|
2459
|
-
});
|
|
2460
|
-
}
|
|
2461
|
-
|
|
2462
|
-
private async runRuntime(
|
|
2463
|
-
args: string[],
|
|
2464
|
-
timeoutMs = runtimeCommandTimeoutMs,
|
|
2465
|
-
signal?: AbortSignal,
|
|
2466
|
-
environment: Record<string, string> = {},
|
|
2467
|
-
onOutput?: IOciRuntimeCommandRequest['onOutput'],
|
|
2468
|
-
): Promise<IOciRuntimeCommandResult> {
|
|
2469
|
-
return await this.commandRunner({
|
|
2470
|
-
executable: this.config.oci.runtimePath,
|
|
2471
|
-
args,
|
|
2472
|
-
environment: { ...this.runtimeEnvironment, ...environment },
|
|
2473
|
-
timeoutMs,
|
|
2474
|
-
...(signal ? { signal } : {}),
|
|
2475
|
-
...(onOutput ? { onOutput } : {}),
|
|
2476
|
-
});
|
|
2477
|
-
}
|
|
2478
|
-
|
|
2479
|
-
private async runInertContainer(
|
|
2480
|
-
name: string,
|
|
2481
|
-
createArgs: string[],
|
|
2482
|
-
signal?: AbortSignal,
|
|
2483
|
-
activeContainers?: Set<string>,
|
|
2484
|
-
deadline?: () => number | undefined,
|
|
2485
|
-
timeout: () => number = () => runtimeCommandTimeoutMs,
|
|
2486
|
-
setActive?: (name: string | undefined) => boolean,
|
|
2487
|
-
): Promise<Uint8Array> {
|
|
2488
|
-
if (signal?.aborted) throw signal.reason;
|
|
2489
|
-
let createAttempted = false;
|
|
2490
|
-
let started = false;
|
|
2491
|
-
let abortStopPromise: Promise<void> | undefined;
|
|
2492
|
-
const abortListener = (): void => {
|
|
2493
|
-
if (started && !setActive && !abortStopPromise) {
|
|
2494
|
-
abortStopPromise = this.stopContainer(name, deadline, signal);
|
|
2495
|
-
void abortStopPromise.catch(() => undefined);
|
|
2496
|
-
}
|
|
2497
|
-
};
|
|
2498
|
-
signal?.addEventListener('abort', abortListener, { once: true });
|
|
2499
|
-
let output: Uint8Array | undefined;
|
|
2500
|
-
let operationError: unknown;
|
|
2501
|
-
let hasOperationError = false;
|
|
2502
|
-
try {
|
|
2503
|
-
createAttempted = true;
|
|
2504
|
-
const create = await this.runRuntime(createArgs, timeout(), signal);
|
|
2505
|
-
requireSuccess(create, 'Unable to create inert workspace helper container');
|
|
2506
|
-
activeContainers?.add(name);
|
|
2507
|
-
const stopRequested = setActive?.(name) ?? false;
|
|
2508
|
-
if (signal?.aborted) throw signal.reason;
|
|
2509
|
-
if (stopRequested) throw new RunnerError('Workspace helper was stopped before start');
|
|
2510
|
-
const start = await this.runRuntime(['start', name], timeout(), signal);
|
|
2511
|
-
requireSuccess(start, 'Unable to start inert workspace helper container');
|
|
2512
|
-
started = true;
|
|
2513
|
-
if (signal?.aborted) abortListener();
|
|
2514
|
-
const waited = await this.runRuntime(['wait', name], timeout(), signal);
|
|
2515
|
-
requireSuccess(waited, 'Unable to wait for inert workspace helper container');
|
|
2516
|
-
const logs = await this.runRuntime(['logs', name]);
|
|
2517
|
-
requireSuccess(logs, 'Unable to read inert workspace helper output');
|
|
2518
|
-
const inspected = await this.runRuntime(['inspect', name]);
|
|
2519
|
-
requireSuccess(inspected, 'Unable to inspect inert workspace helper container');
|
|
2520
|
-
const state = this.parseContainerState(inspected.stdout);
|
|
2521
|
-
const waitCode = Number(decode(waited.stdout));
|
|
2522
|
-
if (!Number.isInteger(waitCode) || waitCode !== state.exitCode) {
|
|
2523
|
-
throw new RunnerError('Workspace helper wait and inspection results differ');
|
|
2524
|
-
}
|
|
2525
|
-
if (state.oomKilled || state.error || state.exitCode !== 0) {
|
|
2526
|
-
const helperError = decode(logs.stderr.slice(0, maximumWorkspaceHelperErrorBytes));
|
|
2527
|
-
throw new WorkspaceResourceError(
|
|
2528
|
-
`Workspace helper container failed${helperError ? `: ${helperError}` : ''}`,
|
|
2529
|
-
);
|
|
2530
|
-
}
|
|
2531
|
-
output = logs.stdout;
|
|
2532
|
-
} catch (error) {
|
|
2533
|
-
operationError = error;
|
|
2534
|
-
hasOperationError = true;
|
|
2535
|
-
}
|
|
2536
|
-
signal?.removeEventListener('abort', abortListener);
|
|
2537
|
-
const stopErrors: unknown[] = [];
|
|
2538
|
-
if (abortStopPromise) {
|
|
2539
|
-
await abortStopPromise.catch((error) => stopErrors.push(error));
|
|
2540
|
-
}
|
|
2541
|
-
let cleanupError: unknown;
|
|
2542
|
-
if (createAttempted) {
|
|
2543
|
-
try {
|
|
2544
|
-
await this.removeContainer(name);
|
|
2545
|
-
activeContainers?.delete(name);
|
|
2546
|
-
setActive?.(undefined);
|
|
2547
|
-
} catch (error) {
|
|
2548
|
-
cleanupError = error;
|
|
2549
|
-
}
|
|
2550
|
-
}
|
|
2551
|
-
if (cleanupError !== undefined) {
|
|
2552
|
-
throw new ResourceCleanupError(
|
|
2553
|
-
hasOperationError
|
|
2554
|
-
? 'Workspace helper operation and cleanup both failed'
|
|
2555
|
-
: 'Unable to clean workspace helper container',
|
|
2556
|
-
[
|
|
2557
|
-
...(hasOperationError ? [operationError] : []),
|
|
2558
|
-
...stopErrors,
|
|
2559
|
-
cleanupError,
|
|
2560
|
-
],
|
|
2561
|
-
);
|
|
2562
|
-
}
|
|
2563
|
-
if (hasOperationError) throw operationError;
|
|
2564
|
-
if (!output) throw new RunnerError('Workspace helper produced no output');
|
|
2565
|
-
return output;
|
|
2566
|
-
}
|
|
2567
|
-
|
|
2568
|
-
private async runWorkspaceHelper(
|
|
2569
|
-
context: IExecutionContext,
|
|
2570
|
-
image: string,
|
|
2571
|
-
helperPath: string,
|
|
2572
|
-
volumeName: string,
|
|
2573
|
-
command: string[],
|
|
2574
|
-
activeContainers: Set<string>,
|
|
2575
|
-
setActive: (name: string | undefined) => boolean,
|
|
2576
|
-
commandTimeout: () => number,
|
|
2577
|
-
sourcePath?: string,
|
|
2578
|
-
): Promise<Uint8Array> {
|
|
2579
|
-
const name = this.createResourceName('helper');
|
|
2580
|
-
const create = buildOciHelperCreateCommand(this.config, {
|
|
2581
|
-
runnerId: context.runnerId,
|
|
2582
|
-
sessionId: context.sessionId,
|
|
2583
|
-
attemptId: context.lease.attemptId,
|
|
2584
|
-
containerName: name,
|
|
2585
|
-
image,
|
|
2586
|
-
helperPath,
|
|
2587
|
-
volumeName,
|
|
2588
|
-
command,
|
|
2589
|
-
...(sourcePath ? { sourcePath } : {}),
|
|
2590
|
-
});
|
|
2591
|
-
try {
|
|
2592
|
-
return await this.runInertContainer(
|
|
2593
|
-
name,
|
|
2594
|
-
create,
|
|
2595
|
-
context.signal,
|
|
2596
|
-
activeContainers,
|
|
2597
|
-
context.terminationDeadline,
|
|
2598
|
-
commandTimeout,
|
|
2599
|
-
setActive,
|
|
2600
|
-
);
|
|
2601
|
-
} catch (error) {
|
|
2602
|
-
if (error instanceof ResourceCleanupError) throw error;
|
|
2603
|
-
if (error instanceof WorkspaceResourceError) throw error;
|
|
2604
|
-
throw new WorkspaceResourceError('Workspace helper operation failed', { cause: error });
|
|
2605
|
-
} finally {
|
|
2606
|
-
setActive(undefined);
|
|
2607
|
-
}
|
|
2608
|
-
}
|
|
2609
|
-
|
|
2610
|
-
private async startVolumeHolder(
|
|
2611
|
-
context: IExecutionContext,
|
|
2612
|
-
image: string,
|
|
2613
|
-
helperPath: string,
|
|
2614
|
-
volumeName: string,
|
|
2615
|
-
lifetimeContainers: Set<string>,
|
|
2616
|
-
commandTimeout: () => number,
|
|
2617
|
-
): Promise<void> {
|
|
2618
|
-
const name = this.createResourceName('helper');
|
|
2619
|
-
const createArgs = buildOciHelperCreateCommand(this.config, {
|
|
2620
|
-
runnerId: context.runnerId,
|
|
2621
|
-
sessionId: context.sessionId,
|
|
2622
|
-
attemptId: context.lease.attemptId,
|
|
2623
|
-
containerName: name,
|
|
2624
|
-
image,
|
|
2625
|
-
helperPath,
|
|
2626
|
-
volumeName,
|
|
2627
|
-
command: ['hold'],
|
|
2628
|
-
});
|
|
2629
|
-
try {
|
|
2630
|
-
const create = await this.runRuntime(createArgs, commandTimeout(), context.signal);
|
|
2631
|
-
requireSuccess(create, 'Unable to create tmpfs volume holder container');
|
|
2632
|
-
lifetimeContainers.add(name);
|
|
2633
|
-
if (context.signal.aborted) throw context.signal.reason;
|
|
2634
|
-
const start = await this.runRuntime(['start', name], commandTimeout(), context.signal);
|
|
2635
|
-
requireSuccess(start, 'Unable to start tmpfs volume holder container');
|
|
2636
|
-
} catch (error) {
|
|
2637
|
-
let cleanupError: unknown;
|
|
2638
|
-
try {
|
|
2639
|
-
await this.stopAndRemoveContainer(name, context.terminationDeadline, context.signal);
|
|
2640
|
-
lifetimeContainers.delete(name);
|
|
2641
|
-
} catch (caughtCleanupError) {
|
|
2642
|
-
cleanupError = caughtCleanupError;
|
|
2643
|
-
}
|
|
2644
|
-
if (cleanupError !== undefined) {
|
|
2645
|
-
throw new ResourceCleanupError(
|
|
2646
|
-
'Tmpfs volume holder creation and cleanup both failed',
|
|
2647
|
-
[error, cleanupError],
|
|
2648
|
-
);
|
|
2649
|
-
}
|
|
2650
|
-
throw new WorkspaceResourceError('Unable to retain the attempt tmpfs volume mount', {
|
|
2651
|
-
cause: error,
|
|
2652
|
-
});
|
|
2653
|
-
}
|
|
2654
|
-
}
|
|
2655
|
-
|
|
2656
|
-
private async measureWorkspace(
|
|
2657
|
-
context: IExecutionContext,
|
|
2658
|
-
image: string,
|
|
2659
|
-
helperPath: string,
|
|
2660
|
-
volumeName: string,
|
|
2661
|
-
maximumBytes: number,
|
|
2662
|
-
maximumEntries: number,
|
|
2663
|
-
activeContainers: Set<string>,
|
|
2664
|
-
setActive: (name: string | undefined) => boolean,
|
|
2665
|
-
commandTimeout: () => number,
|
|
2666
|
-
): Promise<ICounts> {
|
|
2667
|
-
const output = await this.runWorkspaceHelper(
|
|
2668
|
-
context,
|
|
2669
|
-
image,
|
|
2670
|
-
helperPath,
|
|
2671
|
-
volumeName,
|
|
2672
|
-
[
|
|
2673
|
-
'measure',
|
|
2674
|
-
'--workspace',
|
|
2675
|
-
'/volume/workspace',
|
|
2676
|
-
'--maximum-bytes',
|
|
2677
|
-
String(maximumBytes),
|
|
2678
|
-
'--maximum-entries',
|
|
2679
|
-
String(maximumEntries),
|
|
2680
|
-
],
|
|
2681
|
-
activeContainers,
|
|
2682
|
-
setActive,
|
|
2683
|
-
commandTimeout,
|
|
2684
|
-
);
|
|
2685
|
-
return this.parseCounts(output, 'Workspace measurement helper');
|
|
2686
|
-
}
|
|
2687
|
-
|
|
2688
|
-
private async readWorkspaceCapacity(
|
|
2689
|
-
context: IExecutionContext,
|
|
2690
|
-
image: string,
|
|
2691
|
-
helperPath: string,
|
|
2692
|
-
volumeName: string,
|
|
2693
|
-
activeContainers: Set<string>,
|
|
2694
|
-
setActive: (name: string | undefined) => boolean,
|
|
2695
|
-
commandTimeout: () => number,
|
|
2696
|
-
): Promise<IFilesystemCapacity> {
|
|
2697
|
-
const output = await this.runWorkspaceHelper(
|
|
2698
|
-
context,
|
|
2699
|
-
image,
|
|
2700
|
-
helperPath,
|
|
2701
|
-
volumeName,
|
|
2702
|
-
['filesystem', '--path', '/volume'],
|
|
2703
|
-
activeContainers,
|
|
2704
|
-
setActive,
|
|
2705
|
-
commandTimeout,
|
|
2706
|
-
);
|
|
2707
|
-
const value = firstObject(
|
|
2708
|
-
parseJson(output, 'Workspace filesystem helper output was not valid JSON'),
|
|
2709
|
-
'Workspace filesystem helper output was empty',
|
|
2710
|
-
);
|
|
2711
|
-
const availableBlocks = Number(field(value, 'availableBlocks'));
|
|
2712
|
-
const availableInodes = Number(field(value, 'availableInodes'));
|
|
2713
|
-
nonNegativeSafeInteger(availableBlocks, 'Workspace available block count');
|
|
2714
|
-
nonNegativeSafeInteger(availableInodes, 'Workspace available inode count');
|
|
2715
|
-
return { availableBlocks, availableInodes };
|
|
2716
|
-
}
|
|
2717
|
-
|
|
2718
|
-
private async runStepContainer(
|
|
2719
|
-
name: string,
|
|
2720
|
-
command: IOciRunCommand,
|
|
2721
|
-
context: IExecutionContext,
|
|
2722
|
-
activeContainers: Set<string>,
|
|
2723
|
-
commandTimeout: () => number,
|
|
2724
|
-
remainingJobTimeout: () => number,
|
|
2725
|
-
setActive: (name: string | undefined) => boolean,
|
|
2726
|
-
onLogFailure: () => Promise<void>,
|
|
2727
|
-
): Promise<IContainerState> {
|
|
2728
|
-
let createAttempted = false;
|
|
2729
|
-
const stdoutDecoder = new TextDecoder();
|
|
2730
|
-
const stderrDecoder = new TextDecoder();
|
|
2731
|
-
let containerState: IContainerState | undefined;
|
|
2732
|
-
let operationError: unknown;
|
|
2733
|
-
let hasOperationError = false;
|
|
2734
|
-
try {
|
|
2735
|
-
createAttempted = true;
|
|
2736
|
-
const create = await this.runRuntime(
|
|
2737
|
-
command.args,
|
|
2738
|
-
commandTimeout(),
|
|
2739
|
-
context.signal,
|
|
2740
|
-
command.environment,
|
|
2741
|
-
);
|
|
2742
|
-
requireSuccess(create, 'Unable to create OCI step container');
|
|
2743
|
-
activeContainers.add(name);
|
|
2744
|
-
const stopRequested = setActive(name);
|
|
2745
|
-
if (context.signal.aborted) throw context.signal.reason;
|
|
2746
|
-
if (stopRequested) throw new RunnerError('OCI step was stopped before start');
|
|
2747
|
-
const start = await this.runRuntime(['start', name], commandTimeout(), context.signal);
|
|
2748
|
-
requireSuccess(start, 'Unable to start OCI step container');
|
|
2749
|
-
const logsPromise = this.runRuntime(
|
|
2750
|
-
['logs', '--follow', name],
|
|
2751
|
-
remainingJobTimeout(),
|
|
2752
|
-
undefined,
|
|
2753
|
-
{},
|
|
2754
|
-
async (stream, chunk) => {
|
|
2755
|
-
const decoder = stream === 'stdout' ? stdoutDecoder : stderrDecoder;
|
|
2756
|
-
const text = decoder.decode(chunk, { stream: true });
|
|
2757
|
-
if (text) await context.onLog(stream, text);
|
|
2758
|
-
},
|
|
2759
|
-
).catch(async (error) => {
|
|
2760
|
-
try {
|
|
2761
|
-
await onLogFailure();
|
|
2762
|
-
} catch (stopError) {
|
|
2763
|
-
throw new AggregateError([error, stopError], 'OCI logs and container stop both failed');
|
|
2764
|
-
}
|
|
2765
|
-
throw error;
|
|
2766
|
-
});
|
|
2767
|
-
const waitPromise = this.runRuntime(
|
|
2768
|
-
['wait', name],
|
|
2769
|
-
remainingJobTimeout(),
|
|
2770
|
-
).catch(async (error) => {
|
|
2771
|
-
try {
|
|
2772
|
-
await this.stopContainer(name);
|
|
2773
|
-
} catch (stopError) {
|
|
2774
|
-
throw new AggregateError([error, stopError], 'OCI wait and container stop both failed');
|
|
2775
|
-
}
|
|
2776
|
-
throw error;
|
|
2777
|
-
});
|
|
2778
|
-
const [logsResult, waitResult] = await Promise.allSettled([logsPromise, waitPromise]);
|
|
2779
|
-
const processErrors = [logsResult, waitResult].flatMap((result) =>
|
|
2780
|
-
result.status === 'rejected' ? [result.reason] : []
|
|
2781
|
-
);
|
|
2782
|
-
if (processErrors.length) {
|
|
2783
|
-
if (processErrors.some((error) => error instanceof ResourceCleanupError)) {
|
|
2784
|
-
throw new ResourceCleanupError('OCI step process cleanup failed', processErrors);
|
|
2785
|
-
}
|
|
2786
|
-
throw processErrors.length === 1
|
|
2787
|
-
? processErrors[0]
|
|
2788
|
-
: new AggregateError(processErrors, 'OCI logs and wait both failed');
|
|
2789
|
-
}
|
|
2790
|
-
if (logsResult.status !== 'fulfilled' || waitResult.status !== 'fulfilled') {
|
|
2791
|
-
throw new RunnerError('OCI process results were unavailable');
|
|
2792
|
-
}
|
|
2793
|
-
const logs = logsResult.value;
|
|
2794
|
-
const waited = waitResult.value;
|
|
2795
|
-
requireSuccess(logs, 'Unable to collect OCI step logs');
|
|
2796
|
-
requireSuccess(waited, 'Unable to wait for OCI step container');
|
|
2797
|
-
const finalStdout = stdoutDecoder.decode();
|
|
2798
|
-
const finalStderr = stderrDecoder.decode();
|
|
2799
|
-
if (finalStdout) await context.onLog('stdout', finalStdout);
|
|
2800
|
-
if (finalStderr) await context.onLog('stderr', finalStderr);
|
|
2801
|
-
const inspected = await this.runRuntime(['inspect', name], commandTimeout());
|
|
2802
|
-
requireSuccess(inspected, 'Unable to inspect OCI step container');
|
|
2803
|
-
const state = this.parseContainerState(inspected.stdout);
|
|
2804
|
-
const waitCode = Number(decode(waited.stdout));
|
|
2805
|
-
if (!Number.isInteger(waitCode) || waitCode !== state.exitCode) {
|
|
2806
|
-
throw new RunnerError('OCI step wait and inspection results differ');
|
|
2807
|
-
}
|
|
2808
|
-
containerState = state;
|
|
2809
|
-
} catch (error) {
|
|
2810
|
-
operationError = error;
|
|
2811
|
-
hasOperationError = true;
|
|
2812
|
-
}
|
|
2813
|
-
let cleanupError: unknown;
|
|
2814
|
-
if (createAttempted) {
|
|
2815
|
-
try {
|
|
2816
|
-
await this.removeContainer(name);
|
|
2817
|
-
activeContainers.delete(name);
|
|
2818
|
-
setActive(undefined);
|
|
2819
|
-
} catch (error) {
|
|
2820
|
-
cleanupError = error;
|
|
2821
|
-
}
|
|
2822
|
-
}
|
|
2823
|
-
if (cleanupError !== undefined) {
|
|
2824
|
-
throw new ResourceCleanupError(
|
|
2825
|
-
hasOperationError
|
|
2826
|
-
? 'OCI step operation and cleanup both failed'
|
|
2827
|
-
: 'Unable to clean OCI step container',
|
|
2828
|
-
[...(hasOperationError ? [operationError] : []), cleanupError],
|
|
2829
|
-
);
|
|
2830
|
-
}
|
|
2831
|
-
if (hasOperationError) throw operationError;
|
|
2832
|
-
if (!containerState) throw new RunnerError('OCI step produced no container state');
|
|
2833
|
-
return containerState;
|
|
2834
|
-
}
|
|
2835
|
-
|
|
2836
|
-
private async stopContainer(
|
|
2837
|
-
name: string,
|
|
2838
|
-
deadline?: () => number | undefined,
|
|
2839
|
-
signal?: AbortSignal,
|
|
2840
|
-
): Promise<void> {
|
|
2841
|
-
const stopRequestedAt = this.now();
|
|
2842
|
-
const defaultDeadline = stopRequestedAt + this.config.oci.stopTimeoutSeconds * 1000;
|
|
2843
|
-
let forceAt = Number.POSITIVE_INFINITY;
|
|
2844
|
-
let forceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
2845
|
-
let forcePromise: Promise<void> | undefined;
|
|
2846
|
-
const forceRemove = (): Promise<void> => {
|
|
2847
|
-
if (!forcePromise) {
|
|
2848
|
-
forcePromise = this.removeContainer(name);
|
|
2849
|
-
void forcePromise.catch(() => undefined);
|
|
2850
|
-
}
|
|
2851
|
-
return forcePromise;
|
|
2852
|
-
};
|
|
2853
|
-
const scheduleForceRemoval = (): void => {
|
|
2854
|
-
const configuredDeadline = deadline?.();
|
|
2855
|
-
const nextForceAt = configuredDeadline === undefined
|
|
2856
|
-
? defaultDeadline
|
|
2857
|
-
: Math.min(defaultDeadline, configuredDeadline);
|
|
2858
|
-
if (nextForceAt >= forceAt) return;
|
|
2859
|
-
forceAt = nextForceAt;
|
|
2860
|
-
if (forceTimer !== undefined) clearTimeout(forceTimer);
|
|
2861
|
-
forceTimer = setTimeout(() => {
|
|
2862
|
-
forceTimer = undefined;
|
|
2863
|
-
forceRemove();
|
|
2864
|
-
}, Math.max(0, forceAt - this.now()));
|
|
2865
|
-
};
|
|
2866
|
-
const deadlineChanged = (): void => scheduleForceRemoval();
|
|
2867
|
-
signal?.addEventListener('abort', deadlineChanged, { once: true });
|
|
2868
|
-
scheduleForceRemoval();
|
|
2869
|
-
if (signal?.aborted) deadlineChanged();
|
|
2870
|
-
const remainingMs = Math.max(0, forceAt - stopRequestedAt);
|
|
2871
|
-
const graceSeconds = Math.max(0, Math.floor(remainingMs / 1000));
|
|
2872
|
-
let stopError: unknown;
|
|
2873
|
-
try {
|
|
2874
|
-
const stopped = await this.runRuntime(
|
|
2875
|
-
['stop', '--time', String(graceSeconds), name],
|
|
2876
|
-
remainingMs + 5_000,
|
|
2877
|
-
);
|
|
2878
|
-
if (!stopped.success) {
|
|
2879
|
-
stopError = new RunnerError(`Unable to stop OCI container ${name}`);
|
|
2880
|
-
}
|
|
2881
|
-
} catch (error) {
|
|
2882
|
-
stopError = error;
|
|
2883
|
-
} finally {
|
|
2884
|
-
if (forceTimer !== undefined) clearTimeout(forceTimer);
|
|
2885
|
-
signal?.removeEventListener('abort', deadlineChanged);
|
|
2886
|
-
}
|
|
2887
|
-
if (stopError !== undefined) {
|
|
2888
|
-
try {
|
|
2889
|
-
await forceRemove();
|
|
2890
|
-
} catch (forceError) {
|
|
2891
|
-
throw new ResourceCleanupError(
|
|
2892
|
-
`Unable to stop or force-remove OCI container ${name}`,
|
|
2893
|
-
[stopError, forceError],
|
|
2894
|
-
);
|
|
2895
|
-
}
|
|
2896
|
-
return;
|
|
2897
|
-
}
|
|
2898
|
-
if (forcePromise) {
|
|
2899
|
-
try {
|
|
2900
|
-
await forcePromise;
|
|
2901
|
-
} catch (error) {
|
|
2902
|
-
throw new ResourceCleanupError(`Unable to force-remove OCI container ${name}`, [error]);
|
|
2903
|
-
}
|
|
2904
|
-
}
|
|
2905
|
-
}
|
|
2906
|
-
|
|
2907
|
-
private async stopAndRemoveContainer(
|
|
2908
|
-
name: string,
|
|
2909
|
-
deadline?: () => number | undefined,
|
|
2910
|
-
signal?: AbortSignal,
|
|
2911
|
-
): Promise<void> {
|
|
2912
|
-
let stopError: unknown;
|
|
2913
|
-
try {
|
|
2914
|
-
await this.stopContainer(name, deadline, signal);
|
|
2915
|
-
} catch (error) {
|
|
2916
|
-
stopError = error;
|
|
2917
|
-
}
|
|
2918
|
-
try {
|
|
2919
|
-
await this.removeContainer(name);
|
|
2920
|
-
} catch (removeError) {
|
|
2921
|
-
throw new ResourceCleanupError(
|
|
2922
|
-
`Unable to stop or remove OCI container ${name}`,
|
|
2923
|
-
stopError === undefined ? [removeError] : [stopError, removeError],
|
|
2924
|
-
);
|
|
2925
|
-
}
|
|
2926
|
-
}
|
|
2927
|
-
|
|
2928
|
-
private async removeContainer(name: string): Promise<void> {
|
|
2929
|
-
try {
|
|
2930
|
-
const result = await this.runRuntime(['rm', '--force', '--volumes', name], 15_000);
|
|
2931
|
-
if (!result.success) {
|
|
2932
|
-
const inspection = await this.runRuntime(['inspect', name], 5_000);
|
|
2933
|
-
if (inspection.success) {
|
|
2934
|
-
throw new ResourceCleanupError(`Unable to remove OCI container ${name}`, [
|
|
2935
|
-
new RunnerError(`OCI runtime retained container ${name}`),
|
|
2936
|
-
]);
|
|
2937
|
-
}
|
|
2938
|
-
}
|
|
2939
|
-
} catch (error) {
|
|
2940
|
-
if (error instanceof ResourceCleanupError) throw error;
|
|
2941
|
-
throw new ResourceCleanupError(`Unable to remove OCI container ${name}`, [error]);
|
|
2942
|
-
}
|
|
2943
|
-
}
|
|
2944
|
-
|
|
2945
|
-
private async removeVolume(name: string): Promise<void> {
|
|
2946
|
-
try {
|
|
2947
|
-
const result = await this.runRuntime(['volume', 'rm', '--force', name], 15_000);
|
|
2948
|
-
if (!result.success) {
|
|
2949
|
-
const inspection = await this.runRuntime(['volume', 'inspect', name], 5_000);
|
|
2950
|
-
if (inspection.success) {
|
|
2951
|
-
throw new ResourceCleanupError(`Unable to remove OCI volume ${name}`, [
|
|
2952
|
-
new RunnerError(`OCI runtime retained volume ${name}`),
|
|
2953
|
-
]);
|
|
2954
|
-
}
|
|
2955
|
-
}
|
|
2956
|
-
} catch (error) {
|
|
2957
|
-
if (error instanceof ResourceCleanupError) throw error;
|
|
2958
|
-
throw new ResourceCleanupError(`Unable to remove OCI volume ${name}`, [error]);
|
|
2959
|
-
}
|
|
2960
|
-
}
|
|
2961
|
-
|
|
2962
|
-
private async removePath(path: string): Promise<void> {
|
|
2963
|
-
try {
|
|
2964
|
-
await this.remove(path, { recursive: true });
|
|
2965
|
-
} catch (error) {
|
|
2966
|
-
if (!isNotFound(error)) {
|
|
2967
|
-
throw new ResourceCleanupError(`Unable to remove owned path ${path}`, [error]);
|
|
2968
|
-
}
|
|
2969
|
-
}
|
|
2970
|
-
}
|
|
2971
|
-
|
|
2972
|
-
private createResourceName(kind: 'helper' | 'probe' | 'step' | 'volume'): string {
|
|
2973
|
-
const name = `shipzone-ci-${kind}-${this.randomHex()}`;
|
|
2974
|
-
return validateGeneratedName(name, kind === 'volume' ? 'volume' : 'container');
|
|
2975
|
-
}
|
|
2976
|
-
|
|
2977
|
-
private randomHex(): string {
|
|
2978
|
-
const value = this.randomId().replaceAll('-', '').toLowerCase();
|
|
2979
|
-
if (!/^[a-f0-9]{32}$/.test(value)) {
|
|
2980
|
-
throw new RunnerError('Random ID source returned an invalid value');
|
|
2981
|
-
}
|
|
2982
|
-
return value;
|
|
2983
|
-
}
|
|
2984
|
-
}
|
|
2985
|
-
|
|
2986
|
-
export const copyOciConfig = (config: IOciExecutorConfig): IOciExecutorConfig => ({
|
|
2987
|
-
...config,
|
|
2988
|
-
allowedNetworks: [...config.allowedNetworks],
|
|
2989
|
-
});
|