xref: /openbmc/qemu/tests/vm/basevm.py (revision ff2ebff079da153c2a2d37d7c78d2ce14833b259)
1*ff2ebff0SFam Zheng#!/usr/bin/env python
2*ff2ebff0SFam Zheng#
3*ff2ebff0SFam Zheng# VM testing base class
4*ff2ebff0SFam Zheng#
5*ff2ebff0SFam Zheng# Copyright 2017 Red Hat Inc.
6*ff2ebff0SFam Zheng#
7*ff2ebff0SFam Zheng# Authors:
8*ff2ebff0SFam Zheng#  Fam Zheng <famz@redhat.com>
9*ff2ebff0SFam Zheng#
10*ff2ebff0SFam Zheng# This code is licensed under the GPL version 2 or later.  See
11*ff2ebff0SFam Zheng# the COPYING file in the top-level directory.
12*ff2ebff0SFam Zheng#
13*ff2ebff0SFam Zheng
14*ff2ebff0SFam Zhengimport os
15*ff2ebff0SFam Zhengimport sys
16*ff2ebff0SFam Zhengimport logging
17*ff2ebff0SFam Zhengimport time
18*ff2ebff0SFam Zhengimport datetime
19*ff2ebff0SFam Zhengsys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "scripts"))
20*ff2ebff0SFam Zhengfrom qemu import QEMUMachine
21*ff2ebff0SFam Zhengimport subprocess
22*ff2ebff0SFam Zhengimport hashlib
23*ff2ebff0SFam Zhengimport optparse
24*ff2ebff0SFam Zhengimport atexit
25*ff2ebff0SFam Zhengimport tempfile
26*ff2ebff0SFam Zhengimport shutil
27*ff2ebff0SFam Zhengimport multiprocessing
28*ff2ebff0SFam Zhengimport traceback
29*ff2ebff0SFam Zheng
30*ff2ebff0SFam ZhengSSH_KEY = open(os.path.join(os.path.dirname(__file__),
31*ff2ebff0SFam Zheng               "..", "keys", "id_rsa")).read()
32*ff2ebff0SFam ZhengSSH_PUB_KEY = open(os.path.join(os.path.dirname(__file__),
33*ff2ebff0SFam Zheng                   "..", "keys", "id_rsa.pub")).read()
34*ff2ebff0SFam Zheng
35*ff2ebff0SFam Zhengclass BaseVM(object):
36*ff2ebff0SFam Zheng    GUEST_USER = "qemu"
37*ff2ebff0SFam Zheng    GUEST_PASS = "qemupass"
38*ff2ebff0SFam Zheng    ROOT_PASS = "qemupass"
39*ff2ebff0SFam Zheng
40*ff2ebff0SFam Zheng    # The script to run in the guest that builds QEMU
41*ff2ebff0SFam Zheng    BUILD_SCRIPT = ""
42*ff2ebff0SFam Zheng    # The guest name, to be overridden by subclasses
43*ff2ebff0SFam Zheng    name = "#base"
44*ff2ebff0SFam Zheng    def __init__(self, debug=False, vcpus=None):
45*ff2ebff0SFam Zheng        self._guest = None
46*ff2ebff0SFam Zheng        self._tmpdir = os.path.realpath(tempfile.mkdtemp(prefix="vm-test-",
47*ff2ebff0SFam Zheng                                                         suffix=".tmp",
48*ff2ebff0SFam Zheng                                                         dir="."))
49*ff2ebff0SFam Zheng        atexit.register(shutil.rmtree, self._tmpdir)
50*ff2ebff0SFam Zheng
51*ff2ebff0SFam Zheng        self._ssh_key_file = os.path.join(self._tmpdir, "id_rsa")
52*ff2ebff0SFam Zheng        open(self._ssh_key_file, "w").write(SSH_KEY)
53*ff2ebff0SFam Zheng        subprocess.check_call(["chmod", "600", self._ssh_key_file])
54*ff2ebff0SFam Zheng
55*ff2ebff0SFam Zheng        self._ssh_pub_key_file = os.path.join(self._tmpdir, "id_rsa.pub")
56*ff2ebff0SFam Zheng        open(self._ssh_pub_key_file, "w").write(SSH_PUB_KEY)
57*ff2ebff0SFam Zheng
58*ff2ebff0SFam Zheng        self.debug = debug
59*ff2ebff0SFam Zheng        self._stderr = sys.stderr
60*ff2ebff0SFam Zheng        self._devnull = open(os.devnull, "w")
61*ff2ebff0SFam Zheng        if self.debug:
62*ff2ebff0SFam Zheng            self._stdout = sys.stdout
63*ff2ebff0SFam Zheng        else:
64*ff2ebff0SFam Zheng            self._stdout = self._devnull
65*ff2ebff0SFam Zheng        self._args = [ \
66*ff2ebff0SFam Zheng            "-nodefaults", "-m", "2G",
67*ff2ebff0SFam Zheng            "-cpu", "host",
68*ff2ebff0SFam Zheng            "-netdev", "user,id=vnet,hostfwd=:127.0.0.1:0-:22",
69*ff2ebff0SFam Zheng            "-device", "virtio-net-pci,netdev=vnet",
70*ff2ebff0SFam Zheng            "-vnc", "127.0.0.1:0,to=20",
71*ff2ebff0SFam Zheng            "-serial", "file:%s" % os.path.join(self._tmpdir, "serial.out")]
72*ff2ebff0SFam Zheng        if vcpus:
73*ff2ebff0SFam Zheng            self._args += ["-smp", str(vcpus)]
74*ff2ebff0SFam Zheng        if os.access("/dev/kvm", os.R_OK | os.W_OK):
75*ff2ebff0SFam Zheng            self._args += ["-enable-kvm"]
76*ff2ebff0SFam Zheng        else:
77*ff2ebff0SFam Zheng            logging.info("KVM not available, not using -enable-kvm")
78*ff2ebff0SFam Zheng        self._data_args = []
79*ff2ebff0SFam Zheng
80*ff2ebff0SFam Zheng    def _download_with_cache(self, url, sha256sum=None):
81*ff2ebff0SFam Zheng        def check_sha256sum(fname):
82*ff2ebff0SFam Zheng            if not sha256sum:
83*ff2ebff0SFam Zheng                return True
84*ff2ebff0SFam Zheng            checksum = subprocess.check_output(["sha256sum", fname]).split()[0]
85*ff2ebff0SFam Zheng            return sha256sum == checksum
86*ff2ebff0SFam Zheng
87*ff2ebff0SFam Zheng        cache_dir = os.path.expanduser("~/.cache/qemu-vm/download")
88*ff2ebff0SFam Zheng        if not os.path.exists(cache_dir):
89*ff2ebff0SFam Zheng            os.makedirs(cache_dir)
90*ff2ebff0SFam Zheng        fname = os.path.join(cache_dir, hashlib.sha1(url).hexdigest())
91*ff2ebff0SFam Zheng        if os.path.exists(fname) and check_sha256sum(fname):
92*ff2ebff0SFam Zheng            return fname
93*ff2ebff0SFam Zheng        logging.debug("Downloading %s to %s...", url, fname)
94*ff2ebff0SFam Zheng        subprocess.check_call(["wget", "-c", url, "-O", fname + ".download"],
95*ff2ebff0SFam Zheng                              stdout=self._stdout, stderr=self._stderr)
96*ff2ebff0SFam Zheng        os.rename(fname + ".download", fname)
97*ff2ebff0SFam Zheng        return fname
98*ff2ebff0SFam Zheng
99*ff2ebff0SFam Zheng    def _ssh_do(self, user, cmd, check, interactive=False):
100*ff2ebff0SFam Zheng        ssh_cmd = ["ssh", "-q",
101*ff2ebff0SFam Zheng                   "-o", "StrictHostKeyChecking=no",
102*ff2ebff0SFam Zheng                   "-o", "UserKnownHostsFile=" + os.devnull,
103*ff2ebff0SFam Zheng                   "-o", "ConnectTimeout=1",
104*ff2ebff0SFam Zheng                   "-p", self.ssh_port, "-i", self._ssh_key_file]
105*ff2ebff0SFam Zheng        if interactive:
106*ff2ebff0SFam Zheng            ssh_cmd += ['-t']
107*ff2ebff0SFam Zheng        assert not isinstance(cmd, str)
108*ff2ebff0SFam Zheng        ssh_cmd += ["%s@127.0.0.1" % user] + list(cmd)
109*ff2ebff0SFam Zheng        logging.debug("ssh_cmd: %s", " ".join(ssh_cmd))
110*ff2ebff0SFam Zheng        r = subprocess.call(ssh_cmd,
111*ff2ebff0SFam Zheng                            stdin=sys.stdin if interactive else self._devnull,
112*ff2ebff0SFam Zheng                            stdout=sys.stdout if interactive else self._stdout,
113*ff2ebff0SFam Zheng                            stderr=sys.stderr if interactive else self._stderr)
114*ff2ebff0SFam Zheng        if check and r != 0:
115*ff2ebff0SFam Zheng            raise Exception("SSH command failed: %s" % cmd)
116*ff2ebff0SFam Zheng        return r
117*ff2ebff0SFam Zheng
118*ff2ebff0SFam Zheng    def ssh(self, *cmd):
119*ff2ebff0SFam Zheng        return self._ssh_do(self.GUEST_USER, cmd, False)
120*ff2ebff0SFam Zheng
121*ff2ebff0SFam Zheng    def ssh_interactive(self, *cmd):
122*ff2ebff0SFam Zheng        return self._ssh_do(self.GUEST_USER, cmd, False, True)
123*ff2ebff0SFam Zheng
124*ff2ebff0SFam Zheng    def ssh_root(self, *cmd):
125*ff2ebff0SFam Zheng        return self._ssh_do("root", cmd, False)
126*ff2ebff0SFam Zheng
127*ff2ebff0SFam Zheng    def ssh_check(self, *cmd):
128*ff2ebff0SFam Zheng        self._ssh_do(self.GUEST_USER, cmd, True)
129*ff2ebff0SFam Zheng
130*ff2ebff0SFam Zheng    def ssh_root_check(self, *cmd):
131*ff2ebff0SFam Zheng        self._ssh_do("root", cmd, True)
132*ff2ebff0SFam Zheng
133*ff2ebff0SFam Zheng    def build_image(self, img):
134*ff2ebff0SFam Zheng        raise NotImplementedError
135*ff2ebff0SFam Zheng
136*ff2ebff0SFam Zheng    def add_source_dir(self, src_dir):
137*ff2ebff0SFam Zheng        name = "data-" + hashlib.sha1(src_dir).hexdigest()[:5]
138*ff2ebff0SFam Zheng        tarfile = os.path.join(self._tmpdir, name + ".tar")
139*ff2ebff0SFam Zheng        logging.debug("Creating archive %s for src_dir dir: %s", tarfile, src_dir)
140*ff2ebff0SFam Zheng        subprocess.check_call(["./scripts/archive-source.sh", tarfile],
141*ff2ebff0SFam Zheng                              cwd=src_dir, stdin=self._devnull,
142*ff2ebff0SFam Zheng                              stdout=self._stdout, stderr=self._stderr)
143*ff2ebff0SFam Zheng        self._data_args += ["-drive",
144*ff2ebff0SFam Zheng                            "file=%s,if=none,id=%s,cache=writeback,format=raw" % \
145*ff2ebff0SFam Zheng                                    (tarfile, name),
146*ff2ebff0SFam Zheng                            "-device",
147*ff2ebff0SFam Zheng                            "virtio-blk,drive=%s,serial=%s,bootindex=1" % (name, name)]
148*ff2ebff0SFam Zheng
149*ff2ebff0SFam Zheng    def boot(self, img, extra_args=[]):
150*ff2ebff0SFam Zheng        args = self._args + [
151*ff2ebff0SFam Zheng            "-device", "VGA",
152*ff2ebff0SFam Zheng            "-drive", "file=%s,if=none,id=drive0,cache=writeback" % img,
153*ff2ebff0SFam Zheng            "-device", "virtio-blk,drive=drive0,bootindex=0"]
154*ff2ebff0SFam Zheng        args += self._data_args + extra_args
155*ff2ebff0SFam Zheng        logging.debug("QEMU args: %s", " ".join(args))
156*ff2ebff0SFam Zheng        qemu_bin = os.environ.get("QEMU", "qemu-system-x86_64")
157*ff2ebff0SFam Zheng        guest = QEMUMachine(binary=qemu_bin, args=args)
158*ff2ebff0SFam Zheng        try:
159*ff2ebff0SFam Zheng            guest.launch()
160*ff2ebff0SFam Zheng        except:
161*ff2ebff0SFam Zheng            logging.error("Failed to launch QEMU, command line:")
162*ff2ebff0SFam Zheng            logging.error(" ".join([qemu_bin] + args))
163*ff2ebff0SFam Zheng            logging.error("Log:")
164*ff2ebff0SFam Zheng            logging.error(guest.get_log())
165*ff2ebff0SFam Zheng            logging.error("QEMU version >= 2.10 is required")
166*ff2ebff0SFam Zheng            raise
167*ff2ebff0SFam Zheng        atexit.register(self.shutdown)
168*ff2ebff0SFam Zheng        self._guest = guest
169*ff2ebff0SFam Zheng        usernet_info = guest.qmp("human-monitor-command",
170*ff2ebff0SFam Zheng                                 command_line="info usernet")
171*ff2ebff0SFam Zheng        self.ssh_port = None
172*ff2ebff0SFam Zheng        for l in usernet_info["return"].splitlines():
173*ff2ebff0SFam Zheng            fields = l.split()
174*ff2ebff0SFam Zheng            if "TCP[HOST_FORWARD]" in fields and "22" in fields:
175*ff2ebff0SFam Zheng                self.ssh_port = l.split()[3]
176*ff2ebff0SFam Zheng        if not self.ssh_port:
177*ff2ebff0SFam Zheng            raise Exception("Cannot find ssh port from 'info usernet':\n%s" % \
178*ff2ebff0SFam Zheng                            usernet_info)
179*ff2ebff0SFam Zheng
180*ff2ebff0SFam Zheng    def wait_ssh(self, seconds=120):
181*ff2ebff0SFam Zheng        starttime = datetime.datetime.now()
182*ff2ebff0SFam Zheng        guest_up = False
183*ff2ebff0SFam Zheng        while (datetime.datetime.now() - starttime).total_seconds() < seconds:
184*ff2ebff0SFam Zheng            if self.ssh("exit 0") == 0:
185*ff2ebff0SFam Zheng                guest_up = True
186*ff2ebff0SFam Zheng                break
187*ff2ebff0SFam Zheng            time.sleep(1)
188*ff2ebff0SFam Zheng        if not guest_up:
189*ff2ebff0SFam Zheng            raise Exception("Timeout while waiting for guest ssh")
190*ff2ebff0SFam Zheng
191*ff2ebff0SFam Zheng    def shutdown(self):
192*ff2ebff0SFam Zheng        self._guest.shutdown()
193*ff2ebff0SFam Zheng
194*ff2ebff0SFam Zheng    def wait(self):
195*ff2ebff0SFam Zheng        self._guest.wait()
196*ff2ebff0SFam Zheng
197*ff2ebff0SFam Zheng    def qmp(self, *args, **kwargs):
198*ff2ebff0SFam Zheng        return self._guest.qmp(*args, **kwargs)
199*ff2ebff0SFam Zheng
200*ff2ebff0SFam Zhengdef parse_args(vm_name):
201*ff2ebff0SFam Zheng    parser = optparse.OptionParser(
202*ff2ebff0SFam Zheng        description="VM test utility.  Exit codes: "
203*ff2ebff0SFam Zheng                    "0 = success, "
204*ff2ebff0SFam Zheng                    "1 = command line error, "
205*ff2ebff0SFam Zheng                    "2 = environment initialization failed, "
206*ff2ebff0SFam Zheng                    "3 = test command failed")
207*ff2ebff0SFam Zheng    parser.add_option("--debug", "-D", action="store_true",
208*ff2ebff0SFam Zheng                      help="enable debug output")
209*ff2ebff0SFam Zheng    parser.add_option("--image", "-i", default="%s.img" % vm_name,
210*ff2ebff0SFam Zheng                      help="image file name")
211*ff2ebff0SFam Zheng    parser.add_option("--force", "-f", action="store_true",
212*ff2ebff0SFam Zheng                      help="force build image even if image exists")
213*ff2ebff0SFam Zheng    parser.add_option("--jobs", type=int, default=multiprocessing.cpu_count() / 2,
214*ff2ebff0SFam Zheng                      help="number of virtual CPUs")
215*ff2ebff0SFam Zheng    parser.add_option("--build-image", "-b", action="store_true",
216*ff2ebff0SFam Zheng                      help="build image")
217*ff2ebff0SFam Zheng    parser.add_option("--build-qemu",
218*ff2ebff0SFam Zheng                      help="build QEMU from source in guest")
219*ff2ebff0SFam Zheng    parser.add_option("--interactive", "-I", action="store_true",
220*ff2ebff0SFam Zheng                      help="Interactively run command")
221*ff2ebff0SFam Zheng    parser.disable_interspersed_args()
222*ff2ebff0SFam Zheng    return parser.parse_args()
223*ff2ebff0SFam Zheng
224*ff2ebff0SFam Zhengdef main(vmcls):
225*ff2ebff0SFam Zheng    try:
226*ff2ebff0SFam Zheng        args, argv = parse_args(vmcls.name)
227*ff2ebff0SFam Zheng        if not argv and not args.build_qemu and not args.build_image:
228*ff2ebff0SFam Zheng            print "Nothing to do?"
229*ff2ebff0SFam Zheng            return 1
230*ff2ebff0SFam Zheng        if args.debug:
231*ff2ebff0SFam Zheng            logging.getLogger().setLevel(logging.DEBUG)
232*ff2ebff0SFam Zheng        vm = vmcls(debug=args.debug, vcpus=args.jobs)
233*ff2ebff0SFam Zheng        if args.build_image:
234*ff2ebff0SFam Zheng            if os.path.exists(args.image) and not args.force:
235*ff2ebff0SFam Zheng                sys.stderr.writelines(["Image file exists: %s\n" % args.image,
236*ff2ebff0SFam Zheng                                      "Use --force option to overwrite\n"])
237*ff2ebff0SFam Zheng                return 1
238*ff2ebff0SFam Zheng            return vm.build_image(args.image)
239*ff2ebff0SFam Zheng        if args.build_qemu:
240*ff2ebff0SFam Zheng            vm.add_source_dir(args.build_qemu)
241*ff2ebff0SFam Zheng            cmd = [vm.BUILD_SCRIPT.format(
242*ff2ebff0SFam Zheng                   configure_opts = " ".join(argv),
243*ff2ebff0SFam Zheng                   jobs=args.jobs)]
244*ff2ebff0SFam Zheng        else:
245*ff2ebff0SFam Zheng            cmd = argv
246*ff2ebff0SFam Zheng        vm.boot(args.image + ",snapshot=on")
247*ff2ebff0SFam Zheng        vm.wait_ssh()
248*ff2ebff0SFam Zheng    except Exception as e:
249*ff2ebff0SFam Zheng        if isinstance(e, SystemExit) and e.code == 0:
250*ff2ebff0SFam Zheng            return 0
251*ff2ebff0SFam Zheng        sys.stderr.write("Failed to prepare guest environment\n")
252*ff2ebff0SFam Zheng        traceback.print_exc()
253*ff2ebff0SFam Zheng        return 2
254*ff2ebff0SFam Zheng
255*ff2ebff0SFam Zheng    if args.interactive:
256*ff2ebff0SFam Zheng        if vm.ssh_interactive(*cmd) == 0:
257*ff2ebff0SFam Zheng            return 0
258*ff2ebff0SFam Zheng        vm.ssh_interactive()
259*ff2ebff0SFam Zheng        return 3
260*ff2ebff0SFam Zheng    else:
261*ff2ebff0SFam Zheng        if vm.ssh(*cmd) != 0:
262*ff2ebff0SFam Zheng            return 3
263