-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
1843 lines (1687 loc) · 76.1 KB
/
Copy pathindex.js
File metadata and controls
1843 lines (1687 loc) · 76.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as cache from '@actions/cache';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as https from 'https';
import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const backgroundPromises = [];
let activeBackgroundTasks = 0;
// Check if anyvm.py supports --cache-dir (>=0.1.4)
function isAnyvmCacheSupported(version) {
if (!version) return false;
const parts = version.split('.');
const major = parseInt(parts[0], 10) || 0;
const minor = parseInt(parts[1], 10) || 0;
// patch part may contain suffix, parseInt will ignore after first non-digit
const patch = parseInt((parts[2] || '0'), 10) || 0;
if (major > 0) return true;
if (major === 0 && minor > 1) return true;
if (major === 0 && minor === 1 && patch >= 4) return true;
return false;
}
// Check if anyvm.py supports the 'sys-nfs' sync method (>=0.4.9). Older
// versions don't know that argument, so we must keep using plain 'nfs'.
function isAnyvmSysNfsSupported(version) {
if (!version) return false;
const parts = version.split('.');
const major = parseInt(parts[0], 10) || 0;
const minor = parseInt(parts[1], 10) || 0;
const patch = parseInt((parts[2] || '0'), 10) || 0;
if (major > 0) return true;
if (major === 0 && minor > 4) return true;
if (major === 0 && minor === 4 && patch >= 9) return true;
return false;
}
// Helper to expand shell-style variables
function expandVars(str, env) {
if (!str) {
return str;
}
return str.replace(/\$\{([a-zA-Z0-9_]+)\}/g, (match, key) => {
return env[key] || match;
}).replace(/\$([a-zA-Z0-9_]+)/g, (match, key) => {
return env[key] || match;
});
}
// Parse shell-style config file
function parseConfig(filePath, initialEnv = {}) {
if (!fs.existsSync(filePath)) {
return initialEnv;
}
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n');
const env = { ...initialEnv };
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) {
continue;
}
// Simple shell variable assignment parsing: KEY="VALUE" or KEY=VALUE
const match = trimmed.match(/^([a-zA-Z0-9_]+)=(.*)$/);
if (match) {
const key = match[1];
let value = match[2];
// Remove wrapping quotes
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
// Expand variables based on current env
value = expandVars(value, env);
env[key] = value;
}
}
return env;
}
// The conf file of a non-x86_64 build is "<release>-<arch>.conf", so the arch
// suffixes have to be known to tell them apart from a release name that just
// carries a dash of its own: GhostBSD ships "26.1-xfce", Solaris "11.4-gcc-14",
// OmniOS "r151058-build". Keep in sync with ARCHES in
// .github/tpl/generate.tpl.yml, the arch matrix in .github/tpl/test.tpl.yml,
// and the two arch regexes in bump.py.
const CONF_ARCHES = [
"aarch64", "riscv64", "powerpc64", "sparc64", "ppc64le", "s390x", "i386", "loongarch64"
];
// Split one release component into the pieces a human compares: runs of digits
// and runs of everything else, so "10" sorts after "9" and "-SP5" after "-SP4".
function releaseChunks(part) {
return part.match(/\d+|\D+/g) || [];
}
// Compare a single dot separated component of two release names.
function compareReleaseParts(a, b) {
const ca = releaseChunks(a);
const cb = releaseChunks(b);
const n = Math.min(ca.length, cb.length);
for (let i = 0; i < n; i++) {
const x = ca[i];
const y = cb[i];
if (/^\d+$/.test(x) && /^\d+$/.test(y)) {
const nx = parseInt(x, 10);
const ny = parseInt(y, 10);
if (nx !== ny) return nx < ny ? -1 : 1;
} else if (x.toLowerCase() !== y.toLowerCase()) {
return x.toLowerCase() < y.toLowerCase() ? -1 : 1;
}
}
// Equal so far: the one WITHOUT the extra pieces wins. A trailing suffix is a
// flavor, not a newer version -- "26.1" is the plain GhostBSD release and
// "26.1-xfce" a variant of it, so "release: 26" has to pick "26.1".
if (ca.length !== cb.length) return ca.length < cb.length ? 1 : -1;
return 0;
}
// Compare two release names, oldest first. A release name is not always a
// number: openEuler ships "24.03-LTS-SP4", Haiku "r1beta5", Tribblix "0m40".
function compareReleaseNames(a, b) {
const pa = a.split('.');
const pb = b.split('.');
const n = Math.min(pa.length, pb.length);
for (let i = 0; i < n; i++) {
const c = compareReleaseParts(pa[i], pb[i]);
if (c !== 0) return c;
}
// More components = more specific = newer ("6.4.2" after "6.4").
if (pa.length !== pb.length) return pa.length < pb.length ? -1 : 1;
return 0;
}
// Every release this repo ships a conf for, for one arch, oldest first.
// Each entry is { release, confName }: for x86_64 they are the same, for any
// other arch confName is "<release>-<arch>".
function listConfReleases(confDir, arch) {
const archSuffix = arch ? `-${arch.toLowerCase()}` : '';
const found = [];
for (const file of fs.readdirSync(confDir)) {
if (!file.endsWith('.conf')) continue;
const name = file.slice(0, -'.conf'.length);
if (name === 'default.release') continue;
const lower = name.toLowerCase();
if (arch) {
if (!lower.endsWith(archSuffix)) continue;
found.push({ release: name.slice(0, -archSuffix.length), confName: name });
} else {
// conf/<release>.conf is the x86_64 one, so every other arch is out.
if (CONF_ARCHES.some((a) => lower.endsWith(`-${a}`))) continue;
found.push({ release: name, confName: name });
}
}
return found
.filter((r) => r.release)
.sort((x, y) => compareReleaseNames(x.release, y.release));
}
// Resolve a partial release -- "14" -> the newest 14.x, "14.3" -> the newest
// 14.3.x -- to the release it stands for. The number of components is not
// fixed ("6.4.2", "14.3", "24.03-LTS-SP4"), but all releases of one VM have the
// same shape, so a shorter input can only be a leading part of a full name.
// Every component given must match in full: "14" picks 14.4 but never 140.x,
// and "13.4" never falls through to 13.5. Returns null when nothing matches.
function resolveReleasePrefix(confDir, prefix, arch) {
const wanted = prefix.toLowerCase().split('.');
let best = null;
for (const item of listConfReleases(confDir, arch)) {
const parts = item.release.split('.');
if (parts.length < wanted.length) continue;
if (wanted.some((w, i) => parts[i].toLowerCase() !== w)) continue;
if (!best || compareReleaseNames(best.release, item.release) < 0) {
best = item;
}
}
return best;
}
function downloadFileOnce(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
let settled = false;
const fail = (err) => {
if (settled) return;
settled = true;
file.destroy();
fs.unlink(dest, () => { });
reject(err);
};
const handleResponse = (response) => {
if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 307 || response.statusCode === 308) {
if (response.headers.location) {
core.info(`Redirecting to ${response.headers.location}`);
https.get(response.headers.location, handleResponse).on('error', fail);
return;
}
}
if (response.statusCode !== 200) {
fail(new Error(`Failed to download ${url}: Status Code ${response.statusCode}`));
return;
}
// A socket reset mid-body errors on the response stream, not the
// request; without this the file never 'finish'es and we hang forever.
response.on('error', fail);
response.pipe(file);
};
https.get(url, handleResponse).on('error', fail);
file.on('finish', () => {
if (settled) return;
settled = true;
file.close(() => resolve());
});
file.on('error', fail);
});
}
// Transient network errors (e.g. `read ECONNRESET` from raw.githubusercontent.com,
// which killed freebsd-vm run 29292440869) should not fail the whole job:
// retry a few times with a short growing backoff before giving up.
async function downloadFile(url, dest, retries = 4) {
core.info(`Downloading ${url} to ${dest}`);
let lastErr;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
await downloadFileOnce(url, dest);
return;
} catch (err) {
lastErr = err;
if (attempt < retries) {
const delayMs = 3000 * (attempt + 1);
core.warning(`Download failed: ${err.message}, retrying in ${delayMs / 1000}s (${attempt + 1}/${retries})...`);
await new Promise((r) => setTimeout(r, delayMs));
}
}
}
throw lastErr;
}
// Run `ssh ... sh` once, piping `input` to its stdin. Returns the exit code.
// If timeoutMs > 0 and the ssh process has not exited by then, it is killed
// (SIGTERM, then SIGKILL after a short grace) and the promise rejects with a
// timeout error. We spawn directly instead of using exec.exec() because
// @actions/exec 1.1.1 silently ignores the AbortSignal option, so it cannot
// interrupt a wedged ssh session (observed: Haiku ssh occasionally prints its
// output but never tears down the channel, hanging the job for the GHA 6h max;
// see haiku-vm run 71585652274).
function runSSHOnce(args, sshHost, input, silent, timeoutMs) {
return new Promise((resolve, reject) => {
const child = spawn("ssh", [...args, sshHost, "sh"], { stdio: ["pipe", "pipe", "pipe"] });
let settled = false;
let timedOut = false;
let overallTimer = null;
let killTimer = null;
const cleanup = () => {
if (overallTimer) clearTimeout(overallTimer);
if (killTimer) clearTimeout(killTimer);
};
if (timeoutMs > 0) {
overallTimer = setTimeout(() => {
timedOut = true;
try { child.kill("SIGTERM"); } catch (e) { /* already gone */ }
// Escalate if ssh does not die promptly.
killTimer = setTimeout(() => { try { child.kill("SIGKILL"); } catch (e) { /* already gone */ } }, 5000);
}, timeoutMs);
}
child.stdout.on("data", (d) => { if (!silent) process.stdout.write(d); });
child.stderr.on("data", (d) => { if (!silent) process.stderr.write(d); });
child.on("error", (err) => {
if (settled) return;
settled = true;
cleanup();
reject(err);
});
child.on("close", (code) => {
if (settled) return;
settled = true;
cleanup();
if (timedOut) {
reject(new Error(`ssh timed out after ${timeoutMs}ms`));
} else {
resolve(code == null ? 1 : code);
}
});
// Feed the command script to ssh stdin and close it so the remote sh sees EOF.
child.stdin.on("error", () => { /* ignore EPIPE if ssh already exited */ });
child.stdin.write(input);
child.stdin.end();
});
}
async function execSSH(cmd, sshConfig, ignoreReturn = false, silent = false, options = {}) {
core.info(`Exec SSH: ${cmd}`);
const sshHost = sshConfig.host;
const osName = sshConfig.osName;
const work = sshConfig.work;
const vmwork = sshConfig.vmwork;
// timeoutMs: kill the ssh child if it has not finished after this many ms (0 = no timeout).
// retries: number of additional attempts on timeout / failure (0 = no retry).
// Use these only for internal/idempotent commands -- user-supplied run/prepare scripts
// can legitimately run for hours, so leave them at the defaults (unbounded, no retry).
const timeoutMs = options.timeoutMs || 0;
const retries = Math.max(0, options.retries || 0);
// Standard options for CI/CD
const args = [
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
];
let envExports = "";
if ((osName === 'haiku' || osName === 'blissos') && work && vmwork) {
const workRegex = new RegExp(work.replace(/\\/g, '\\\\'), 'gi');
const envNames = (sshConfig.envs || '').split(/\s+/).filter(Boolean);
for (const key of Object.keys(process.env)) {
if (key.startsWith('GITHUB_') || key === 'CI' || envNames.includes(key)) {
const val = process.env[key] || "";
const newVal = val.replace(workRegex, vmwork).replace(/'/g, "'\\''");
envExports += `export ${key}='${newVal}'\n`;
}
}
}
// Pipe prefix exports + command to sh stdin
const fullCmd = "set -eu\n" + envExports + cmd;
const input = Buffer.from(fullCmd);
let lastErr;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const code = await runSSHOnce(args, sshHost, input, silent, timeoutMs);
if (code === 0) {
return;
}
lastErr = new Error(`ssh exited with code ${code}`);
} catch (err) {
lastErr = err;
}
if (attempt < retries) {
core.warning(`SSH ${lastErr && lastErr.message}, retrying (${attempt + 1}/${retries})...`);
}
}
if (!ignoreReturn) {
throw lastErr;
}
}
// Value for rsync's --rsync-path on the remote.
// We wrap with `sh -c '...'` so the remote login shell (which may be csh on
// FreeBSD/DragonFly root) only sees `sh -c <script> rsync ...` and just exec's
// sh -- the script itself is interpreted by sh (POSIX), so we can safely use
// `PATH=$PATH:... rsync` syntax and let $PATH expand at remote runtime.
// The appended dirs cover BSD pkg (/usr/local/{bin,sbin}), NetBSD pkgsrc
// (/usr/pkg/{bin,sbin}) and Tribblix/MacPorts (/opt/local/{bin,sbin}).
const REMOTE_RSYNC_PATH = `sh -c 'PATH=$PATH:/usr/local/bin:/usr/local/sbin:/usr/pkg/bin:/usr/pkg/sbin:/opt/local/bin:/opt/local/sbin exec rsync "$@"' rsync`;
// Fixed host-side forward of a telnet guest's control channel (guest port
// 23). The telnet guests (ReactOS, Redox, RISC OS) have no sshd; anyvm
// drives them over a baked-in telnet agent, and this action reaches a
// running VM through `anyvm.py --attach --ssh-port <port>`. Runners are
// single-job, so a fixed port cannot collide.
const TELNET_CTRL_PORT = 10023;
// Pinned host port for a 9P guest's file channel (Plan 9). Same reason as
// the control port above: the copyback runs in a SEPARATE anyvm process
// (`--attach --pull-files`) which cannot discover a randomly chosen forward.
const P9_PORT = 20564;
// Run one command in a telnet-transport guest through `anyvm.py --attach`.
// The attach exec is marker-based: it waits until the command actually
// finishes (no fixed read window) and exits with the command's 0/1 status
// where the guest shell can express one; the RISC OS agent has no status
// channel, so there completion always reports 0.
async function execTelnet(cmd, osName, anyvmPath, ignoreReturn = false) {
core.info(`Exec (telnet): ${cmd}`);
const rc = await exec.exec("python3", [
anyvmPath, "--os", osName, "--attach",
"--ssh-port", String(TELNET_CTRL_PORT), "--", cmd,
], { ignoreReturnCode: true });
if (rc !== 0 && !ignoreReturn) {
throw new Error(`Guest command failed with exit code ${rc}`);
}
return rc;
}
// A multi-line prepare/run script on a telnet guest. cmd.exe (ReactOS) and
// ion (Redox) chain lines with && inside ONE session, which gives the same
// stop-on-first-failure semantics the ssh guests get from `sh -e`-style
// scripts. The RISC OS agent has no operators, so each line goes as its own
// command (its agent gives every line a fresh CLI anyway).
async function execTelnetScript(script, osName, anyvmPath) {
const lines = script.split('\n').map((l) => l.trim()).filter(Boolean);
if (!lines.length) {
return;
}
if (osName === 'riscos') {
for (const line of lines) {
await execTelnet(line, osName, anyvmPath);
}
} else {
await execTelnet(lines.join(' && '), osName, anyvmPath);
}
}
// In-guest poweroff commands used by cache-after-prepare to shut the VM down
// cleanly before caching the prepared qcow2. Values copied from each
// anyvm-org/<os>-builder conf's VM_SHUTDOWN_CMD (the builders run the same
// command to shut down every image build). A VM_SHUTDOWN_CMD baked into the
// release conf takes precedence over this fallback table.
const SHUTDOWN_CMDS = {
freebsd: "/sbin/shutdown -p now",
ghostbsd: "/sbin/shutdown -p now",
midnightbsd: "/sbin/shutdown -p now",
dragonflybsd: "/sbin/shutdown -p now",
netbsd: "/sbin/shutdown -p now",
openbsd: "/sbin/shutdown -p now",
solaris: "shutdown -y -i5 -g0",
omnios: "shutdown -y -i5 -g0",
openindiana: "shutdown -y -i5 -g0",
tribblix: "/usr/sbin/poweroff",
haiku: "shutdown -q",
blissos: "reboot -p",
ubuntu: "shutdown -h now",
};
// On GitHub's x86_64 runners only an x86_64/amd64 guest gets KVM acceleration;
// every other guest arch runs under full TCG emulation and is dramatically
// slower (sparc64, riscv64, powerpc64, s390x, aarch64-on-x64, ...). Writing a
// large source tree (e.g. a big node_modules) into such a VM can stall long
// enough that ssh's keepalive declares the server dead mid-transfer
// ("Timeout, server 127.0.0.1 not responding"), killing rsync with a broken
// pipe (exit 255). `arch` is already normalized here: '' means x86_64/amd64.
function isSlowEmulatedArch(arch) {
return !!arch && arch !== 'x86_64' && arch !== 'amd64';
}
// AlmaLinux 10 and Rocky 10 ship rsync 3.4.4, and its ppc64le build hands
// utimensat a struct timespec with one field left uninitialized. strace on the
// receiver shows either a stack address duplicated into both members
// ({tv_sec=140736855219272, tv_nsec=140736855219272}) or a garbage pair
// ({tv_sec=-1167088121787636991, tv_nsec=1167088121787636990}); tv_nsec is then
// far outside 0..999999999, the kernel returns EINVAL, and rsync exits 23. It
// hits a different ~0.05% of files every run because it depends on what the
// stack happened to hold, and it takes the customshell job down with it, since
// that defaults to rsync.
//
// Only the timestamp call fails -- file CONTENT always transfers correctly
// (verified: 5000/5000 identical by sha256 with -t dropped). So skip -t rather
// than give up rsync on the arch; the trees CI syncs come from actions/checkout,
// where every mtime is already just "checkout time".
//
// Not a kernel, XFS or emulation fault: an in-guest utimensat probe on the same
// image accepts 5000/5000 timestamps including every nsec edge value, and the
// identical push to almalinux x86_64 -- same rsync build, same XFS -- is clean.
// Debian ppc64le is clean too, so it is this rsync build, not the architecture.
function rsyncOmitsTimes(osName, arch) {
return arch === 'ppc64le' && (osName === 'almalinux' || osName === 'rocky');
}
// ssh transport handed to rsync for slow emulated guests: stay connected
// through long stalls instead of giving up after the default keepalive window.
// 30s interval x 60 unanswered probes = ~30 min of grace before disconnecting.
const RSYNC_SSH_SLOW = "ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=60 -o ConnectTimeout=120";
// rsync's own I/O timeout (seconds) for slow guests: a defined upper bound
// matching the ssh grace above, so a genuinely wedged sync still fails while a
// slow-but-progressing one is not aborted. Fast (KVM) arches keep rsync's
// default of no --timeout.
const RSYNC_SLOW_TIMEOUT = "1800";
async function handleErrorWithDebug(sshHost, vncLink, debug) {
const message = vncLink
? `Please open the remote vnc link for debugging: ${vncLink} . To finish debugging, you can run \`touch ~/continue\` in the VM. In the VM, you can use \`ssh host\` to access the host.`
: "Please open the remote vnc link for debugging. To finish debugging, you can run `touch ~/continue` in the VM. In the VM, you can use `ssh host` to access the host.";
core.warning(message);
const args = [
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "ConnectTimeout=3",
sshHost
];
core.info("Monitoring ~/continue file in the VM...");
const continueFile = "~/continue";
let finished = false;
let counter = 0;
while (!finished) {
counter++;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 3000);
try {
if (debug === 'true') {
core.info(`[Debug] Checking for ${continueFile} in VM (Attempt ${counter})...`);
}
const exitCode = await exec.exec("ssh", [...args, `test -f ${continueFile}`], {
silent: true,
ignoreReturnCode: true,
signal: controller.signal
});
if (debug === 'true') {
core.info(`[Debug] SSH exit code: ${exitCode}`);
}
if (exitCode === 0) {
core.info(`${continueFile} found. Cleaning up and continuing...`);
await exec.exec("ssh", [...args, `rm -f ${continueFile}`], { silent: true });
finished = true;
} else if (exitCode === 1) {
// File not found, but SSH is fine. Just wait and retry.
await new Promise(r => setTimeout(r, 5000));
} else {
// Any other exit code (like 255) usually means SSH connection failed
if (debug === 'true') {
core.info(`[Debug] SSH failed with exit code ${exitCode}. Assuming VM exited.`);
}
throw new Error("The VM has exited (SSH connection failed), so the debugging process is terminating.");
}
} catch (e) {
if (debug === 'true') {
core.info(`[Debug] SSH check threw error: ${e.message}`);
}
throw new Error("The VM has exited, so the debugging process is terminating.");
} finally {
clearTimeout(timer);
}
}
}
async function install(arch, sync, builderVersion, debug, disableCache) {
const start = Date.now();
core.info("Installing dependencies...");
if (process.platform === 'linux') {
const pkgs = [
"qemu-utils"
];
if (!arch || arch === 'x86_64' || arch === 'amd64' || arch === 'i386') {
// qemu-system-x86 ships BOTH qemu-system-x86_64 and qemu-system-i386
// on Debian/Ubuntu (i386 is the GNU Hurd 2025-i386 guest).
pkgs.push("qemu-system-x86", "ovmf");
} else if (arch === 'aarch64' || arch === 'arm64') {
pkgs.push("qemu-system-arm", "qemu-efi-aarch64", "ipxe-qemu");
} else {
// qemu-system-misc covers riscv64 (and the other "misc" targets), but
// ppc64 / sparc64 / s390x ship in their own packages on Ubuntu. These
// only *recommend* seabios (which --no-install-recommends skips), unlike
// qemu-system-x86 which depends on it; install it explicitly so the VGA
// romfiles (e.g. vgabios-stdvga.bin, used by the pseries default display)
// are present.
pkgs.push("qemu-system-misc", "u-boot-qemu", "ipxe-qemu", "seabios");
if (arch === 'powerpc64' || arch === 'ppc64' || arch === 'ppc64le') {
pkgs.push("qemu-system-ppc");
} else if (arch === 'sparc64' || arch === 'sparc') {
pkgs.push("qemu-system-sparc");
} else if (arch === 's390x') {
pkgs.push("qemu-system-s390x");
}
}
if (sync === 'nfs') {
pkgs.push("nfs-kernel-server");
}
if (sync === 'rsync') {
let rsyncRequired = true;
if (builderVersion) {
const parts = builderVersion.split('.');
const major = parseInt(parts[0], 10) || 0;
if (major >= 2) {
rsyncRequired = false;
}
}
if (rsyncRequired) {
pkgs.push("rsync");
}
}
const aptOpts = [
"-o", "Acquire::Retries=3",
"-o", "Dpkg::Options::=--force-confdef",
"-o", "Dpkg::Options::=--force-confold",
"-o", "Dpkg::Options::=--force-unsafe-io",
"-o", "Acquire::Languages=none",
];
// 1. Drop apt's needrestart hook. After every install it scans the running
// processes to report which services want restarting -- measured 3-4.7s on
// a runner that gets destroyed minutes later. The hook is a single
// DPkg::Post-Invoke line in this one file, so removing the file is enough.
// (No point touching man-db: the runner image already ships
// man-db/auto-update false, so that trigger is a no-op before we start.)
await exec.exec("sudo", ["rm", "-f", "/etc/apt/apt.conf.d/99needrestart"],
{ silent: true, ignoreReturnCode: true });
// 2. Restore the .deb files from a previous run into apt's archive cache,
// so step 3 installs from disk instead of pulling them off the Ubuntu
// mirror -- the least reliable link in the job (measured: a median 378
// kB/s for a whole hour on freebsd-vm run 32207630189 attempt 1, worst 14
// kB/s, one job stuck in apt for 56 minutes).
//
// The key carries ImageVersion, so a weekly runner-image rebuild starts a
// fresh entry rather than serving .debs that no longer match the
// preinstalled index step 3 resolves against. Even when it does go stale,
// apt only reuses a cached .deb whose hash matches the index, so the worst
// case is a partial download, never a wrong install.
const aptCacheDir = path.join(os.homedir(), ".apt-cache");
const imageTag = `${process.env.ImageOS || 'linux'}-${process.env.ImageVersion || os.release()}`;
const pkgsHash = crypto.createHash('md5').update(pkgs.slice().sort().join(',')).digest('hex');
const aptCacheKey = `apt-pkgs-${process.platform}-${process.arch}-${imageTag}-${pkgsHash}`;
let aptRestoredKey = null;
if (!disableCache) {
try {
if (!fs.existsSync(aptCacheDir)) {
fs.mkdirSync(aptCacheDir, { recursive: true });
}
aptRestoredKey = await cache.restoreCache([aptCacheDir], aptCacheKey);
if (aptRestoredKey) {
core.info(`Restored apt packages from cache: ${aptRestoredKey}`);
await exec.exec("sudo", ["sh", "-c",
`cp -p ${aptCacheDir}/*.deb /var/cache/apt/archives/ 2>/dev/null || true`],
{ silent: true, ignoreReturnCode: true });
}
} catch (e) {
core.warning(`Apt cache restore failed: ${e.message}`);
}
}
// 3. Install the packages straight off the preinstalled apt index. The
// runner image keeps /var/lib/apt/lists (actions/runner-images cleanup.sh
// only runs 'apt-get clean'), so the index resolves without a refresh and
// the retry in step 4 stays unused.
//
// Measured across all 17 *-vm repos, each against its own pre-change run:
// install() went from a median 19.9s to 13.4s, improving in 16 of 17. The
// odd one out (freebsd-vm) hit an hour where the mirror itself was sick.
// An early worry that skipping the update caused intermittent mirror
// stalls did NOT survive that wider sample -- sub-1MB/s downloads ran
// 18/208 BEFORE the change and 9/208 after. The 375 clean pre-change
// samples that raised the worry were all from one repo.
const installArgs = ["apt-get", "install", "-y", "-q", ...aptOpts, "--no-install-recommends", ...pkgs];
const installRc = await exec.exec("sudo", installArgs, { ignoreReturnCode: true });
// 4. Fall back to a refreshed index and retry. Not silent, and not
// ignoreReturnCode: a failure here is a real failure.
if (installRc !== 0) {
core.info(`apt-get install failed against the preinstalled index (exit ${installRc}); refreshing it and retrying.`);
await exec.exec("sudo", ["apt-get", "update", "-q"], { silent: true });
await exec.exec("sudo", installArgs);
}
// 5. Save the downloaded .debs for the next run. Only on a miss -- on a hit
// the entry already holds them and the key is immutable, so re-saving would
// just burn an upload and log an "already exists" warning. Runs in the
// background: the VM boot that follows does not depend on it.
if (!disableCache && !aptRestoredKey) {
const saveAptCache = async () => {
activeBackgroundTasks++;
try {
// apt-get leaves the .debs behind: Ubuntu's
// Keep-Downloaded-Packages "0" is scoped to binary::apt::, so it
// applies to `apt` but not to the `apt-get` above (verified both
// ways on 24.04).
if (!fs.existsSync(aptCacheDir)) {
fs.mkdirSync(aptCacheDir, { recursive: true });
}
await exec.exec("sh", ["-c",
`cp -p /var/cache/apt/archives/*.deb ${aptCacheDir}/ 2>/dev/null || true`],
{ silent: true, ignoreReturnCode: true });
if (fs.readdirSync(aptCacheDir).some(f => f.endsWith('.deb'))) {
await cache.saveCache([aptCacheDir], aptCacheKey);
core.info(`Saved apt packages to cache: ${aptCacheKey}`);
}
} catch (e) {
if (e.message && (e.message.includes('already exists') ||
e.message.includes('Cache already exists'))) {
core.info(`Apt cache save skipped (benign): ${e.message}`);
} else {
core.warning(`Apt cache save failed: ${e.message}`);
}
} finally {
activeBackgroundTasks--;
}
};
backgroundPromises.push(saveAptCache());
}
if (fs.existsSync('/dev/kvm')) {
await exec.exec("sudo", ["chmod", "666", "/dev/kvm"]);
}
} else if (process.platform === 'darwin') {
await exec.exec("brew", ["install", "qemu"]);
} else if (process.platform === 'win32') {
await exec.exec("choco", ["install", "qemu", "-y"]);
}
if (debug === 'true') {
const elapsed = Date.now() - start;
core.info(`install() took ${elapsed}ms`);
}
}
// Recursively check whether any file named `name` exists under `dir`.
// Used to decide between fast-path `scp -r` and slow-path file-by-file scp.
async function treeContainsFile(dir, name) {
let entries;
try {
entries = await fs.promises.readdir(dir, { withFileTypes: true });
} catch {
return false;
}
for (const entry of entries) {
if (entry.name === name) return true;
if (entry.isDirectory()) {
if (await treeContainsFile(path.join(dir, entry.name), name)) return true;
}
}
return false;
}
// Recursively scp `localPath` into `remoteDir` on `sshHost`, skipping any entry
// whose basename is in `excludeNames`. Preserves directory structure.
async function scpTreeExcluding(sshHost, localPath, remoteDir, excludeNames, debug, sshConfig) {
const name = path.basename(localPath);
if (excludeNames.includes(name)) return;
let stat;
try {
stat = await fs.promises.stat(localPath);
} catch {
return;
}
if (stat.isFile()) {
const scpArgs = [
"-O", "-p",
"-o", "StrictHostKeyChecking=no",
localPath,
`${sshHost}:${remoteDir}/`,
];
if (debug === 'true') {
core.info(`Uploading: ${localPath} to ${sshHost}:${remoteDir}/`);
}
await exec.exec("scp", scpArgs, { silent: debug !== 'true' });
return;
}
if (!stat.isDirectory()) return;
const remoteSubdir = `${remoteDir}/${name}`;
await execSSH(`mkdir -p '${remoteSubdir}'`, sshConfig, false, debug !== 'true');
const entries = await fs.promises.readdir(localPath, { withFileTypes: true });
for (const entry of entries) {
await scpTreeExcluding(sshHost, path.join(localPath, entry.name), remoteSubdir, excludeNames, debug, sshConfig);
}
}
async function scpToVM(sshHost, work, vmwork, osName, debug, disableCache) {
const sshConfig = { host: sshHost, osName, work, vmwork };
core.info(`==> Ensuring ${vmwork} exists...`);
await execSSH(`mkdir -p ${vmwork}`, sshConfig);
const excludeNote = disableCache ? "" : ", cache.tzst";
core.info(`==> Uploading files via scp (excluding _actions, _PipelineMapping${excludeNote})...`);
const items = await fs.promises.readdir(work, { withFileTypes: true });
for (const item of items) {
const itemName = item.name;
if (itemName === "_actions" || itemName === "_PipelineMapping") {
continue;
}
const localPath = path.join(work, itemName);
// `cache.tzst` is written by the background Save-Cache task and may vanish
// mid-transfer, which would fail `scp -r`. If the tree contains one, fall
// back to per-file scp that skips it. Skipped entirely when cache is disabled.
if (!disableCache && item.isDirectory() && await treeContainsFile(localPath, "cache.tzst")) {
await scpTreeExcluding(sshHost, localPath, vmwork, ["cache.tzst"], debug, sshConfig);
continue;
}
const scpArgs = [
"-O",
"-r",
"-p",
"-o", "StrictHostKeyChecking=no",
localPath,
`${sshHost}:${vmwork}/`
];
if (debug === 'true') {
core.info(`Uploading: ${localPath} to ${sshHost}:${vmwork}/`);
}
await exec.exec("scp", scpArgs, { silent: debug !== 'true' });
}
core.info("==> Done.");
}
async function main() {
try {
// 1. Inputs
const debug = core.getInput("debug");
// NOT lowercased: a release name can carry upper case (openEuler ships
// "24.03-LTS-SP4"), and it is used verbatim for the conf file name AND
// handed to anyvm.py, which builds the image asset URL from it. The conf
// lookup below still matches case-insensitively, so a user typing
// "24.03-lts-sp4" keeps working and gets the canonical spelling back.
const releaseInput = core.getInput("release");
const archInput = core.getInput("arch").toLowerCase();
const inputOsName = core.getInput("osname").toLowerCase();
const mem = core.getInput("mem");
const cpu = core.getInput("cpu");
const nat = core.getInput("nat");
const envs = core.getInput("envs");
const prepare = core.getInput("prepare");
const run = core.getInput("run");
// The effective default is resolved against the conf's VM_SYNC_METHODS
// once the config is loaded (see below); empty here means "use the conf
// default".
let sync = core.getInput("sync").toLowerCase();
const copyback = core.getInput("copyback").toLowerCase();
const syncTime = core.getInput("sync-time").toLowerCase();
const disableCache = core.getInput("disable-cache").toLowerCase() === 'true';
const cacheAfterPrepareInput = core.getInput("cache-after-prepare").toLowerCase() === 'true';
let debugOnError = core.getInput("debug-on-error").toLowerCase() === 'true';
const vncPassword = core.getInput("vnc-password");
const work = path.join(process.env["HOME"], "work");
let vmwork = path.join(process.env["HOME"], "work");
if (inputOsName === 'haiku') {
vmwork = `/boot/home/${os.userInfo().username}/work`;
} else if (inputOsName === 'blissos') {
// BlissOS (Android) logs in as root via dropbear with HOME=/data/dropbear.
// The system partition is read-only at runtime, so /data/dropbear is the
// only writable, persistent path; the runner's $HOME/work does not exist
// in the guest. (Same situation as Haiku: env paths are rewritten to this
// vmwork by the injection block in execSSH.)
vmwork = `/data/dropbear/work`;
}
// 2. Load Config
let env = {};
// Defaults
env = parseConfig(path.join(__dirname, 'conf/default.release.conf'), env);
let release = releaseInput || env['DEFAULT_RELEASE'];
let arch = archInput;
// Handle Arch logic
if (!arch) {
// x86_64 implicit -- unless the repo declares another default arch in
// conf/default.release.conf (ReactOS ships i386 only, RISC OS armv7
// only; neither has an x86_64 build at all).
arch = (env['DEFAULT_ARCH'] || '').toLowerCase();
} else if (arch === 'arm64') {
arch = 'aarch64';
} else if (arch === 'x86_64' || arch === 'amd64') {
arch = '';
}
// Load specific conf files
const confDir = path.join(__dirname, 'conf');
let confName = release;
if (arch) confName += `-${arch}`;
let confPath = path.join(confDir, `${confName}.conf`);
if (!fs.existsSync(confPath)) {
// Fall back to a case-insensitive match on the conf directory, then
// adopt the file's spelling as the canonical release: the conf name and
// the release passed to anyvm.py must match the builder's asset names
// exactly (e.g. "24.03-LTS-SP4"), whatever case the user typed.
const wanted = `${confName.toLowerCase()}.conf`;
const found = fs.readdirSync(confDir).find((f) => f.toLowerCase() === wanted);
if (found) {
confName = found.slice(0, -'.conf'.length);
release = arch ? confName.slice(0, -(arch.length + 1)) : confName;
confPath = path.join(confDir, found);
}
}
if (!fs.existsSync(confPath)) {
// Not a full release name: take it as the leading, dot separated part of
// one and run the newest release that starts with it, so "release: 14"
// follows 14.x and "release: 14.3" follows 14.3.x on their own.
const resolved = resolveReleasePrefix(confDir, release, arch);
if (resolved) {
core.info(`Release "${release}" resolved to "${resolved.release}"`);
release = resolved.release;
confName = resolved.confName;
confPath = path.join(confDir, `${confName}.conf`);
}
}
if (!fs.existsSync(confPath)) {
const available = listConfReleases(confDir, arch).map((r) => r.release);
throw new Error(
`Release "${release}" is not available` +
(arch ? ` for arch ${arch}` : '') +
` (config not found: ${confPath}).` +
(available.length ? ` Available releases: ${available.join(', ')}` : ''));
}
env = parseConfig(confPath, env);
const anyvmVersion = env['ANYVM_VERSION'];
const builderVersion = env['BUILDER_VERSION'];
const osName = inputOsName;
// VM_SYNC_METHODS is the builder's declared support list for this
// release/arch (comma separated, first = default), baked into the conf.
// When the conf doesn't declare it (e.g. an older builder version that
// predates this field), keep the legacy behavior: default to rsync and
// don't reject anything.
const syncMethods = (env['VM_SYNC_METHODS'] || '')
.split(',').map((m) => m.trim()).filter(Boolean);
if (!sync) {
sync = syncMethods[0] || 'rsync';
} else if (sync !== 'no' && syncMethods.length && !syncMethods.includes(sync)) {
// Only reject when the conf actually declares a list and this method is
// not in it. 'no' (do-not-sync) is always allowed.
throw new Error(
`sync method '${sync}' is not supported by ${osName} ${confName}. ` +
`Supported methods: ${syncMethods.join(', ')}`);
}
// Remote-exec transport, declared per release conf (VM_TRANSPORT=telnet).
// The telnet guests (ReactOS, Redox, RISC OS) ship no sshd at all: anyvm
// drives them over a baked-in telnet agent, and this action runs
// prepare/run/copyback through `anyvm.py --attach` instead of ssh.
const transport = (env['VM_TRANSPORT'] || 'ssh').toLowerCase();
const isTelnet = transport === 'telnet';
// Guest-side work dir. The ssh guests use $HOME/work (with the per-OS
// overrides above); a telnet guest has no $HOME contract, so its conf
// declares the path (ReactOS: C:\work, Redox / RISC OS: /work).
if (env['VM_WORKPATH']) {
vmwork = env['VM_WORKPATH'];
}
if (isTelnet && debugOnError) {
core.warning(`debug-on-error is not supported on ${osName} (telnet transport, no ssh); ignoring it.`);
debugOnError = false;
}
if (isTelnet && envs) {
core.warning(`envs is not supported on ${osName} (telnet transport, no ssh SendEnv); ignoring it.`);
}
core.startGroup("Configuration AnyVM.org");
core.info(`Using ANYVM_VERSION: ${anyvmVersion}`);
core.info(`Using BUILDER_VERSION: ${builderVersion}`);
core.info(`Target OS: ${osName}, Release: ${release}`);
// 3. Download anyvm.py
if (!anyvmVersion) {
throw new Error("ANYVM_VERSION not defined in config");
}
// Fetch the runtime as a release asset of the pinned version, the same
// matched-pair rule the VM images follow -- never a branch, never
// releases/latest.
const anyvmUrl = `https://github.com/anyvm-org/anyvm/releases/download/v${anyvmVersion}/anyvm.py`;
const anyvmPath = path.join(__dirname, 'anyvm.py');
// No raw-URL fallback on purpose: a pinned version whose release has no
// anyvm.py asset is a bad pin, and quietly pulling the tag's raw file
// would hide that behind a warning nobody reads. Fail with a message that
// says what to fix.
try {
await downloadFile(anyvmUrl, anyvmPath);
} catch (err) {
throw new Error(
`Could not download anyvm.py for v${anyvmVersion} (${err.message}). ` +
`Check that the anyvm release v${anyvmVersion} exists and has anyvm.py ` +
`attached as a release asset.`);