Genode Packages collection https://git.sr.ht/~ehmry/genodepkgs/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test-driver.py 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. #! /somewhere/python3
  2. # Copyright (c) 2003-2020 Nixpkgs/NixOS contributors
  3. from contextlib import contextmanager, _GeneratorContextManager
  4. from queue import Queue, Empty
  5. from typing import Tuple, Any, Callable, Dict, Iterator, Optional, List
  6. from xml.sax.saxutils import XMLGenerator
  7. import queue
  8. import io
  9. import _thread
  10. import argparse
  11. import atexit
  12. import base64
  13. import codecs
  14. import os
  15. import pathlib
  16. import ptpython.repl
  17. import pty
  18. import re
  19. import shlex
  20. import shutil
  21. import socket
  22. import subprocess
  23. import sys
  24. import tempfile
  25. import time
  26. import traceback
  27. import unicodedata
  28. CHAR_TO_KEY = {
  29. "A": "shift-a",
  30. "N": "shift-n",
  31. "-": "0x0C",
  32. "_": "shift-0x0C",
  33. "B": "shift-b",
  34. "O": "shift-o",
  35. "=": "0x0D",
  36. "+": "shift-0x0D",
  37. "C": "shift-c",
  38. "P": "shift-p",
  39. "[": "0x1A",
  40. "{": "shift-0x1A",
  41. "D": "shift-d",
  42. "Q": "shift-q",
  43. "]": "0x1B",
  44. "}": "shift-0x1B",
  45. "E": "shift-e",
  46. "R": "shift-r",
  47. ";": "0x27",
  48. ":": "shift-0x27",
  49. "F": "shift-f",
  50. "S": "shift-s",
  51. "'": "0x28",
  52. '"': "shift-0x28",
  53. "G": "shift-g",
  54. "T": "shift-t",
  55. "`": "0x29",
  56. "~": "shift-0x29",
  57. "H": "shift-h",
  58. "U": "shift-u",
  59. "\\": "0x2B",
  60. "|": "shift-0x2B",
  61. "I": "shift-i",
  62. "V": "shift-v",
  63. ",": "0x33",
  64. "<": "shift-0x33",
  65. "J": "shift-j",
  66. "W": "shift-w",
  67. ".": "0x34",
  68. ">": "shift-0x34",
  69. "K": "shift-k",
  70. "X": "shift-x",
  71. "/": "0x35",
  72. "?": "shift-0x35",
  73. "L": "shift-l",
  74. "Y": "shift-y",
  75. " ": "spc",
  76. "M": "shift-m",
  77. "Z": "shift-z",
  78. "\n": "ret",
  79. "!": "shift-0x02",
  80. "@": "shift-0x03",
  81. "#": "shift-0x04",
  82. "$": "shift-0x05",
  83. "%": "shift-0x06",
  84. "^": "shift-0x07",
  85. "&": "shift-0x08",
  86. "*": "shift-0x09",
  87. "(": "shift-0x0A",
  88. ")": "shift-0x0B",
  89. }
  90. # Forward references
  91. log: "Logger"
  92. machines: "List[Machine]"
  93. def eprint(*args: object, **kwargs: Any) -> None:
  94. print(*args, file=sys.stderr, **kwargs)
  95. def make_command(args: list) -> str:
  96. return " ".join(map(shlex.quote, (map(str, args))))
  97. def create_vlan(vlan_nr: str) -> Tuple[str, str, "subprocess.Popen[bytes]", Any]:
  98. global log
  99. log.log("starting VDE switch for network {}".format(vlan_nr))
  100. vde_socket = tempfile.mkdtemp(
  101. prefix="nixos-test-vde-", suffix="-vde{}.ctl".format(vlan_nr)
  102. )
  103. pty_master, pty_slave = pty.openpty()
  104. vde_process = subprocess.Popen(
  105. ["vde_switch", "-s", vde_socket, "--dirmode", "0700"],
  106. bufsize=1,
  107. stdin=pty_slave,
  108. stdout=subprocess.PIPE,
  109. stderr=subprocess.PIPE,
  110. shell=False,
  111. )
  112. fd = os.fdopen(pty_master, "w")
  113. fd.write("version\n")
  114. # TODO: perl version checks if this can be read from
  115. # an if not, dies. we could hang here forever. Fix it.
  116. assert vde_process.stdout is not None
  117. vde_process.stdout.readline()
  118. if not os.path.exists(os.path.join(vde_socket, "ctl")):
  119. raise Exception("cannot start vde_switch")
  120. return (vlan_nr, vde_socket, vde_process, fd)
  121. def retry(fn: Callable) -> None:
  122. """Call the given function repeatedly, with 1 second intervals,
  123. until it returns True or a timeout is reached.
  124. """
  125. for _ in range(900):
  126. if fn(False):
  127. return
  128. time.sleep(1)
  129. if not fn(True):
  130. raise Exception("action timed out")
  131. class Logger:
  132. def __init__(self) -> None:
  133. self.logfile = os.environ.get("LOGFILE", "/dev/null")
  134. self.logfile_handle = codecs.open(self.logfile, "wb")
  135. self.xml = XMLGenerator(self.logfile_handle, encoding="utf-8")
  136. self.queue: "Queue[Dict[str, str]]" = Queue()
  137. self.xml.startDocument()
  138. self.xml.startElement("logfile", attrs={})
  139. def close(self) -> None:
  140. self.xml.endElement("logfile")
  141. self.xml.endDocument()
  142. self.logfile_handle.close()
  143. def sanitise(self, message: str) -> str:
  144. return "".join(ch for ch in message if unicodedata.category(ch)[0] != "C")
  145. def maybe_prefix(self, message: str, attributes: Dict[str, str]) -> str:
  146. if "machine" in attributes:
  147. return "{}: {}".format(attributes["machine"], message)
  148. return message
  149. def log_line(self, message: str, attributes: Dict[str, str]) -> None:
  150. self.xml.startElement("line", attributes)
  151. self.xml.characters(message)
  152. self.xml.endElement("line")
  153. def log(self, message: str, attributes: Dict[str, str] = {}) -> None:
  154. eprint(self.maybe_prefix(message, attributes))
  155. self.drain_log_queue()
  156. self.log_line(message, attributes)
  157. def enqueue(self, message: Dict[str, str]) -> None:
  158. self.queue.put(message)
  159. def drain_log_queue(self) -> None:
  160. try:
  161. while True:
  162. item = self.queue.get_nowait()
  163. attributes = {"machine": item["machine"], "type": "serial"}
  164. self.log_line(self.sanitise(item["msg"]), attributes)
  165. except Empty:
  166. pass
  167. @contextmanager
  168. def nested(self, message: str, attributes: Dict[str, str] = {}) -> Iterator[None]:
  169. eprint(self.maybe_prefix(message, attributes))
  170. self.xml.startElement("nest", attrs={})
  171. self.xml.startElement("head", attributes)
  172. self.xml.characters(message)
  173. self.xml.endElement("head")
  174. tic = time.time()
  175. self.drain_log_queue()
  176. yield
  177. self.drain_log_queue()
  178. toc = time.time()
  179. self.log("({:.2f} seconds)".format(toc - tic))
  180. self.xml.endElement("nest")
  181. class Machine:
  182. def __init__(self, args: Dict[str, Any]) -> None:
  183. if "name" in args:
  184. self.name = args["name"]
  185. else:
  186. self.name = "machine"
  187. cmd = args.get("startCommand", None)
  188. if cmd:
  189. match = re.search("bin/run-(.+)-vm$", cmd)
  190. if match:
  191. self.name = match.group(1)
  192. self.script = args.get("startCommand", self.create_startcommand(args))
  193. tmp_dir = os.environ.get("TMPDIR", tempfile.gettempdir())
  194. def create_dir(name: str) -> str:
  195. path = os.path.join(tmp_dir, name)
  196. os.makedirs(path, mode=0o700, exist_ok=True)
  197. return path
  198. self.state_dir = create_dir("vm-state-{}".format(self.name))
  199. self.shared_dir = create_dir("shared-xchg")
  200. self.booted = False
  201. self.connected = False
  202. self.pid: Optional[int] = None
  203. self.socket = None
  204. self.monitor: Optional[socket.socket] = None
  205. self.logger: Logger = args["log"]
  206. self.serialQueue: "Queue[str]" = Queue()
  207. self.allow_reboot = args.get("allowReboot", False)
  208. @staticmethod
  209. def create_startcommand(args: Dict[str, str]) -> str:
  210. net_backend = "-netdev user,id=net0"
  211. net_frontend = "-device virtio-net-pci,netdev=net0"
  212. if "netBackendArgs" in args:
  213. net_backend += "," + args["netBackendArgs"]
  214. if "netFrontendArgs" in args:
  215. net_frontend += "," + args["netFrontendArgs"]
  216. start_command = (
  217. "qemu-kvm -m 384 " + net_backend + " " + net_frontend + " $QEMU_OPTS "
  218. )
  219. if "hda" in args:
  220. hda_path = os.path.abspath(args["hda"])
  221. if args.get("hdaInterface", "") == "scsi":
  222. start_command += (
  223. "-drive id=hda,file="
  224. + hda_path
  225. + ",werror=report,if=none "
  226. + "-device scsi-hd,drive=hda "
  227. )
  228. else:
  229. start_command += (
  230. "-drive file="
  231. + hda_path
  232. + ",if="
  233. + args["hdaInterface"]
  234. + ",werror=report "
  235. )
  236. if "cdrom" in args:
  237. start_command += "-cdrom " + args["cdrom"] + " "
  238. if "usb" in args:
  239. start_command += (
  240. "-device piix3-usb-uhci -drive "
  241. + "id=usbdisk,file="
  242. + args["usb"]
  243. + ",if=none,readonly "
  244. + "-device usb-storage,drive=usbdisk "
  245. )
  246. if "bios" in args:
  247. start_command += "-bios " + args["bios"] + " "
  248. start_command += args.get("qemuFlags", "")
  249. return start_command
  250. def is_up(self) -> bool:
  251. return self.booted and self.connected
  252. def log(self, msg: str) -> None:
  253. self.logger.log(msg, {"machine": self.name})
  254. def nested(self, msg: str, attrs: Dict[str, str] = {}) -> _GeneratorContextManager:
  255. my_attrs = {"machine": self.name}
  256. my_attrs.update(attrs)
  257. return self.logger.nested(msg, my_attrs)
  258. def wait_for_monitor_prompt(self) -> str:
  259. assert self.monitor is not None
  260. answer = ""
  261. while True:
  262. undecoded_answer = self.monitor.recv(1024)
  263. if not undecoded_answer:
  264. break
  265. answer += undecoded_answer.decode()
  266. if answer.endswith("(qemu) "):
  267. break
  268. return answer
  269. def send_monitor_command(self, command: str) -> str:
  270. message = ("{}\n".format(command)).encode()
  271. self.log("sending monitor command: {}".format(command))
  272. assert self.monitor is not None
  273. self.monitor.send(message)
  274. return self.wait_for_monitor_prompt()
  275. def wait_for_unit(self, unit: str, user: Optional[str] = None) -> None:
  276. """Wait for a systemd unit to get into "active" state.
  277. Throws exceptions on "failed" and "inactive" states as well as
  278. after timing out.
  279. """
  280. def check_active(_: Any) -> bool:
  281. info = self.get_unit_info(unit, user)
  282. state = info["ActiveState"]
  283. if state == "failed":
  284. raise Exception('unit "{}" reached state "{}"'.format(unit, state))
  285. if state == "inactive":
  286. status, jobs = self.systemctl("list-jobs --full 2>&1", user)
  287. if "No jobs" in jobs:
  288. info = self.get_unit_info(unit, user)
  289. if info["ActiveState"] == state:
  290. raise Exception(
  291. (
  292. 'unit "{}" is inactive and there ' "are no pending jobs"
  293. ).format(unit)
  294. )
  295. return state == "active"
  296. retry(check_active)
  297. def get_unit_info(self, unit: str, user: Optional[str] = None) -> Dict[str, str]:
  298. status, lines = self.systemctl('--no-pager show "{}"'.format(unit), user)
  299. if status != 0:
  300. raise Exception(
  301. 'retrieving systemctl info for unit "{}" {} failed with exit code {}'.format(
  302. unit, "" if user is None else 'under user "{}"'.format(user), status
  303. )
  304. )
  305. line_pattern = re.compile(r"^([^=]+)=(.*)$")
  306. def tuple_from_line(line: str) -> Tuple[str, str]:
  307. match = line_pattern.match(line)
  308. assert match is not None
  309. return match[1], match[2]
  310. return dict(
  311. tuple_from_line(line)
  312. for line in lines.split("\n")
  313. if line_pattern.match(line)
  314. )
  315. def systemctl(self, q: str, user: Optional[str] = None) -> Tuple[int, str]:
  316. if user is not None:
  317. q = q.replace("'", "\\'")
  318. return self.execute(
  319. (
  320. "su -l {} --shell /bin/sh -c "
  321. "$'XDG_RUNTIME_DIR=/run/user/`id -u` "
  322. "systemctl --user {}'"
  323. ).format(user, q)
  324. )
  325. return self.execute("systemctl {}".format(q))
  326. def require_unit_state(self, unit: str, require_state: str = "active") -> None:
  327. with self.nested(
  328. "checking if unit ‘{}’ has reached state '{}'".format(unit, require_state)
  329. ):
  330. info = self.get_unit_info(unit)
  331. state = info["ActiveState"]
  332. if state != require_state:
  333. raise Exception(
  334. "Expected unit ‘{}’ to to be in state ".format(unit)
  335. + "'{}' but it is in state ‘{}’".format(require_state, state)
  336. )
  337. def execute(self, command: str) -> Tuple[int, str]:
  338. self.connect()
  339. out_command = "( {} ); echo '|!=EOF' $?\n".format(command)
  340. self.shell.send(out_command.encode())
  341. output = ""
  342. status_code_pattern = re.compile(r"(.*)\|\!=EOF\s+(\d+)")
  343. while True:
  344. chunk = self.shell.recv(4096).decode(errors="ignore")
  345. match = status_code_pattern.match(chunk)
  346. if match:
  347. output += match[1]
  348. status_code = int(match[2])
  349. return (status_code, output)
  350. output += chunk
  351. def succeed(self, *commands: str) -> str:
  352. """Execute each command and check that it succeeds."""
  353. output = ""
  354. for command in commands:
  355. with self.nested("must succeed: {}".format(command)):
  356. (status, out) = self.execute(command)
  357. if status != 0:
  358. self.log("output: {}".format(out))
  359. raise Exception(
  360. "command `{}` failed (exit code {})".format(command, status)
  361. )
  362. output += out
  363. return output
  364. def fail(self, *commands: str) -> None:
  365. """Execute each command and check that it fails."""
  366. for command in commands:
  367. with self.nested("must fail: {}".format(command)):
  368. status, output = self.execute(command)
  369. if status == 0:
  370. raise Exception(
  371. "command `{}` unexpectedly succeeded".format(command)
  372. )
  373. def wait_until_succeeds(self, command: str) -> str:
  374. """Wait until a command returns success and return its output.
  375. Throws an exception on timeout.
  376. """
  377. output = ""
  378. def check_success(_: Any) -> bool:
  379. nonlocal output
  380. status, output = self.execute(command)
  381. return status == 0
  382. with self.nested("waiting for success: {}".format(command)):
  383. retry(check_success)
  384. return output
  385. def wait_until_fails(self, command: str) -> str:
  386. """Wait until a command returns failure.
  387. Throws an exception on timeout.
  388. """
  389. output = ""
  390. def check_failure(_: Any) -> bool:
  391. nonlocal output
  392. status, output = self.execute(command)
  393. return status != 0
  394. with self.nested("waiting for failure: {}".format(command)):
  395. retry(check_failure)
  396. return output
  397. def wait_for_shutdown(self) -> None:
  398. if not self.booted:
  399. return
  400. with self.nested("waiting for the VM to power off"):
  401. sys.stdout.flush()
  402. self.process.wait()
  403. self.pid = None
  404. self.booted = False
  405. self.connected = False
  406. def get_tty_text(self, tty: str) -> str:
  407. status, output = self.execute(
  408. "fold -w$(stty -F /dev/tty{0} size | "
  409. "awk '{{print $2}}') /dev/vcs{0}".format(tty)
  410. )
  411. return output
  412. def wait_until_tty_matches(self, tty: str, regexp: str) -> None:
  413. """Wait until the visible output on the chosen TTY matches regular
  414. expression. Throws an exception on timeout.
  415. """
  416. matcher = re.compile(regexp)
  417. def tty_matches(last: bool) -> bool:
  418. text = self.get_tty_text(tty)
  419. if last:
  420. self.log(
  421. f"Last chance to match /{regexp}/ on TTY{tty}, "
  422. f"which currently contains: {text}"
  423. )
  424. return len(matcher.findall(text)) > 0
  425. with self.nested("waiting for {} to appear on tty {}".format(regexp, tty)):
  426. retry(tty_matches)
  427. def wait_until_serial_output(self, regexp: str) -> None:
  428. """Wait until the serial output matches regular expression.
  429. Throws an exception on timeout.
  430. """
  431. matcher = re.compile(regexp)
  432. def serial_matches(last: bool) -> bool:
  433. while not self.serialQueue.empty():
  434. text = self.serialQueue.get()
  435. if last:
  436. self.log(
  437. f"Last chance to match /{regexp}/ on serial, "
  438. f"which currently contains: {text}"
  439. )
  440. if len(matcher.findall(text)) > 0:
  441. return True
  442. return False
  443. with self.nested("waiting for {} to appear on serial output".format(regexp)):
  444. retry(serial_matches)
  445. def send_chars(self, chars: List[str]) -> None:
  446. with self.nested("sending keys ‘{}‘".format(chars)):
  447. for char in chars:
  448. self.send_key(char)
  449. def wait_for_file(self, filename: str) -> None:
  450. """Waits until the file exists in machine's file system."""
  451. def check_file(_: Any) -> bool:
  452. status, _ = self.execute("test -e {}".format(filename))
  453. return status == 0
  454. with self.nested("waiting for file ‘{}‘".format(filename)):
  455. retry(check_file)
  456. def wait_for_open_port(self, port: int) -> None:
  457. def port_is_open(_: Any) -> bool:
  458. status, _ = self.execute("nc -z localhost {}".format(port))
  459. return status == 0
  460. with self.nested("waiting for TCP port {}".format(port)):
  461. retry(port_is_open)
  462. def wait_for_closed_port(self, port: int) -> None:
  463. def port_is_closed(_: Any) -> bool:
  464. status, _ = self.execute("nc -z localhost {}".format(port))
  465. return status != 0
  466. retry(port_is_closed)
  467. def start_job(self, jobname: str, user: Optional[str] = None) -> Tuple[int, str]:
  468. return self.systemctl("start {}".format(jobname), user)
  469. def stop_job(self, jobname: str, user: Optional[str] = None) -> Tuple[int, str]:
  470. return self.systemctl("stop {}".format(jobname), user)
  471. def wait_for_job(self, jobname: str) -> None:
  472. self.wait_for_unit(jobname)
  473. def connect(self) -> None:
  474. if self.connected:
  475. return
  476. with self.nested("waiting for the VM to finish booting"):
  477. self.start()
  478. tic = time.time()
  479. self.shell.recv(1024)
  480. # TODO: Timeout
  481. toc = time.time()
  482. self.log("connected to guest root shell")
  483. self.log("(connecting took {:.2f} seconds)".format(toc - tic))
  484. self.connected = True
  485. def screenshot(self, filename: str) -> None:
  486. out_dir = os.environ.get("out", os.getcwd())
  487. word_pattern = re.compile(r"^\w+$")
  488. if word_pattern.match(filename):
  489. filename = os.path.join(out_dir, "{}.png".format(filename))
  490. tmp = "{}.ppm".format(filename)
  491. with self.nested(
  492. "making screenshot {}".format(filename),
  493. {"image": os.path.basename(filename)},
  494. ):
  495. self.send_monitor_command("screendump {}".format(tmp))
  496. ret = subprocess.run("pnmtopng {} > {}".format(tmp, filename), shell=True)
  497. os.unlink(tmp)
  498. if ret.returncode != 0:
  499. raise Exception("Cannot convert screenshot")
  500. def copy_from_host_via_shell(self, source: str, target: str) -> None:
  501. """Copy a file from the host into the guest by piping it over the
  502. shell into the destination file. Works without host-guest shared folder.
  503. Prefer copy_from_host for whenever possible.
  504. """
  505. with open(source, "rb") as fh:
  506. content_b64 = base64.b64encode(fh.read()).decode()
  507. self.succeed(
  508. f"mkdir -p $(dirname {target})",
  509. f"echo -n {content_b64} | base64 -d > {target}",
  510. )
  511. def copy_from_host(self, source: str, target: str) -> None:
  512. """Copy a file from the host into the guest via the `shared_dir` shared
  513. among all the VMs (using a temporary directory).
  514. """
  515. host_src = pathlib.Path(source)
  516. vm_target = pathlib.Path(target)
  517. with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td:
  518. shared_temp = pathlib.Path(shared_td)
  519. host_intermediate = shared_temp / host_src.name
  520. vm_shared_temp = pathlib.Path("/tmp/shared") / shared_temp.name
  521. vm_intermediate = vm_shared_temp / host_src.name
  522. self.succeed(make_command(["mkdir", "-p", vm_shared_temp]))
  523. if host_src.is_dir():
  524. shutil.copytree(host_src, host_intermediate)
  525. else:
  526. shutil.copy(host_src, host_intermediate)
  527. self.succeed("sync")
  528. self.succeed(make_command(["mkdir", "-p", vm_target.parent]))
  529. self.succeed(make_command(["cp", "-r", vm_intermediate, vm_target]))
  530. # Make sure the cleanup is synced into VM
  531. self.succeed("sync")
  532. def copy_from_vm(self, source: str, target_dir: str = "") -> None:
  533. """Copy a file from the VM (specified by an in-VM source path) to a path
  534. relative to `$out`. The file is copied via the `shared_dir` shared among
  535. all the VMs (using a temporary directory).
  536. """
  537. # Compute the source, target, and intermediate shared file names
  538. out_dir = pathlib.Path(os.environ.get("out", os.getcwd()))
  539. vm_src = pathlib.Path(source)
  540. with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td:
  541. shared_temp = pathlib.Path(shared_td)
  542. vm_shared_temp = pathlib.Path("/tmp/shared") / shared_temp.name
  543. vm_intermediate = vm_shared_temp / vm_src.name
  544. intermediate = shared_temp / vm_src.name
  545. # Copy the file to the shared directory inside VM
  546. self.succeed(make_command(["mkdir", "-p", vm_shared_temp]))
  547. self.succeed(make_command(["cp", "-r", vm_src, vm_intermediate]))
  548. self.succeed("sync")
  549. abs_target = out_dir / target_dir / vm_src.name
  550. abs_target.parent.mkdir(exist_ok=True, parents=True)
  551. # Copy the file from the shared directory outside VM
  552. if intermediate.is_dir():
  553. shutil.copytree(intermediate, abs_target)
  554. else:
  555. shutil.copy(intermediate, abs_target)
  556. # Make sure the cleanup is synced into VM
  557. self.succeed("sync")
  558. def dump_tty_contents(self, tty: str) -> None:
  559. """Debugging: Dump the contents of the TTY<n>
  560. """
  561. self.execute("fold -w 80 /dev/vcs{} | systemd-cat".format(tty))
  562. def get_screen_text(self) -> str:
  563. if shutil.which("tesseract") is None:
  564. raise Exception("get_screen_text used but enableOCR is false")
  565. magick_args = (
  566. "-filter Catrom -density 72 -resample 300 "
  567. + "-contrast -normalize -despeckle -type grayscale "
  568. + "-sharpen 1 -posterize 3 -negate -gamma 100 "
  569. + "-blur 1x65535"
  570. )
  571. tess_args = "-c debug_file=/dev/null --psm 11 --oem 2"
  572. with self.nested("performing optical character recognition"):
  573. with tempfile.NamedTemporaryFile() as tmpin:
  574. self.send_monitor_command("screendump {}".format(tmpin.name))
  575. cmd = "convert {} {} tiff:- | tesseract - - {}".format(
  576. magick_args, tmpin.name, tess_args
  577. )
  578. ret = subprocess.run(cmd, shell=True, capture_output=True)
  579. if ret.returncode != 0:
  580. raise Exception(
  581. "OCR failed with exit code {}".format(ret.returncode)
  582. )
  583. return ret.stdout.decode("utf-8")
  584. def wait_for_text(self, regex: str) -> None:
  585. def screen_matches(last: bool) -> bool:
  586. text = self.get_screen_text()
  587. matches = re.search(regex, text) is not None
  588. if last and not matches:
  589. self.log("Last OCR attempt failed. Text was: {}".format(text))
  590. return matches
  591. with self.nested("waiting for {} to appear on screen".format(regex)):
  592. retry(screen_matches)
  593. def send_key(self, key: str) -> None:
  594. key = CHAR_TO_KEY.get(key, key)
  595. self.send_monitor_command("sendkey {}".format(key))
  596. def start(self) -> None:
  597. if self.booted:
  598. return
  599. self.log("starting vm")
  600. def create_socket(path: str) -> socket.socket:
  601. if os.path.exists(path):
  602. os.unlink(path)
  603. s = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)
  604. s.bind(path)
  605. s.listen(1)
  606. return s
  607. monitor_path = os.path.join(self.state_dir, "monitor")
  608. self.monitor_socket = create_socket(monitor_path)
  609. shell_path = os.path.join(self.state_dir, "shell")
  610. self.shell_socket = create_socket(shell_path)
  611. qemu_options = (
  612. " ".join(
  613. [
  614. "" if self.allow_reboot else "-no-reboot",
  615. "-monitor unix:{}".format(monitor_path),
  616. "-chardev socket,id=shell,path={}".format(shell_path),
  617. "-device virtio-serial",
  618. "-device virtconsole,chardev=shell",
  619. "-device virtio-rng-pci",
  620. "-serial stdio" if "DISPLAY" in os.environ else "-nographic",
  621. ]
  622. )
  623. + " "
  624. + os.environ.get("QEMU_OPTS", "")
  625. )
  626. environment = dict(os.environ)
  627. environment.update(
  628. {
  629. "TMPDIR": self.state_dir,
  630. "SHARED_DIR": self.shared_dir,
  631. "USE_TMPDIR": "1",
  632. "QEMU_OPTS": qemu_options,
  633. }
  634. )
  635. self.process = subprocess.Popen(
  636. self.script,
  637. bufsize=1,
  638. stdin=subprocess.DEVNULL,
  639. stdout=subprocess.PIPE,
  640. stderr=subprocess.STDOUT,
  641. shell=True,
  642. cwd=self.state_dir,
  643. env=environment,
  644. )
  645. self.monitor, _ = self.monitor_socket.accept()
  646. self.shell, _ = self.shell_socket.accept()
  647. def process_serial_output() -> None:
  648. assert self.process.stdout is not None
  649. for _line in self.process.stdout:
  650. # Ignore undecodable bytes that may occur in boot menus
  651. line = _line.decode(errors="ignore").replace("\r", "").rstrip()
  652. eprint("{} # {}".format(self.name, line))
  653. self.logger.enqueue({"msg": line, "machine": self.name})
  654. self.serialQueue.put(line)
  655. _thread.start_new_thread(process_serial_output, ())
  656. self.wait_for_monitor_prompt()
  657. self.pid = self.process.pid
  658. self.booted = True
  659. self.log("QEMU running (pid {})".format(self.pid))
  660. def shutdown(self) -> None:
  661. if not self.booted:
  662. return
  663. self.shell.send("poweroff\n".encode())
  664. self.wait_for_shutdown()
  665. def crash(self) -> None:
  666. if not self.booted:
  667. return
  668. self.log("forced crash")
  669. self.send_monitor_command("quit")
  670. self.wait_for_shutdown()
  671. def wait_for_x(self) -> None:
  672. """Wait until it is possible to connect to the X server. Note that
  673. testing the existence of /tmp/.X11-unix/X0 is insufficient.
  674. """
  675. def check_x(_: Any) -> bool:
  676. cmd = (
  677. "journalctl -b SYSLOG_IDENTIFIER=systemd | "
  678. + 'grep "Reached target Current graphical"'
  679. )
  680. status, _ = self.execute(cmd)
  681. if status != 0:
  682. return False
  683. status, _ = self.execute("[ -e /tmp/.X11-unix/X0 ]")
  684. return status == 0
  685. with self.nested("waiting for the X11 server"):
  686. retry(check_x)
  687. def get_window_names(self) -> List[str]:
  688. return self.succeed(
  689. r"xwininfo -root -tree | sed 's/.*0x[0-9a-f]* \"\([^\"]*\)\".*/\1/; t; d'"
  690. ).splitlines()
  691. def wait_for_window(self, regexp: str) -> None:
  692. pattern = re.compile(regexp)
  693. def window_is_visible(last_try: bool) -> bool:
  694. names = self.get_window_names()
  695. if last_try:
  696. self.log(
  697. "Last chance to match {} on the window list,".format(regexp)
  698. + " which currently contains: "
  699. + ", ".join(names)
  700. )
  701. return any(pattern.search(name) for name in names)
  702. with self.nested("Waiting for a window to appear"):
  703. retry(window_is_visible)
  704. def sleep(self, secs: int) -> None:
  705. time.sleep(secs)
  706. def forward_port(self, host_port: int = 8080, guest_port: int = 80) -> None:
  707. """Forward a TCP port on the host to a TCP port on the guest.
  708. Useful during interactive testing.
  709. """
  710. self.send_monitor_command(
  711. "hostfwd_add tcp::{}-:{}".format(host_port, guest_port)
  712. )
  713. def block(self) -> None:
  714. """Make the machine unreachable by shutting down eth1 (the multicast
  715. interface used to talk to the other VMs). We keep eth0 up so that
  716. the test driver can continue to talk to the machine.
  717. """
  718. self.send_monitor_command("set_link virtio-net-pci.1 off")
  719. def unblock(self) -> None:
  720. """Make the machine reachable.
  721. """
  722. self.send_monitor_command("set_link virtio-net-pci.1 on")
  723. def create_machine(args: Dict[str, Any]) -> Machine:
  724. global log
  725. args["log"] = log
  726. args["redirectSerial"] = os.environ.get("USE_SERIAL", "0") == "1"
  727. return Machine(args)
  728. def start_all() -> None:
  729. global machines
  730. with log.nested("starting all VMs"):
  731. for machine in machines:
  732. machine.start()
  733. def join_all() -> None:
  734. global machines
  735. with log.nested("waiting for all VMs to finish"):
  736. for machine in machines:
  737. machine.wait_for_shutdown()
  738. def test_script() -> None:
  739. exec(os.environ["testScript"])
  740. def run_tests() -> None:
  741. global machines
  742. tests = os.environ.get("tests", None)
  743. if tests is not None:
  744. with log.nested("running the VM test script"):
  745. try:
  746. exec(tests, globals())
  747. except Exception as e:
  748. eprint("error: {}".format(str(e)))
  749. sys.exit(1)
  750. else:
  751. ptpython.repl.embed(locals(), globals())
  752. # TODO: Collect coverage data
  753. for machine in machines:
  754. if machine.is_up():
  755. machine.execute("sync")
  756. @contextmanager
  757. def subtest(name: str) -> Iterator[None]:
  758. with log.nested(name):
  759. try:
  760. yield
  761. return True
  762. except Exception as e:
  763. log.log(f'Test "{name}" failed with error: "{e}"')
  764. raise e
  765. return False
  766. if __name__ == "__main__":
  767. arg_parser = argparse.ArgumentParser()
  768. arg_parser.add_argument(
  769. "-K",
  770. "--keep-vm-state",
  771. help="re-use a VM state coming from a previous run",
  772. action="store_true",
  773. )
  774. (cli_args, vm_scripts) = arg_parser.parse_known_args()
  775. log = Logger()
  776. vlan_nrs = list(dict.fromkeys(os.environ.get("VLANS", "").split()))
  777. vde_sockets = [create_vlan(v) for v in vlan_nrs]
  778. for nr, vde_socket, _, _ in vde_sockets:
  779. os.environ["QEMU_VDE_SOCKET_{}".format(nr)] = vde_socket
  780. machines = [
  781. create_machine({"startCommand": s, "keepVmState": cli_args.keep_vm_state})
  782. for s in vm_scripts
  783. ]
  784. machine_eval = [
  785. "{0} = machines[{1}]".format(m.name, idx) for idx, m in enumerate(machines)
  786. ]
  787. exec("\n".join(machine_eval))
  788. @atexit.register
  789. def clean_up() -> None:
  790. with log.nested("cleaning up"):
  791. for machine in machines:
  792. if machine.pid is None:
  793. continue
  794. log.log("killing {} (pid {})".format(machine.name, machine.pid))
  795. machine.process.kill()
  796. log.close()
  797. tic = time.time()
  798. run_tests()
  799. toc = time.time()
  800. print("test script finished in {:.2f}s".format(toc - tic))