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