Repository navigation
Expand file tree
/
Copy pathrun
More file actions
executable file
·2146 lines (1939 loc) · 85.9 KB
/
Copy pathrun
File metadata and controls
executable file
·2146 lines (1939 loc) · 85.9 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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""
virtio-villain test runner.
Spawns one VM per test to isolate VMM crashes. Collects serial output
and exit codes, prints a summary.
"""
import argparse
from collections import Counter
from contextlib import ExitStack
import fnmatch
import json
import hashlib
import mmap
import os
import random
import re
import shlex
import signal
import stat
import subprocess
import sys
import fcntl
import shutil
import tempfile
import threading
import platform
import time
from concurrent.futures import ThreadPoolExecutor
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(_SCRIPT_DIR, "lib", "python"))
from villain import execution, images, process, reporting # noqa: E402
from villain.cli import ( # noqa: E402
ShortFirstHelpFormatter, print_banner, normalize_memory as _normalize_mem,
canonicalize_tests as _canonicalize_tests,
)
from villain.console import ( # noqa: E402
merge_streams as _merge_streams,
restore_terminal as _restore_term, save_terminal as _save_term,
drain_stream,
)
from villain.diagnostics import security_triage as _security_triage # noqa: E402
from villain.host import enable_sysconfigs # noqa: E402
from villain.process import ( # noqa: E402
install_termination_as_interrupt as _install_termination_as_interrupt,
kill_all_processes as _kill_all_live_procs, kill_process as _kill_proc,
)
from villain.vmm import ( # noqa: E402
DEFAULT_VMM_TRACE_FILE, CloudHypervisor, Qemu, QemuMicrovm,
detect_vmm, fetch_kernel,
)
sys.stdout.reconfigure(line_buffering=True)
_print_lock = threading.Lock()
INIT_BINARY = os.path.join(_SCRIPT_DIR, "target", "init")
INITRAMFS = os.path.join(_SCRIPT_DIR, "target", "initramfs.cpio.gz")
DISK_SIZE = 16 * 1024 * 1024 # 16 MiB
PMEM_SIZE = 128 * 1024 * 1024
DISK_FORMATS = images.FORMATS
def get_test_list(init_binary=INIT_BINARY):
"""Get available tests by running target/init --list-tsv on the host.
Returns (list of test IDs, dict mapping ID to (desc, ver, section),
dict mapping ID to {device_id, flags}).
The --list-tsv output is TAB separated:
name<TAB>desc<TAB>version<TAB>section[<TAB>device_id<TAB>flags]
"""
result = subprocess.run(
[init_binary, "--list-tsv"],
capture_output=True, text=True
)
if result.returncode != 0:
sys.exit(f"Failed to list tests: {result.stderr}")
tests = []
info = {}
meta = {}
for line in result.stdout.splitlines():
if not line:
continue
fields = line.split("\t")
if len(fields) < 4:
continue
tid, desc, ver, sec = fields[0], fields[1], fields[2], fields[3]
tests.append(tid)
info[tid] = (desc, ver, sec)
if len(fields) >= 6:
meta[tid] = {
"device_id": int(fields[4], 16),
"flags": int(fields[5]),
"required_features": int(fields[6], 16) if len(fields) >= 7 else 0,
"min_queues": int(fields[7]) if len(fields) >= 8 else 0,
}
return tests, info, meta
def _parse_result(output, returncode):
"""Parse VM output into a result status string.
The verdict line is `[TAG] <name>` printed by the guest harness,
but the VMM may interleave its own log lines into the same stdout
stream at any character boundary (CH writes its own warnings
inline). Strip those log lines first, then look for the tag.
"""
cleaned = _clean_result_output(output)
m = re.search(r"\[(XPASS|XFAIL|FAIL|REJECT|WEDGED|SKIP|PASS)\]", cleaned)
if m:
return m.group(1)
if returncode < 0:
return "FAIL"
if "[vv]" not in cleaned:
return "FAIL"
return "WEDGED"
def _parse_batch_results(output, test_names):
"""Parse VM output for multiple verdict lines.
Returns a dict mapping test name to (status, output). Tests not
found in the output are marked WEDGED (the VM died before
reaching them).
"""
cleaned = _clean_result_output(output)
results = {}
for name in test_names:
marker = re.search(
rf"\[(XPASS|XFAIL|FAIL|REJECT|WEDGED|SKIP|PASS)\]\s+"
rf"{re.escape(name)}(?![A-Za-z0-9_])",
cleaned)
results[name] = marker.group(1) if marker else "WEDGED"
return results
_VERDICT_MARKER_RE = re.compile(
r"\[(?:XPASS|XFAIL|FAIL|REJECT|WEDGED|SKIP|PASS)\]")
def _remove_spliced_log_lines(output, pattern):
"""Remove matching logs while retaining any verdict text inside them."""
def replace(match):
line = match.group(0)
marker = _VERDICT_MARKER_RE.search(line)
if not marker:
return ""
return line[marker.start():].rstrip("\n")
return re.sub(pattern, replace, output)
def _clean_result_output(output):
"""Remove host and guest log lines that can splice into verdict markers."""
output = _remove_spliced_log_lines(
output, r"cloud-hypervisor:[^\n]*(?:\n|$)")
return _remove_spliced_log_lines(
output, r"\[\s*\d+\.\d+\][^\n]*(?:\n|$)")
def _find_virtiofsd():
"""Locate a virtiofsd binary on the host. Returns path or None.
Checked locations in order. The first match wins.
"""
for cand in ("virtiofsd",
"/usr/libexec/virtiofsd",
"/usr/lib/virtiofsd",
"/usr/lib/qemu/virtiofsd"):
p = shutil.which(cand) if "/" not in cand else cand
if p and os.path.exists(p) and os.access(p, os.X_OK):
return p
return None
# Default timeout for VMM API control calls. Scaled at startup by the
# host oversubscription factor so sidecars do not flake with a hard
# 5s ceiling when ch-remote and the CH API thread are CPU starved.
_VM_API_TIMEOUT = 5.0
_SIDECAR_JOIN_TIMEOUT = 5.0
_PROBE_CACHE_DIR = f"/dev/shm/virtio-villain-probes-{os.getuid()}"
_PROBE_CACHE_SIZE = 65536
def _probe_cache_key(backend, kernel, initramfs, opts):
identities = []
for path in (backend.binary, kernel, initramfs, __file__):
path = os.path.realpath(path)
stat = os.stat(path)
identities.append((path, stat.st_dev, stat.st_ino, stat.st_size,
stat.st_mtime_ns, stat.st_ctime_ns))
with open("/proc/sys/kernel/random/boot_id") as stream:
boot_id = stream.read().strip()
data = (boot_id, platform.machine(), backend.name, identities, opts)
return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
def _probe_records(output):
records = []
cleaned = _clean_result_output(output.decode(errors="replace"))
for line in cleaned.splitlines():
if not line.startswith("PROBE\t"):
continue
parts = line.split("\t")
if len(parts) < 4:
raise ValueError(f"incomplete probe record: {line!r}")
records.append((
int(parts[1], 16), int(parts[2], 16), int(parts[3]),
int(parts[4]) if len(parts) >= 5 else 1,
int(parts[5]) if len(parts) >= 6 else 1))
if not records:
raise ValueError("probe returned no device records")
return records
def _probe_payload(records):
return "".join(
f"PROBE\t{dev:x}\t{features:x}\t{queues}\t{isr}\t{cfg}\n"
for dev, features, queues, isr, cfg in records).encode()
def _read_probe_cache(fd, decode=_probe_records):
if os.fstat(fd).st_size != _PROBE_CACHE_SIZE:
return None
with mmap.mmap(fd, _PROBE_CACHE_SIZE,
access=mmap.ACCESS_READ) as memory:
length = int.from_bytes(memory[:8], "little")
if length == 0:
return None
return decode(memory[8:8 + length])
def _cached_probe(key, probe, decode=_probe_records, encode=_probe_payload):
"""Reuse shared probe results independently of the launching process."""
os.makedirs(_PROBE_CACHE_DIR, mode=0o700, exist_ok=True)
directory = os.stat(_PROBE_CACHE_DIR, follow_symlinks=False)
if (not stat.S_ISDIR(directory.st_mode) or directory.st_uid != os.getuid()
or stat.S_IMODE(directory.st_mode) != 0o700):
raise RuntimeError(f"unsafe probe cache directory: {_PROBE_CACHE_DIR}")
cache_key = key() if callable(key) else key
path = os.path.join(_PROBE_CACHE_DIR, cache_key)
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError:
pass
else:
try:
cached = _read_probe_cache(fd, decode)
if cached is not None:
return cached
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
records = decode(probe())
if records is None:
return None
payload = encode(records)
if len(payload) > _PROBE_CACHE_SIZE - 8:
raise ValueError("capability probe exceeds shared memory size")
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return records
if _read_probe_cache(fd, decode) is not None:
return records
os.ftruncate(fd, _PROBE_CACHE_SIZE)
with mmap.mmap(fd, _PROBE_CACHE_SIZE) as memory:
memory[:8] = bytes(8)
memory[8:8 + len(payload)] = payload
memory[:8] = len(payload).to_bytes(8, "little")
return records
finally:
os.close(fd)
def _mmio_boots(backend, kernel, initramfs):
def probe():
with tempfile.TemporaryDirectory(prefix="vv-mmio-boot-") as directory:
disk = os.path.join(directory, "disk.raw")
images.create_raw(disk, DISK_SIZE)
command = backend.build_cmd(
kernel, initramfs, disk,
f"console={backend.console_device} vv.test=list")
try:
result = process.capture(command, timeout=2)
return result.stdout
except subprocess.TimeoutExpired as error:
return error.stdout or b""
except OSError as error:
print(f"Note: MMIO boot probe failed: {error}",
file=sys.stderr)
return b""
def ready(output):
return True if b"[vv]" in output else None
try:
return bool(_cached_probe(
lambda: _probe_cache_key(
backend, kernel, initramfs, {"probe": "mmio-boot"}),
probe, decode=ready, encode=lambda result: b"[vv]"))
except (OSError, ValueError, RuntimeError) as error:
print(f"Warning: MMIO boot probe cache unavailable: {error}. "
"Checking boot without cache.", file=sys.stderr)
return bool(ready(probe()))
def vm_api(api_socket, backend, command, args=None, timeout=None):
"""Send a control request to a running VM through its API socket.
For CH, backend must be a CloudHypervisor instance and the call
shells out to ch-remote. command is the subcommand name, for
example 'ping', 'info', 'snapshot', 'pause', 'add-disk'. args is
a list of extra positional or option arguments passed verbatim.
Returns CompletedProcess with captured stdout and stderr.
For QEMU, backend must be a Qemu instance and the call speaks
raw QMP JSON over the unix socket. command is the QMP execute
name, for example 'query-status' or 'stop'. args is a dict of
QMP arguments. Returns parsed JSON response or raw bytes on
parse failure. Raises OSError on connect failure.
"""
if timeout is None:
timeout = _VM_API_TIMEOUT
deadline = time.time() + timeout
while not os.path.exists(api_socket):
if time.time() > deadline:
raise OSError(f"api socket not ready: {api_socket}")
time.sleep(0.02)
if isinstance(backend, CloudHypervisor):
ch_remote = _find_ch_remote(backend.binary)
if not ch_remote:
raise FileNotFoundError(
"ch-remote not found next to the cloud-hypervisor binary "
"or in PATH")
cmd = [ch_remote, "--api-socket", api_socket, command]
if args:
cmd += list(args)
return subprocess.run(cmd, capture_output=True, text=True,
timeout=timeout)
if isinstance(backend, (Qemu, QemuMicrovm)):
import json
import socket as _socket
s = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect(api_socket)
try:
with s.makefile("rb") as stream:
def read_reply():
while True:
remaining = deadline - time.time()
if remaining <= 0:
raise TimeoutError(f"QMP {command} timed out")
s.settimeout(remaining)
line = stream.readline().rstrip(b"\r\n")
try:
reply = json.loads(line.decode())
except (ValueError, UnicodeDecodeError):
return line
if not isinstance(reply, dict) or "event" not in reply:
return reply
greeting = read_reply()
if not isinstance(greeting, dict) or "QMP" not in greeting:
raise RuntimeError(f"invalid QMP greeting: {greeting!r}")
s.sendall(b'{"execute":"qmp_capabilities"}\n')
capabilities = read_reply()
if (not isinstance(capabilities, dict)
or "return" not in capabilities
or "error" in capabilities):
raise RuntimeError(
f"QMP capabilities failed: {capabilities!r}")
req = {"execute": command}
if args is not None:
req["arguments"] = args
s.sendall((json.dumps(req) + "\n").encode())
return read_reply()
finally:
s.close()
raise ValueError(f"vm_api unsupported backend: {backend}")
def _find_ch_remote(ch_binary):
"""Locate the ch-remote client. Looks next to the cloud-hypervisor
binary first, then PATH.
"""
sibling = os.path.join(os.path.dirname(os.path.abspath(ch_binary)),
"ch-remote")
if os.path.isfile(sibling) and os.access(sibling, os.X_OK):
return sibling
return shutil.which("ch-remote")
# ---------------------------------------------------------------------------
# Sidecar mechanism. A sidecar is an optional Python file next to a C
# test source. The runner imports it and calls run(ctx) on a daemon
# thread alongside the guest test. The sidecar can drive anything on
# the host side, for example flap a tap link, kill a vhost backend,
# truncate the disk file, or call the VMM control socket. It is not
# tied to the API socket. Tests that do not need a host actor simply
# do not ship a sidecar.
class _SidecarSkip(Exception):
pass
class _Ctx:
"""Context object passed to a sidecar's run() function."""
def __init__(self, *, test_id, backend, vmm_pid, tmpdir, api_sock,
disk, log, output_buf, output_lock, stop_event, control=None):
self.test_id = test_id
self.backend = backend
self.vmm_pid = vmm_pid
self.tmpdir = tmpdir
self.api_sock = api_sock
self.disk = disk
self.log = log
self.stop = stop_event
self._buf = output_buf
self._lock = output_lock
self._control = control
def skip(self, reason):
"""Stop the host actor because a required prerequisite is absent."""
raise _SidecarSkip(reason)
def vm_api(self, command, args=None, timeout=None):
"""Convenience wrapper. Calls vm_api with this context's
api_sock and backend. Raises RuntimeError if the api socket
is disabled or the VMM has already exited. API responses and
connection errors are passed through without changing them.
"""
if self.api_sock is None:
raise RuntimeError("api socket disabled for this test")
if not self.vm_alive():
raise RuntimeError(f"VMM exited before API command {command}")
if self._control is not None:
return self._control(command, args, timeout)
return vm_api(self.api_sock, self.backend, command, args,
timeout=timeout)
def vm_alive(self):
"""Return True if the VMM process is still around. The guest
test may finish and the VMM may exit before the sidecar
reaches a later step. Sidecars should use this to skip
unnecessary follow up calls instead of erroring out.
"""
if self.vmm_pid is None:
return False
try:
os.kill(self.vmm_pid, 0)
except OSError:
return False
return True
def wait_text(self, pattern, timeout=10.0):
"""Block until the VMM stdout buffer contains pattern. Returns
True if seen, False on timeout or stop signal.
"""
needle = pattern.encode() if isinstance(pattern, str) else pattern
deadline = time.time() + timeout
while time.time() < deadline:
with self._lock:
joined = b"".join(self._buf)
if needle in joined:
return True
if self.stop.is_set():
return False
time.sleep(0.05)
return False
def _find_sidecar(test_name):
"""Return absolute path to a sidecar .py for test_name, or None.
Sidecars live next to the C source under tests/<dir>/. Match is
case insensitive and accepts the bare ID stem or a stem followed
by an underscore and free form text.
"""
td = _test_dir(test_name)
if not td:
return None
base = os.path.join(_SCRIPT_DIR, "tests", td)
if not os.path.isdir(base):
return None
low = test_name.lower()
for entry in os.listdir(base):
if not entry.endswith(".py"):
continue
stem = entry[:-3].lower()
if stem == low or stem.startswith(low + "_"):
return os.path.join(base, entry)
return None
def _load_sidecar(path):
"""Import a sidecar file as an anonymous module."""
import importlib.util
spec = importlib.util.spec_from_file_location(
"vv_sidecar_" + os.path.splitext(os.path.basename(path))[0], path)
if spec is None or spec.loader is None:
raise ImportError(f"cannot load sidecar: {path}")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def run_test(backend, kernel, test_name, timeout, verbose=0, console=False,
disk_format="raw", opts=None, stop=None):
"""Run one or more tests in a fresh VM.
test_name is a single test ID string or a list of IDs. When a
list is given, the tests are submitted as a comma separated
batch and each gets its own verdict line in the output. Sidecar
scripts are only supported for single test runs.
opts["initramfs"] selects a guest archive without changing source paths.
Returns a list of (name, status, output) tuples.
"""
if stop is not None and stop.is_set():
raise KeyboardInterrupt
if isinstance(test_name, str):
test_names = [test_name]
else:
test_names = list(test_name)
batch = len(test_names) > 1
sidecar_path = _find_sidecar(test_names[0]) if not batch else None
sidecar_mod = _load_sidecar(sidecar_path) if sidecar_path else None
supported = getattr(sidecar_mod, "SUPPORTED_BACKENDS", None)
if supported is not None and backend.name not in supported:
output = (f"[vv-sidecar] SKIP: backend {backend.name} is not "
f"supported by {os.path.basename(sidecar_path)}\n")
return [(test_names[0], "SKIP", output)]
required_tools = getattr(sidecar_mod, "REQUIRED_TOOLS", {})
for tool in required_tools.get(backend.name, ()):
executable = (_find_ch_remote(backend.binary)
if backend.name == "ch" and tool == "ch-remote"
else shutil.which(tool))
if not executable:
output = f"[vv-sidecar] SKIP: required host tool {tool} not found\n"
return [(test_names[0], "SKIP", output)]
# A batch runs every test in one VM, so the timeout budget scales
# with the number of tests. A single per test timeout routinely
# trips under heavy parallelism and kills the VM mid batch, wedging
# the tests that had not run yet. A single test keeps its own
# budget since the factor is one.
effective_timeout = timeout * len(test_names)
suffix = {"raw": ".raw", "qcow2": ".qcow2", "vhd": ".vhd",
"vhdx": ".vhdx"}[disk_format]
disk_path = tempfile.mktemp(suffix=suffix)
images.create(disk_path, DISK_SIZE, image_format=disk_format)
# Optional per test sidecar (single test only). It may declare launch
# requirements via vmm_config() and/or a run(ctx) host actor.
sidecar_cfg = {}
if sidecar_mod is not None and hasattr(sidecar_mod, "vmm_config"):
sidecar_cfg = sidecar_mod.vmm_config() or {}
# Guest kernel initcalls to skip. The block device is always present,
# so keep its guest driver from claiming it. A test whose sidecar
# drives a device the kernel would otherwise own adds more here (for
# example the net repro that owns the net and iommu devices itself).
skip_initcalls = [
"virtio_blk_init",
"virtio_scsi_init",
"virtio_net_driver_init",
"virtio_console_init",
"virtio_balloon_driver_init",
"virtio_rng_driver_init",
"virtio_mem_driver_init",
"virtio_pmem_driver_init",
"virtio_iommu_drv_init",
"virtio_fs_init",
"p9_virtio_init",
"virtio_vsock_init",
"virtio_rtc_drv_init",
"virtio_watchdog_driver_init",
"virtio_input_driver_init",
"virtio_crypto_driver_init",
# Subsystems unused by the harness
"ext4_init_fs",
"fuse_init",
"audit_init",
"cpufreq_core_init",
]
skip_initcalls += list(sidecar_cfg.get("skip_initcalls", []))
wait_scale = (opts or {}).get("wait_scale", 1)
transport = "mmio" if backend.name == "qemu-mmio" else "pci"
cmdline = (f"console={backend.console_device} "
f"initcall_blacklist={','.join(skip_initcalls)} "
f"vv.wait_scale={wait_scale} "
f"vv.transport={transport} "
f"vv.test={','.join(test_names)}")
# Create pmem backing file
pmem_path = disk_path.rsplit(".", 1)[0] + ".pmem"
images.create_raw(pmem_path, PMEM_SIZE)
# Copy so per test mutations do not leak into the shared opts
# dict that the caller reuses across every test.
opts = dict(opts) if opts else {}
opts["pmem_path"] = pmem_path
# Create the virtio-scsi backing file so a SCSI READ has real data
# to return from the block backend.
scsi_path = disk_path.rsplit(".", 1)[0] + ".scsi"
images.create_raw(scsi_path, DISK_SIZE)
opts["scsi_path"] = scsi_path
# Second backing file for the 4K block LUN at LUN 1.
scsi_path2 = disk_path.rsplit(".", 1)[0] + ".scsi2"
images.create_raw(scsi_path2, DISK_SIZE)
opts["scsi_path2"] = scsi_path2
api_socket = None
openvmm_control = bool(opts.get("api_enabled") and backend.name == "openvmm")
if opts.get("api_enabled") and backend.name in ("ch", "qemu", "qemu-mmio"):
api_socket = disk_path.rsplit(".", 1)[0] + ".api"
opts["api_socket"] = api_socket
else:
opts.pop("api_socket", None)
opts.pop("api_enabled", None)
# Spawn virtiofsd if this test targets virtio-fs and a daemon is
# available. The shared directory is a fresh empty tmpdir per test.
fs_proc = None
fs_socket = None
fs_sharedir = None
if test_names[0].upper().startswith("F"):
fs_daemon = _find_virtiofsd()
if fs_daemon:
fs_socket = disk_path.rsplit(".", 1)[0] + ".fsd"
fs_sharedir = tempfile.mkdtemp(prefix="vvfs.")
fs_proc = subprocess.Popen(
[fs_daemon, "--socket-path", fs_socket,
"--shared-dir", fs_sharedir,
"--cache", "never"],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
# Wait briefly for the socket to appear so CH/QEMU can connect.
for _ in range(50):
if os.path.exists(fs_socket):
break
time.sleep(0.02)
opts["fs_socket"] = fs_socket
p9_sharedir = None
if test_names[0].upper().startswith("PLAN9"):
p9_sharedir = tempfile.mkdtemp(prefix="vvp9.")
opts["p9_sharedir"] = p9_sharedir
# Apply any VMM opts the sidecar declared (for example placing the
# net device behind the vIOMMU). These are generic opts the backend
# build_cmd already understands, so the runner stays test agnostic.
for key, value in sidecar_cfg.get("opts", {}).items():
opts[key] = value
cmd = backend.build_cmd(
kernel, opts.get("initramfs", INITRAMFS), disk_path, cmdline, opts)
if verbose >= 1:
with _print_lock:
print(f" $ {shlex.join(cmd)}")
# Result markers printed by the in-VM harness. As soon as we see one
# we kill the VM, since not every VMM cleanly exits on guest reboot
# (notably CH on triple fault, and any teardown wedged by a test).
# The VMM writes its own log lines into the same stdout stream and
# can split a verdict marker at any character boundary; strip those
# lines first, then match the tag.
vmm_noise_re = re.compile(rb"cloud-hypervisor:[^\n]*(?:\n|$)")
kernel_noise_re = re.compile(rb"\[\s*\d+\.\d+\][^\n]*(?:\n|$)")
verdict_marker_re = re.compile(
rb"\[(?:XPASS|XFAIL|FAIL|REJECT|WEDGED|SKIP|PASS)\]")
def _remove_stream_log(match):
line = match.group(0)
marker = verdict_marker_re.search(line)
if not marker:
return b""
return line[marker.start():].rstrip(b"\n")
wanted = {t.encode() for t in test_names}
escaped_names = sorted((re.escape(t) for t in wanted), key=len,
reverse=True)
# Wait for the full line so killing the VM cannot truncate skip reasons.
marker_name_re = re.compile(
rb"\[(?:PASS|FAIL|REJECT|WEDGED|SKIP|XFAIL|XPASS)\]\s+("
+ rb"|".join(escaped_names)
+ rb")(?![A-Za-z0-9_])[^\r\n]*[\r\n]")
saved_term = _save_term() if console else None
proc = None
openvmm_master = None
processes = ExitStack()
timer = None
sidecar_thread = None
sidecar_state = {"err": None, "skip": None}
sidecar_stop = threading.Event()
sidecar_tmpdir = None
sidecar_log_lines = []
output_lock = threading.Lock()
output = ""
parse_text = ""
status = "FAIL"
# The VMM writes the guest serial, which carries the verdict
# markers, to its stdout, and its own log lines to stderr. Merging
# the two into one pipe lets a log line splice into a marker at a
# byte boundary and corrupt it, which surfaces as a spurious WEDGED
# for whichever test provoked a VMM log at verdict time. Keep stderr
# on its own pipe so the marker stream stays clean, and drain it in
# a thread. In console mode the drain thread also streams stderr live.
err_chunks = []
err_thread = None
try:
old_sigint = None
if console:
old_sigint = signal.signal(signal.SIGINT, signal.SIG_IGN)
proc, openvmm_master = processes.enter_context(process.spawn(
cmd, terminal=backend.name == "openvmm", start_new_session=not console,
stop=stop, stdout=subprocess.PIPE, stderr=subprocess.PIPE))
if proc.stderr is not None:
err_thread = threading.Thread(
target=drain_stream,
args=(proc.stderr, err_chunks, console),
name=f"stderr-{test_names[0]}", daemon=True)
err_thread.start()
chunks = []
if sidecar_mod is not None and hasattr(sidecar_mod, "run"):
sidecar_tmpdir = tempfile.mkdtemp(prefix=f"vv-sc-{test_names[0]}.")
sidecar_log_lines = []
def _sc_log(msg):
line = f"[vv-sidecar] {msg}"
sidecar_log_lines.append(line)
if console:
print(line)
ctx = _Ctx(
test_id=test_names[0],
backend=backend,
vmm_pid=proc.pid,
tmpdir=sidecar_tmpdir,
api_sock="repl" if openvmm_control else opts.get("api_socket"),
disk=disk_path,
log=_sc_log,
output_buf=chunks,
output_lock=output_lock,
stop_event=sidecar_stop,
)
if openvmm_control:
command_mode = False
def _openvmm_command(command, arguments, timeout):
nonlocal command_mode
acknowledgements = {
"pause": b"pause complete",
"resume": b"resumed complete",
"pulse-save-restore": b"pulse save/restore complete",
}
if command not in acknowledgements or arguments:
raise ValueError(f"unsupported OpenVMM command: {command}")
deadline = time.monotonic() + (
_VM_API_TIMEOUT if timeout is None else timeout)
if not command_mode:
os.write(openvmm_master, b"\x11")
while b"openvmm> " not in (
b"".join(chunks) + b"".join(err_chunks)):
if proc.poll() is not None:
raise RuntimeError(
"OpenVMM exited before command prompt")
if time.monotonic() >= deadline:
raise TimeoutError("OpenVMM command prompt timed out")
time.sleep(0.01)
command_mode = True
start = len(err_chunks)
os.write(openvmm_master, command.encode() + b"\n")
while True:
stderr_closed = not err_thread.is_alive()
reply = b"".join(err_chunks[start:])
if acknowledgements[command] in reply:
return subprocess.CompletedProcess(
[command], 0, "", reply.decode(errors="replace"))
complete_reply = (
reply if stderr_closed
else reply[:reply.rfind(b"\n") + 1])
for line in complete_reply.splitlines():
if b"ERROR" not in line and b"error:" not in line:
continue
if command == "pulse-save-restore" and re.search(
rb"\bERROR\b[^\r\n]*pulse save/restore failed "
rb'error=(?:"reset not supported"|reset not supported)'
rb"[ \t\r]*$", line):
ctx.skip(
"OpenVMM pulse-save-restore unavailable: "
"reset not supported")
raise RuntimeError(
f"OpenVMM {command} failed: "
f"{reply.decode(errors='replace')}")
if proc.poll() is not None and stderr_closed:
raise RuntimeError(f"OpenVMM exited during {command}")
if time.monotonic() >= deadline:
raise TimeoutError(f"OpenVMM {command} timed out")
time.sleep(0.01)
ctx._control = _openvmm_command
def _sc_run():
try:
sidecar_mod.run(ctx)
except _SidecarSkip as e:
sidecar_state["skip"] = str(e)
except BaseException as e: # capture for the runner
import traceback as _tb
sidecar_state["err"] = (e, _tb.format_exc())
sidecar_thread = threading.Thread(
target=_sc_run, name=f"sidecar-{test_names[0]}", daemon=True)
sidecar_thread.start()
timer_fired = [False]
def _on_timeout():
timer_fired[0] = True
if console:
proc.kill()
else:
_kill_proc(proc)
timer = threading.Timer(effective_timeout, _on_timeout)
timer.start()
reported = set()
scan_from = 0
marker_seen = False
for chunk in iter(lambda: proc.stdout.read1(4096), b""):
if console:
sys.stdout.buffer.write(chunk)
sys.stdout.buffer.flush()
with output_lock:
chunks.append(chunk)
if not marker_seen:
with output_lock:
joined = b"".join(chunks)
# Scan only the new tail, with an overlap so a verdict
# line split across a chunk boundary or a CH log line is
# still matched. Rescanning the whole growing buffer
# every chunk is O(n^2) and dominates a long batch run.
# Accumulate the reported test names and kill once every
# expected test has printed a full "[TAG] NAME" line,
# matching how the results are parsed. A bare tag count
# could reach the target before a verdict line was
# complete and kill with a name not yet captured, which
# then parses as a spurious WEDGED.
tail = joined[max(scan_from - 8192, 0):]
cleaned_tail = vmm_noise_re.sub(_remove_stream_log, tail)
cleaned_tail = kernel_noise_re.sub(
_remove_stream_log, cleaned_tail)
for m in marker_name_re.finditer(cleaned_tail):
reported.add(m.group(1))
scan_from = len(joined)
if wanted <= reported:
marker_seen = True
if console:
proc.kill()
else:
_kill_proc(proc)
proc.wait()
timer.cancel()
timed_out = not marker_seen and timer_fired[0]
if old_sigint is not None:
signal.signal(signal.SIGINT, old_sigint)
if timed_out:
raise subprocess.TimeoutExpired(cmd, effective_timeout)
if err_thread is not None:
err_thread.join(timeout=5)
parse_text = b"".join(chunks).decode(errors="replace")
status = _parse_result(parse_text, proc.returncode)
output = _merge_streams(parse_text, err_chunks)
except subprocess.TimeoutExpired:
if proc:
proc.kill()
proc.wait()
if err_thread is not None:
err_thread.join(timeout=5)
# Keep everything the VM already printed. A batch runs many
# tests in one VM, so discarding the captured output here would
# erase the verdicts of tests that already reported and mark the
# whole batch WEDGED. Preserve the real output so only the tests
# that never printed a marker stay WEDGED; append a timeout note
# for the single test case where the run itself is the failure.
parse_text = b"".join(chunks).decode(errors="replace") + \
f"\n[vv] TIMEOUT after {effective_timeout}s\n"
output = _merge_streams(parse_text, err_chunks)
status = "FAIL"
except KeyboardInterrupt:
if proc:
if console:
proc.kill()
else:
_kill_proc(proc)
proc.wait()
raise
except Exception as e:
output = str(e)
status = "FAIL"
finally:
if timer is not None:
timer.cancel()
if timer.ident is not None:
timer.join()
if proc and proc.poll() is None:
_kill_proc(proc, process_group=not console or backend.name == "openvmm")
if err_thread is not None and err_thread.is_alive():
err_thread.join(timeout=5)
sidecar_stop.set()
if sidecar_thread is not None:
sidecar_thread.join(timeout=_SIDECAR_JOIN_TIMEOUT)
err = sidecar_state.get("err")
if sidecar_thread.is_alive():
err = (RuntimeError(
"host action did not exit within "
f"{_SIDECAR_JOIN_TIMEOUT:g}s"), "")
extra = ""
if sidecar_log_lines:
extra += "\n" + "\n".join(sidecar_log_lines) + "\n"
skip_reason = sidecar_state["skip"]
if skip_reason is not None:
extra += f"\n[vv-sidecar] SKIP: {skip_reason}\n"
if status not in ("FAIL", "WEDGED", "XPASS"):
status = "SKIP"
if err is not None:
missing_device = status == "SKIP" and re.search(
r"\[SKIP\]\s+" + re.escape(test_names[0])
+ r"\s+\(no device 0x[0-9a-fA-F]+\)", parse_text)
if missing_device:
extra += ("\n[vv-sidecar] SKIP: guest device unavailable"
f"; host action stopped: {err[0]}\n")
else:
extra += f"\n[vv-sidecar] FAIL: {err[0]}\n{err[1]}\n"
if status != "WEDGED":
status = "FAIL"
output += extra
if sidecar_tmpdir:
shutil.rmtree(sidecar_tmpdir, ignore_errors=True)
processes.close()
_restore_term(saved_term)
if console:
signal.signal(signal.SIGINT, signal.default_int_handler)
if fs_proc:
try:
fs_proc.terminate()
fs_proc.wait(timeout=2)
except (subprocess.TimeoutExpired, OSError):
try:
fs_proc.kill()
except OSError:
pass
if fs_socket:
try:
os.unlink(fs_socket)
except FileNotFoundError:
pass
try:
os.unlink(fs_socket + ".pid")
except FileNotFoundError:
pass
if fs_sharedir:
shutil.rmtree(fs_sharedir, ignore_errors=True)
if p9_sharedir:
shutil.rmtree(p9_sharedir, ignore_errors=True)
os.unlink(disk_path)
try:
os.unlink(pmem_path)
except FileNotFoundError:
pass
try:
os.unlink(scsi_path)
except FileNotFoundError:
pass
try:
os.unlink(scsi_path2)
except FileNotFoundError:
pass
if api_socket:
try:
os.unlink(api_socket)
except FileNotFoundError:
pass
vsock_sock = disk_path.replace(suffix, ".vsock")
try:
os.unlink(vsock_sock)
except FileNotFoundError:
pass