xref: /openbmc/qemu/tests/vm/basevm.py (revision e6e03dcf)
1#!/usr/bin/env python
2#
3# VM testing base class
4#
5# Copyright 2017-2019 Red Hat Inc.
6#
7# Authors:
8#  Fam Zheng <famz@redhat.com>
9#  Gerd Hoffmann <kraxel@redhat.com>
10#
11# This code is licensed under the GPL version 2 or later.  See
12# the COPYING file in the top-level directory.
13#
14
15from __future__ import print_function
16import os
17import re
18import sys
19import socket
20import logging
21import time
22import datetime
23sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python'))
24from qemu import kvm_available
25from qemu.machine import QEMUMachine
26import subprocess
27import hashlib
28import optparse
29import atexit
30import tempfile
31import shutil
32import multiprocessing
33import traceback
34
35SSH_KEY = open(os.path.join(os.path.dirname(__file__),
36               "..", "keys", "id_rsa")).read()
37SSH_PUB_KEY = open(os.path.join(os.path.dirname(__file__),
38                   "..", "keys", "id_rsa.pub")).read()
39
40class BaseVM(object):
41    GUEST_USER = "qemu"
42    GUEST_PASS = "qemupass"
43    ROOT_PASS = "qemupass"
44
45    envvars = [
46        "https_proxy",
47        "http_proxy",
48        "ftp_proxy",
49        "no_proxy",
50    ]
51
52    # The script to run in the guest that builds QEMU
53    BUILD_SCRIPT = ""
54    # The guest name, to be overridden by subclasses
55    name = "#base"
56    # The guest architecture, to be overridden by subclasses
57    arch = "#arch"
58    # command to halt the guest, can be overridden by subclasses
59    poweroff = "poweroff"
60    # enable IPv6 networking
61    ipv6 = True
62    def __init__(self, debug=False, vcpus=None):
63        self._guest = None
64        self._tmpdir = os.path.realpath(tempfile.mkdtemp(prefix="vm-test-",
65                                                         suffix=".tmp",
66                                                         dir="."))
67        atexit.register(shutil.rmtree, self._tmpdir)
68
69        self._ssh_key_file = os.path.join(self._tmpdir, "id_rsa")
70        open(self._ssh_key_file, "w").write(SSH_KEY)
71        subprocess.check_call(["chmod", "600", self._ssh_key_file])
72
73        self._ssh_pub_key_file = os.path.join(self._tmpdir, "id_rsa.pub")
74        open(self._ssh_pub_key_file, "w").write(SSH_PUB_KEY)
75
76        self.debug = debug
77        self._stderr = sys.stderr
78        self._devnull = open(os.devnull, "w")
79        if self.debug:
80            self._stdout = sys.stdout
81        else:
82            self._stdout = self._devnull
83        self._args = [ \
84            "-nodefaults", "-m", "4G",
85            "-cpu", "max",
86            "-netdev", "user,id=vnet,hostfwd=:127.0.0.1:0-:22" +
87                       (",ipv6=no" if not self.ipv6 else ""),
88            "-device", "virtio-net-pci,netdev=vnet",
89            "-vnc", "127.0.0.1:0,to=20"]
90        if vcpus and vcpus > 1:
91            self._args += ["-smp", "%d" % vcpus]
92        if kvm_available(self.arch):
93            self._args += ["-enable-kvm"]
94        else:
95            logging.info("KVM not available, not using -enable-kvm")
96        self._data_args = []
97
98    def _download_with_cache(self, url, sha256sum=None):
99        def check_sha256sum(fname):
100            if not sha256sum:
101                return True
102            checksum = subprocess.check_output(["sha256sum", fname]).split()[0]
103            return sha256sum == checksum.decode("utf-8")
104
105        cache_dir = os.path.expanduser("~/.cache/qemu-vm/download")
106        if not os.path.exists(cache_dir):
107            os.makedirs(cache_dir)
108        fname = os.path.join(cache_dir,
109                             hashlib.sha1(url.encode("utf-8")).hexdigest())
110        if os.path.exists(fname) and check_sha256sum(fname):
111            return fname
112        logging.debug("Downloading %s to %s...", url, fname)
113        subprocess.check_call(["wget", "-c", url, "-O", fname + ".download"],
114                              stdout=self._stdout, stderr=self._stderr)
115        os.rename(fname + ".download", fname)
116        return fname
117
118    def _ssh_do(self, user, cmd, check):
119        ssh_cmd = ["ssh", "-q", "-t",
120                   "-o", "StrictHostKeyChecking=no",
121                   "-o", "UserKnownHostsFile=" + os.devnull,
122                   "-o", "ConnectTimeout=1",
123                   "-p", self.ssh_port, "-i", self._ssh_key_file]
124        for var in self.envvars:
125            ssh_cmd += ['-o', "SendEnv=%s" % var ]
126        assert not isinstance(cmd, str)
127        ssh_cmd += ["%s@127.0.0.1" % user] + list(cmd)
128        logging.debug("ssh_cmd: %s", " ".join(ssh_cmd))
129        r = subprocess.call(ssh_cmd)
130        if check and r != 0:
131            raise Exception("SSH command failed: %s" % cmd)
132        return r
133
134    def ssh(self, *cmd):
135        return self._ssh_do(self.GUEST_USER, cmd, False)
136
137    def ssh_root(self, *cmd):
138        return self._ssh_do("root", cmd, False)
139
140    def ssh_check(self, *cmd):
141        self._ssh_do(self.GUEST_USER, cmd, True)
142
143    def ssh_root_check(self, *cmd):
144        self._ssh_do("root", cmd, True)
145
146    def build_image(self, img):
147        raise NotImplementedError
148
149    def add_source_dir(self, src_dir):
150        name = "data-" + hashlib.sha1(src_dir.encode("utf-8")).hexdigest()[:5]
151        tarfile = os.path.join(self._tmpdir, name + ".tar")
152        logging.debug("Creating archive %s for src_dir dir: %s", tarfile, src_dir)
153        subprocess.check_call(["./scripts/archive-source.sh", tarfile],
154                              cwd=src_dir, stdin=self._devnull,
155                              stdout=self._stdout, stderr=self._stderr)
156        self._data_args += ["-drive",
157                            "file=%s,if=none,id=%s,cache=writeback,format=raw" % \
158                                    (tarfile, name),
159                            "-device",
160                            "virtio-blk,drive=%s,serial=%s,bootindex=1" % (name, name)]
161
162    def boot(self, img, extra_args=[]):
163        args = self._args + [
164            "-device", "VGA",
165            "-drive", "file=%s,if=none,id=drive0,cache=writeback" % img,
166            "-device", "virtio-blk,drive=drive0,bootindex=0"]
167        args += self._data_args + extra_args
168        logging.debug("QEMU args: %s", " ".join(args))
169        qemu_bin = os.environ.get("QEMU", "qemu-system-" + self.arch)
170        guest = QEMUMachine(binary=qemu_bin, args=args)
171        guest.set_machine('pc')
172        guest.set_console()
173        try:
174            guest.launch()
175        except:
176            logging.error("Failed to launch QEMU, command line:")
177            logging.error(" ".join([qemu_bin] + args))
178            logging.error("Log:")
179            logging.error(guest.get_log())
180            logging.error("QEMU version >= 2.10 is required")
181            raise
182        atexit.register(self.shutdown)
183        self._guest = guest
184        usernet_info = guest.qmp("human-monitor-command",
185                                 command_line="info usernet")
186        self.ssh_port = None
187        for l in usernet_info["return"].splitlines():
188            fields = l.split()
189            if "TCP[HOST_FORWARD]" in fields and "22" in fields:
190                self.ssh_port = l.split()[3]
191        if not self.ssh_port:
192            raise Exception("Cannot find ssh port from 'info usernet':\n%s" % \
193                            usernet_info)
194
195    def console_init(self, timeout = 120):
196        vm = self._guest
197        vm.console_socket.settimeout(timeout)
198
199    def console_log(self, text):
200        for line in re.split("[\r\n]", text):
201            # filter out terminal escape sequences
202            line = re.sub("\x1b\[[0-9;?]*[a-zA-Z]", "", line)
203            line = re.sub("\x1b\([0-9;?]*[a-zA-Z]", "", line)
204            # replace unprintable chars
205            line = re.sub("\x1b", "<esc>", line)
206            line = re.sub("[\x00-\x1f]", ".", line)
207            line = re.sub("[\x80-\xff]", ".", line)
208            if line == "":
209                continue
210            # log console line
211            sys.stderr.write("con recv: %s\n" % line)
212
213    def console_wait(self, expect, expectalt = None):
214        vm = self._guest
215        output = ""
216        while True:
217            try:
218                chars = vm.console_socket.recv(1)
219            except socket.timeout:
220                sys.stderr.write("console: *** read timeout ***\n")
221                sys.stderr.write("console: waiting for: '%s'\n" % expect)
222                if not expectalt is None:
223                    sys.stderr.write("console: waiting for: '%s' (alt)\n" % expectalt)
224                sys.stderr.write("console: line buffer:\n")
225                sys.stderr.write("\n")
226                self.console_log(output.rstrip())
227                sys.stderr.write("\n")
228                raise
229            output += chars.decode("latin1")
230            if expect in output:
231                break
232            if not expectalt is None and expectalt in output:
233                break
234            if "\r" in output or "\n" in output:
235                lines = re.split("[\r\n]", output)
236                output = lines.pop()
237                if self.debug:
238                    self.console_log("\n".join(lines))
239        if self.debug:
240            self.console_log(output)
241        if not expectalt is None and expectalt in output:
242            return False
243        return True
244
245    def console_send(self, command):
246        vm = self._guest
247        if self.debug:
248            logline = re.sub("\n", "<enter>", command)
249            logline = re.sub("[\x00-\x1f]", ".", logline)
250            sys.stderr.write("con send: %s\n" % logline)
251        for char in list(command):
252            vm.console_socket.send(char.encode("utf-8"))
253            time.sleep(0.01)
254
255    def console_wait_send(self, wait, command):
256        self.console_wait(wait)
257        self.console_send(command)
258
259    def console_ssh_init(self, prompt, user, pw):
260        sshkey_cmd = "echo '%s' > .ssh/authorized_keys\n" % SSH_PUB_KEY.rstrip()
261        self.console_wait_send("login:",    "%s\n" % user)
262        self.console_wait_send("Password:", "%s\n" % pw)
263        self.console_wait_send(prompt,      "mkdir .ssh\n")
264        self.console_wait_send(prompt,      sshkey_cmd)
265        self.console_wait_send(prompt,      "chmod 755 .ssh\n")
266        self.console_wait_send(prompt,      "chmod 644 .ssh/authorized_keys\n")
267
268    def console_sshd_config(self, prompt):
269        self.console_wait(prompt)
270        self.console_send("echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config\n")
271        for var in self.envvars:
272            self.console_wait(prompt)
273            self.console_send("echo 'AcceptEnv %s' >> /etc/ssh/sshd_config\n" % var)
274
275    def print_step(self, text):
276        sys.stderr.write("### %s ...\n" % text)
277
278    def wait_ssh(self, seconds=300):
279        starttime = datetime.datetime.now()
280        endtime = starttime + datetime.timedelta(seconds=seconds)
281        guest_up = False
282        while datetime.datetime.now() < endtime:
283            if self.ssh("exit 0") == 0:
284                guest_up = True
285                break
286            seconds = (endtime - datetime.datetime.now()).total_seconds()
287            logging.debug("%ds before timeout", seconds)
288            time.sleep(1)
289        if not guest_up:
290            raise Exception("Timeout while waiting for guest ssh")
291
292    def shutdown(self):
293        self._guest.shutdown()
294
295    def wait(self):
296        self._guest.wait()
297
298    def graceful_shutdown(self):
299        self.ssh_root(self.poweroff)
300        self._guest.wait()
301
302    def qmp(self, *args, **kwargs):
303        return self._guest.qmp(*args, **kwargs)
304
305def parse_args(vmcls):
306
307    def get_default_jobs():
308        if kvm_available(vmcls.arch):
309            return multiprocessing.cpu_count() // 2
310        else:
311            return 1
312
313    parser = optparse.OptionParser(
314        description="VM test utility.  Exit codes: "
315                    "0 = success, "
316                    "1 = command line error, "
317                    "2 = environment initialization failed, "
318                    "3 = test command failed")
319    parser.add_option("--debug", "-D", action="store_true",
320                      help="enable debug output")
321    parser.add_option("--image", "-i", default="%s.img" % vmcls.name,
322                      help="image file name")
323    parser.add_option("--force", "-f", action="store_true",
324                      help="force build image even if image exists")
325    parser.add_option("--jobs", type=int, default=get_default_jobs(),
326                      help="number of virtual CPUs")
327    parser.add_option("--verbose", "-V", action="store_true",
328                      help="Pass V=1 to builds within the guest")
329    parser.add_option("--build-image", "-b", action="store_true",
330                      help="build image")
331    parser.add_option("--build-qemu",
332                      help="build QEMU from source in guest")
333    parser.add_option("--build-target",
334                      help="QEMU build target", default="check")
335    parser.add_option("--interactive", "-I", action="store_true",
336                      help="Interactively run command")
337    parser.add_option("--snapshot", "-s", action="store_true",
338                      help="run tests with a snapshot")
339    parser.disable_interspersed_args()
340    return parser.parse_args()
341
342def main(vmcls):
343    try:
344        args, argv = parse_args(vmcls)
345        if not argv and not args.build_qemu and not args.build_image:
346            print("Nothing to do?")
347            return 1
348        logging.basicConfig(level=(logging.DEBUG if args.debug
349                                   else logging.WARN))
350        vm = vmcls(debug=args.debug, vcpus=args.jobs)
351        if args.build_image:
352            if os.path.exists(args.image) and not args.force:
353                sys.stderr.writelines(["Image file exists: %s\n" % args.image,
354                                      "Use --force option to overwrite\n"])
355                return 1
356            return vm.build_image(args.image)
357        if args.build_qemu:
358            vm.add_source_dir(args.build_qemu)
359            cmd = [vm.BUILD_SCRIPT.format(
360                   configure_opts = " ".join(argv),
361                   jobs=int(args.jobs),
362                   target=args.build_target,
363                   verbose = "V=1" if args.verbose else "")]
364        else:
365            cmd = argv
366        img = args.image
367        if args.snapshot:
368            img += ",snapshot=on"
369        vm.boot(img)
370        vm.wait_ssh()
371    except Exception as e:
372        if isinstance(e, SystemExit) and e.code == 0:
373            return 0
374        sys.stderr.write("Failed to prepare guest environment\n")
375        traceback.print_exc()
376        return 2
377
378    exitcode = 0
379    if vm.ssh(*cmd) != 0:
380        exitcode = 3
381    if exitcode != 0 and args.interactive:
382        vm.ssh()
383
384    if not args.snapshot:
385        vm.graceful_shutdown()
386
387    return exitcode
388