@ship.zone/runner 3.0.0 → 4.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 +43 -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.js +39 -11
- package/dist_ts/config.js +70 -20
- 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 +93 -22
- 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 +1045 -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 -3
- package/dist_ts/protocol-validator.js +26 -21
- package/dist_ts/redactor.js +1 -1
- package/dist_ts/registration-state.js +1 -1
- package/dist_ts/runner.d.ts +6 -5
- package/dist_ts/runner.js +48 -18
- 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 +9 -6
- package/readme.md +72 -61
- 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 +33 -11
- package/ts/config.ts +96 -23
- package/ts/egress-proxy.ts +649 -0
- package/ts/index.ts +5 -1
- package/ts/interfaces.ts +103 -21
- package/ts/microvm-executor.ts +1265 -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 -25
- package/ts/runner.ts +51 -17
- 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/protocol-validator.ts
CHANGED
|
@@ -464,34 +464,37 @@ const requireLeaseCoherence = (lease: IJobLease): void => {
|
|
|
464
464
|
};
|
|
465
465
|
|
|
466
466
|
/**
|
|
467
|
-
* Narrows a coherent lease to
|
|
468
|
-
*
|
|
469
|
-
*
|
|
467
|
+
* Narrows a coherent lease to an executable Firecracker `microvm` lease (`oci`, `vm`, or
|
|
468
|
+
* `oci-image`). Refuses `container` isolation unconditionally because this runner uses
|
|
469
|
+
* Firecracker microVMs exclusively.
|
|
470
470
|
*/
|
|
471
471
|
export const requireExecutableLease = (lease: IJobLease): IOciJobLease => {
|
|
472
472
|
const job = lease.job;
|
|
473
|
-
if (job.requirements.
|
|
473
|
+
if (job.requirements.isolation !== 'microvm') {
|
|
474
|
+
throw new UnsupportedJobError('container isolation is not supported by this runner');
|
|
475
|
+
}
|
|
476
|
+
if (job.requirements.platform && !job.requirements.platform.startsWith('linux/')) {
|
|
474
477
|
throw new UnsupportedJobError(
|
|
475
|
-
`
|
|
478
|
+
`Platform ${job.requirements.platform} is not supported by this Linux Firecracker runner`,
|
|
476
479
|
);
|
|
477
480
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
if (
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
481
|
+
const profile = job.requirements.executionProfile;
|
|
482
|
+
if (profile === 'oci') {
|
|
483
|
+
if (!hasSteps(job) || job.execution.profile !== 'oci') {
|
|
484
|
+
throw new UnsupportedJobError('Job execution does not match the oci profile');
|
|
485
|
+
}
|
|
486
|
+
} else if (profile === 'vm') {
|
|
487
|
+
if (!hasSteps(job) || job.execution.profile !== 'vm') {
|
|
488
|
+
throw new UnsupportedJobError('Job execution does not match the vm profile');
|
|
489
|
+
}
|
|
490
|
+
} else if (profile === 'oci-image') {
|
|
491
|
+
if (!('build' in job)) {
|
|
492
|
+
throw new UnsupportedJobError('Job does not match the oci-image build profile');
|
|
493
|
+
}
|
|
494
|
+
} else {
|
|
495
|
+
throw new UnsupportedJobError(
|
|
496
|
+
`Execution profile ${String(profile)} is not supported by this runner`,
|
|
497
|
+
);
|
|
495
498
|
}
|
|
496
499
|
return {
|
|
497
500
|
jobId: lease.jobId,
|
|
@@ -499,9 +502,10 @@ export const requireExecutableLease = (lease: IJobLease): IOciJobLease => {
|
|
|
499
502
|
leaseId: lease.leaseId,
|
|
500
503
|
fencingToken: lease.fencingToken,
|
|
501
504
|
leaseExpiresAt: lease.leaseExpiresAt,
|
|
502
|
-
job: job as
|
|
503
|
-
grants:
|
|
504
|
-
bindings:
|
|
505
|
+
job: job as IOciJobLease['job'],
|
|
506
|
+
grants: lease.grants,
|
|
507
|
+
bindings: lease.bindings,
|
|
508
|
+
...(lease.npmGrants !== undefined ? { npmGrants: lease.npmGrants } : {}),
|
|
505
509
|
};
|
|
506
510
|
};
|
|
507
511
|
|
package/ts/runner.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type {
|
|
|
19
19
|
ICompleteJobRequest,
|
|
20
20
|
ICompleteJobResponse,
|
|
21
21
|
IDiscoveryResponse,
|
|
22
|
+
IImageRecord,
|
|
22
23
|
IJobExecutor,
|
|
23
24
|
IJobHeartbeatRequest,
|
|
24
25
|
IJobHeartbeatResponse,
|
|
@@ -30,6 +31,7 @@ import type {
|
|
|
30
31
|
IPreparedOciLease,
|
|
31
32
|
IPreparedWorkspace,
|
|
32
33
|
IProtocolLimits,
|
|
34
|
+
IRecordImageRequest,
|
|
33
35
|
IRecoverAttemptRequest,
|
|
34
36
|
IRunnerCapabilities,
|
|
35
37
|
IRunnerConfig,
|
|
@@ -66,6 +68,7 @@ export interface IRunnerCoordinatorClient {
|
|
|
66
68
|
signal?: AbortSignal,
|
|
67
69
|
): Promise<IJobHeartbeatResponse>;
|
|
68
70
|
appendLog(chunk: ILogChunk, signal?: AbortSignal): Promise<ILogAcknowledgement>;
|
|
71
|
+
recordImage?(request: IRecordImageRequest, signal?: AbortSignal): Promise<IImageRecord>;
|
|
69
72
|
completeJob(request: ICompleteJobRequest, signal?: AbortSignal): Promise<ICompleteJobResponse>;
|
|
70
73
|
abandonJob(request: IAbandonJobRequest, signal?: AbortSignal): Promise<void>;
|
|
71
74
|
recoverAttempt(request: IRecoverAttemptRequest, signal?: AbortSignal): Promise<void>;
|
|
@@ -210,22 +213,24 @@ class LeaseGuard {
|
|
|
210
213
|
}
|
|
211
214
|
|
|
212
215
|
/**
|
|
213
|
-
* The capabilities this runner advertises:
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
* image
|
|
216
|
+
* The capabilities this Firecracker runner advertises:
|
|
217
|
+
* - `runnerProfile: 'workload'` → `['oci', 'vm']` in `microvm` isolation (never `oci-image`).
|
|
218
|
+
* - `runnerProfile: 'builder'` → `['oci-image']` exclusively in `microvm` isolation (dedicated builder).
|
|
219
|
+
* Both advertise `image-pull-grants`, `candidate-bindings`, and `npm-read-grants`.
|
|
217
220
|
*/
|
|
218
221
|
export const runnerCapabilities = (
|
|
219
222
|
config: IRunnerConfig,
|
|
220
223
|
runtime: Pick<IOciRuntimeFacts, 'os' | 'architecture'>,
|
|
221
224
|
): IRunnerCapabilities => {
|
|
222
|
-
const
|
|
223
|
-
|
|
225
|
+
const isBuilder = config.oci.runnerProfile === 'builder';
|
|
226
|
+
const artifactEnabled = !isBuilder && config.maximumArtifacts > 0 &&
|
|
227
|
+
config.maximumArtifactBytes > 0 && config.maximumArtifactExtractedBytes > 0 &&
|
|
228
|
+
config.maximumArtifactEntries > 0;
|
|
224
229
|
const cacheEnabled = config.maximumCaches > 0 && config.maximumCacheArchiveBytes > 0 &&
|
|
225
230
|
config.maximumCacheExtractedBytes > 0 && config.maximumCacheEntries > 0;
|
|
226
231
|
return createRunnerCapabilitySnapshot({
|
|
227
|
-
executionProfiles: ['oci'],
|
|
228
|
-
isolation: ['
|
|
232
|
+
executionProfiles: isBuilder ? ['oci-image'] : ['oci', 'vm'],
|
|
233
|
+
isolation: ['microvm'],
|
|
229
234
|
platforms: [`${runtime.os}/${runtime.architecture}`],
|
|
230
235
|
labels: [...config.labels],
|
|
231
236
|
features: [
|
|
@@ -258,7 +263,7 @@ export const runnerCapabilities = (
|
|
|
258
263
|
maximumPids: config.oci.maximumPids,
|
|
259
264
|
maximumSharedMemoryBytes: config.oci.maximumSharedMemoryBytes,
|
|
260
265
|
},
|
|
261
|
-
leaseFeatures: [],
|
|
266
|
+
leaseFeatures: ['image-pull-grants', 'candidate-bindings', 'npm-read-grants'],
|
|
262
267
|
maximumTimeoutMs: config.oci.maximumTimeoutMs,
|
|
263
268
|
});
|
|
264
269
|
};
|
|
@@ -712,14 +717,18 @@ export class ShipRunner {
|
|
|
712
717
|
recordFailure(error);
|
|
713
718
|
};
|
|
714
719
|
|
|
720
|
+
const isImageBuild = lease.job.requirements.executionProfile === 'oci-image';
|
|
721
|
+
const hasArtifacts = !isImageBuild && 'artifacts' in lease.job && lease.job.artifacts.length > 0;
|
|
722
|
+
const hasStepCaches = !isImageBuild && lease.job.caches.length > 0;
|
|
723
|
+
|
|
715
724
|
const deadlineTimer = setTimeout(() => {
|
|
716
725
|
if (!executionAbort.signal.aborted) executionAbort.abort('job_timeout');
|
|
717
726
|
}, Math.max(0, lease.job.timeoutMs - (this.monotonicNow() - acceptedAt)));
|
|
718
727
|
try {
|
|
719
|
-
if (
|
|
728
|
+
if (hasArtifacts && !this.dependencies.artifactManager) {
|
|
720
729
|
throw new RunnerError('Artifact manager is not configured');
|
|
721
730
|
}
|
|
722
|
-
if (
|
|
731
|
+
if (hasStepCaches && !this.dependencies.cacheManager) {
|
|
723
732
|
throw new RunnerError('Cache manager is not configured');
|
|
724
733
|
}
|
|
725
734
|
stagingWorkspace = await this.dependencies.workspaceManager.prepare({
|
|
@@ -727,7 +736,7 @@ export class ShipRunner {
|
|
|
727
736
|
job: lease.job,
|
|
728
737
|
signal: executionSignal,
|
|
729
738
|
});
|
|
730
|
-
if (lease.job
|
|
739
|
+
if (hasStepCaches && 'steps' in lease.job) {
|
|
731
740
|
await this.dependencies.cacheManager!.restore({
|
|
732
741
|
workspacePath: stagingWorkspace.path,
|
|
733
742
|
workspaceEntryCount: stagingWorkspace.materializedEntryCount,
|
|
@@ -751,9 +760,34 @@ export class ShipRunner {
|
|
|
751
760
|
onLog: (stream, data) => logs.write(stream, data),
|
|
752
761
|
});
|
|
753
762
|
runtimeWorkspace = result.workspace;
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
763
|
+
if (isImageBuild) {
|
|
764
|
+
exitCode = null;
|
|
765
|
+
if (result.stopReason) {
|
|
766
|
+
status = this.completionStatus(result.stopReason, null, heartbeatState);
|
|
767
|
+
} else if (result.producedImage) {
|
|
768
|
+
if (!this.dependencies.api.recordImage) {
|
|
769
|
+
throw new RunnerError('Coordinator API client does not implement recordImage');
|
|
770
|
+
}
|
|
771
|
+
await this.dependencies.api.recordImage(
|
|
772
|
+
{
|
|
773
|
+
recordRequestId: plugins.crypto.randomUUID(),
|
|
774
|
+
identity,
|
|
775
|
+
manifestDigest: result.producedImage.manifestDigest,
|
|
776
|
+
mediaType: result.producedImage.mediaType,
|
|
777
|
+
sizeBytes: result.producedImage.sizeBytes,
|
|
778
|
+
platform: result.producedImage.platform,
|
|
779
|
+
},
|
|
780
|
+
executionSignal,
|
|
781
|
+
);
|
|
782
|
+
status = 'succeeded';
|
|
783
|
+
} else {
|
|
784
|
+
status = 'failed';
|
|
785
|
+
}
|
|
786
|
+
} else {
|
|
787
|
+
exitCode = result.exitCode;
|
|
788
|
+
status = this.completionStatus(result.stopReason, result.exitCode, heartbeatState);
|
|
789
|
+
if (status !== 'succeeded' && status !== 'failed') exitCode = null;
|
|
790
|
+
}
|
|
757
791
|
} catch (error) {
|
|
758
792
|
if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
|
|
759
793
|
else if (
|
|
@@ -798,7 +832,7 @@ export class ShipRunner {
|
|
|
798
832
|
}
|
|
799
833
|
|
|
800
834
|
if (runtimeWorkspace && !cleanupFailure && !transferSignal.aborted) {
|
|
801
|
-
if (lease.job
|
|
835
|
+
if (hasStepCaches && 'steps' in lease.job) {
|
|
802
836
|
try {
|
|
803
837
|
await this.dependencies.cacheManager!.save({
|
|
804
838
|
workspace: runtimeWorkspace,
|
|
@@ -814,7 +848,7 @@ export class ShipRunner {
|
|
|
814
848
|
}
|
|
815
849
|
}
|
|
816
850
|
if (
|
|
817
|
-
lease.job
|
|
851
|
+
hasArtifacts && 'steps' in lease.job && !cleanupFailure &&
|
|
818
852
|
!transferSignal.aborted
|
|
819
853
|
) {
|
|
820
854
|
try {
|
package/ts/state-owner.ts
CHANGED
|
@@ -71,7 +71,14 @@ export const resolvePackagedWorkspaceHelperPath = async (
|
|
|
71
71
|
`This executable embeds only the ${embeddedTarget} workspace helper, not ${target}`,
|
|
72
72
|
);
|
|
73
73
|
}
|
|
74
|
-
return await plugins.smartsea.getSidecarPath(workspaceHelperSidecarName)
|
|
74
|
+
return await plugins.smartsea.getSidecarPath(workspaceHelperSidecarName).catch((error) => {
|
|
75
|
+
throw new RunnerError(
|
|
76
|
+
`The embedded ${embeddedTarget} workspace helper is unavailable: ${
|
|
77
|
+
error instanceof Error ? error.message : String(error)
|
|
78
|
+
}`,
|
|
79
|
+
{ cause: error },
|
|
80
|
+
);
|
|
81
|
+
});
|
|
75
82
|
}
|
|
76
83
|
return plugins.url.fileURLToPath(
|
|
77
84
|
new URL(`../dist_rust/runnerworkspace_${target}_musl`, import.meta.url),
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import { RunnerError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
export const GUEST_VSOCK_PORT = 1024;
|
|
5
|
+
|
|
6
|
+
export const FRAME_JSON_REQ = 0x01;
|
|
7
|
+
export const FRAME_JSON_RES = 0x02;
|
|
8
|
+
export const FRAME_DATA = 0x03;
|
|
9
|
+
export const FRAME_DATA_EOF = 0x04;
|
|
10
|
+
export const FRAME_STDOUT = 0x05;
|
|
11
|
+
export const FRAME_STDERR = 0x06;
|
|
12
|
+
export const FRAME_CANCEL = 0x07;
|
|
13
|
+
|
|
14
|
+
const MAXIMUM_FRAME_BYTES = 4 * 1024 * 1024;
|
|
15
|
+
const STREAM_CHUNK_BYTES = 32 * 1024;
|
|
16
|
+
|
|
17
|
+
export interface IGuestFrame {
|
|
18
|
+
kind: number;
|
|
19
|
+
payload: Buffer;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface IGuestHello {
|
|
23
|
+
ok: true;
|
|
24
|
+
version: string;
|
|
25
|
+
os: string;
|
|
26
|
+
architecture: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface IGuestTransferResult {
|
|
30
|
+
ok: true;
|
|
31
|
+
bytes: number;
|
|
32
|
+
entries: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface IGuestStepRequest {
|
|
36
|
+
command: string[];
|
|
37
|
+
env: Record<string, string>;
|
|
38
|
+
workingDirectory: string;
|
|
39
|
+
uid: number;
|
|
40
|
+
gid: number;
|
|
41
|
+
rootMode?: boolean;
|
|
42
|
+
timeoutMs: number;
|
|
43
|
+
memoryBytes: number;
|
|
44
|
+
cpus: number;
|
|
45
|
+
pids: number;
|
|
46
|
+
sharedMemoryBytes: number;
|
|
47
|
+
temporarySizeBytes: number;
|
|
48
|
+
maximumWorkspaceBytes: number;
|
|
49
|
+
maximumWorkspaceEntries: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface IGuestImageBuildRequest {
|
|
53
|
+
context: string;
|
|
54
|
+
dockerfile: string;
|
|
55
|
+
target?: string;
|
|
56
|
+
platform: string;
|
|
57
|
+
buildArgs: Record<string, string>;
|
|
58
|
+
secrets: Record<string, string>;
|
|
59
|
+
labels: Record<string, string>;
|
|
60
|
+
baseImages: Array<{ name: string; image: string }>;
|
|
61
|
+
npmrcContent?: string;
|
|
62
|
+
pushRegistry: string;
|
|
63
|
+
pushRepository: string;
|
|
64
|
+
grants: Array<{ registry: string; username: string; secret: string }>;
|
|
65
|
+
timeoutMs: number;
|
|
66
|
+
importCacheDir?: string;
|
|
67
|
+
exportCacheDir?: string;
|
|
68
|
+
buildctlPath?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface IGuestImageBuildResult {
|
|
72
|
+
ok: true;
|
|
73
|
+
exitCode: number | null;
|
|
74
|
+
timedOut: boolean;
|
|
75
|
+
canceled: boolean;
|
|
76
|
+
manifestDigest: string | null;
|
|
77
|
+
mediaType: string | null;
|
|
78
|
+
sizeBytes: number | null;
|
|
79
|
+
cacheExported: boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface IGuestStepResult {
|
|
83
|
+
ok: true;
|
|
84
|
+
exitCode: number | null;
|
|
85
|
+
signal: number | null;
|
|
86
|
+
timedOut: boolean;
|
|
87
|
+
canceled: boolean;
|
|
88
|
+
oomKilled: boolean;
|
|
89
|
+
workspaceBytes: number;
|
|
90
|
+
workspaceEntries: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface IGuestRunStepCallbacks {
|
|
94
|
+
onStdout?: (chunk: Uint8Array) => Promise<void>;
|
|
95
|
+
onStderr?: (chunk: Uint8Array) => Promise<void>;
|
|
96
|
+
signal?: AbortSignal;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
class FrameReader {
|
|
100
|
+
private chunks: Buffer[] = [];
|
|
101
|
+
private buffered = 0;
|
|
102
|
+
private ended = false;
|
|
103
|
+
private failure?: Error;
|
|
104
|
+
private waiters: Array<() => void> = [];
|
|
105
|
+
|
|
106
|
+
constructor(private readonly socket: plugins.net.Socket) {
|
|
107
|
+
socket.on('data', (chunk: Buffer) => {
|
|
108
|
+
this.chunks.push(chunk);
|
|
109
|
+
this.buffered += chunk.length;
|
|
110
|
+
this.wake();
|
|
111
|
+
});
|
|
112
|
+
socket.on('end', () => {
|
|
113
|
+
this.ended = true;
|
|
114
|
+
this.wake();
|
|
115
|
+
});
|
|
116
|
+
socket.on('close', () => {
|
|
117
|
+
this.ended = true;
|
|
118
|
+
this.wake();
|
|
119
|
+
});
|
|
120
|
+
socket.on('error', (error: Error) => {
|
|
121
|
+
this.failure = error;
|
|
122
|
+
this.ended = true;
|
|
123
|
+
this.wake();
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private wake(): void {
|
|
128
|
+
const list = this.waiters;
|
|
129
|
+
this.waiters = [];
|
|
130
|
+
for (const resolve of list) resolve();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private async ensure(bytes: number): Promise<boolean> {
|
|
134
|
+
while (this.buffered < bytes) {
|
|
135
|
+
if (this.failure) throw new RunnerError(`Guest vsock stream error: ${this.failure.message}`, { cause: this.failure });
|
|
136
|
+
if (this.ended) return false;
|
|
137
|
+
await new Promise<void>((resolve) => {
|
|
138
|
+
this.waiters.push(resolve);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private take(bytes: number): Buffer {
|
|
145
|
+
const parts: Buffer[] = [];
|
|
146
|
+
let remaining = bytes;
|
|
147
|
+
while (remaining > 0) {
|
|
148
|
+
const head = this.chunks[0];
|
|
149
|
+
if (head.length <= remaining) {
|
|
150
|
+
parts.push(head);
|
|
151
|
+
this.chunks.shift();
|
|
152
|
+
remaining -= head.length;
|
|
153
|
+
} else {
|
|
154
|
+
parts.push(head.subarray(0, remaining));
|
|
155
|
+
this.chunks[0] = head.subarray(remaining);
|
|
156
|
+
remaining = 0;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
this.buffered -= bytes;
|
|
160
|
+
return parts.length === 1 ? parts[0] : Buffer.concat(parts, bytes);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async nextFrame(): Promise<IGuestFrame | null> {
|
|
164
|
+
const hasHeader = await this.ensure(5);
|
|
165
|
+
if (!hasHeader) {
|
|
166
|
+
if (this.buffered > 0) {
|
|
167
|
+
throw new RunnerError('Guest vsock stream closed mid-frame');
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
const header = this.take(5);
|
|
172
|
+
const length = header.readUInt32BE(0);
|
|
173
|
+
const kind = header[4];
|
|
174
|
+
if (length > MAXIMUM_FRAME_BYTES) {
|
|
175
|
+
throw new RunnerError('Guest vsock frame exceeds maximum allowed size');
|
|
176
|
+
}
|
|
177
|
+
if (length === 0) return { kind, payload: Buffer.alloc(0) };
|
|
178
|
+
const hasPayload = await this.ensure(length);
|
|
179
|
+
if (!hasPayload) throw new RunnerError('Guest vsock stream closed before frame payload completed');
|
|
180
|
+
return { kind, payload: this.take(length) };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const writeAllSocket = (socket: plugins.net.Socket, data: Uint8Array): Promise<void> =>
|
|
185
|
+
new Promise((resolve, reject) => {
|
|
186
|
+
if (socket.destroyed) {
|
|
187
|
+
reject(new RunnerError('Guest vsock socket is closed'));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
socket.write(data, (error?: Error | null) => {
|
|
191
|
+
if (error) reject(new RunnerError(`Guest vsock write failed: ${error.message}`, { cause: error }));
|
|
192
|
+
else resolve();
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
const encodeFrame = (kind: number, payload: Uint8Array): Buffer => {
|
|
197
|
+
if (payload.byteLength > MAXIMUM_FRAME_BYTES) {
|
|
198
|
+
throw new RunnerError('Outbound vsock frame exceeds maximum allowed size');
|
|
199
|
+
}
|
|
200
|
+
const buf = Buffer.allocUnsafe(5 + payload.byteLength);
|
|
201
|
+
buf.writeUInt32BE(payload.byteLength, 0);
|
|
202
|
+
buf[4] = kind;
|
|
203
|
+
if (payload.byteLength > 0) buf.set(payload, 5);
|
|
204
|
+
return buf;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Framed binary/JSON RPC client talking to `runnerworkspace guest-init` inside a Firecracker
|
|
209
|
+
* microVM over vsock (or over a Unix socket in unit tests).
|
|
210
|
+
*/
|
|
211
|
+
export class GuestVsockClient {
|
|
212
|
+
private readonly reader: FrameReader;
|
|
213
|
+
|
|
214
|
+
constructor(private readonly socket: plugins.net.Socket) {
|
|
215
|
+
this.reader = new FrameReader(socket);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
close(): void {
|
|
219
|
+
if (!this.socket.destroyed) this.socket.destroy();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private async sendJson(request: Record<string, unknown>): Promise<void> {
|
|
223
|
+
const payload = Buffer.from(JSON.stringify(request), 'utf8');
|
|
224
|
+
await writeAllSocket(this.socket, encodeFrame(FRAME_JSON_REQ, payload));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async readJsonResponse<T extends { ok: true }>(): Promise<T> {
|
|
228
|
+
const frame = await this.reader.nextFrame();
|
|
229
|
+
if (!frame) throw new RunnerError('Guest closed vsock connection before responding');
|
|
230
|
+
if (frame.kind !== FRAME_JSON_RES) {
|
|
231
|
+
throw new RunnerError(`Guest returned unexpected frame type ${frame.kind}`);
|
|
232
|
+
}
|
|
233
|
+
let parsed: unknown;
|
|
234
|
+
try {
|
|
235
|
+
parsed = JSON.parse(frame.payload.toString('utf8'));
|
|
236
|
+
} catch (error) {
|
|
237
|
+
throw new RunnerError('Guest returned malformed JSON response', { cause: error });
|
|
238
|
+
}
|
|
239
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
240
|
+
throw new RunnerError('Guest returned non-object JSON response');
|
|
241
|
+
}
|
|
242
|
+
const record = parsed as Record<string, unknown>;
|
|
243
|
+
if (record.ok !== true) {
|
|
244
|
+
const message = typeof record.error === 'string' ? record.error : 'Unknown guest error';
|
|
245
|
+
throw new RunnerError(`Guest operation failed: ${message}`);
|
|
246
|
+
}
|
|
247
|
+
return record as T;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async hello(): Promise<IGuestHello> {
|
|
251
|
+
await this.sendJson({ op: 'hello' });
|
|
252
|
+
return await this.readJsonResponse<IGuestHello>();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async prepareWorkspace(options: {
|
|
256
|
+
workspaceSizeBytes: number;
|
|
257
|
+
maximumWorkspaceEntries: number;
|
|
258
|
+
uid: number;
|
|
259
|
+
gid: number;
|
|
260
|
+
mode?: 'oci' | 'vm' | 'oci-image';
|
|
261
|
+
npmrcContent?: string;
|
|
262
|
+
}): Promise<void> {
|
|
263
|
+
await this.sendJson({ op: 'prepare_workspace', ...options });
|
|
264
|
+
await this.readJsonResponse<{ ok: true }>();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async importTar(
|
|
268
|
+
tarBytes: Uint8Array,
|
|
269
|
+
options: { maximumBytes: number; maximumEntries: number; uid: number; gid: number },
|
|
270
|
+
): Promise<IGuestTransferResult> {
|
|
271
|
+
await this.sendJson({ op: 'import_tar', ...options });
|
|
272
|
+
for (let offset = 0; offset < tarBytes.byteLength; offset += STREAM_CHUNK_BYTES) {
|
|
273
|
+
const slice = tarBytes.subarray(offset, Math.min(tarBytes.byteLength, offset + STREAM_CHUNK_BYTES));
|
|
274
|
+
await writeAllSocket(this.socket, encodeFrame(FRAME_DATA, slice));
|
|
275
|
+
}
|
|
276
|
+
await writeAllSocket(this.socket, encodeFrame(FRAME_DATA_EOF, Buffer.alloc(0)));
|
|
277
|
+
return await this.readJsonResponse<IGuestTransferResult>();
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async runStep(
|
|
281
|
+
spec: IGuestStepRequest,
|
|
282
|
+
callbacks: IGuestRunStepCallbacks = {},
|
|
283
|
+
): Promise<IGuestStepResult> {
|
|
284
|
+
let cancelSent = false;
|
|
285
|
+
const sendCancel = (): void => {
|
|
286
|
+
if (cancelSent || this.socket.destroyed) return;
|
|
287
|
+
cancelSent = true;
|
|
288
|
+
void writeAllSocket(this.socket, encodeFrame(FRAME_CANCEL, Buffer.alloc(0))).catch(() => {});
|
|
289
|
+
};
|
|
290
|
+
const onAbort = (): void => sendCancel();
|
|
291
|
+
callbacks.signal?.addEventListener('abort', onAbort, { once: true });
|
|
292
|
+
try {
|
|
293
|
+
await this.sendJson({ op: 'run_step', ...spec });
|
|
294
|
+
if (callbacks.signal?.aborted) sendCancel();
|
|
295
|
+
|
|
296
|
+
for (;;) {
|
|
297
|
+
const frame = await this.reader.nextFrame();
|
|
298
|
+
if (!frame) throw new RunnerError('Guest closed vsock connection while step was running');
|
|
299
|
+
if (frame.kind === FRAME_STDOUT) {
|
|
300
|
+
if (callbacks.onStdout && frame.payload.byteLength > 0) {
|
|
301
|
+
await callbacks.onStdout(frame.payload);
|
|
302
|
+
}
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (frame.kind === FRAME_STDERR) {
|
|
306
|
+
if (callbacks.onStderr && frame.payload.byteLength > 0) {
|
|
307
|
+
await callbacks.onStderr(frame.payload);
|
|
308
|
+
}
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (frame.kind === FRAME_JSON_RES) {
|
|
312
|
+
let parsed: unknown;
|
|
313
|
+
try {
|
|
314
|
+
parsed = JSON.parse(frame.payload.toString('utf8'));
|
|
315
|
+
} catch (error) {
|
|
316
|
+
throw new RunnerError('Guest returned malformed step JSON response', { cause: error });
|
|
317
|
+
}
|
|
318
|
+
const record = parsed as Record<string, unknown>;
|
|
319
|
+
if (record.ok !== true) {
|
|
320
|
+
const message = typeof record.error === 'string' ? record.error : 'Step failed in guest';
|
|
321
|
+
throw new RunnerError(`Guest step execution failed: ${message}`);
|
|
322
|
+
}
|
|
323
|
+
return record as unknown as IGuestStepResult;
|
|
324
|
+
}
|
|
325
|
+
throw new RunnerError(`Guest sent unexpected frame ${frame.kind} during step execution`);
|
|
326
|
+
}
|
|
327
|
+
} finally {
|
|
328
|
+
callbacks.signal?.removeEventListener('abort', onAbort);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async exportTar(options: {
|
|
333
|
+
selections: string[];
|
|
334
|
+
maximumBytes: number;
|
|
335
|
+
maximumEntries: number;
|
|
336
|
+
maximumStreamBytes?: number;
|
|
337
|
+
}): Promise<{ tarBytes: Buffer; bytes: number; entries: number }> {
|
|
338
|
+
const maximumStreamBytes = options.maximumStreamBytes ??
|
|
339
|
+
options.maximumBytes + options.maximumEntries * 1024 + 1024 * 1024;
|
|
340
|
+
await this.sendJson({
|
|
341
|
+
op: 'export_tar',
|
|
342
|
+
selections: options.selections,
|
|
343
|
+
maximumBytes: options.maximumBytes,
|
|
344
|
+
maximumEntries: options.maximumEntries,
|
|
345
|
+
});
|
|
346
|
+
const chunks: Buffer[] = [];
|
|
347
|
+
let total = 0;
|
|
348
|
+
for (;;) {
|
|
349
|
+
const frame = await this.reader.nextFrame();
|
|
350
|
+
if (!frame) throw new RunnerError('Guest closed vsock connection during workspace export');
|
|
351
|
+
if (frame.kind === FRAME_DATA) {
|
|
352
|
+
total += frame.payload.byteLength;
|
|
353
|
+
if (total > maximumStreamBytes) {
|
|
354
|
+
throw new RunnerError('Exported workspace stream exceeds maximum allowed size');
|
|
355
|
+
}
|
|
356
|
+
chunks.push(frame.payload);
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (frame.kind === FRAME_DATA_EOF) {
|
|
360
|
+
const result = await this.readJsonResponse<IGuestTransferResult>();
|
|
361
|
+
return {
|
|
362
|
+
tarBytes: chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, total),
|
|
363
|
+
bytes: result.bytes,
|
|
364
|
+
entries: result.entries,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
if (frame.kind === FRAME_JSON_RES) {
|
|
368
|
+
// Guest returned an error before streaming any data frames.
|
|
369
|
+
const parsed = JSON.parse(frame.payload.toString('utf8')) as Record<string, unknown>;
|
|
370
|
+
const message = typeof parsed.error === 'string' ? parsed.error : 'Workspace export failed';
|
|
371
|
+
throw new RunnerError(`Guest workspace export failed: ${message}`);
|
|
372
|
+
}
|
|
373
|
+
throw new RunnerError(`Guest sent unexpected frame ${frame.kind} during workspace export`);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async runImageBuild(
|
|
378
|
+
spec: IGuestImageBuildRequest,
|
|
379
|
+
callbacks: IGuestRunStepCallbacks = {},
|
|
380
|
+
): Promise<IGuestImageBuildResult> {
|
|
381
|
+
let cancelSent = false;
|
|
382
|
+
const sendCancel = (): void => {
|
|
383
|
+
if (cancelSent || this.socket.destroyed) return;
|
|
384
|
+
cancelSent = true;
|
|
385
|
+
void writeAllSocket(this.socket, encodeFrame(FRAME_CANCEL, Buffer.alloc(0))).catch(() => {});
|
|
386
|
+
};
|
|
387
|
+
const onAbort = (): void => sendCancel();
|
|
388
|
+
callbacks.signal?.addEventListener('abort', onAbort, { once: true });
|
|
389
|
+
try {
|
|
390
|
+
await this.sendJson({ op: 'run_image_build', ...spec });
|
|
391
|
+
if (callbacks.signal?.aborted) sendCancel();
|
|
392
|
+
|
|
393
|
+
for (;;) {
|
|
394
|
+
const frame = await this.reader.nextFrame();
|
|
395
|
+
if (!frame) throw new RunnerError('Guest closed vsock connection during image build');
|
|
396
|
+
if (frame.kind === FRAME_STDOUT) {
|
|
397
|
+
if (callbacks.onStdout && frame.payload.byteLength > 0) {
|
|
398
|
+
await callbacks.onStdout(frame.payload);
|
|
399
|
+
}
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
if (frame.kind === FRAME_STDERR) {
|
|
403
|
+
if (callbacks.onStderr && frame.payload.byteLength > 0) {
|
|
404
|
+
await callbacks.onStderr(frame.payload);
|
|
405
|
+
}
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (frame.kind === FRAME_JSON_RES) {
|
|
409
|
+
let parsed: unknown;
|
|
410
|
+
try {
|
|
411
|
+
parsed = JSON.parse(frame.payload.toString('utf8'));
|
|
412
|
+
} catch (error) {
|
|
413
|
+
throw new RunnerError('Guest returned malformed image build JSON response', {
|
|
414
|
+
cause: error,
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
const record = parsed as Record<string, unknown>;
|
|
418
|
+
if (record.ok !== true) {
|
|
419
|
+
const message = typeof record.error === 'string'
|
|
420
|
+
? record.error
|
|
421
|
+
: 'Image build failed in guest';
|
|
422
|
+
throw new RunnerError(`Guest image build failed: ${message}`);
|
|
423
|
+
}
|
|
424
|
+
return record as unknown as IGuestImageBuildResult;
|
|
425
|
+
}
|
|
426
|
+
throw new RunnerError(`Guest sent unexpected frame ${frame.kind} during image build`);
|
|
427
|
+
}
|
|
428
|
+
} finally {
|
|
429
|
+
callbacks.signal?.removeEventListener('abort', onAbort);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async shutdown(): Promise<void> {
|
|
434
|
+
await this.sendJson({ op: 'shutdown' });
|
|
435
|
+
await this.readJsonResponse<{ ok: true }>();
|
|
436
|
+
}
|
|
437
|
+
}
|