relayrunner 0.7.0 → 0.9.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/LICENSE +202 -0
- package/README.md +56 -2
- package/dist/cli.js +1295 -448
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
import * as clack from "@clack/prompts";
|
|
3
3
|
import { defineCommand, runMain } from "citty";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import { arch, availableParallelism, cpus, homedir, hostname, platform, totalmem } from "node:os";
|
|
5
|
+
import { arch, availableParallelism, cpus, homedir, hostname, networkInterfaces, platform, release, tmpdir, totalmem } from "node:os";
|
|
6
6
|
import { basename, dirname, join, resolve } from "node:path";
|
|
7
|
-
import { chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { execFile, spawn } from "node:child_process";
|
|
7
|
+
import { appendFileSync, chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { execFile, spawn, spawnSync } from "node:child_process";
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
10
|
import { Readable, Transform } from "node:stream";
|
|
11
11
|
import { pipeline } from "node:stream/promises";
|
|
@@ -30,25 +30,31 @@ const Device = z.object({
|
|
|
30
30
|
memoryMb: z.number().int().positive().max(1e9).optional(),
|
|
31
31
|
osVersion: text.optional()
|
|
32
32
|
});
|
|
33
|
+
const os = z.enum([
|
|
34
|
+
"linux",
|
|
35
|
+
"macos",
|
|
36
|
+
"windows"
|
|
37
|
+
]);
|
|
38
|
+
const arch$1 = z.enum([
|
|
39
|
+
"x64",
|
|
40
|
+
"arm64",
|
|
41
|
+
"arm"
|
|
42
|
+
]);
|
|
33
43
|
const HelloMessage = z.object({
|
|
34
44
|
v: version$1,
|
|
35
45
|
type: z.literal("hello"),
|
|
36
46
|
machineId: z.string().min(1),
|
|
37
|
-
os
|
|
38
|
-
|
|
39
|
-
"macos",
|
|
40
|
-
"windows"
|
|
41
|
-
]),
|
|
42
|
-
arch: z.enum([
|
|
43
|
-
"x64",
|
|
44
|
-
"arm64",
|
|
45
|
-
"arm"
|
|
46
|
-
]),
|
|
47
|
+
os,
|
|
48
|
+
arch: arch$1,
|
|
47
49
|
runnerVersion: z.string().min(1),
|
|
48
50
|
cliVersion: z.string().trim().min(1).max(40).optional(),
|
|
49
51
|
device: Device.optional().catch(void 0),
|
|
50
52
|
rotatesToken: z.boolean().optional(),
|
|
51
|
-
slots: z.number().int().positive().max(1e3).optional()
|
|
53
|
+
slots: z.number().int().positive().max(1e3).optional(),
|
|
54
|
+
isolated: z.object({
|
|
55
|
+
os,
|
|
56
|
+
arch: arch$1
|
|
57
|
+
}).optional()
|
|
52
58
|
});
|
|
53
59
|
const StatusMessage = z.object({
|
|
54
60
|
v: version$1,
|
|
@@ -81,7 +87,8 @@ const RunMessage = z.object({
|
|
|
81
87
|
v: version$1,
|
|
82
88
|
type: z.literal("run"),
|
|
83
89
|
routeId,
|
|
84
|
-
jitConfig: z.string().min(1)
|
|
90
|
+
jitConfig: z.string().min(1),
|
|
91
|
+
isolated: z.boolean().optional()
|
|
85
92
|
});
|
|
86
93
|
const ErrorMessage = z.object({
|
|
87
94
|
v: version$1,
|
|
@@ -145,8 +152,25 @@ function parse$1(schema, frame) {
|
|
|
145
152
|
function isRunnerForRoute(runnerName, routeId) {
|
|
146
153
|
return runnerName.endsWith(`-${routeId}`);
|
|
147
154
|
}
|
|
155
|
+
// ../../packages/machine-protocol/src/cli-version.ts
|
|
156
|
+
/** Whether `candidate` is a newer release than `current`. Only plain x.y.z releases count, so a prerelease never reads as newer. */
|
|
157
|
+
function isNewerVersion(candidate, current) {
|
|
158
|
+
const a = parse(candidate);
|
|
159
|
+
const b = parse(current);
|
|
160
|
+
if (!a || !b) return false;
|
|
161
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
function parse(version) {
|
|
165
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
|
|
166
|
+
return match ? [
|
|
167
|
+
Number(match[1]),
|
|
168
|
+
Number(match[2]),
|
|
169
|
+
Number(match[3])
|
|
170
|
+
] : null;
|
|
171
|
+
}
|
|
148
172
|
// version.ts
|
|
149
|
-
const cliVersion = "0.
|
|
173
|
+
const cliVersion = "0.9.0";
|
|
150
174
|
// paths.ts
|
|
151
175
|
function relayrunnerHome() {
|
|
152
176
|
return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
|
|
@@ -170,6 +194,7 @@ async function connect(options) {
|
|
|
170
194
|
const heartbeatMs = options.heartbeatMs ?? 3e4;
|
|
171
195
|
const minBackoffMs = options.minBackoffMs ?? 1e3;
|
|
172
196
|
const maxBackoffMs = options.maxBackoffMs ?? 3e4;
|
|
197
|
+
const reconnectSpreadMs = options.reconnectSpreadMs ?? 1e4;
|
|
173
198
|
const emit = options.onEvent ?? (() => {});
|
|
174
199
|
const signal = options.signal;
|
|
175
200
|
const slots = options.slots ?? 1;
|
|
@@ -350,7 +375,7 @@ async function connect(options) {
|
|
|
350
375
|
message: gatewayError || reason || "protocol error"
|
|
351
376
|
};
|
|
352
377
|
if (!opened && await tokenRejected()) return { reason: "revoked" };
|
|
353
|
-
const retryInMs = backoff(attempt, minBackoffMs, maxBackoffMs);
|
|
378
|
+
const retryInMs = opened ? Math.round(Math.random() * reconnectSpreadMs) : backoff(attempt, minBackoffMs, maxBackoffMs);
|
|
354
379
|
emit({
|
|
355
380
|
type: "disconnected",
|
|
356
381
|
code,
|
|
@@ -420,13 +445,23 @@ function pickDownload(release, target) {
|
|
|
420
445
|
sha256
|
|
421
446
|
};
|
|
422
447
|
}
|
|
423
|
-
async function
|
|
448
|
+
async function latestRelease() {
|
|
424
449
|
const response = await fetch(LATEST_RELEASE, { headers: {
|
|
425
450
|
accept: "application/vnd.github+json",
|
|
426
451
|
"user-agent": userAgent
|
|
427
452
|
} });
|
|
428
453
|
if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
|
|
429
|
-
return
|
|
454
|
+
return response.json();
|
|
455
|
+
}
|
|
456
|
+
async function latestRunnerVersion(log = () => {}) {
|
|
457
|
+
try {
|
|
458
|
+
return Release.parse(await latestRelease()).tag_name.slice(1);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
const [newest] = installedRunners();
|
|
461
|
+
if (!newest) throw error;
|
|
462
|
+
log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
|
|
463
|
+
return newest.version;
|
|
464
|
+
}
|
|
430
465
|
}
|
|
431
466
|
function installedRunners(root = runnersDir()) {
|
|
432
467
|
if (!existsSync(root)) return [];
|
|
@@ -446,7 +481,7 @@ async function ensureRunner(options = {}) {
|
|
|
446
481
|
const target = runnerPlatform();
|
|
447
482
|
let download;
|
|
448
483
|
try {
|
|
449
|
-
download = await
|
|
484
|
+
download = pickDownload(await latestRelease(), target);
|
|
450
485
|
} catch (error) {
|
|
451
486
|
const [newest] = installedRunners(root);
|
|
452
487
|
if (newest) {
|
|
@@ -622,7 +657,7 @@ const run = (command, args) => new Promise((resolve) => {
|
|
|
622
657
|
resolve(error ? null : stdout.trim() || null);
|
|
623
658
|
});
|
|
624
659
|
});
|
|
625
|
-
const read
|
|
660
|
+
const read = (path) => {
|
|
626
661
|
try {
|
|
627
662
|
return readFileSync(path, "utf8").replaceAll("\0", "").trim() || null;
|
|
628
663
|
} catch {
|
|
@@ -633,7 +668,7 @@ function defaultSources() {
|
|
|
633
668
|
const list = cpus();
|
|
634
669
|
return {
|
|
635
670
|
run,
|
|
636
|
-
read
|
|
671
|
+
read,
|
|
637
672
|
cpuModel: list[0]?.model,
|
|
638
673
|
cpuCount: list.length,
|
|
639
674
|
totalMemory: totalmem()
|
|
@@ -787,11 +822,8 @@ function compact(device) {
|
|
|
787
822
|
}
|
|
788
823
|
return out;
|
|
789
824
|
}
|
|
790
|
-
//
|
|
791
|
-
function
|
|
792
|
-
return join(home, "declined-repos.json");
|
|
793
|
-
}
|
|
794
|
-
function read(path) {
|
|
825
|
+
// list-file.ts
|
|
826
|
+
function readList(path) {
|
|
795
827
|
try {
|
|
796
828
|
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
797
829
|
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
@@ -799,17 +831,23 @@ function read(path) {
|
|
|
799
831
|
return [];
|
|
800
832
|
}
|
|
801
833
|
}
|
|
802
|
-
function
|
|
803
|
-
return read(path).includes(repo);
|
|
804
|
-
}
|
|
805
|
-
function rememberDeclined(repo, path = declinedPath()) {
|
|
806
|
-
const repos = read(path);
|
|
807
|
-
if (repos.includes(repo)) return;
|
|
834
|
+
function writeList(path, list) {
|
|
808
835
|
mkdirSync(dirname(path), {
|
|
809
836
|
recursive: true,
|
|
810
837
|
mode: 448
|
|
811
838
|
});
|
|
812
|
-
writeFileSync(path, `${JSON.stringify(
|
|
839
|
+
writeFileSync(path, `${JSON.stringify(list, null, 2)}\n`);
|
|
840
|
+
}
|
|
841
|
+
// declined.ts
|
|
842
|
+
function declinedPath(home = relayrunnerHome()) {
|
|
843
|
+
return join(home, "declined-repos.json");
|
|
844
|
+
}
|
|
845
|
+
function isDeclined(repo, path = declinedPath()) {
|
|
846
|
+
return readList(path).includes(repo);
|
|
847
|
+
}
|
|
848
|
+
function rememberDeclined(repo, path = declinedPath()) {
|
|
849
|
+
const repos = readList(path);
|
|
850
|
+
if (!repos.includes(repo)) writeList(path, [...repos, repo]);
|
|
813
851
|
}
|
|
814
852
|
// diff.ts
|
|
815
853
|
function unifiedDiff(before, after, file, context = 2) {
|
|
@@ -856,85 +894,665 @@ function unifiedDiff(before, after, file, context = 2) {
|
|
|
856
894
|
}
|
|
857
895
|
return out.join("\n");
|
|
858
896
|
}
|
|
859
|
-
//
|
|
860
|
-
const
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
897
|
+
// jit-config.ts
|
|
898
|
+
const GITHUB_HOSTS = [
|
|
899
|
+
/^github\.com$/,
|
|
900
|
+
/\.github\.com$/,
|
|
901
|
+
/\.githubusercontent\.com$/
|
|
902
|
+
];
|
|
903
|
+
const FILES = [
|
|
904
|
+
".runner",
|
|
905
|
+
".credentials",
|
|
906
|
+
".credentials_rsaparams"
|
|
907
|
+
];
|
|
908
|
+
const URL_FIELDS = /* @__PURE__ */ new Set([
|
|
909
|
+
"serverurl",
|
|
910
|
+
"serverurlv2",
|
|
911
|
+
"githuburl",
|
|
912
|
+
"authorizationurl"
|
|
913
|
+
]);
|
|
914
|
+
function checkJitConfig(encoded, routeId) {
|
|
915
|
+
let files;
|
|
916
|
+
try {
|
|
917
|
+
files = decodeJson(encoded);
|
|
918
|
+
if (!files || typeof files !== "object") throw new Error();
|
|
919
|
+
} catch {
|
|
920
|
+
return {
|
|
921
|
+
ok: false,
|
|
922
|
+
reason: "it isn't a runner config"
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
const names = Object.keys(files);
|
|
926
|
+
if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
|
|
927
|
+
ok: false,
|
|
928
|
+
reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
|
|
929
|
+
};
|
|
930
|
+
const decoded = {};
|
|
931
|
+
for (const [name, value] of Object.entries(files)) {
|
|
932
|
+
if (typeof value !== "string") return {
|
|
933
|
+
ok: false,
|
|
934
|
+
reason: `${name} isn't a file`
|
|
935
|
+
};
|
|
936
|
+
try {
|
|
937
|
+
decoded[name] = decodeJson(value);
|
|
938
|
+
} catch {
|
|
939
|
+
return {
|
|
940
|
+
ok: false,
|
|
941
|
+
reason: `${name} isn't JSON`
|
|
942
|
+
};
|
|
943
|
+
}
|
|
869
944
|
}
|
|
945
|
+
const runner = decoded[".runner"];
|
|
946
|
+
if (!runner || typeof runner !== "object") return {
|
|
947
|
+
ok: false,
|
|
948
|
+
reason: "it has no .runner"
|
|
949
|
+
};
|
|
950
|
+
const duplicate = duplicateKey(decoded);
|
|
951
|
+
if (duplicate) return {
|
|
952
|
+
ok: false,
|
|
953
|
+
reason: `it has ${duplicate} twice`
|
|
954
|
+
};
|
|
955
|
+
for (const url of urls(decoded)) {
|
|
956
|
+
const parsed = URL.canParse(url) ? new URL(url) : null;
|
|
957
|
+
if (!parsed) return {
|
|
958
|
+
ok: false,
|
|
959
|
+
reason: `it names a URL that doesn't parse: ${url}`
|
|
960
|
+
};
|
|
961
|
+
if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
|
|
962
|
+
ok: false,
|
|
963
|
+
reason: `it points the runner at ${parsed.origin}, not GitHub`
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
const field = (key) => {
|
|
967
|
+
const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
|
|
968
|
+
return typeof entry?.[1] === "string" ? entry[1] : null;
|
|
969
|
+
};
|
|
970
|
+
if (!field("serverurl") && !field("serverurlv2")) return {
|
|
971
|
+
ok: false,
|
|
972
|
+
reason: "it doesn't say which GitHub server to use"
|
|
973
|
+
};
|
|
974
|
+
const runnerName = field("agentname");
|
|
975
|
+
if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
|
|
976
|
+
ok: false,
|
|
977
|
+
reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
|
|
978
|
+
};
|
|
979
|
+
return {
|
|
980
|
+
ok: true,
|
|
981
|
+
target: target(field("githuburl"))
|
|
982
|
+
};
|
|
870
983
|
}
|
|
871
|
-
function
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
return
|
|
875
|
-
file: `${WORKFLOWS_DIR}/${name}`,
|
|
876
|
-
source: readFileSync(join(dir, name), "utf8")
|
|
877
|
-
}));
|
|
984
|
+
function target(url) {
|
|
985
|
+
if (!url || !URL.canParse(url)) return null;
|
|
986
|
+
const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
|
|
987
|
+
return path.length ? path.join("/") : null;
|
|
878
988
|
}
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
989
|
+
function urls(value, found = [], key = "") {
|
|
990
|
+
if (typeof value === "string") {
|
|
991
|
+
const text = value.trim();
|
|
992
|
+
if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
|
|
993
|
+
} else if (Array.isArray(value)) for (const item of value) urls(item, found);
|
|
994
|
+
else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
|
|
995
|
+
return found;
|
|
883
996
|
}
|
|
884
|
-
function
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
997
|
+
function duplicateKey(value) {
|
|
998
|
+
if (Array.isArray(value)) for (const item of value) {
|
|
999
|
+
const found = duplicateKey(item);
|
|
1000
|
+
if (found) return found;
|
|
1001
|
+
}
|
|
1002
|
+
else if (value && typeof value === "object") {
|
|
1003
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1004
|
+
for (const [name, item] of Object.entries(value)) {
|
|
1005
|
+
if (seen.has(name.toLowerCase())) return name;
|
|
1006
|
+
seen.add(name.toLowerCase());
|
|
1007
|
+
const found = duplicateKey(item);
|
|
1008
|
+
if (found) return found;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
return null;
|
|
897
1012
|
}
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
1013
|
+
function decodeJson(base64) {
|
|
1014
|
+
return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
|
|
1015
|
+
}
|
|
1016
|
+
// job.ts
|
|
1017
|
+
const runnerEnv = () => Object.fromEntries([
|
|
1018
|
+
"HOME",
|
|
1019
|
+
"USER",
|
|
1020
|
+
"LOGNAME",
|
|
1021
|
+
"PATH",
|
|
1022
|
+
"LANG",
|
|
1023
|
+
"LC_ALL",
|
|
1024
|
+
"TMPDIR",
|
|
1025
|
+
"SHELL"
|
|
1026
|
+
].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
|
|
1027
|
+
async function runJob(run, options) {
|
|
1028
|
+
const { launcher, report } = options;
|
|
1029
|
+
const { routeId } = run;
|
|
1030
|
+
const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
|
|
1031
|
+
const finish = (update) => {
|
|
1032
|
+
report(update);
|
|
1033
|
+
return update;
|
|
1034
|
+
};
|
|
1035
|
+
const failed = (message) => finish({
|
|
1036
|
+
routeId,
|
|
1037
|
+
state: "failed",
|
|
1038
|
+
message
|
|
1039
|
+
});
|
|
1040
|
+
const checked = checkJitConfig(run.jitConfig, routeId);
|
|
1041
|
+
if (!checked.ok) return failed(`Refused the job's runner config: ${checked.reason}.`);
|
|
1042
|
+
options.onChecked?.(checked.target);
|
|
1043
|
+
let clean = false;
|
|
903
1044
|
try {
|
|
904
|
-
const
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
1045
|
+
const child = launcher.start(run);
|
|
1046
|
+
child.stdout.on("data", (chunk) => output(chunk, "stdout"));
|
|
1047
|
+
child.stderr.on("data", (chunk) => output(chunk, "stderr"));
|
|
1048
|
+
const started = await new Promise((resolve) => {
|
|
1049
|
+
child.once("spawn", () => resolve(null));
|
|
1050
|
+
child.once("error", resolve);
|
|
910
1051
|
});
|
|
911
|
-
if (
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
1052
|
+
if (started) return failed(`Could not start the runner: ${started.message}`);
|
|
1053
|
+
report({
|
|
1054
|
+
routeId,
|
|
1055
|
+
state: "started"
|
|
1056
|
+
});
|
|
1057
|
+
const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
|
|
1058
|
+
clean = code === 0;
|
|
1059
|
+
if (clean) return finish({
|
|
1060
|
+
routeId,
|
|
1061
|
+
state: "finished"
|
|
1062
|
+
});
|
|
1063
|
+
return failed(signal ? `The runner was stopped by ${signal}` : `The runner exited with ${code}`);
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
return failed(error instanceof Error ? error.message : String(error));
|
|
1066
|
+
} finally {
|
|
1067
|
+
await launcher.cleanup(run, clean);
|
|
916
1068
|
}
|
|
917
1069
|
}
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
1070
|
+
const JOB_STATE = [
|
|
1071
|
+
"_work",
|
|
1072
|
+
".runner",
|
|
1073
|
+
".credentials",
|
|
1074
|
+
".credentials_rsaparams"
|
|
1075
|
+
];
|
|
1076
|
+
function hostLauncher(dir) {
|
|
1077
|
+
const lock = join(dir, "job.lock");
|
|
1078
|
+
let locked = false;
|
|
1079
|
+
return {
|
|
1080
|
+
start(run) {
|
|
1081
|
+
locked = takeLock(lock);
|
|
1082
|
+
if (!locked) throw new Error(`Another job is using the runner in ${dir}.`);
|
|
1083
|
+
clean(dir);
|
|
1084
|
+
return spawn(join(dir, "run.sh"), ["--jitconfig", run.jitConfig], {
|
|
1085
|
+
cwd: dir,
|
|
1086
|
+
env: runnerEnv(),
|
|
1087
|
+
stdio: [
|
|
1088
|
+
"ignore",
|
|
1089
|
+
"pipe",
|
|
1090
|
+
"pipe"
|
|
1091
|
+
]
|
|
1092
|
+
});
|
|
1093
|
+
},
|
|
1094
|
+
cleanup() {
|
|
1095
|
+
if (!locked) return;
|
|
1096
|
+
clean(dir);
|
|
1097
|
+
rmSync(lock, { force: true });
|
|
1098
|
+
locked = false;
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
function clean(dir) {
|
|
1103
|
+
for (const name of JOB_STATE) rmSync(join(dir, name), {
|
|
1104
|
+
recursive: true,
|
|
1105
|
+
force: true
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
function takeLock(lock) {
|
|
1109
|
+
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
1110
|
+
symlinkSync(String(process.pid), lock);
|
|
1111
|
+
return true;
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
if (error.code !== "EEXIST") throw error;
|
|
1114
|
+
if (isAlive(Number(readlinkSync(lock)))) return false;
|
|
1115
|
+
rmSync(lock, { force: true });
|
|
1116
|
+
}
|
|
1117
|
+
return false;
|
|
1118
|
+
}
|
|
1119
|
+
function isAlive(pid) {
|
|
1120
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
1121
|
+
try {
|
|
1122
|
+
process.kill(pid, 0);
|
|
1123
|
+
return true;
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
return error.code === "EPERM";
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
function prefixLines(prefix, write) {
|
|
1129
|
+
const partial = {
|
|
1130
|
+
stdout: "",
|
|
1131
|
+
stderr: ""
|
|
1132
|
+
};
|
|
1133
|
+
const output = (chunk, stream) => {
|
|
1134
|
+
const text = partial[stream] + chunk.toString();
|
|
1135
|
+
const end = text.lastIndexOf("\n") + 1;
|
|
1136
|
+
partial[stream] = text.slice(end);
|
|
1137
|
+
if (end === 0) return;
|
|
1138
|
+
const lines = text.slice(0, end).replace(/^(?=.)/gm, prefix);
|
|
1139
|
+
write(Buffer.from(lines), stream);
|
|
1140
|
+
};
|
|
1141
|
+
const flush = () => {
|
|
1142
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
1143
|
+
if (partial[stream]) write(Buffer.from(`${prefix}${partial[stream]}\n`), stream);
|
|
1144
|
+
partial[stream] = "";
|
|
1145
|
+
}
|
|
1146
|
+
};
|
|
1147
|
+
return {
|
|
1148
|
+
output,
|
|
1149
|
+
flush
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
// isolated.ts
|
|
1153
|
+
const RUNNER_IMAGE = "ghcr.io/actions/actions-runner";
|
|
1154
|
+
const RELEASES = "https://github.com/apple/container/releases";
|
|
1155
|
+
function unsupportedReason(system = platform(), chip = arch(), darwin = release()) {
|
|
1156
|
+
if (system !== "darwin") return "Running jobs in VMs needs a Mac with Apple silicon and macOS 26 or later.";
|
|
1157
|
+
if (chip !== "arm64") return "Running jobs in VMs needs a Mac with Apple silicon. This one has an Intel chip.";
|
|
1158
|
+
if (Number.parseInt(darwin, 10) < 25) return "Running jobs in VMs needs macOS 26 or later. Update macOS, then try again.";
|
|
1159
|
+
return null;
|
|
1160
|
+
}
|
|
1161
|
+
async function isolationState(command = "container", reason = unsupportedReason()) {
|
|
1162
|
+
if (reason !== null) return "unsupported";
|
|
1163
|
+
const status = await call(command, ["system", "status"], NO_LOG, true);
|
|
1164
|
+
if (status === null) return "missing";
|
|
1165
|
+
return status === 0 ? "ready" : "stopped";
|
|
1166
|
+
}
|
|
1167
|
+
function setupHint(state) {
|
|
1168
|
+
if (state !== "missing" && state !== "stopped") return null;
|
|
1169
|
+
return `Jobs run on this Mac itself, where they can read your files. To run each job in its own Linux VM, ${state === "missing" ? `install Apple's container tool from ${RELEASES} and run \`container system start\`` : "run `container system start`"}.`;
|
|
1170
|
+
}
|
|
1171
|
+
function debugLog(path = join(relayrunnerHome(), "isolated.log")) {
|
|
1172
|
+
const home = homedir();
|
|
1173
|
+
const write = (text, flag = "a") => {
|
|
1174
|
+
try {
|
|
1175
|
+
const stamped = `${(/* @__PURE__ */ new Date()).toISOString()} ${text.trimEnd().replaceAll(home, "~")}\n`;
|
|
1176
|
+
if (flag === "w") {
|
|
1177
|
+
rmSync(path, { force: true });
|
|
1178
|
+
writeFileSync(path, stamped, { mode: 384 });
|
|
1179
|
+
} else appendFileSync(path, stamped);
|
|
1180
|
+
} catch {}
|
|
1181
|
+
};
|
|
1182
|
+
try {
|
|
1183
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1184
|
+
} catch {}
|
|
1185
|
+
write(`relayrunner ${cliVersion}, ${platform()} ${release()} ${arch()}, ${availableParallelism()} cores, ${Math.round(totalmem() / 1024 ** 3)} GB`, "w");
|
|
1186
|
+
return {
|
|
1187
|
+
path,
|
|
1188
|
+
write
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
const NO_LOG = {
|
|
1192
|
+
path: "",
|
|
1193
|
+
write: () => {}
|
|
1194
|
+
};
|
|
1195
|
+
const START_SCRIPT = `#!/bin/sh
|
|
1196
|
+
set -eu
|
|
1197
|
+
drop=""
|
|
1198
|
+
if [ "\${RELAYRUNNER_LOCAL_NETWORK:-}" != 1 ]; then
|
|
1199
|
+
drop="--bounding-set -net_admin,-net_raw"
|
|
1200
|
+
dns=$(awk '$1 == "nameserver" && $2 ~ /^[0-9.]+$/ { printf "%s%s", sep, $2; sep = ", " }' /etc/resolv.conf)
|
|
1201
|
+
allow_dns=""
|
|
1202
|
+
[ -z "$dns" ] || allow_dns="ip daddr { $dns } meta l4proto { tcp, udp } th dport 53 accept"
|
|
1203
|
+
nft -f - <<EOF
|
|
1204
|
+
table inet relayrunner {
|
|
1205
|
+
chain private {
|
|
1206
|
+
oifname { "lo", "docker0" } accept
|
|
1207
|
+
oifname "br-*" accept
|
|
1208
|
+
$allow_dns
|
|
1209
|
+
ip daddr { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 } drop
|
|
1210
|
+
meta nfproto ipv6 drop
|
|
1211
|
+
}
|
|
1212
|
+
chain out {
|
|
1213
|
+
type filter hook output priority 0; policy accept;
|
|
1214
|
+
jump private
|
|
1215
|
+
}
|
|
1216
|
+
chain forward {
|
|
1217
|
+
type filter hook forward priority 0; policy accept;
|
|
1218
|
+
jump private
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
EOF
|
|
1222
|
+
fi
|
|
1223
|
+
# Docker sets kernel network settings under /proc/sys, which starts read-only. A job without
|
|
1224
|
+
# Docker loses nothing if it can't start, so failures here only reach the Docker log.
|
|
1225
|
+
if command -v dockerd >/dev/null 2>&1; then
|
|
1226
|
+
mount -o remount,rw /proc/sys 2>/dev/null || true
|
|
1227
|
+
dockerd >/var/log/dockerd.log 2>&1 &
|
|
1228
|
+
tries=0
|
|
1229
|
+
until docker info >/dev/null 2>&1 || [ "$tries" -ge 50 ]; do
|
|
1230
|
+
tries=$((tries + 1))
|
|
1231
|
+
sleep 0.2
|
|
1232
|
+
done
|
|
1233
|
+
fi
|
|
1234
|
+
# A new VM's DNS answers nothing for its first 2 seconds or so, and a lookup sent then waits 5
|
|
1235
|
+
# seconds to ask again. So the runner starts once a lookup gets through, or after 5 tries.
|
|
1236
|
+
tries=0
|
|
1237
|
+
until RES_OPTIONS="timeout:1 attempts:1" getent hosts github.com >/dev/null 2>&1 || [ "$tries" -ge 4 ]; do
|
|
1238
|
+
tries=$((tries + 1))
|
|
1239
|
+
done
|
|
1240
|
+
cd /home/runner
|
|
1241
|
+
# With arguments, runs them in place of the runner, to check the VM by hand.
|
|
1242
|
+
[ $# -gt 0 ] || set -- ./run.sh --jitconfig "$RUNNER_JIT_CONFIG"
|
|
1243
|
+
exec setpriv --reuid runner --regid runner --init-groups $drop \\
|
|
1244
|
+
env HOME=/home/runner USER=runner LOGNAME=runner "$@"
|
|
1245
|
+
`;
|
|
1246
|
+
const START_PATH = "/usr/local/bin/relayrunner-start";
|
|
1247
|
+
const TOOLS = [
|
|
1248
|
+
"build-essential pkg-config cmake",
|
|
1249
|
+
"python3-pip python3-venv python-is-python3",
|
|
1250
|
+
"zip xz-utils zstd bzip2",
|
|
1251
|
+
"wget rsync file gettext-base bc time",
|
|
1252
|
+
"git-lfs sqlite3",
|
|
1253
|
+
"docker-compose-v2",
|
|
1254
|
+
"netcat-openbsd iputils-ping dnsutils iproute2",
|
|
1255
|
+
"libssl-dev",
|
|
1256
|
+
"gh"
|
|
1257
|
+
].join(" ");
|
|
1258
|
+
const GH_KEYRING = "/usr/share/keyrings/githubcli-archive-keyring.gpg";
|
|
1259
|
+
function dockerfile(base, tools = true) {
|
|
1260
|
+
const install = `RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o ${GH_KEYRING} \\
|
|
1261
|
+
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=${GH_KEYRING}] https://cli.github.com/packages stable main" > /etc/apt/sources.list.d/github-cli.list \\
|
|
1262
|
+
&& apt-get update && apt-get install -y --no-install-recommends ${TOOLS} \\
|
|
1263
|
+
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
|
1264
|
+
RUN node=$(ls -d /home/runner/externals/node[0-9]* 2>/dev/null | sort -V | tail -n 1) \\
|
|
1265
|
+
&& { [ -z "$node" ] || { ln -sf "$node"/bin/* /usr/local/bin/ \\
|
|
1266
|
+
&& echo prefix=/usr/local > "$node"/lib/node_modules/npm/npmrc \\
|
|
1267
|
+
&& mkdir -p /usr/local/lib/node_modules \\
|
|
1268
|
+
&& chown runner /usr/local/bin /usr/local/lib/node_modules; }; }
|
|
1269
|
+
`;
|
|
1270
|
+
return `FROM ${base}
|
|
1271
|
+
USER root
|
|
1272
|
+
RUN apt-get update && apt-get install -y --no-install-recommends iptables nftables && apt-get clean
|
|
1273
|
+
${tools ? install : ""}COPY --chmod=755 start.sh ${START_PATH}
|
|
1274
|
+
`;
|
|
1275
|
+
}
|
|
1276
|
+
function jobImage(base, tools = true) {
|
|
1277
|
+
return `relayrunner-runner:${createHash("sha256").update(dockerfile(base, tools)).update(START_SCRIPT).digest("hex").slice(0, 12)}`;
|
|
1278
|
+
}
|
|
1279
|
+
function parseVmSize(cpus, memory, cores = availableParallelism(), memoryBytes = totalmem()) {
|
|
1280
|
+
const whole = (flag, value, most, unit) => {
|
|
1281
|
+
if (value === void 0 || value === "") return void 0;
|
|
1282
|
+
const n = Number(value);
|
|
1283
|
+
if (!/^\d+$/.test(value.trim()) || n < 1) throw new RunnerError("USAGE", `${flag} takes a whole number, not "${value}".`);
|
|
1284
|
+
if (n > most) throw new RunnerError("USAGE", `${flag} ${n} is more than this machine's ${most} ${unit}.`);
|
|
1285
|
+
return n;
|
|
1286
|
+
};
|
|
1287
|
+
return {
|
|
1288
|
+
cpus: whole("--cpus", cpus, cores, "CPU cores"),
|
|
1289
|
+
memoryGb: whole("--memory", memory, Math.floor(memoryBytes / 1024 ** 3), "GB of memory")
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
function slotsFor(size, cores = availableParallelism(), memoryBytes = totalmem()) {
|
|
1293
|
+
if (size.cpus === void 0 && size.memoryGb === void 0) return void 0;
|
|
1294
|
+
const gb = memoryBytes / 1024 ** 3;
|
|
1295
|
+
const byCpu = size.cpus ? Math.floor(cores / size.cpus) : Infinity;
|
|
1296
|
+
const byMemory = size.memoryGb ? Math.floor(gb / 2 / size.memoryGb) : Infinity;
|
|
1297
|
+
return Math.max(1, Math.min(byCpu, byMemory));
|
|
1298
|
+
}
|
|
1299
|
+
function checkFits(size, slots, memoryBytes = totalmem()) {
|
|
1300
|
+
const gb = Math.floor(memoryBytes / 1024 ** 3);
|
|
1301
|
+
if (size.memoryGb !== void 0 && size.memoryGb * slots > gb) throw new RunnerError("USAGE", `${slots} jobs with ${size.memoryGb} GB each is more than this machine's ${gb} GB of memory. Lower --concurrency or --memory.`);
|
|
1302
|
+
}
|
|
1303
|
+
function vmSize(slots, wanted = {}, cores = availableParallelism(), memoryBytes = totalmem()) {
|
|
1304
|
+
const gb = memoryBytes / 1024 ** 3;
|
|
1305
|
+
return {
|
|
1306
|
+
cpus: wanted.cpus ?? Math.max(2, Math.floor(cores / slots)),
|
|
1307
|
+
memoryGb: wanted.memoryGb ?? Math.min(16, Math.max(2, Math.floor(gb / 2 / slots)))
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
async function prepareIsolation(options) {
|
|
1311
|
+
const command = options.command ?? "container";
|
|
1312
|
+
const log = options.log ?? (() => {});
|
|
1313
|
+
const debug = options.debug ?? NO_LOG;
|
|
1314
|
+
const localNetwork = options.localNetwork ?? false;
|
|
1315
|
+
const tool = (args) => call(command, args, debug);
|
|
1316
|
+
const hasImage = async (image) => await call(command, [
|
|
1317
|
+
"image",
|
|
1318
|
+
"inspect",
|
|
1319
|
+
image
|
|
1320
|
+
], debug, true) === 0;
|
|
1321
|
+
const fail = (code, message) => new RunnerError(code, debug.path ? `${message} Details are in ${debug.path}.` : message);
|
|
1322
|
+
const latest = latestRunnerVersion(log);
|
|
1323
|
+
latest.catch(() => {});
|
|
1324
|
+
const [status] = await Promise.all([tool(["system", "status"]), tool(["--version"])]);
|
|
1325
|
+
if (status === null) throw new RunnerError("ISOLATED_SETUP", `Running jobs in VMs needs Apple's container tool. Install it from ${RELEASES}, then run \`container system start\`.`);
|
|
1326
|
+
if (status !== 0) throw fail("ISOLATED_SETUP", "Apple's container tool isn't running. Run `container system start`, then try again.");
|
|
1327
|
+
const runnerVersion = await latest;
|
|
1328
|
+
const base = options.image ?? `${RUNNER_IMAGE}:${runnerVersion}`;
|
|
1329
|
+
const mine = [];
|
|
1330
|
+
if (!await hasImage(base)) {
|
|
1331
|
+
log(`Downloading ${base}. This happens once per runner version…`);
|
|
1332
|
+
if (await tool([
|
|
1333
|
+
"image",
|
|
1334
|
+
"pull",
|
|
1335
|
+
base
|
|
1336
|
+
]) !== 0) throw fail("ISOLATED_IMAGE", `Could not download ${base}.`);
|
|
1337
|
+
if (!options.image) mine.push(base);
|
|
1338
|
+
}
|
|
1339
|
+
const image = jobImage(base, !options.image);
|
|
1340
|
+
mine.push(image);
|
|
1341
|
+
if (!await hasImage(image)) {
|
|
1342
|
+
log(`Building the job image from ${base}. This happens once per runner version…`);
|
|
1343
|
+
const context = mkdtempSync(join(tmpdir(), "relayrunner-image-"));
|
|
1344
|
+
try {
|
|
1345
|
+
writeFileSync(join(context, "Dockerfile"), dockerfile(base, !options.image));
|
|
1346
|
+
writeFileSync(join(context, "start.sh"), START_SCRIPT);
|
|
1347
|
+
if (await tool([
|
|
1348
|
+
"build",
|
|
1349
|
+
"--progress",
|
|
1350
|
+
"plain",
|
|
1351
|
+
"--tag",
|
|
1352
|
+
image,
|
|
1353
|
+
context
|
|
1354
|
+
]) !== 0) throw fail("ISOLATED_IMAGE", `Could not build the job image from ${base}.`);
|
|
1355
|
+
} finally {
|
|
1356
|
+
rmSync(context, {
|
|
1357
|
+
recursive: true,
|
|
1358
|
+
force: true
|
|
1359
|
+
});
|
|
1360
|
+
await tool(["builder", "stop"]);
|
|
1361
|
+
await tool(["builder", "delete"]);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
await pruneImages(options.managed ?? managedImagesFile(), [base, image], mine, tool, log);
|
|
1365
|
+
const size = vmSize(options.slots, options.size);
|
|
1366
|
+
log(`Each job runs in its own Linux VM with ${size.cpus} CPUs and ${size.memoryGb} GB of memory.`);
|
|
1367
|
+
if (localNetwork) log("Jobs can reach this Mac and your local network.");
|
|
1368
|
+
if (debug.path) log(`If something goes wrong, ${debug.path} has the details.`);
|
|
1369
|
+
return {
|
|
1370
|
+
command,
|
|
1371
|
+
image,
|
|
1372
|
+
localNetwork,
|
|
1373
|
+
debug,
|
|
1374
|
+
runnerVersion,
|
|
1375
|
+
...size
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
function managedImagesFile() {
|
|
1379
|
+
return join(relayrunnerHome(), "isolated-images.json");
|
|
1380
|
+
}
|
|
1381
|
+
async function pruneImages(file, inUse, mine, tool, log) {
|
|
1382
|
+
const recorded = readList(file);
|
|
1383
|
+
for (const image of recorded) {
|
|
1384
|
+
if (inUse.includes(image)) continue;
|
|
1385
|
+
if (await tool([
|
|
1386
|
+
"image",
|
|
1387
|
+
"delete",
|
|
1388
|
+
image
|
|
1389
|
+
]) === 0) log(`Removed the old image ${image}.`);
|
|
1390
|
+
}
|
|
1391
|
+
try {
|
|
1392
|
+
writeList(file, inUse.filter((image) => recorded.includes(image) || mine.includes(image)));
|
|
1393
|
+
} catch {}
|
|
1394
|
+
}
|
|
1395
|
+
function containerName(routeId) {
|
|
1396
|
+
return `relayrunner-${routeId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
|
1397
|
+
}
|
|
1398
|
+
function runArgs(routeId, isolation) {
|
|
1399
|
+
return [
|
|
1400
|
+
"run",
|
|
1401
|
+
"--rm",
|
|
1402
|
+
"--name",
|
|
1403
|
+
containerName(routeId),
|
|
1404
|
+
"--cpus",
|
|
1405
|
+
String(isolation.cpus),
|
|
1406
|
+
"--memory",
|
|
1407
|
+
`${isolation.memoryGb}g`,
|
|
1408
|
+
"--progress",
|
|
1409
|
+
"none",
|
|
1410
|
+
"-e",
|
|
1411
|
+
"RUNNER_JIT_CONFIG",
|
|
1412
|
+
"-e",
|
|
1413
|
+
"ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=false",
|
|
1414
|
+
...isolation.localNetwork ? ["-e", "RELAYRUNNER_LOCAL_NETWORK=1"] : [],
|
|
1415
|
+
"--user",
|
|
1416
|
+
"0",
|
|
1417
|
+
"--cap-add",
|
|
1418
|
+
"ALL",
|
|
1419
|
+
isolation.image,
|
|
1420
|
+
START_PATH
|
|
1421
|
+
];
|
|
1422
|
+
}
|
|
1423
|
+
function isolatedLauncher(isolation) {
|
|
1424
|
+
const { command, debug } = isolation;
|
|
1425
|
+
return {
|
|
1426
|
+
start(run) {
|
|
1427
|
+
const name = containerName(run.routeId);
|
|
1428
|
+
const args = runArgs(run.routeId, isolation);
|
|
1429
|
+
debug.write(`$ ${command} ${args.join(" ")}`);
|
|
1430
|
+
const child = spawn(command, args, {
|
|
1431
|
+
env: {
|
|
1432
|
+
...runnerEnv(),
|
|
1433
|
+
RUNNER_JIT_CONFIG: run.jitConfig
|
|
1434
|
+
},
|
|
1435
|
+
stdio: [
|
|
1436
|
+
"ignore",
|
|
1437
|
+
"pipe",
|
|
1438
|
+
"pipe"
|
|
1439
|
+
]
|
|
1440
|
+
});
|
|
1441
|
+
child.once("error", (error) => debug.write(`${name}: ${error.message}`));
|
|
1442
|
+
child.once("close", (code, signal) => debug.write(`${name}: exit ${signal ?? code}`));
|
|
1443
|
+
return child;
|
|
1444
|
+
},
|
|
1445
|
+
async cleanup(run, clean) {
|
|
1446
|
+
if (clean) return;
|
|
1447
|
+
const args = [
|
|
1448
|
+
"delete",
|
|
1449
|
+
"--force",
|
|
1450
|
+
containerName(run.routeId)
|
|
1451
|
+
];
|
|
1452
|
+
if (await call(command, args, debug) !== 0) await call(command, args, debug);
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
function call(command, args, debug, quiet = false) {
|
|
1457
|
+
return new Promise((resolve) => {
|
|
1458
|
+
const child = spawn(command, args, { stdio: [
|
|
1459
|
+
"ignore",
|
|
1460
|
+
"pipe",
|
|
1461
|
+
"pipe"
|
|
1462
|
+
] });
|
|
1463
|
+
let output = "";
|
|
1464
|
+
const keep = (chunk) => {
|
|
1465
|
+
if (!quiet) output += chunk.toString();
|
|
1466
|
+
};
|
|
1467
|
+
child.stdout.on("data", keep);
|
|
1468
|
+
child.stderr.on("data", keep);
|
|
1469
|
+
const done = (code, extra = "") => {
|
|
1470
|
+
debug.write(`$ ${command} ${args.join(" ")}\n${output}${extra}exit ${code}`);
|
|
1471
|
+
resolve(code);
|
|
1472
|
+
};
|
|
1473
|
+
child.once("error", (error) => done(null, `${error.message}\n`));
|
|
1474
|
+
child.once("close", (code) => done(code));
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
// repo.ts
|
|
1478
|
+
const WORKFLOWS_DIR = ".github/workflows";
|
|
1479
|
+
/** The nearest directory at or above `from` that holds a `.git`, or null outside a checkout. */
|
|
1480
|
+
function findRepoRoot(from = process.cwd()) {
|
|
1481
|
+
let dir = resolve(from);
|
|
1482
|
+
for (;;) {
|
|
1483
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
1484
|
+
const parent = dirname(dir);
|
|
1485
|
+
if (parent === dir) return null;
|
|
1486
|
+
dir = parent;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
function readWorkflowFiles(root) {
|
|
1490
|
+
const dir = join(root, WORKFLOWS_DIR);
|
|
1491
|
+
if (!existsSync(dir)) return [];
|
|
1492
|
+
return readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => ({
|
|
1493
|
+
file: `${WORKFLOWS_DIR}/${name}`,
|
|
1494
|
+
source: readFileSync(join(dir, name), "utf8")
|
|
1495
|
+
}));
|
|
1496
|
+
}
|
|
1497
|
+
/** `owner/name` from a GitHub remote URL (https or ssh), or null for anything else. */
|
|
1498
|
+
function parseGitHubRemote(url) {
|
|
1499
|
+
const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
1500
|
+
return match ? `${match[1]}/${match[2]}` : null;
|
|
1501
|
+
}
|
|
1502
|
+
function originRepo(root) {
|
|
1503
|
+
return new Promise((done) => {
|
|
1504
|
+
execFile("git", [
|
|
1505
|
+
"-C",
|
|
1506
|
+
root,
|
|
1507
|
+
"remote",
|
|
1508
|
+
"get-url",
|
|
1509
|
+
"origin"
|
|
1510
|
+
], {
|
|
1511
|
+
timeout: 3e3,
|
|
1512
|
+
encoding: "utf8"
|
|
1513
|
+
}, (error, stdout) => done(error ? null : parseGitHubRemote(stdout)));
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Asks GitHub without signing in. A public repo answers; a private one (or one that doesn't exist)
|
|
1518
|
+
* is a 404 to an anonymous caller. Anything else, such as no network or a rate limit, is unknown.
|
|
1519
|
+
*/
|
|
1520
|
+
async function repoVisibility(repo, fetcher = fetch) {
|
|
1521
|
+
try {
|
|
1522
|
+
const response = await fetcher(`https://api.github.com/repos/${repo}`, {
|
|
1523
|
+
headers: {
|
|
1524
|
+
accept: "application/vnd.github+json",
|
|
1525
|
+
"user-agent": userAgent
|
|
1526
|
+
},
|
|
1527
|
+
signal: AbortSignal.timeout(5e3)
|
|
1528
|
+
});
|
|
1529
|
+
if (response.status === 404) return "private";
|
|
1530
|
+
if (!response.ok) return "unknown";
|
|
1531
|
+
return (await response.json()).private === false ? "public" : "private";
|
|
1532
|
+
} catch {
|
|
1533
|
+
return "unknown";
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
// ../../packages/providers/src/prices.ts
|
|
1537
|
+
/** A provider's rates, and what one minute of each is per. */
|
|
1538
|
+
const RATES = {
|
|
1539
|
+
blacksmith: {
|
|
1540
|
+
linux: "vcpu",
|
|
1541
|
+
arm: "vcpu",
|
|
1542
|
+
windows: "vcpu",
|
|
1543
|
+
macos: "vcpu"
|
|
1544
|
+
},
|
|
1545
|
+
depot: {
|
|
1546
|
+
linux: "vcpu",
|
|
1547
|
+
arm: "vcpu",
|
|
1548
|
+
windows: "vcpu",
|
|
1549
|
+
macos: "vcpu"
|
|
1550
|
+
},
|
|
1551
|
+
warpbuild: {
|
|
1552
|
+
linux: "vcpu",
|
|
1553
|
+
arm: "vcpu",
|
|
1554
|
+
windows: "vcpu",
|
|
1555
|
+
macos: "vcpu"
|
|
938
1556
|
},
|
|
939
1557
|
ubicloud: {
|
|
940
1558
|
standard: "vcpu",
|
|
@@ -949,7 +1567,13 @@ const RATES = {
|
|
|
949
1567
|
macos: "runner"
|
|
950
1568
|
}
|
|
951
1569
|
};
|
|
952
|
-
|
|
1570
|
+
/** The one rate a provider operators added has: a minute of any of its runners. */
|
|
1571
|
+
const ADDED_RATE = "runner";
|
|
1572
|
+
/**
|
|
1573
|
+
* Whether a provider has this rate: one RATES lists, or the per-runner rate of a provider RATES
|
|
1574
|
+
* doesn't price (the admin only records that one for providers operators added).
|
|
1575
|
+
*/
|
|
1576
|
+
const isRate = (provider, rate) => Object.hasOwn(RATES, provider) ? Object.hasOwn(RATES[provider], rate) : rate === ADDED_RATE;
|
|
953
1577
|
const vcpu = (perRunner, vcpus) => perRunner / vcpus;
|
|
954
1578
|
const BASE_PRICES = [
|
|
955
1579
|
{
|
|
@@ -1144,7 +1768,9 @@ const LABEL_PREFIXES = {
|
|
|
1144
1768
|
ubicloud: ["ubicloud-"],
|
|
1145
1769
|
"runs-on": ["runs-on=", "runs-on/"]
|
|
1146
1770
|
};
|
|
1147
|
-
|
|
1771
|
+
/** Whether a lowercase label starts with one of `prefixes`, or is the bare name one ends in `-`. */
|
|
1772
|
+
const matchesPrefix = (prefixes, lower) => prefixes.some((prefix) => lower.startsWith(prefix) || prefix.endsWith("-") && lower === prefix.slice(0, -1));
|
|
1773
|
+
const matches = (provider, lower) => matchesPrefix(LABEL_PREFIXES[provider], lower);
|
|
1148
1774
|
/** The hosted provider whose runners a label asks for, or null. */
|
|
1149
1775
|
function hostedProviderOf(label) {
|
|
1150
1776
|
const lower = label.toLowerCase();
|
|
@@ -1269,8 +1895,9 @@ function deploySignal(job, workflow) {
|
|
|
1269
1895
|
}
|
|
1270
1896
|
function jobWarnings(job, options) {
|
|
1271
1897
|
const warnings = [];
|
|
1272
|
-
|
|
1273
|
-
if (job.
|
|
1898
|
+
const docker = !options.vm;
|
|
1899
|
+
if (docker && job.services !== void 0) warnings.push("uses services, which need Docker on the machine");
|
|
1900
|
+
if (docker && job.container !== void 0) warnings.push("runs in a container, which needs Docker on the machine");
|
|
1274
1901
|
const steps = Array.isArray(job.steps) ? job.steps : [];
|
|
1275
1902
|
const providerActions = /* @__PURE__ */ new Set();
|
|
1276
1903
|
let packages = false;
|
|
@@ -1280,10 +1907,10 @@ function jobWarnings(job, options) {
|
|
|
1280
1907
|
if (typeof step.uses === "string") {
|
|
1281
1908
|
const action = step.uses.split("@")[0];
|
|
1282
1909
|
if (action.startsWith("useblacksmith/")) providerActions.add(action);
|
|
1283
|
-
if (action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
|
|
1910
|
+
if (docker && action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
|
|
1284
1911
|
}
|
|
1285
1912
|
}
|
|
1286
|
-
if (packages && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
|
|
1913
|
+
if (packages && !options.vm && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
|
|
1287
1914
|
for (const action of providerActions) warnings.push(`uses ${action}, which is made for Blacksmith runners`);
|
|
1288
1915
|
return warnings;
|
|
1289
1916
|
}
|
|
@@ -1357,7 +1984,10 @@ async function planInit(cwd = process.cwd(), options = {}) {
|
|
|
1357
1984
|
const repo = await originRepo(root);
|
|
1358
1985
|
const visibility = repo ? await repoVisibility(repo, options.fetcher) : "unknown";
|
|
1359
1986
|
const files = readWorkflowFiles(root);
|
|
1360
|
-
const { jobs, errors } = analyzeWorkflows(files,
|
|
1987
|
+
const { jobs, errors } = analyzeWorkflows(files, options.hostOs ? options : {
|
|
1988
|
+
hostOs: hostOs(),
|
|
1989
|
+
vm: await isolationState() === "ready"
|
|
1990
|
+
});
|
|
1361
1991
|
return {
|
|
1362
1992
|
root,
|
|
1363
1993
|
repo,
|
|
@@ -1534,318 +2164,65 @@ async function chooseAndWrite(plan, finish) {
|
|
|
1534
2164
|
* yet, and at least one job could be.
|
|
1535
2165
|
*/
|
|
1536
2166
|
function shouldOfferSetup(plan) {
|
|
1537
|
-
return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
|
|
1538
|
-
}
|
|
1539
|
-
/**
|
|
1540
|
-
* Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
|
|
1541
|
-
* yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
|
|
1542
|
-
* remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
|
|
1543
|
-
* throws: setup is a convenience, and `connect` goes online either way.
|
|
1544
|
-
*/
|
|
1545
|
-
async function offerSetup(cwd = process.cwd()) {
|
|
1546
|
-
try {
|
|
1547
|
-
const plan = await planInit(cwd).catch((error) => {
|
|
1548
|
-
if (error instanceof InitError) return null;
|
|
1549
|
-
throw error;
|
|
1550
|
-
});
|
|
1551
|
-
if (!plan || !shouldOfferSetup(plan)) return;
|
|
1552
|
-
const key = plan.repo ?? plan.root;
|
|
1553
|
-
if (isDeclined(key)) return;
|
|
1554
|
-
const answer = await clack.confirm({
|
|
1555
|
-
message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
|
|
1556
|
-
initialValue: false
|
|
1557
|
-
});
|
|
1558
|
-
if (clack.isCancel(answer)) return;
|
|
1559
|
-
if (!answer) {
|
|
1560
|
-
rememberDeclined(key);
|
|
1561
|
-
clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
|
|
1562
|
-
return;
|
|
1563
|
-
}
|
|
1564
|
-
await chooseAndWrite(plan, (message) => clack.log.success(message));
|
|
1565
|
-
} catch (error) {
|
|
1566
|
-
clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
function describeRepo(plan) {
|
|
1570
|
-
if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
|
|
1571
|
-
return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
|
|
1572
|
-
}
|
|
1573
|
-
function jobLine(job) {
|
|
1574
|
-
const name = `${shortFile(job.file)} › ${job.job}`;
|
|
1575
|
-
if (job.verdict === "skipped") return `${name}: ${job.reason}`;
|
|
1576
|
-
if (job.verdict === "routed") return name;
|
|
1577
|
-
return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
|
|
1578
|
-
}
|
|
1579
|
-
function shortFile(file) {
|
|
1580
|
-
return file.replace(/^\.github\/workflows\//, "");
|
|
1581
|
-
}
|
|
1582
|
-
function colorDiff(diff) {
|
|
1583
|
-
return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
|
|
1584
|
-
}
|
|
1585
|
-
// machine-name.ts
|
|
1586
|
-
const MAX_LENGTH = 64;
|
|
1587
|
-
async function defaultMachineName(run$1 = run, system = platform(), host = hostname()) {
|
|
1588
|
-
const names = [];
|
|
1589
|
-
if (system === "darwin") for (const key of [
|
|
1590
|
-
"HostName",
|
|
1591
|
-
"ComputerName",
|
|
1592
|
-
"LocalHostName"
|
|
1593
|
-
]) names.push(await run$1("scutil", ["--get", key]));
|
|
1594
|
-
names.push(host.replace(/\.local$/i, ""));
|
|
1595
|
-
return (names.find((name) => name?.trim()) ?? "").trim().slice(0, MAX_LENGTH);
|
|
1596
|
-
}
|
|
1597
|
-
// jit-config.ts
|
|
1598
|
-
const GITHUB_HOSTS = [
|
|
1599
|
-
/^github\.com$/,
|
|
1600
|
-
/\.github\.com$/,
|
|
1601
|
-
/\.githubusercontent\.com$/
|
|
1602
|
-
];
|
|
1603
|
-
const FILES = [
|
|
1604
|
-
".runner",
|
|
1605
|
-
".credentials",
|
|
1606
|
-
".credentials_rsaparams"
|
|
1607
|
-
];
|
|
1608
|
-
const URL_FIELDS = /* @__PURE__ */ new Set([
|
|
1609
|
-
"serverurl",
|
|
1610
|
-
"serverurlv2",
|
|
1611
|
-
"githuburl",
|
|
1612
|
-
"authorizationurl"
|
|
1613
|
-
]);
|
|
1614
|
-
function checkJitConfig(encoded, routeId) {
|
|
1615
|
-
let files;
|
|
1616
|
-
try {
|
|
1617
|
-
files = decodeJson(encoded);
|
|
1618
|
-
if (!files || typeof files !== "object") throw new Error();
|
|
1619
|
-
} catch {
|
|
1620
|
-
return {
|
|
1621
|
-
ok: false,
|
|
1622
|
-
reason: "it isn't a runner config"
|
|
1623
|
-
};
|
|
1624
|
-
}
|
|
1625
|
-
const names = Object.keys(files);
|
|
1626
|
-
if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
|
|
1627
|
-
ok: false,
|
|
1628
|
-
reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
|
|
1629
|
-
};
|
|
1630
|
-
const decoded = {};
|
|
1631
|
-
for (const [name, value] of Object.entries(files)) {
|
|
1632
|
-
if (typeof value !== "string") return {
|
|
1633
|
-
ok: false,
|
|
1634
|
-
reason: `${name} isn't a file`
|
|
1635
|
-
};
|
|
1636
|
-
try {
|
|
1637
|
-
decoded[name] = decodeJson(value);
|
|
1638
|
-
} catch {
|
|
1639
|
-
return {
|
|
1640
|
-
ok: false,
|
|
1641
|
-
reason: `${name} isn't JSON`
|
|
1642
|
-
};
|
|
1643
|
-
}
|
|
1644
|
-
}
|
|
1645
|
-
const runner = decoded[".runner"];
|
|
1646
|
-
if (!runner || typeof runner !== "object") return {
|
|
1647
|
-
ok: false,
|
|
1648
|
-
reason: "it has no .runner"
|
|
1649
|
-
};
|
|
1650
|
-
const duplicate = duplicateKey(decoded);
|
|
1651
|
-
if (duplicate) return {
|
|
1652
|
-
ok: false,
|
|
1653
|
-
reason: `it has ${duplicate} twice`
|
|
1654
|
-
};
|
|
1655
|
-
for (const url of urls(decoded)) {
|
|
1656
|
-
const parsed = URL.canParse(url) ? new URL(url) : null;
|
|
1657
|
-
if (!parsed) return {
|
|
1658
|
-
ok: false,
|
|
1659
|
-
reason: `it names a URL that doesn't parse: ${url}`
|
|
1660
|
-
};
|
|
1661
|
-
if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
|
|
1662
|
-
ok: false,
|
|
1663
|
-
reason: `it points the runner at ${parsed.origin}, not GitHub`
|
|
1664
|
-
};
|
|
1665
|
-
}
|
|
1666
|
-
const field = (key) => {
|
|
1667
|
-
const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
|
|
1668
|
-
return typeof entry?.[1] === "string" ? entry[1] : null;
|
|
1669
|
-
};
|
|
1670
|
-
if (!field("serverurl") && !field("serverurlv2")) return {
|
|
1671
|
-
ok: false,
|
|
1672
|
-
reason: "it doesn't say which GitHub server to use"
|
|
1673
|
-
};
|
|
1674
|
-
const runnerName = field("agentname");
|
|
1675
|
-
if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
|
|
1676
|
-
ok: false,
|
|
1677
|
-
reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
|
|
1678
|
-
};
|
|
1679
|
-
return {
|
|
1680
|
-
ok: true,
|
|
1681
|
-
target: target(field("githuburl"))
|
|
1682
|
-
};
|
|
1683
|
-
}
|
|
1684
|
-
function target(url) {
|
|
1685
|
-
if (!url || !URL.canParse(url)) return null;
|
|
1686
|
-
const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
|
|
1687
|
-
return path.length ? path.join("/") : null;
|
|
1688
|
-
}
|
|
1689
|
-
function urls(value, found = [], key = "") {
|
|
1690
|
-
if (typeof value === "string") {
|
|
1691
|
-
const text = value.trim();
|
|
1692
|
-
if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
|
|
1693
|
-
} else if (Array.isArray(value)) for (const item of value) urls(item, found);
|
|
1694
|
-
else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
|
|
1695
|
-
return found;
|
|
1696
|
-
}
|
|
1697
|
-
function duplicateKey(value) {
|
|
1698
|
-
if (Array.isArray(value)) for (const item of value) {
|
|
1699
|
-
const found = duplicateKey(item);
|
|
1700
|
-
if (found) return found;
|
|
1701
|
-
}
|
|
1702
|
-
else if (value && typeof value === "object") {
|
|
1703
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1704
|
-
for (const [name, item] of Object.entries(value)) {
|
|
1705
|
-
if (seen.has(name.toLowerCase())) return name;
|
|
1706
|
-
seen.add(name.toLowerCase());
|
|
1707
|
-
const found = duplicateKey(item);
|
|
1708
|
-
if (found) return found;
|
|
1709
|
-
}
|
|
1710
|
-
}
|
|
1711
|
-
return null;
|
|
1712
|
-
}
|
|
1713
|
-
function decodeJson(base64) {
|
|
1714
|
-
return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
|
|
1715
|
-
}
|
|
1716
|
-
// job.ts
|
|
1717
|
-
const runnerEnv = () => Object.fromEntries([
|
|
1718
|
-
"HOME",
|
|
1719
|
-
"USER",
|
|
1720
|
-
"LOGNAME",
|
|
1721
|
-
"PATH",
|
|
1722
|
-
"LANG",
|
|
1723
|
-
"LC_ALL",
|
|
1724
|
-
"TMPDIR",
|
|
1725
|
-
"SHELL"
|
|
1726
|
-
].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
|
|
1727
|
-
const JOB_STATE = [
|
|
1728
|
-
"_work",
|
|
1729
|
-
".runner",
|
|
1730
|
-
".credentials",
|
|
1731
|
-
".credentials_rsaparams"
|
|
1732
|
-
];
|
|
1733
|
-
async function runJob(run, options) {
|
|
1734
|
-
const { dir, report } = options;
|
|
1735
|
-
const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
|
|
1736
|
-
const finish = (update) => {
|
|
1737
|
-
report(update);
|
|
1738
|
-
return update;
|
|
1739
|
-
};
|
|
1740
|
-
const checked = checkJitConfig(run.jitConfig, run.routeId);
|
|
1741
|
-
if (!checked.ok) return finish({
|
|
1742
|
-
routeId: run.routeId,
|
|
1743
|
-
state: "failed",
|
|
1744
|
-
message: `Refused the job's runner config: ${checked.reason}.`
|
|
1745
|
-
});
|
|
1746
|
-
options.onChecked?.(checked.target);
|
|
1747
|
-
const lock = join(dir, "job.lock");
|
|
1748
|
-
if (!takeLock(lock)) return finish({
|
|
1749
|
-
routeId: run.routeId,
|
|
1750
|
-
state: "failed",
|
|
1751
|
-
message: `Another job is using the runner in ${dir}.`
|
|
1752
|
-
});
|
|
1753
|
-
try {
|
|
1754
|
-
clean(dir);
|
|
1755
|
-
const child = spawn(join(dir, "run.sh"), ["--jitconfig", run.jitConfig], {
|
|
1756
|
-
cwd: dir,
|
|
1757
|
-
env: runnerEnv(),
|
|
1758
|
-
stdio: [
|
|
1759
|
-
"ignore",
|
|
1760
|
-
"pipe",
|
|
1761
|
-
"pipe"
|
|
1762
|
-
]
|
|
1763
|
-
});
|
|
1764
|
-
child.stdout.on("data", (chunk) => output(chunk, "stdout"));
|
|
1765
|
-
child.stderr.on("data", (chunk) => output(chunk, "stderr"));
|
|
1766
|
-
const started = await new Promise((resolve) => {
|
|
1767
|
-
child.once("spawn", () => resolve(null));
|
|
1768
|
-
child.once("error", resolve);
|
|
1769
|
-
});
|
|
1770
|
-
if (started) return finish({
|
|
1771
|
-
routeId: run.routeId,
|
|
1772
|
-
state: "failed",
|
|
1773
|
-
message: `Could not start the runner: ${started.message}`
|
|
1774
|
-
});
|
|
1775
|
-
report({
|
|
1776
|
-
routeId: run.routeId,
|
|
1777
|
-
state: "started"
|
|
1778
|
-
});
|
|
1779
|
-
const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
|
|
1780
|
-
if (code === 0) return finish({
|
|
1781
|
-
routeId: run.routeId,
|
|
1782
|
-
state: "finished"
|
|
2167
|
+
return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
|
|
2171
|
+
* yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
|
|
2172
|
+
* remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
|
|
2173
|
+
* throws: setup is a convenience, and `connect` goes online either way.
|
|
2174
|
+
*/
|
|
2175
|
+
async function offerSetup(cwd = process.cwd()) {
|
|
2176
|
+
try {
|
|
2177
|
+
const plan = await planInit(cwd).catch((error) => {
|
|
2178
|
+
if (error instanceof InitError) return null;
|
|
2179
|
+
throw error;
|
|
1783
2180
|
});
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
2181
|
+
if (!plan || !shouldOfferSetup(plan)) return;
|
|
2182
|
+
const key = plan.repo ?? plan.root;
|
|
2183
|
+
if (isDeclined(key)) return;
|
|
2184
|
+
const answer = await clack.confirm({
|
|
2185
|
+
message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
|
|
2186
|
+
initialValue: false
|
|
1788
2187
|
});
|
|
2188
|
+
if (clack.isCancel(answer)) return;
|
|
2189
|
+
if (!answer) {
|
|
2190
|
+
rememberDeclined(key);
|
|
2191
|
+
clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
|
|
2192
|
+
return;
|
|
2193
|
+
}
|
|
2194
|
+
await chooseAndWrite(plan, (message) => clack.log.success(message));
|
|
1789
2195
|
} catch (error) {
|
|
1790
|
-
|
|
1791
|
-
routeId: run.routeId,
|
|
1792
|
-
state: "failed",
|
|
1793
|
-
message: error instanceof Error ? error.message : String(error)
|
|
1794
|
-
});
|
|
1795
|
-
} finally {
|
|
1796
|
-
clean(dir);
|
|
1797
|
-
rmSync(lock, { force: true });
|
|
2196
|
+
clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
|
|
1798
2197
|
}
|
|
1799
2198
|
}
|
|
1800
|
-
function
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
force: true
|
|
1804
|
-
});
|
|
2199
|
+
function describeRepo(plan) {
|
|
2200
|
+
if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
|
|
2201
|
+
return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
|
|
1805
2202
|
}
|
|
1806
|
-
function
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
}
|
|
1811
|
-
if (error.code !== "EEXIST") throw error;
|
|
1812
|
-
if (isAlive(Number(readlinkSync(lock)))) return false;
|
|
1813
|
-
rmSync(lock, { force: true });
|
|
1814
|
-
}
|
|
1815
|
-
return false;
|
|
2203
|
+
function jobLine(job) {
|
|
2204
|
+
const name = `${shortFile(job.file)} › ${job.job}`;
|
|
2205
|
+
if (job.verdict === "skipped") return `${name}: ${job.reason}`;
|
|
2206
|
+
if (job.verdict === "routed") return name;
|
|
2207
|
+
return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
|
|
1816
2208
|
}
|
|
1817
|
-
function
|
|
1818
|
-
|
|
1819
|
-
try {
|
|
1820
|
-
process.kill(pid, 0);
|
|
1821
|
-
return true;
|
|
1822
|
-
} catch (error) {
|
|
1823
|
-
return error.code === "EPERM";
|
|
1824
|
-
}
|
|
2209
|
+
function shortFile(file) {
|
|
2210
|
+
return file.replace(/^\.github\/workflows\//, "");
|
|
1825
2211
|
}
|
|
1826
|
-
function
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
for (const stream of ["stdout", "stderr"]) {
|
|
1841
|
-
if (partial[stream]) write(Buffer.from(`${prefix}${partial[stream]}\n`), stream);
|
|
1842
|
-
partial[stream] = "";
|
|
1843
|
-
}
|
|
1844
|
-
};
|
|
1845
|
-
return {
|
|
1846
|
-
output,
|
|
1847
|
-
flush
|
|
1848
|
-
};
|
|
2212
|
+
function colorDiff(diff) {
|
|
2213
|
+
return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
|
|
2214
|
+
}
|
|
2215
|
+
// machine-name.ts
|
|
2216
|
+
const MAX_LENGTH = 64;
|
|
2217
|
+
async function defaultMachineName(run$1 = run, system = platform(), host = hostname()) {
|
|
2218
|
+
const names = [];
|
|
2219
|
+
if (system === "darwin") for (const key of [
|
|
2220
|
+
"HostName",
|
|
2221
|
+
"ComputerName",
|
|
2222
|
+
"LocalHostName"
|
|
2223
|
+
]) names.push(await run$1("scutil", ["--get", key]));
|
|
2224
|
+
names.push(host.replace(/\.local$/i, ""));
|
|
2225
|
+
return (names.find((name) => name?.trim()) ?? "").trim().slice(0, MAX_LENGTH);
|
|
1849
2226
|
}
|
|
1850
2227
|
// live.ts
|
|
1851
2228
|
const INITIAL_STATE = {
|
|
@@ -1983,27 +2360,12 @@ async function checkForUpdate(options = {}) {
|
|
|
1983
2360
|
writeCache(cache);
|
|
1984
2361
|
}
|
|
1985
2362
|
}
|
|
1986
|
-
return cache &&
|
|
2363
|
+
return cache && isNewerVersion(cache.latest, current) ? cache.latest : null;
|
|
1987
2364
|
}
|
|
1988
2365
|
/** The line to print for a newer version, with the command that updates the way this one runs. */
|
|
1989
2366
|
function updateNotice(latest, current = cliVersion, argv1 = process.argv[1] ?? "") {
|
|
1990
2367
|
return `relayrunner ${latest} is available (you have ${current}). Update with \`${/[\\/]_npx[\\/]/.test(argv1) ? "npx relayrunner@latest connect" : "npm install --global relayrunner@latest"}\`.`;
|
|
1991
2368
|
}
|
|
1992
|
-
function isNewer(candidate, current) {
|
|
1993
|
-
const a = parse(candidate);
|
|
1994
|
-
const b = parse(current);
|
|
1995
|
-
if (!a || !b) return false;
|
|
1996
|
-
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
|
1997
|
-
return false;
|
|
1998
|
-
}
|
|
1999
|
-
function parse(version) {
|
|
2000
|
-
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
|
|
2001
|
-
return match ? [
|
|
2002
|
-
Number(match[1]),
|
|
2003
|
-
Number(match[2]),
|
|
2004
|
-
Number(match[3])
|
|
2005
|
-
] : null;
|
|
2006
|
-
}
|
|
2007
2369
|
async function fetchLatest(fetcher) {
|
|
2008
2370
|
try {
|
|
2009
2371
|
const response = await fetcher(REGISTRY_URL, {
|
|
@@ -2359,6 +2721,124 @@ async function setSharing(options) {
|
|
|
2359
2721
|
sharing: parsed.data.machine.sharing
|
|
2360
2722
|
};
|
|
2361
2723
|
}
|
|
2724
|
+
// firewall.ts
|
|
2725
|
+
const ANCHOR = "com.apple/relayrunner";
|
|
2726
|
+
const LABEL = "app.relayrunner.firewall";
|
|
2727
|
+
const RULES_FILE = "/etc/pf.anchors/app.relayrunner";
|
|
2728
|
+
const DAEMON_FILE = `/Library/LaunchDaemons/${LABEL}.plist`;
|
|
2729
|
+
const VM_NETWORK = "192.168.64.0/24";
|
|
2730
|
+
const VM_GATEWAY = "192.168.64.1";
|
|
2731
|
+
const DEFAULT_INTERFACE = "bridge100";
|
|
2732
|
+
function vmInterface(interfaces = networkInterfaces()) {
|
|
2733
|
+
for (const [name, addresses] of Object.entries(interfaces)) if (addresses?.some((address) => address.address === VM_GATEWAY)) return name;
|
|
2734
|
+
return DEFAULT_INTERFACE;
|
|
2735
|
+
}
|
|
2736
|
+
function firewallRules(iface) {
|
|
2737
|
+
return `pass in quick on ${iface} proto udp from any port 68 to any port 67
|
|
2738
|
+
block drop in quick on ${iface} inet from ! ${VM_NETWORK} to any
|
|
2739
|
+
pass in quick on ${iface} proto { udp, tcp } from ${VM_NETWORK} to ${VM_GATEWAY} port 53
|
|
2740
|
+
block drop in quick on ${iface} inet to { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 }
|
|
2741
|
+
pass in quick on ${iface} inet6 proto icmp6 icmp6-type { neighbrsol, neighbradv, routersol }
|
|
2742
|
+
block drop in quick on ${iface} inet6 all
|
|
2743
|
+
`;
|
|
2744
|
+
}
|
|
2745
|
+
const LOAD = `/sbin/pfctl -q -a ${ANCHOR} -f ${RULES_FILE}; /sbin/pfctl -s info 2>/dev/null | /usr/bin/grep -q "Status: Enabled" || /sbin/pfctl -q -E`;
|
|
2746
|
+
function daemonPlist() {
|
|
2747
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
2748
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
2749
|
+
<plist version="1.0">
|
|
2750
|
+
<dict>
|
|
2751
|
+
<key>Label</key>
|
|
2752
|
+
<string>${LABEL}</string>
|
|
2753
|
+
<key>ProgramArguments</key>
|
|
2754
|
+
<array>
|
|
2755
|
+
<string>/bin/sh</string>
|
|
2756
|
+
<string>-c</string>
|
|
2757
|
+
<string>${LOAD.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")}</string>
|
|
2758
|
+
</array>
|
|
2759
|
+
<key>RunAtLoad</key>
|
|
2760
|
+
<true/>
|
|
2761
|
+
<key>StartInterval</key>
|
|
2762
|
+
<integer>300</integer>
|
|
2763
|
+
</dict>
|
|
2764
|
+
</plist>
|
|
2765
|
+
`;
|
|
2766
|
+
}
|
|
2767
|
+
function onScript(rules, plist) {
|
|
2768
|
+
return [
|
|
2769
|
+
"set -e",
|
|
2770
|
+
`install -m 644 -o root -g wheel "${rules}" ${RULES_FILE}`,
|
|
2771
|
+
`install -m 644 -o root -g wheel "${plist}" ${DAEMON_FILE}`,
|
|
2772
|
+
`launchctl bootout system/${LABEL} 2>/dev/null || true`,
|
|
2773
|
+
`launchctl bootstrap system ${DAEMON_FILE}`,
|
|
2774
|
+
LOAD
|
|
2775
|
+
].join("\n");
|
|
2776
|
+
}
|
|
2777
|
+
function offScript() {
|
|
2778
|
+
return [
|
|
2779
|
+
`launchctl bootout system/${LABEL} 2>/dev/null || true`,
|
|
2780
|
+
`rm -f ${DAEMON_FILE} ${RULES_FILE}`,
|
|
2781
|
+
`/sbin/pfctl -q -a ${ANCHOR} -F all 2>/dev/null || true`
|
|
2782
|
+
].join("\n");
|
|
2783
|
+
}
|
|
2784
|
+
function firewallInstalled(exists = existsSync) {
|
|
2785
|
+
return exists("/etc/pf.anchors/app.relayrunner") && exists("/Library/LaunchDaemons/app.relayrunner.firewall.plist");
|
|
2786
|
+
}
|
|
2787
|
+
function sudo(script) {
|
|
2788
|
+
console.log("This needs your password, to change the Mac's firewall.");
|
|
2789
|
+
return spawnSync("sudo", [
|
|
2790
|
+
"/bin/sh",
|
|
2791
|
+
"-c",
|
|
2792
|
+
script
|
|
2793
|
+
], { stdio: "inherit" }).status === 0;
|
|
2794
|
+
}
|
|
2795
|
+
function status() {
|
|
2796
|
+
if (!firewallInstalled()) {
|
|
2797
|
+
console.log("The firewall on this Mac is off. Isolated jobs rely on the firewall inside each VM, which a job using Docker can remove.\nTurn it on with `relayrunner firewall on`.");
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
console.log("The firewall on this Mac is on. Isolated jobs can reach the internet, not this Mac or your local network.\nTurn it off with `relayrunner firewall off`.");
|
|
2801
|
+
}
|
|
2802
|
+
const firewallCommand = defineCommand({
|
|
2803
|
+
meta: {
|
|
2804
|
+
name: "firewall",
|
|
2805
|
+
description: "Show or change the firewall on this Mac that keeps isolated jobs off the Mac and your local network."
|
|
2806
|
+
},
|
|
2807
|
+
args: { state: {
|
|
2808
|
+
type: "positional",
|
|
2809
|
+
required: false,
|
|
2810
|
+
description: "on or off; leave out to show the current setting"
|
|
2811
|
+
} },
|
|
2812
|
+
run({ args }) {
|
|
2813
|
+
const fail = (message) => {
|
|
2814
|
+
console.error(message);
|
|
2815
|
+
process.exitCode = 1;
|
|
2816
|
+
};
|
|
2817
|
+
const unsupported = unsupportedReason();
|
|
2818
|
+
if (unsupported) return fail(unsupported.replace("Running jobs in VMs needs", "The firewall needs"));
|
|
2819
|
+
if (!args.state) return status();
|
|
2820
|
+
if (args.state === "off") {
|
|
2821
|
+
if (!sudo(offScript())) return fail("Couldn't turn the firewall off.");
|
|
2822
|
+
console.log("The firewall on this Mac is off.");
|
|
2823
|
+
return;
|
|
2824
|
+
}
|
|
2825
|
+
if (args.state !== "on") return fail("Use `relayrunner firewall on` or `relayrunner firewall off`.");
|
|
2826
|
+
const dir = mkdtempSync(join(tmpdir(), "relayrunner-firewall-"));
|
|
2827
|
+
try {
|
|
2828
|
+
const rules = join(dir, "rules");
|
|
2829
|
+
const plist = join(dir, "daemon.plist");
|
|
2830
|
+
writeFileSync(rules, firewallRules(vmInterface()));
|
|
2831
|
+
writeFileSync(plist, daemonPlist());
|
|
2832
|
+
if (!sudo(onScript(rules, plist))) return fail("Couldn't turn the firewall on.");
|
|
2833
|
+
} finally {
|
|
2834
|
+
rmSync(dir, {
|
|
2835
|
+
recursive: true,
|
|
2836
|
+
force: true
|
|
2837
|
+
});
|
|
2838
|
+
}
|
|
2839
|
+
console.log("The firewall on this Mac is on. Isolated jobs can reach the internet, not this Mac or your local network.\nIt also applies to other VMs that use Apple's shared VM network. Turn it off with `relayrunner firewall off`.");
|
|
2840
|
+
}
|
|
2841
|
+
});
|
|
2362
2842
|
// whoami.ts
|
|
2363
2843
|
const WhoamiResponse = z.object({
|
|
2364
2844
|
machine: z.object({
|
|
@@ -2411,6 +2891,279 @@ async function whoami(options) {
|
|
|
2411
2891
|
identity: parsed.data
|
|
2412
2892
|
};
|
|
2413
2893
|
}
|
|
2894
|
+
// machine-workspaces.ts
|
|
2895
|
+
const Choice = z.object({
|
|
2896
|
+
id: z.string().min(1),
|
|
2897
|
+
name: z.string(),
|
|
2898
|
+
slug: z.string().nullish()
|
|
2899
|
+
});
|
|
2900
|
+
const MachineWorkspaces = z.object({
|
|
2901
|
+
machine: z.object({
|
|
2902
|
+
id: z.string().min(1),
|
|
2903
|
+
name: z.string(),
|
|
2904
|
+
sharing: z.enum(["only_me", "anyone"])
|
|
2905
|
+
}),
|
|
2906
|
+
workspaces: z.array(Choice),
|
|
2907
|
+
others: z.array(Choice)
|
|
2908
|
+
});
|
|
2909
|
+
/** GET the machine's workspaces, or PUT/DELETE one of them when `change` is given. */
|
|
2910
|
+
async function machineWorkspaces(options) {
|
|
2911
|
+
const fetcher = options.fetcher ?? fetch;
|
|
2912
|
+
const { change } = options;
|
|
2913
|
+
const path = change ? `/api/machines/me/workspaces/${encodeURIComponent(change.workspaceId)}` : "/api/machines/me/workspaces";
|
|
2914
|
+
let response;
|
|
2915
|
+
try {
|
|
2916
|
+
response = await fetcher(new URL(path, options.server), {
|
|
2917
|
+
method: change ? change.action === "add" ? "PUT" : "DELETE" : "GET",
|
|
2918
|
+
headers: {
|
|
2919
|
+
authorization: `Bearer ${options.token}`,
|
|
2920
|
+
"user-agent": userAgent
|
|
2921
|
+
}
|
|
2922
|
+
});
|
|
2923
|
+
} catch (error) {
|
|
2924
|
+
const cause = error.cause?.message;
|
|
2925
|
+
return {
|
|
2926
|
+
status: "failed",
|
|
2927
|
+
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
2928
|
+
};
|
|
2929
|
+
}
|
|
2930
|
+
if (response.status === 401) return { status: "revoked" };
|
|
2931
|
+
const body = await response.json().catch(() => null);
|
|
2932
|
+
if (change && response.status === 404 && body?.error === "not_found") return { status: "not_found" };
|
|
2933
|
+
if (response.status === 404 || response.status === 405) return {
|
|
2934
|
+
status: "failed",
|
|
2935
|
+
reason: `${options.server} doesn't support choosing workspaces yet`
|
|
2936
|
+
};
|
|
2937
|
+
if (response.status === 403) return {
|
|
2938
|
+
status: "failed",
|
|
2939
|
+
reason: "only the machine's owner can change its workspaces"
|
|
2940
|
+
};
|
|
2941
|
+
if (!response.ok) return {
|
|
2942
|
+
status: "failed",
|
|
2943
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
2944
|
+
};
|
|
2945
|
+
const parsed = MachineWorkspaces.safeParse(body);
|
|
2946
|
+
if (!parsed.success) return {
|
|
2947
|
+
status: "failed",
|
|
2948
|
+
reason: `${options.server} sent an unexpected response`
|
|
2949
|
+
};
|
|
2950
|
+
return {
|
|
2951
|
+
status: "ok",
|
|
2952
|
+
choice: parsed.data
|
|
2953
|
+
};
|
|
2954
|
+
}
|
|
2955
|
+
/** The workspace `query` names: its id, or its name or slug in any case. */
|
|
2956
|
+
function matchWorkspace(workspaces, query) {
|
|
2957
|
+
const byId = workspaces.find((workspace) => workspace.id === query);
|
|
2958
|
+
if (byId) return {
|
|
2959
|
+
status: "one",
|
|
2960
|
+
workspace: byId
|
|
2961
|
+
};
|
|
2962
|
+
const wanted = query.trim().toLowerCase();
|
|
2963
|
+
const found = workspaces.filter((workspace) => workspace.name.toLowerCase() === wanted || workspace.slug?.toLowerCase() === wanted);
|
|
2964
|
+
if (found.length === 1) return {
|
|
2965
|
+
status: "one",
|
|
2966
|
+
workspace: found[0]
|
|
2967
|
+
};
|
|
2968
|
+
return found.length ? {
|
|
2969
|
+
status: "several",
|
|
2970
|
+
workspaces: found
|
|
2971
|
+
} : { status: "none" };
|
|
2972
|
+
}
|
|
2973
|
+
/** "Acme (acme)" for listing, so two workspaces with the same name can be told apart. */
|
|
2974
|
+
function labelWorkspace(workspace, withId = false) {
|
|
2975
|
+
const slug = workspace.slug && workspace.slug !== workspace.name ? ` (${workspace.slug})` : "";
|
|
2976
|
+
return `${workspace.name}${slug}${withId ? ` ${workspace.id}` : ""}`;
|
|
2977
|
+
}
|
|
2978
|
+
/** What `relayrunner workspaces` prints. */
|
|
2979
|
+
function describeMachineWorkspaces({ machine, workspaces, others }) {
|
|
2980
|
+
const lines = [];
|
|
2981
|
+
if (!workspaces.length && !others.length) {
|
|
2982
|
+
lines.push(`${machine.name} isn't in a workspace yet. It takes jobs once RelayRunner is installed on a GitHub account or org you belong to.`);
|
|
2983
|
+
return lines.join("\n");
|
|
2984
|
+
}
|
|
2985
|
+
lines.push(`${machine.name} runs jobs in:`);
|
|
2986
|
+
if (workspaces.length) for (const w of workspaces) lines.push(` ✓ ${labelWorkspace(w)}`);
|
|
2987
|
+
else lines.push(" (none: it takes no jobs)");
|
|
2988
|
+
if (others.length) {
|
|
2989
|
+
lines.push("", "Not in:");
|
|
2990
|
+
for (const w of others) lines.push(` · ${labelWorkspace(w)}`);
|
|
2991
|
+
}
|
|
2992
|
+
lines.push("", `Sharing: ${toChoice(machine.sharing)}: ${sharingMeaning(machine.sharing, "these workspaces")}`);
|
|
2993
|
+
if (others.length) lines.push("Add one with `relayrunner workspaces add <name>`.");
|
|
2994
|
+
else if (workspaces.length) lines.push("Remove one with `relayrunner workspaces remove <name>`.");
|
|
2995
|
+
return lines.join("\n");
|
|
2996
|
+
}
|
|
2997
|
+
/** Said when `add` puts a machine that runs anyone's jobs into another workspace. */
|
|
2998
|
+
function anyoneWarning(machine, workspace) {
|
|
2999
|
+
return `${machine} is set to run anyone's jobs, so anyone who can push to ${workspace}'s private repos can run jobs on it. Use \`relayrunner share only-me\` to limit it to jobs you started.`;
|
|
3000
|
+
}
|
|
3001
|
+
// workspaces-command.ts
|
|
3002
|
+
function signedIn() {
|
|
3003
|
+
const credentials = readCredentials();
|
|
3004
|
+
if (!credentials) {
|
|
3005
|
+
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
3006
|
+
process.exitCode = 1;
|
|
3007
|
+
}
|
|
3008
|
+
return credentials;
|
|
3009
|
+
}
|
|
3010
|
+
function revoked(name) {
|
|
3011
|
+
console.error(`${name} was removed or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
3012
|
+
process.exitCode = 1;
|
|
3013
|
+
}
|
|
3014
|
+
const listCommand = defineCommand({
|
|
3015
|
+
meta: {
|
|
3016
|
+
name: "list",
|
|
3017
|
+
description: "List your workspaces, showing which ones this machine runs jobs in."
|
|
3018
|
+
},
|
|
3019
|
+
args: { json: {
|
|
3020
|
+
type: "boolean",
|
|
3021
|
+
description: "Print the result as JSON"
|
|
3022
|
+
} },
|
|
3023
|
+
async run({ args }) {
|
|
3024
|
+
const credentials = signedIn();
|
|
3025
|
+
if (!credentials) return;
|
|
3026
|
+
const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3027
|
+
server: credentials.server,
|
|
3028
|
+
token
|
|
3029
|
+
}));
|
|
3030
|
+
if (result.status === "revoked") return revoked(credentials.machine.name);
|
|
3031
|
+
if (result.status !== "ok") {
|
|
3032
|
+
console.error(`Couldn't list workspaces for ${credentials.machine.name}: ${result.status === "failed" ? result.reason : "not found"}.`);
|
|
3033
|
+
process.exitCode = 1;
|
|
3034
|
+
return;
|
|
3035
|
+
}
|
|
3036
|
+
console.log(args.json ? JSON.stringify(result.choice, null, 2) : describeMachineWorkspaces(result.choice));
|
|
3037
|
+
}
|
|
3038
|
+
});
|
|
3039
|
+
function changeCommand(action) {
|
|
3040
|
+
const adding = action === "add";
|
|
3041
|
+
return defineCommand({
|
|
3042
|
+
meta: {
|
|
3043
|
+
name: action,
|
|
3044
|
+
description: adding ? "Run jobs from one more of your workspaces on this machine." : "Stop running jobs from one of your workspaces on this machine. It keeps running jobs in the others."
|
|
3045
|
+
},
|
|
3046
|
+
args: { workspace: {
|
|
3047
|
+
type: "positional",
|
|
3048
|
+
required: false,
|
|
3049
|
+
description: "The workspace's name, slug or id; leave out to pick from a list"
|
|
3050
|
+
} },
|
|
3051
|
+
async run({ args }) {
|
|
3052
|
+
const credentials = signedIn();
|
|
3053
|
+
if (!credentials) return;
|
|
3054
|
+
const { server, machine } = credentials;
|
|
3055
|
+
const current = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3056
|
+
server,
|
|
3057
|
+
token
|
|
3058
|
+
}));
|
|
3059
|
+
if (current.status === "revoked") return revoked(machine.name);
|
|
3060
|
+
if (current.status !== "ok") {
|
|
3061
|
+
console.error(`Couldn't ${action} a workspace for ${machine.name}: ${current.status === "failed" ? current.reason : "not found"}.`);
|
|
3062
|
+
process.exitCode = 1;
|
|
3063
|
+
return;
|
|
3064
|
+
}
|
|
3065
|
+
const { workspaces, others } = current.choice;
|
|
3066
|
+
const picked = await pick(adding ? others : workspaces, args.workspace, {
|
|
3067
|
+
action,
|
|
3068
|
+
machine: machine.name,
|
|
3069
|
+
elsewhere: adding ? workspaces : others,
|
|
3070
|
+
noWorkspaces: !workspaces.length && !others.length,
|
|
3071
|
+
server
|
|
3072
|
+
});
|
|
3073
|
+
if (!picked) return;
|
|
3074
|
+
const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3075
|
+
server,
|
|
3076
|
+
token,
|
|
3077
|
+
change: {
|
|
3078
|
+
action,
|
|
3079
|
+
workspaceId: picked.id
|
|
3080
|
+
}
|
|
3081
|
+
}));
|
|
3082
|
+
if (result.status === "revoked") return revoked(machine.name);
|
|
3083
|
+
if (result.status === "not_found") {
|
|
3084
|
+
console.error(`You're no longer a member of ${picked.name}.`);
|
|
3085
|
+
process.exitCode = 1;
|
|
3086
|
+
return;
|
|
3087
|
+
}
|
|
3088
|
+
if (result.status === "failed") {
|
|
3089
|
+
console.error(`Couldn't ${action} ${picked.name}: ${result.reason}.`);
|
|
3090
|
+
process.exitCode = 1;
|
|
3091
|
+
return;
|
|
3092
|
+
}
|
|
3093
|
+
const now = result.choice;
|
|
3094
|
+
if (adding) {
|
|
3095
|
+
console.log(`${machine.name} now runs jobs in ${workspaceNames(now.workspaces)}.`);
|
|
3096
|
+
if (now.machine.sharing === "anyone") console.warn(`Warning: ${anyoneWarning(machine.name, picked.name)}`);
|
|
3097
|
+
} else if (now.workspaces.length) console.log(`${machine.name} no longer runs jobs in ${picked.name}. It still runs jobs in ${workspaceNames(now.workspaces)}.`);
|
|
3098
|
+
else {
|
|
3099
|
+
console.log(`${machine.name} no longer runs jobs in ${picked.name}.`);
|
|
3100
|
+
console.warn(`${machine.name} isn't in any workspace now, so it takes no jobs. Add one with \`relayrunner workspaces add <name>\`.`);
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
});
|
|
3104
|
+
}
|
|
3105
|
+
/** The workspace to add or remove: named on the command line, or picked from a list in a terminal. */
|
|
3106
|
+
async function pick(candidates, query, context) {
|
|
3107
|
+
const fail = (message) => {
|
|
3108
|
+
console.error(message);
|
|
3109
|
+
process.exitCode = 1;
|
|
3110
|
+
return null;
|
|
3111
|
+
};
|
|
3112
|
+
if (context.noWorkspaces) return fail(noWorkspaceYet(context.machine, context.server));
|
|
3113
|
+
const adding = context.action === "add";
|
|
3114
|
+
if (query) {
|
|
3115
|
+
const match = matchWorkspace(candidates, query);
|
|
3116
|
+
if (match.status === "one") return match.workspace;
|
|
3117
|
+
if (match.status === "several") return fail([`More than one workspace is called ${JSON.stringify(query)}. Name it by id:`, ...match.workspaces.map((w) => ` ${labelWorkspace(w, true)}`)].join("\n"));
|
|
3118
|
+
const other = matchWorkspace(context.elsewhere, query);
|
|
3119
|
+
if (other.status !== "none") {
|
|
3120
|
+
const name = other.status === "one" ? other.workspace.name : query;
|
|
3121
|
+
console.log(adding ? `${context.machine} already runs jobs in ${name}.` : `${context.machine} doesn't run jobs in ${name}.`);
|
|
3122
|
+
return null;
|
|
3123
|
+
}
|
|
3124
|
+
return fail([`None of your workspaces is called ${JSON.stringify(query)}.`, ...candidates.length ? [adding ? "Workspaces you can add:" : "Workspaces you can remove:", ...candidates.map((w) => ` ${labelWorkspace(w)}`)] : []].join("\n"));
|
|
3125
|
+
}
|
|
3126
|
+
if (!candidates.length) {
|
|
3127
|
+
console.log(adding ? `${context.machine} already runs jobs in all your workspaces.` : `${context.machine} isn't in any workspace.`);
|
|
3128
|
+
return null;
|
|
3129
|
+
}
|
|
3130
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return fail(`Name the workspace: \`relayrunner workspaces ${context.action} <name>\`.`);
|
|
3131
|
+
const choice = await clack.select({
|
|
3132
|
+
message: adding ? `Which workspace should ${context.machine} run jobs in too?` : `Which workspace should ${context.machine} stop running jobs in?`,
|
|
3133
|
+
options: candidates.map((w) => ({
|
|
3134
|
+
value: w.id,
|
|
3135
|
+
label: w.name,
|
|
3136
|
+
...w.slug && w.slug !== w.name && { hint: w.slug }
|
|
3137
|
+
}))
|
|
3138
|
+
});
|
|
3139
|
+
if (clack.isCancel(choice)) return null;
|
|
3140
|
+
return candidates.find((w) => w.id === choice) ?? null;
|
|
3141
|
+
}
|
|
3142
|
+
const workspacesCommand = defineCommand({
|
|
3143
|
+
meta: {
|
|
3144
|
+
name: "workspaces",
|
|
3145
|
+
description: "Show or change which of your workspaces this machine runs jobs in: `list` (the default), `add <name>`, `remove <name>`."
|
|
3146
|
+
},
|
|
3147
|
+
default: "list",
|
|
3148
|
+
subCommands: {
|
|
3149
|
+
list: listCommand,
|
|
3150
|
+
add: changeCommand("add"),
|
|
3151
|
+
remove: changeCommand("remove")
|
|
3152
|
+
}
|
|
3153
|
+
});
|
|
3154
|
+
/**
|
|
3155
|
+
* Why a machine has no workspaces, for `connect` and `whoami`: its owner has none yet (install
|
|
3156
|
+
* RelayRunner), or the machine just isn't in any of theirs (`relayrunner workspaces add`).
|
|
3157
|
+
*/
|
|
3158
|
+
async function emptyWorkspacesNotice(credentials) {
|
|
3159
|
+
const { server, machine } = credentials;
|
|
3160
|
+
const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3161
|
+
server,
|
|
3162
|
+
token
|
|
3163
|
+
}));
|
|
3164
|
+
if (result.status === "ok" && result.choice.others.length) return `${machine.name} isn't in any of your workspaces, so it takes no jobs. Add one with \`relayrunner workspaces add <name>\` (${workspaceNames(result.choice.others)}).`;
|
|
3165
|
+
return noWorkspaceYet(machine.name, server);
|
|
3166
|
+
}
|
|
2414
3167
|
// cli.ts
|
|
2415
3168
|
const DEFAULT_SERVER = "https://app.relayrunner.app";
|
|
2416
3169
|
const connectCommand = defineCommand({
|
|
@@ -2433,14 +3186,42 @@ const connectCommand = defineCommand({
|
|
|
2433
3186
|
},
|
|
2434
3187
|
concurrency: {
|
|
2435
3188
|
type: "string",
|
|
2436
|
-
description: "How many jobs to run at once (default: 2 with 8 or more CPU cores, otherwise 1)"
|
|
3189
|
+
description: "How many jobs to run at once (default: 2 with 8 or more CPU cores, otherwise 1; with --cpus or --memory, as many as fit)"
|
|
3190
|
+
},
|
|
3191
|
+
isolated: {
|
|
3192
|
+
type: "boolean",
|
|
3193
|
+
description: "Run each job in its own Linux VM, away from your files. The default on a Mac with Apple silicon and Apple's container tool.",
|
|
3194
|
+
negativeDescription: "Run jobs on this machine itself, where they can read your files."
|
|
3195
|
+
},
|
|
3196
|
+
macos: {
|
|
3197
|
+
type: "boolean",
|
|
3198
|
+
description: "Also take macOS jobs, which run on this Mac itself. Linux jobs still run in a VM."
|
|
3199
|
+
},
|
|
3200
|
+
cpus: {
|
|
3201
|
+
type: "string",
|
|
3202
|
+
description: "CPUs for each job's VM (default: an even share of this Mac's cores)"
|
|
3203
|
+
},
|
|
3204
|
+
memory: {
|
|
3205
|
+
type: "string",
|
|
3206
|
+
description: "Memory for each job's VM, in GB (default: an even share of half this Mac's)"
|
|
3207
|
+
},
|
|
3208
|
+
image: {
|
|
3209
|
+
type: "string",
|
|
3210
|
+
description: "Your own runner image for the VMs (default: GitHub's, with everyday tools)"
|
|
3211
|
+
},
|
|
3212
|
+
"local-network": {
|
|
3213
|
+
type: "boolean",
|
|
3214
|
+
description: "Let jobs in VMs reach this Mac and your local network. They can't by default."
|
|
2437
3215
|
}
|
|
2438
3216
|
},
|
|
2439
3217
|
async run({ args }) {
|
|
2440
3218
|
clack.intro("RelayRunner");
|
|
2441
3219
|
let concurrency;
|
|
3220
|
+
let size;
|
|
2442
3221
|
try {
|
|
2443
|
-
|
|
3222
|
+
size = parseVmSize(args.cpus, args.memory);
|
|
3223
|
+
concurrency = args.concurrency ? parseConcurrency(args.concurrency) : slotsFor(size) ?? parseConcurrency(void 0);
|
|
3224
|
+
checkFits(size, concurrency);
|
|
2444
3225
|
} catch (error) {
|
|
2445
3226
|
clack.log.error(error.message);
|
|
2446
3227
|
process.exitCode = 1;
|
|
@@ -2449,7 +3230,8 @@ const connectCommand = defineCommand({
|
|
|
2449
3230
|
try {
|
|
2450
3231
|
await connectMachine({
|
|
2451
3232
|
...args,
|
|
2452
|
-
concurrency
|
|
3233
|
+
concurrency,
|
|
3234
|
+
size
|
|
2453
3235
|
});
|
|
2454
3236
|
} catch (error) {
|
|
2455
3237
|
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
@@ -2460,7 +3242,26 @@ const connectCommand = defineCommand({
|
|
|
2460
3242
|
});
|
|
2461
3243
|
async function connectMachine(args) {
|
|
2462
3244
|
const share = shareArg(args.share);
|
|
2463
|
-
const
|
|
3245
|
+
const vmFlag = [
|
|
3246
|
+
"macos",
|
|
3247
|
+
"image",
|
|
3248
|
+
"local-network"
|
|
3249
|
+
].find((flag) => args[flag]) ?? (args.size.cpus !== void 0 ? "cpus" : args.size.memoryGb !== void 0 ? "memory" : null);
|
|
3250
|
+
if (args.isolated === false && vmFlag) throw new RunnerError("USAGE", `--${vmFlag} doesn't go with --no-isolated.`);
|
|
3251
|
+
const host = machinePlatform();
|
|
3252
|
+
const asked = args.isolated === true || Boolean(vmFlag);
|
|
3253
|
+
const unsupported = asked ? unsupportedReason() : null;
|
|
3254
|
+
if (unsupported) throw new RunnerError("ISOLATED_UNSUPPORTED", unsupported);
|
|
3255
|
+
const state = asked || args.isolated === false ? null : await isolationState();
|
|
3256
|
+
const isolated = asked || state === "ready";
|
|
3257
|
+
const vm = {
|
|
3258
|
+
os: "linux",
|
|
3259
|
+
arch: host.arch
|
|
3260
|
+
};
|
|
3261
|
+
const platform = !isolated ? host : args.macos ? {
|
|
3262
|
+
...host,
|
|
3263
|
+
isolated: vm
|
|
3264
|
+
} : vm;
|
|
2464
3265
|
let credentials = readCredentials();
|
|
2465
3266
|
const server = serverFor(args.server, credentials);
|
|
2466
3267
|
if (credentials && credentials.server !== server) {
|
|
@@ -2482,9 +3283,42 @@ async function connectMachine(args) {
|
|
|
2482
3283
|
updateTimer = setInterval(notifyUpdate, CHECK_INTERVAL_MS);
|
|
2483
3284
|
updateTimer.unref();
|
|
2484
3285
|
}
|
|
2485
|
-
const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
|
|
2486
3286
|
const slots = args.concurrency;
|
|
2487
|
-
const
|
|
3287
|
+
const log = (line) => clack.log.info(line);
|
|
3288
|
+
const onHost = !isolated || args.macos ? ensureRunner({ log }) : void 0;
|
|
3289
|
+
onHost?.catch(() => {});
|
|
3290
|
+
let runnerVersion = "";
|
|
3291
|
+
let launchers = [];
|
|
3292
|
+
let vmLauncher;
|
|
3293
|
+
let isolatedOnly;
|
|
3294
|
+
if (isolated) {
|
|
3295
|
+
const firewall = firewallInstalled();
|
|
3296
|
+
if (firewall) log(args["local-network"] ? "The firewall on this Mac is on, so --local-network has no effect. Turn it off with `relayrunner firewall off`." : "The firewall on this Mac is on.");
|
|
3297
|
+
const isolation = await prepareIsolation({
|
|
3298
|
+
slots,
|
|
3299
|
+
size: args.size,
|
|
3300
|
+
image: args.image,
|
|
3301
|
+
localNetwork: args["local-network"] && !firewall,
|
|
3302
|
+
log,
|
|
3303
|
+
debug: debugLog()
|
|
3304
|
+
});
|
|
3305
|
+
runnerVersion = isolation.runnerVersion;
|
|
3306
|
+
const launcher = isolatedLauncher(isolation);
|
|
3307
|
+
if (args.macos) vmLauncher = launcher;
|
|
3308
|
+
else {
|
|
3309
|
+
launchers = Array.from({ length: slots }, () => isolatedOnly = launcher);
|
|
3310
|
+
log("Jobs run in a Linux VM on this Mac. To take macOS jobs too, run `relayrunner connect --macos`.");
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
if (onHost) {
|
|
3314
|
+
const runner = await onHost;
|
|
3315
|
+
runnerVersion = runner.version;
|
|
3316
|
+
launchers = ensureSlots(runner, slots, log).map(hostLauncher);
|
|
3317
|
+
const hint = !isolated && state ? setupHint(state) : null;
|
|
3318
|
+
if (hint) clack.log.warn(hint);
|
|
3319
|
+
if (args.macos) clack.log.warn("Linux jobs run in a VM. macOS jobs run on this Mac itself, where they can read your files. Only take macOS jobs from repos you trust.");
|
|
3320
|
+
else if (args.isolated === false) clack.log.warn("Jobs run on this machine itself, where they can read your files. Only take jobs from repos you trust.");
|
|
3321
|
+
}
|
|
2488
3322
|
clack.log.info(slots === 1 ? "Running 1 job at a time. Change with --concurrency." : `Running up to ${slots} jobs at once. Change with --concurrency.`);
|
|
2489
3323
|
const device = await detectDevice();
|
|
2490
3324
|
const stop = new AbortController();
|
|
@@ -2517,16 +3351,26 @@ async function connectMachine(args) {
|
|
|
2517
3351
|
hello: {
|
|
2518
3352
|
machineId: credentials.machine.id,
|
|
2519
3353
|
...platform,
|
|
2520
|
-
runnerVersion
|
|
3354
|
+
runnerVersion,
|
|
2521
3355
|
cliVersion,
|
|
2522
3356
|
device
|
|
2523
3357
|
},
|
|
2524
3358
|
slots,
|
|
2525
3359
|
runJob: async (run, slot, report) => {
|
|
2526
3360
|
const prefixed = slots > 1 ? prefixLines(`[slot ${slot}] `, (chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk)) : void 0;
|
|
3361
|
+
const launcher = run.isolated ? vmLauncher ?? isolatedOnly : launchers[slot - 1];
|
|
3362
|
+
if (!launcher) {
|
|
3363
|
+
const update = {
|
|
3364
|
+
routeId: run.routeId,
|
|
3365
|
+
state: "failed",
|
|
3366
|
+
message: "The job was sent for a VM, and this machine isn't running jobs in one."
|
|
3367
|
+
};
|
|
3368
|
+
report(update);
|
|
3369
|
+
return update;
|
|
3370
|
+
}
|
|
2527
3371
|
try {
|
|
2528
3372
|
return await runJob(run, {
|
|
2529
|
-
|
|
3373
|
+
launcher,
|
|
2530
3374
|
report,
|
|
2531
3375
|
output: prefixed?.output,
|
|
2532
3376
|
onChecked: (target) => {
|
|
@@ -2615,7 +3459,7 @@ async function applySharing(credentials, choice, workspaces) {
|
|
|
2615
3459
|
const loginCommand = defineCommand({
|
|
2616
3460
|
meta: {
|
|
2617
3461
|
name: "login",
|
|
2618
|
-
description: "Sign this machine in without putting it online.
|
|
3462
|
+
description: "Sign this machine in without putting it online. You pick its workspaces when you approve it. Run `relayrunner connect` afterwards to take jobs."
|
|
2619
3463
|
},
|
|
2620
3464
|
args: {
|
|
2621
3465
|
server: {
|
|
@@ -2680,9 +3524,9 @@ function machinePlatform() {
|
|
|
2680
3524
|
async function enroll(server, name, platform, share) {
|
|
2681
3525
|
const { credentials, workspaces } = await signIn(server, name || await defaultMachineName(), platform);
|
|
2682
3526
|
writeCredentials(credentials);
|
|
2683
|
-
|
|
2684
|
-
clack.log.
|
|
2685
|
-
|
|
3527
|
+
clack.log.success(`Enrolled as ${credentials.machine.name}. Token saved to ${credentialsPath()}.`);
|
|
3528
|
+
if (workspaces.length) clack.log.info(`Runs jobs in ${workspaceNames(workspaces)}.\nChange with: relayrunner workspaces`);
|
|
3529
|
+
else clack.log.warn(await emptyWorkspacesNotice(credentials));
|
|
2686
3530
|
let choice = share;
|
|
2687
3531
|
if (!choice && hasTeammates(workspaces)) {
|
|
2688
3532
|
if (process.stdin.isTTY && process.stdout.isTTY) choice = await askSharing(workspaces);
|
|
@@ -2787,7 +3631,7 @@ const whoamiCommand = defineCommand({
|
|
|
2787
3631
|
}));
|
|
2788
3632
|
switch (result.status) {
|
|
2789
3633
|
case "ok":
|
|
2790
|
-
print(describeIdentity(credentials.server, result.identity), {
|
|
3634
|
+
print(describeIdentity(credentials.server, result.identity, !args.json && !readWorkspaces(result.identity).length ? await emptyWorkspacesNotice(credentials) : void 0), {
|
|
2791
3635
|
status: "ok",
|
|
2792
3636
|
server: credentials.server,
|
|
2793
3637
|
...result.identity
|
|
@@ -2808,19 +3652,20 @@ const whoamiCommand = defineCommand({
|
|
|
2808
3652
|
}
|
|
2809
3653
|
}
|
|
2810
3654
|
});
|
|
2811
|
-
function describeIdentity(server, identity) {
|
|
3655
|
+
function describeIdentity(server, identity, emptyNotice) {
|
|
2812
3656
|
const { machine, enrolledBy } = identity;
|
|
2813
3657
|
const workspaces = readWorkspaces(identity);
|
|
2814
3658
|
const status = (machine.status.online ? `online${machine.status.state ? `, ${machine.status.state}` : ""}` : "offline") + (machine.paused ? `, paused${machine.paused.by ? ` by ${machine.paused.by}` : ""}` : "");
|
|
2815
3659
|
const enrolled = [enrolledBy && `by ${enrolledBy.name} <${enrolledBy.email}>`, `on ${new Date(machine.createdAt).toLocaleDateString()}`].filter(Boolean).join(" ");
|
|
2816
|
-
|
|
2817
|
-
["Workspaces", workspaces.length ? workspaceNames(workspaces) : "none
|
|
3660
|
+
const details = table(`${machine.name} (${machine.id})`, [
|
|
3661
|
+
["Workspaces", workspaces.length ? workspaceNames(workspaces) : "none"],
|
|
2818
3662
|
["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
|
|
2819
3663
|
["Enrolled", enrolled],
|
|
2820
3664
|
["Status", status],
|
|
2821
3665
|
...machine.sharing ? [["Sharing", describeSharing(machine.sharing, sharingScope(workspaces))]] : [],
|
|
2822
3666
|
["Gateway", server]
|
|
2823
3667
|
]);
|
|
3668
|
+
return emptyNotice ? `${details}\n\n${emptyNotice}` : details;
|
|
2824
3669
|
}
|
|
2825
3670
|
function describeSaved(saved) {
|
|
2826
3671
|
return table(`${saved.machine.name} (${saved.machine.id})`, [["Gateway", saved.server]]);
|
|
@@ -2940,7 +3785,9 @@ const main = defineCommand({
|
|
|
2940
3785
|
init: initCommand,
|
|
2941
3786
|
pause: pauseCommand(true),
|
|
2942
3787
|
resume: pauseCommand(false),
|
|
2943
|
-
share: shareCommand
|
|
3788
|
+
share: shareCommand,
|
|
3789
|
+
workspaces: workspacesCommand,
|
|
3790
|
+
firewall: firewallCommand
|
|
2944
3791
|
}
|
|
2945
3792
|
});
|
|
2946
3793
|
runMain(main);
|