2017-09-05 04:11:53 +02:00
|
|
|
#
|
|
|
|
# VM testing base class
|
|
|
|
#
|
2019-06-17 06:38:53 +02:00
|
|
|
# Copyright 2017-2019 Red Hat Inc.
|
2017-09-05 04:11:53 +02:00
|
|
|
#
|
|
|
|
# Authors:
|
|
|
|
# Fam Zheng <famz@redhat.com>
|
2019-06-17 06:38:53 +02:00
|
|
|
# Gerd Hoffmann <kraxel@redhat.com>
|
2017-09-05 04:11:53 +02:00
|
|
|
#
|
|
|
|
# This code is licensed under the GPL version 2 or later. See
|
|
|
|
# the COPYING file in the top-level directory.
|
|
|
|
#
|
|
|
|
|
|
|
|
import os
|
2019-06-17 06:38:53 +02:00
|
|
|
import re
|
2017-09-05 04:11:53 +02:00
|
|
|
import sys
|
2019-06-17 06:38:53 +02:00
|
|
|
import socket
|
2017-09-05 04:11:53 +02:00
|
|
|
import logging
|
|
|
|
import time
|
|
|
|
import datetime
|
|
|
|
import subprocess
|
|
|
|
import hashlib
|
2020-07-01 15:56:26 +02:00
|
|
|
import argparse
|
2017-09-05 04:11:53 +02:00
|
|
|
import atexit
|
|
|
|
import tempfile
|
|
|
|
import shutil
|
|
|
|
import multiprocessing
|
|
|
|
import traceback
|
2020-07-01 15:56:18 +02:00
|
|
|
import shlex
|
|
|
|
|
2022-05-26 02:09:19 +02:00
|
|
|
from qemu.machine import QEMUMachine
|
|
|
|
from qemu.utils import get_info_usernet_hostfwd_port, kvm_available
|
|
|
|
|
2020-07-01 15:56:18 +02:00
|
|
|
SSH_KEY_FILE = os.path.join(os.path.dirname(__file__),
|
|
|
|
"..", "keys", "id_rsa")
|
|
|
|
SSH_PUB_KEY_FILE = os.path.join(os.path.dirname(__file__),
|
|
|
|
"..", "keys", "id_rsa.pub")
|
|
|
|
|
|
|
|
# This is the standard configuration.
|
|
|
|
# Any or all of these can be overridden by
|
|
|
|
# passing in a config argument to the VM constructor.
|
|
|
|
DEFAULT_CONFIG = {
|
|
|
|
'cpu' : "max",
|
|
|
|
'machine' : 'pc',
|
|
|
|
'guest_user' : "qemu",
|
|
|
|
'guest_pass' : "qemupass",
|
2020-10-27 11:21:21 +01:00
|
|
|
'root_user' : "root",
|
2020-07-01 15:56:18 +02:00
|
|
|
'root_pass' : "qemupass",
|
|
|
|
'ssh_key_file' : SSH_KEY_FILE,
|
|
|
|
'ssh_pub_key_file': SSH_PUB_KEY_FILE,
|
|
|
|
'memory' : "4G",
|
|
|
|
'extra_args' : [],
|
|
|
|
'qemu_args' : "",
|
|
|
|
'dns' : "",
|
|
|
|
'ssh_port' : 0,
|
|
|
|
'install_cmds' : "",
|
|
|
|
'boot_dev_type' : "block",
|
|
|
|
'ssh_timeout' : 1,
|
|
|
|
}
|
|
|
|
BOOT_DEVICE = {
|
|
|
|
'block' : "-drive file={},if=none,id=drive0,cache=writeback "\
|
|
|
|
"-device virtio-blk,drive=drive0,bootindex=0",
|
|
|
|
'scsi' : "-device virtio-scsi-device,id=scsi "\
|
|
|
|
"-drive file={},format=raw,if=none,id=hd0 "\
|
|
|
|
"-device scsi-hd,drive=hd0,bootindex=0",
|
|
|
|
}
|
2017-09-05 04:11:53 +02:00
|
|
|
class BaseVM(object):
|
|
|
|
|
2019-06-17 06:38:48 +02:00
|
|
|
envvars = [
|
|
|
|
"https_proxy",
|
|
|
|
"http_proxy",
|
|
|
|
"ftp_proxy",
|
|
|
|
"no_proxy",
|
|
|
|
]
|
|
|
|
|
2017-09-05 04:11:53 +02:00
|
|
|
# The script to run in the guest that builds QEMU
|
|
|
|
BUILD_SCRIPT = ""
|
|
|
|
# The guest name, to be overridden by subclasses
|
|
|
|
name = "#base"
|
2018-10-13 02:40:30 +02:00
|
|
|
# The guest architecture, to be overridden by subclasses
|
|
|
|
arch = "#arch"
|
2019-06-17 06:38:51 +02:00
|
|
|
# command to halt the guest, can be overridden by subclasses
|
|
|
|
poweroff = "poweroff"
|
2020-07-24 08:45:09 +02:00
|
|
|
# Time to wait for shutdown to finish.
|
|
|
|
shutdown_timeout_default = 30
|
2019-10-18 20:17:04 +02:00
|
|
|
# enable IPv6 networking
|
|
|
|
ipv6 = True
|
2020-07-01 15:56:18 +02:00
|
|
|
# This is the timeout on the wait for console bytes.
|
|
|
|
socket_timeout = 120
|
2020-03-03 16:06:16 +01:00
|
|
|
# Scale up some timeouts under TCG.
|
|
|
|
# 4 is arbitrary, but greater than 2,
|
|
|
|
# since we found we need to wait more than twice as long.
|
2020-07-24 08:45:09 +02:00
|
|
|
tcg_timeout_multiplier = 4
|
2020-07-01 15:56:18 +02:00
|
|
|
def __init__(self, args, config=None):
|
2017-09-05 04:11:53 +02:00
|
|
|
self._guest = None
|
2020-07-01 15:56:17 +02:00
|
|
|
self._genisoimage = args.genisoimage
|
|
|
|
self._build_path = args.build_path
|
2020-07-01 15:56:21 +02:00
|
|
|
self._efi_aarch64 = args.efi_aarch64
|
2021-06-02 12:35:27 +02:00
|
|
|
self._source_path = args.source_path
|
2020-07-01 15:56:18 +02:00
|
|
|
# Allow input config to override defaults.
|
|
|
|
self._config = DEFAULT_CONFIG.copy()
|
2022-07-08 17:34:59 +02:00
|
|
|
|
|
|
|
# 1GB per core, minimum of 4. This is only a default.
|
|
|
|
mem = max(4, args.jobs)
|
|
|
|
self._config['memory'] = f"{mem}G"
|
|
|
|
|
2020-07-01 15:56:18 +02:00
|
|
|
if config != None:
|
|
|
|
self._config.update(config)
|
|
|
|
self.validate_ssh_keys()
|
2017-09-05 04:11:53 +02:00
|
|
|
self._tmpdir = os.path.realpath(tempfile.mkdtemp(prefix="vm-test-",
|
|
|
|
suffix=".tmp",
|
|
|
|
dir="."))
|
|
|
|
atexit.register(shutil.rmtree, self._tmpdir)
|
2020-07-01 15:56:18 +02:00
|
|
|
# Copy the key files to a temporary directory.
|
|
|
|
# Also chmod the key file to agree with ssh requirements.
|
|
|
|
self._config['ssh_key'] = \
|
|
|
|
open(self._config['ssh_key_file']).read().rstrip()
|
|
|
|
self._config['ssh_pub_key'] = \
|
|
|
|
open(self._config['ssh_pub_key_file']).read().rstrip()
|
|
|
|
self._ssh_tmp_key_file = os.path.join(self._tmpdir, "id_rsa")
|
|
|
|
open(self._ssh_tmp_key_file, "w").write(self._config['ssh_key'])
|
|
|
|
subprocess.check_call(["chmod", "600", self._ssh_tmp_key_file])
|
|
|
|
|
|
|
|
self._ssh_tmp_pub_key_file = os.path.join(self._tmpdir, "id_rsa.pub")
|
|
|
|
open(self._ssh_tmp_pub_key_file,
|
|
|
|
"w").write(self._config['ssh_pub_key'])
|
2017-09-05 04:11:53 +02:00
|
|
|
|
2020-07-01 15:56:17 +02:00
|
|
|
self.debug = args.debug
|
2020-07-01 15:56:25 +02:00
|
|
|
self._console_log_path = None
|
|
|
|
if args.log_console:
|
|
|
|
self._console_log_path = \
|
|
|
|
os.path.join(os.path.expanduser("~/.cache/qemu-vm"),
|
|
|
|
"{}.install.log".format(self.name))
|
2017-09-05 04:11:53 +02:00
|
|
|
self._stderr = sys.stderr
|
|
|
|
self._devnull = open(os.devnull, "w")
|
|
|
|
if self.debug:
|
|
|
|
self._stdout = sys.stdout
|
|
|
|
else:
|
|
|
|
self._stdout = self._devnull
|
2020-07-01 15:56:18 +02:00
|
|
|
netdev = "user,id=vnet,hostfwd=:127.0.0.1:{}-:22"
|
2017-09-05 04:11:53 +02:00
|
|
|
self._args = [ \
|
2020-07-01 15:56:18 +02:00
|
|
|
"-nodefaults", "-m", self._config['memory'],
|
|
|
|
"-cpu", self._config['cpu'],
|
|
|
|
"-netdev",
|
|
|
|
netdev.format(self._config['ssh_port']) +
|
|
|
|
(",ipv6=no" if not self.ipv6 else "") +
|
|
|
|
(",dns=" + self._config['dns'] if self._config['dns'] else ""),
|
2017-09-05 04:11:53 +02:00
|
|
|
"-device", "virtio-net-pci,netdev=vnet",
|
2019-06-17 06:38:53 +02:00
|
|
|
"-vnc", "127.0.0.1:0,to=20"]
|
2020-07-01 15:56:17 +02:00
|
|
|
if args.jobs and args.jobs > 1:
|
|
|
|
self._args += ["-smp", "%d" % args.jobs]
|
2018-10-13 02:40:32 +02:00
|
|
|
if kvm_available(self.arch):
|
2020-07-24 08:45:09 +02:00
|
|
|
self._shutdown_timeout = self.shutdown_timeout_default
|
2017-09-05 04:11:53 +02:00
|
|
|
self._args += ["-enable-kvm"]
|
|
|
|
else:
|
|
|
|
logging.info("KVM not available, not using -enable-kvm")
|
2020-07-24 08:45:09 +02:00
|
|
|
self._shutdown_timeout = \
|
|
|
|
self.shutdown_timeout_default * self.tcg_timeout_multiplier
|
2017-09-05 04:11:53 +02:00
|
|
|
self._data_args = []
|
|
|
|
|
2020-07-01 15:56:18 +02:00
|
|
|
if self._config['qemu_args'] != None:
|
|
|
|
qemu_args = self._config['qemu_args']
|
|
|
|
qemu_args = qemu_args.replace('\n',' ').replace('\r','')
|
|
|
|
# shlex groups quoted arguments together
|
|
|
|
# we need this to keep the quoted args together for when
|
|
|
|
# the QEMU command is issued later.
|
|
|
|
args = shlex.split(qemu_args)
|
|
|
|
self._config['extra_args'] = []
|
|
|
|
for arg in args:
|
|
|
|
if arg:
|
|
|
|
# Preserve quotes around arguments.
|
|
|
|
# shlex above takes them out, so add them in.
|
|
|
|
if " " in arg:
|
|
|
|
arg = '"{}"'.format(arg)
|
|
|
|
self._config['extra_args'].append(arg)
|
|
|
|
|
|
|
|
def validate_ssh_keys(self):
|
|
|
|
"""Check to see if the ssh key files exist."""
|
|
|
|
if 'ssh_key_file' not in self._config or\
|
|
|
|
not os.path.exists(self._config['ssh_key_file']):
|
|
|
|
raise Exception("ssh key file not found.")
|
|
|
|
if 'ssh_pub_key_file' not in self._config or\
|
|
|
|
not os.path.exists(self._config['ssh_pub_key_file']):
|
|
|
|
raise Exception("ssh pub key file not found.")
|
|
|
|
|
|
|
|
def wait_boot(self, wait_string=None):
|
|
|
|
"""Wait for the standard string we expect
|
|
|
|
on completion of a normal boot.
|
|
|
|
The user can also choose to override with an
|
|
|
|
alternate string to wait for."""
|
|
|
|
if wait_string is None:
|
|
|
|
if self.login_prompt is None:
|
|
|
|
raise Exception("self.login_prompt not defined")
|
|
|
|
wait_string = self.login_prompt
|
|
|
|
# Intentionally bump up the default timeout under TCG,
|
|
|
|
# since the console wait below takes longer.
|
|
|
|
timeout = self.socket_timeout
|
|
|
|
if not kvm_available(self.arch):
|
|
|
|
timeout *= 8
|
|
|
|
self.console_init(timeout=timeout)
|
|
|
|
self.console_wait(wait_string)
|
|
|
|
|
2019-11-04 18:31:44 +01:00
|
|
|
def _download_with_cache(self, url, sha256sum=None, sha512sum=None):
|
2017-09-05 04:11:53 +02:00
|
|
|
def check_sha256sum(fname):
|
|
|
|
if not sha256sum:
|
|
|
|
return True
|
|
|
|
checksum = subprocess.check_output(["sha256sum", fname]).split()[0]
|
2019-05-20 14:47:04 +02:00
|
|
|
return sha256sum == checksum.decode("utf-8")
|
2017-09-05 04:11:53 +02:00
|
|
|
|
2019-11-04 18:31:44 +01:00
|
|
|
def check_sha512sum(fname):
|
|
|
|
if not sha512sum:
|
|
|
|
return True
|
|
|
|
checksum = subprocess.check_output(["sha512sum", fname]).split()[0]
|
|
|
|
return sha512sum == checksum.decode("utf-8")
|
|
|
|
|
2017-09-05 04:11:53 +02:00
|
|
|
cache_dir = os.path.expanduser("~/.cache/qemu-vm/download")
|
|
|
|
if not os.path.exists(cache_dir):
|
|
|
|
os.makedirs(cache_dir)
|
2019-05-20 14:47:04 +02:00
|
|
|
fname = os.path.join(cache_dir,
|
|
|
|
hashlib.sha1(url.encode("utf-8")).hexdigest())
|
2019-11-04 18:31:44 +01:00
|
|
|
if os.path.exists(fname) and check_sha256sum(fname) and check_sha512sum(fname):
|
2017-09-05 04:11:53 +02:00
|
|
|
return fname
|
|
|
|
logging.debug("Downloading %s to %s...", url, fname)
|
|
|
|
subprocess.check_call(["wget", "-c", url, "-O", fname + ".download"],
|
|
|
|
stdout=self._stdout, stderr=self._stderr)
|
|
|
|
os.rename(fname + ".download", fname)
|
|
|
|
return fname
|
|
|
|
|
2019-06-17 06:38:49 +02:00
|
|
|
def _ssh_do(self, user, cmd, check):
|
2020-03-03 16:06:15 +01:00
|
|
|
ssh_cmd = ["ssh",
|
|
|
|
"-t",
|
2017-09-05 04:11:53 +02:00
|
|
|
"-o", "StrictHostKeyChecking=no",
|
|
|
|
"-o", "UserKnownHostsFile=" + os.devnull,
|
2020-07-01 15:56:18 +02:00
|
|
|
"-o",
|
|
|
|
"ConnectTimeout={}".format(self._config["ssh_timeout"]),
|
2021-04-12 06:46:36 +02:00
|
|
|
"-p", str(self.ssh_port), "-i", self._ssh_tmp_key_file]
|
2020-03-03 16:06:15 +01:00
|
|
|
# If not in debug mode, set ssh to quiet mode to
|
|
|
|
# avoid printing the results of commands.
|
|
|
|
if not self.debug:
|
|
|
|
ssh_cmd.append("-q")
|
2019-06-17 06:38:48 +02:00
|
|
|
for var in self.envvars:
|
|
|
|
ssh_cmd += ['-o', "SendEnv=%s" % var ]
|
2017-09-05 04:11:53 +02:00
|
|
|
assert not isinstance(cmd, str)
|
|
|
|
ssh_cmd += ["%s@127.0.0.1" % user] + list(cmd)
|
|
|
|
logging.debug("ssh_cmd: %s", " ".join(ssh_cmd))
|
2018-03-22 04:47:53 +01:00
|
|
|
r = subprocess.call(ssh_cmd)
|
2017-09-05 04:11:53 +02:00
|
|
|
if check and r != 0:
|
|
|
|
raise Exception("SSH command failed: %s" % cmd)
|
|
|
|
return r
|
|
|
|
|
|
|
|
def ssh(self, *cmd):
|
2020-07-01 15:56:23 +02:00
|
|
|
return self._ssh_do(self._config["guest_user"], cmd, False)
|
2017-09-05 04:11:53 +02:00
|
|
|
|
|
|
|
def ssh_root(self, *cmd):
|
2020-10-27 11:21:21 +01:00
|
|
|
return self._ssh_do(self._config["root_user"], cmd, False)
|
2017-09-05 04:11:53 +02:00
|
|
|
|
|
|
|
def ssh_check(self, *cmd):
|
2020-07-01 15:56:23 +02:00
|
|
|
self._ssh_do(self._config["guest_user"], cmd, True)
|
2017-09-05 04:11:53 +02:00
|
|
|
|
|
|
|
def ssh_root_check(self, *cmd):
|
2020-10-27 11:21:21 +01:00
|
|
|
self._ssh_do(self._config["root_user"], cmd, True)
|
2017-09-05 04:11:53 +02:00
|
|
|
|
|
|
|
def build_image(self, img):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2019-11-14 14:42:46 +01:00
|
|
|
def exec_qemu_img(self, *args):
|
|
|
|
cmd = [os.environ.get("QEMU_IMG", "qemu-img")]
|
|
|
|
cmd.extend(list(args))
|
|
|
|
subprocess.check_call(cmd)
|
|
|
|
|
2017-09-05 04:11:53 +02:00
|
|
|
def add_source_dir(self, src_dir):
|
2019-05-20 14:47:04 +02:00
|
|
|
name = "data-" + hashlib.sha1(src_dir.encode("utf-8")).hexdigest()[:5]
|
2017-09-05 04:11:53 +02:00
|
|
|
tarfile = os.path.join(self._tmpdir, name + ".tar")
|
|
|
|
logging.debug("Creating archive %s for src_dir dir: %s", tarfile, src_dir)
|
|
|
|
subprocess.check_call(["./scripts/archive-source.sh", tarfile],
|
|
|
|
cwd=src_dir, stdin=self._devnull,
|
|
|
|
stdout=self._stdout, stderr=self._stderr)
|
|
|
|
self._data_args += ["-drive",
|
|
|
|
"file=%s,if=none,id=%s,cache=writeback,format=raw" % \
|
|
|
|
(tarfile, name),
|
|
|
|
"-device",
|
|
|
|
"virtio-blk,drive=%s,serial=%s,bootindex=1" % (name, name)]
|
|
|
|
|
|
|
|
def boot(self, img, extra_args=[]):
|
2020-07-01 15:56:18 +02:00
|
|
|
boot_dev = BOOT_DEVICE[self._config['boot_dev_type']]
|
|
|
|
boot_params = boot_dev.format(img)
|
|
|
|
args = self._args + boot_params.split(' ')
|
|
|
|
args += self._data_args + extra_args + self._config['extra_args']
|
2017-09-05 04:11:53 +02:00
|
|
|
logging.debug("QEMU args: %s", " ".join(args))
|
2020-05-29 22:34:51 +02:00
|
|
|
qemu_path = get_qemu_path(self.arch, self._build_path)
|
2020-07-01 15:56:25 +02:00
|
|
|
|
|
|
|
# Since console_log_path is only set when the user provides the
|
|
|
|
# log_console option, we will set drain_console=True so the
|
|
|
|
# console is always drained.
|
|
|
|
guest = QEMUMachine(binary=qemu_path, args=args,
|
|
|
|
console_log=self._console_log_path,
|
|
|
|
drain_console=True)
|
2020-07-01 15:56:18 +02:00
|
|
|
guest.set_machine(self._config['machine'])
|
2019-06-17 06:38:53 +02:00
|
|
|
guest.set_console()
|
2017-09-05 04:11:53 +02:00
|
|
|
try:
|
|
|
|
guest.launch()
|
|
|
|
except:
|
|
|
|
logging.error("Failed to launch QEMU, command line:")
|
2020-05-29 22:34:51 +02:00
|
|
|
logging.error(" ".join([qemu_path] + args))
|
2017-09-05 04:11:53 +02:00
|
|
|
logging.error("Log:")
|
|
|
|
logging.error(guest.get_log())
|
|
|
|
logging.error("QEMU version >= 2.10 is required")
|
|
|
|
raise
|
|
|
|
atexit.register(self.shutdown)
|
|
|
|
self._guest = guest
|
2020-07-01 15:56:25 +02:00
|
|
|
# Init console so we can start consuming the chars.
|
|
|
|
self.console_init()
|
2017-09-05 04:11:53 +02:00
|
|
|
usernet_info = guest.qmp("human-monitor-command",
|
2021-04-12 06:46:36 +02:00
|
|
|
command_line="info usernet").get("return")
|
|
|
|
self.ssh_port = get_info_usernet_hostfwd_port(usernet_info)
|
2017-09-05 04:11:53 +02:00
|
|
|
if not self.ssh_port:
|
|
|
|
raise Exception("Cannot find ssh port from 'info usernet':\n%s" % \
|
|
|
|
usernet_info)
|
|
|
|
|
2020-07-01 15:56:25 +02:00
|
|
|
def console_init(self, timeout = None):
|
|
|
|
if timeout == None:
|
|
|
|
timeout = self.socket_timeout
|
2019-06-17 06:38:53 +02:00
|
|
|
vm = self._guest
|
|
|
|
vm.console_socket.settimeout(timeout)
|
2020-03-23 17:15:04 +01:00
|
|
|
self.console_raw_path = os.path.join(vm._temp_dir,
|
|
|
|
vm._name + "-console.raw")
|
|
|
|
self.console_raw_file = open(self.console_raw_path, 'wb')
|
2019-06-17 06:38:53 +02:00
|
|
|
|
|
|
|
def console_log(self, text):
|
|
|
|
for line in re.split("[\r\n]", text):
|
|
|
|
# filter out terminal escape sequences
|
|
|
|
line = re.sub("\x1b\[[0-9;?]*[a-zA-Z]", "", line)
|
|
|
|
line = re.sub("\x1b\([0-9;?]*[a-zA-Z]", "", line)
|
|
|
|
# replace unprintable chars
|
|
|
|
line = re.sub("\x1b", "<esc>", line)
|
|
|
|
line = re.sub("[\x00-\x1f]", ".", line)
|
|
|
|
line = re.sub("[\x80-\xff]", ".", line)
|
|
|
|
if line == "":
|
|
|
|
continue
|
|
|
|
# log console line
|
|
|
|
sys.stderr.write("con recv: %s\n" % line)
|
|
|
|
|
2019-06-17 06:38:57 +02:00
|
|
|
def console_wait(self, expect, expectalt = None):
|
2019-06-17 06:38:53 +02:00
|
|
|
vm = self._guest
|
|
|
|
output = ""
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
chars = vm.console_socket.recv(1)
|
2020-03-23 17:15:04 +01:00
|
|
|
if self.console_raw_file:
|
|
|
|
self.console_raw_file.write(chars)
|
|
|
|
self.console_raw_file.flush()
|
2019-06-17 06:38:53 +02:00
|
|
|
except socket.timeout:
|
|
|
|
sys.stderr.write("console: *** read timeout ***\n")
|
|
|
|
sys.stderr.write("console: waiting for: '%s'\n" % expect)
|
2019-06-17 06:38:57 +02:00
|
|
|
if not expectalt is None:
|
|
|
|
sys.stderr.write("console: waiting for: '%s' (alt)\n" % expectalt)
|
2019-06-17 06:38:53 +02:00
|
|
|
sys.stderr.write("console: line buffer:\n")
|
|
|
|
sys.stderr.write("\n")
|
|
|
|
self.console_log(output.rstrip())
|
|
|
|
sys.stderr.write("\n")
|
|
|
|
raise
|
|
|
|
output += chars.decode("latin1")
|
|
|
|
if expect in output:
|
|
|
|
break
|
2019-06-17 06:38:57 +02:00
|
|
|
if not expectalt is None and expectalt in output:
|
|
|
|
break
|
2019-06-17 06:38:53 +02:00
|
|
|
if "\r" in output or "\n" in output:
|
|
|
|
lines = re.split("[\r\n]", output)
|
|
|
|
output = lines.pop()
|
|
|
|
if self.debug:
|
|
|
|
self.console_log("\n".join(lines))
|
|
|
|
if self.debug:
|
|
|
|
self.console_log(output)
|
2019-06-17 06:38:57 +02:00
|
|
|
if not expectalt is None and expectalt in output:
|
|
|
|
return False
|
|
|
|
return True
|
2019-06-17 06:38:53 +02:00
|
|
|
|
2019-10-31 09:53:04 +01:00
|
|
|
def console_consume(self):
|
|
|
|
vm = self._guest
|
|
|
|
output = ""
|
|
|
|
vm.console_socket.setblocking(0)
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
chars = vm.console_socket.recv(1)
|
|
|
|
except:
|
|
|
|
break
|
|
|
|
output += chars.decode("latin1")
|
|
|
|
if "\r" in output or "\n" in output:
|
|
|
|
lines = re.split("[\r\n]", output)
|
|
|
|
output = lines.pop()
|
|
|
|
if self.debug:
|
|
|
|
self.console_log("\n".join(lines))
|
|
|
|
if self.debug:
|
|
|
|
self.console_log(output)
|
|
|
|
vm.console_socket.setblocking(1)
|
|
|
|
|
2019-06-17 06:38:53 +02:00
|
|
|
def console_send(self, command):
|
|
|
|
vm = self._guest
|
|
|
|
if self.debug:
|
|
|
|
logline = re.sub("\n", "<enter>", command)
|
|
|
|
logline = re.sub("[\x00-\x1f]", ".", logline)
|
|
|
|
sys.stderr.write("con send: %s\n" % logline)
|
|
|
|
for char in list(command):
|
|
|
|
vm.console_socket.send(char.encode("utf-8"))
|
|
|
|
time.sleep(0.01)
|
|
|
|
|
|
|
|
def console_wait_send(self, wait, command):
|
|
|
|
self.console_wait(wait)
|
|
|
|
self.console_send(command)
|
|
|
|
|
|
|
|
def console_ssh_init(self, prompt, user, pw):
|
2020-07-01 15:56:18 +02:00
|
|
|
sshkey_cmd = "echo '%s' > .ssh/authorized_keys\n" \
|
|
|
|
% self._config['ssh_pub_key'].rstrip()
|
2019-06-17 06:38:53 +02:00
|
|
|
self.console_wait_send("login:", "%s\n" % user)
|
|
|
|
self.console_wait_send("Password:", "%s\n" % pw)
|
|
|
|
self.console_wait_send(prompt, "mkdir .ssh\n")
|
|
|
|
self.console_wait_send(prompt, sshkey_cmd)
|
|
|
|
self.console_wait_send(prompt, "chmod 755 .ssh\n")
|
|
|
|
self.console_wait_send(prompt, "chmod 644 .ssh/authorized_keys\n")
|
|
|
|
|
|
|
|
def console_sshd_config(self, prompt):
|
|
|
|
self.console_wait(prompt)
|
|
|
|
self.console_send("echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config\n")
|
|
|
|
for var in self.envvars:
|
|
|
|
self.console_wait(prompt)
|
|
|
|
self.console_send("echo 'AcceptEnv %s' >> /etc/ssh/sshd_config\n" % var)
|
|
|
|
|
|
|
|
def print_step(self, text):
|
|
|
|
sys.stderr.write("### %s ...\n" % text)
|
|
|
|
|
2020-05-29 22:34:52 +02:00
|
|
|
def wait_ssh(self, wait_root=False, seconds=300, cmd="exit 0"):
|
2020-03-03 16:06:16 +01:00
|
|
|
# Allow more time for VM to boot under TCG.
|
|
|
|
if not kvm_available(self.arch):
|
2020-07-24 08:45:09 +02:00
|
|
|
seconds *= self.tcg_timeout_multiplier
|
2017-09-05 04:11:53 +02:00
|
|
|
starttime = datetime.datetime.now()
|
2018-10-13 02:40:29 +02:00
|
|
|
endtime = starttime + datetime.timedelta(seconds=seconds)
|
2020-05-29 22:34:52 +02:00
|
|
|
cmd_success = False
|
2018-10-13 02:40:29 +02:00
|
|
|
while datetime.datetime.now() < endtime:
|
2020-05-29 22:34:52 +02:00
|
|
|
if wait_root and self.ssh_root(cmd) == 0:
|
|
|
|
cmd_success = True
|
2020-03-03 16:06:17 +01:00
|
|
|
break
|
2020-05-29 22:34:52 +02:00
|
|
|
elif self.ssh(cmd) == 0:
|
|
|
|
cmd_success = True
|
2017-09-05 04:11:53 +02:00
|
|
|
break
|
2018-10-13 02:40:29 +02:00
|
|
|
seconds = (endtime - datetime.datetime.now()).total_seconds()
|
|
|
|
logging.debug("%ds before timeout", seconds)
|
2017-09-05 04:11:53 +02:00
|
|
|
time.sleep(1)
|
2020-05-29 22:34:52 +02:00
|
|
|
if not cmd_success:
|
2017-09-05 04:11:53 +02:00
|
|
|
raise Exception("Timeout while waiting for guest ssh")
|
|
|
|
|
|
|
|
def shutdown(self):
|
2020-07-24 08:45:09 +02:00
|
|
|
self._guest.shutdown(timeout=self._shutdown_timeout)
|
2017-09-05 04:11:53 +02:00
|
|
|
|
|
|
|
def wait(self):
|
2020-07-24 08:45:09 +02:00
|
|
|
self._guest.wait(timeout=self._shutdown_timeout)
|
2017-09-05 04:11:53 +02:00
|
|
|
|
2019-06-17 06:38:51 +02:00
|
|
|
def graceful_shutdown(self):
|
|
|
|
self.ssh_root(self.poweroff)
|
2020-07-24 08:45:09 +02:00
|
|
|
self._guest.wait(timeout=self._shutdown_timeout)
|
2019-06-17 06:38:51 +02:00
|
|
|
|
2017-09-05 04:11:53 +02:00
|
|
|
def qmp(self, *args, **kwargs):
|
|
|
|
return self._guest.qmp(*args, **kwargs)
|
|
|
|
|
2020-03-03 16:06:18 +01:00
|
|
|
def gen_cloud_init_iso(self):
|
|
|
|
cidir = self._tmpdir
|
|
|
|
mdata = open(os.path.join(cidir, "meta-data"), "w")
|
|
|
|
name = self.name.replace(".","-")
|
|
|
|
mdata.writelines(["instance-id: {}-vm-0\n".format(name),
|
|
|
|
"local-hostname: {}-guest\n".format(name)])
|
|
|
|
mdata.close()
|
|
|
|
udata = open(os.path.join(cidir, "user-data"), "w")
|
2020-07-01 15:56:18 +02:00
|
|
|
print("guest user:pw {}:{}".format(self._config['guest_user'],
|
|
|
|
self._config['guest_pass']))
|
2020-03-03 16:06:18 +01:00
|
|
|
udata.writelines(["#cloud-config\n",
|
|
|
|
"chpasswd:\n",
|
|
|
|
" list: |\n",
|
2020-07-01 15:56:18 +02:00
|
|
|
" root:%s\n" % self._config['root_pass'],
|
|
|
|
" %s:%s\n" % (self._config['guest_user'],
|
|
|
|
self._config['guest_pass']),
|
2020-03-03 16:06:18 +01:00
|
|
|
" expire: False\n",
|
|
|
|
"users:\n",
|
2020-07-01 15:56:18 +02:00
|
|
|
" - name: %s\n" % self._config['guest_user'],
|
2020-03-03 16:06:18 +01:00
|
|
|
" sudo: ALL=(ALL) NOPASSWD:ALL\n",
|
|
|
|
" ssh-authorized-keys:\n",
|
2020-07-01 15:56:18 +02:00
|
|
|
" - %s\n" % self._config['ssh_pub_key'],
|
2020-03-03 16:06:18 +01:00
|
|
|
" - name: root\n",
|
|
|
|
" ssh-authorized-keys:\n",
|
2020-07-01 15:56:18 +02:00
|
|
|
" - %s\n" % self._config['ssh_pub_key'],
|
2020-03-03 16:06:18 +01:00
|
|
|
"locale: en_US.UTF-8\n"])
|
|
|
|
proxy = os.environ.get("http_proxy")
|
|
|
|
if not proxy is None:
|
|
|
|
udata.writelines(["apt:\n",
|
|
|
|
" proxy: %s" % proxy])
|
|
|
|
udata.close()
|
2020-05-19 15:22:49 +02:00
|
|
|
subprocess.check_call([self._genisoimage, "-output", "cloud-init.iso",
|
2020-03-03 16:06:18 +01:00
|
|
|
"-volid", "cidata", "-joliet", "-rock",
|
|
|
|
"user-data", "meta-data"],
|
2020-05-19 15:22:49 +02:00
|
|
|
cwd=cidir,
|
|
|
|
stdin=self._devnull, stdout=self._stdout,
|
|
|
|
stderr=self._stdout)
|
2020-03-03 16:06:18 +01:00
|
|
|
return os.path.join(cidir, "cloud-init.iso")
|
|
|
|
|
2020-05-29 22:34:51 +02:00
|
|
|
def get_qemu_path(arch, build_path=None):
|
|
|
|
"""Fetch the path to the qemu binary."""
|
|
|
|
# If QEMU environment variable set, it takes precedence
|
|
|
|
if "QEMU" in os.environ:
|
|
|
|
qemu_path = os.environ["QEMU"]
|
|
|
|
elif build_path:
|
|
|
|
qemu_path = os.path.join(build_path, arch + "-softmmu")
|
|
|
|
qemu_path = os.path.join(qemu_path, "qemu-system-" + arch)
|
|
|
|
else:
|
|
|
|
# Default is to use system path for qemu.
|
|
|
|
qemu_path = "qemu-system-" + arch
|
|
|
|
return qemu_path
|
|
|
|
|
2020-07-01 15:56:21 +02:00
|
|
|
def get_qemu_version(qemu_path):
|
|
|
|
"""Get the version number from the current QEMU,
|
|
|
|
and return the major number."""
|
|
|
|
output = subprocess.check_output([qemu_path, '--version'])
|
|
|
|
version_line = output.decode("utf-8")
|
|
|
|
version_num = re.split(' |\(', version_line)[3].split('.')[0]
|
|
|
|
return int(version_num)
|
|
|
|
|
2020-07-01 15:56:19 +02:00
|
|
|
def parse_config(config, args):
|
|
|
|
""" Parse yaml config and populate our config structure.
|
|
|
|
The yaml config allows the user to override the
|
|
|
|
defaults for VM parameters. In many cases these
|
|
|
|
defaults can be overridden without rebuilding the VM."""
|
|
|
|
if args.config:
|
|
|
|
config_file = args.config
|
|
|
|
elif 'QEMU_CONFIG' in os.environ:
|
|
|
|
config_file = os.environ['QEMU_CONFIG']
|
|
|
|
else:
|
|
|
|
return config
|
|
|
|
if not os.path.exists(config_file):
|
|
|
|
raise Exception("config file {} does not exist".format(config_file))
|
|
|
|
# We gracefully handle importing the yaml module
|
|
|
|
# since it might not be installed.
|
|
|
|
# If we are here it means the user supplied a .yml file,
|
|
|
|
# so if the yaml module is not installed we will exit with error.
|
|
|
|
try:
|
|
|
|
import yaml
|
|
|
|
except ImportError:
|
|
|
|
print("The python3-yaml package is needed "\
|
|
|
|
"to support config.yaml files")
|
|
|
|
# Instead of raising an exception we exit to avoid
|
|
|
|
# a raft of messy (expected) errors to stdout.
|
|
|
|
exit(1)
|
|
|
|
with open(config_file) as f:
|
|
|
|
yaml_dict = yaml.safe_load(f)
|
|
|
|
|
|
|
|
if 'qemu-conf' in yaml_dict:
|
|
|
|
config.update(yaml_dict['qemu-conf'])
|
|
|
|
else:
|
|
|
|
raise Exception("config file {} is not valid"\
|
|
|
|
" missing qemu-conf".format(config_file))
|
|
|
|
return config
|
|
|
|
|
2018-10-13 02:40:33 +02:00
|
|
|
def parse_args(vmcls):
|
2018-10-13 02:40:27 +02:00
|
|
|
|
|
|
|
def get_default_jobs():
|
2020-07-01 15:56:27 +02:00
|
|
|
if multiprocessing.cpu_count() > 1:
|
|
|
|
if kvm_available(vmcls.arch):
|
|
|
|
return multiprocessing.cpu_count() // 2
|
|
|
|
elif os.uname().machine == "x86_64" and \
|
|
|
|
vmcls.arch in ["aarch64", "x86_64", "i386"]:
|
|
|
|
# MTTCG is available on these arches and we can allow
|
|
|
|
# more cores. but only up to a reasonable limit. User
|
|
|
|
# can always override these limits with --jobs.
|
|
|
|
return min(multiprocessing.cpu_count() // 2, 8)
|
2018-10-13 02:40:27 +02:00
|
|
|
else:
|
|
|
|
return 1
|
|
|
|
|
2020-07-01 15:56:26 +02:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
|
|
description="Utility for provisioning VMs and running builds",
|
|
|
|
epilog="""Remaining arguments are passed to the command.
|
|
|
|
Exit codes: 0 = success, 1 = command line error,
|
|
|
|
2 = environment initialization failed,
|
|
|
|
3 = test command failed""")
|
|
|
|
parser.add_argument("--debug", "-D", action="store_true",
|
|
|
|
help="enable debug output")
|
|
|
|
parser.add_argument("--image", "-i", default="%s.img" % vmcls.name,
|
|
|
|
help="image file name")
|
|
|
|
parser.add_argument("--force", "-f", action="store_true",
|
|
|
|
help="force build image even if image exists")
|
|
|
|
parser.add_argument("--jobs", type=int, default=get_default_jobs(),
|
|
|
|
help="number of virtual CPUs")
|
|
|
|
parser.add_argument("--verbose", "-V", action="store_true",
|
|
|
|
help="Pass V=1 to builds within the guest")
|
|
|
|
parser.add_argument("--build-image", "-b", action="store_true",
|
|
|
|
help="build image")
|
|
|
|
parser.add_argument("--build-qemu",
|
|
|
|
help="build QEMU from source in guest")
|
|
|
|
parser.add_argument("--build-target",
|
|
|
|
help="QEMU build target", default="check")
|
|
|
|
parser.add_argument("--build-path", default=None,
|
|
|
|
help="Path of build directory, "\
|
|
|
|
"for using build tree QEMU binary. ")
|
2021-06-02 12:35:27 +02:00
|
|
|
parser.add_argument("--source-path", default=None,
|
|
|
|
help="Path of source directory, "\
|
|
|
|
"for finding additional files. ")
|
2020-07-01 15:56:26 +02:00
|
|
|
parser.add_argument("--interactive", "-I", action="store_true",
|
|
|
|
help="Interactively run command")
|
|
|
|
parser.add_argument("--snapshot", "-s", action="store_true",
|
|
|
|
help="run tests with a snapshot")
|
|
|
|
parser.add_argument("--genisoimage", default="genisoimage",
|
|
|
|
help="iso imaging tool")
|
|
|
|
parser.add_argument("--config", "-c", default=None,
|
|
|
|
help="Provide config yaml for configuration. "\
|
|
|
|
"See config_example.yaml for example.")
|
|
|
|
parser.add_argument("--efi-aarch64",
|
|
|
|
default="/usr/share/qemu-efi-aarch64/QEMU_EFI.fd",
|
|
|
|
help="Path to efi image for aarch64 VMs.")
|
|
|
|
parser.add_argument("--log-console", action="store_true",
|
|
|
|
help="Log console to file.")
|
|
|
|
parser.add_argument("commands", nargs="*", help="""Remaining
|
|
|
|
commands after -- are passed to command inside the VM""")
|
|
|
|
|
2017-09-05 04:11:53 +02:00
|
|
|
return parser.parse_args()
|
|
|
|
|
2020-07-01 15:56:18 +02:00
|
|
|
def main(vmcls, config=None):
|
2017-09-05 04:11:53 +02:00
|
|
|
try:
|
2020-07-01 15:56:18 +02:00
|
|
|
if config == None:
|
|
|
|
config = DEFAULT_CONFIG
|
2020-07-01 15:56:26 +02:00
|
|
|
args = parse_args(vmcls)
|
|
|
|
if not args.commands and not args.build_qemu and not args.build_image:
|
2018-06-08 14:29:43 +02:00
|
|
|
print("Nothing to do?")
|
2017-09-05 04:11:53 +02:00
|
|
|
return 1
|
2020-07-01 15:56:19 +02:00
|
|
|
config = parse_config(config, args)
|
2017-09-27 15:03:37 +02:00
|
|
|
logging.basicConfig(level=(logging.DEBUG if args.debug
|
|
|
|
else logging.WARN))
|
2020-07-01 15:56:18 +02:00
|
|
|
vm = vmcls(args, config=config)
|
2017-09-05 04:11:53 +02:00
|
|
|
if args.build_image:
|
|
|
|
if os.path.exists(args.image) and not args.force:
|
|
|
|
sys.stderr.writelines(["Image file exists: %s\n" % args.image,
|
|
|
|
"Use --force option to overwrite\n"])
|
|
|
|
return 1
|
|
|
|
return vm.build_image(args.image)
|
|
|
|
if args.build_qemu:
|
|
|
|
vm.add_source_dir(args.build_qemu)
|
|
|
|
cmd = [vm.BUILD_SCRIPT.format(
|
2020-07-01 15:56:26 +02:00
|
|
|
configure_opts = " ".join(args.commands),
|
2019-05-20 14:47:04 +02:00
|
|
|
jobs=int(args.jobs),
|
2019-01-21 17:48:15 +01:00
|
|
|
target=args.build_target,
|
2018-08-03 10:52:28 +02:00
|
|
|
verbose = "V=1" if args.verbose else "")]
|
2017-09-05 04:11:53 +02:00
|
|
|
else:
|
2020-07-01 15:56:26 +02:00
|
|
|
cmd = args.commands
|
2018-07-12 03:28:26 +02:00
|
|
|
img = args.image
|
|
|
|
if args.snapshot:
|
|
|
|
img += ",snapshot=on"
|
|
|
|
vm.boot(img)
|
2017-09-05 04:11:53 +02:00
|
|
|
vm.wait_ssh()
|
|
|
|
except Exception as e:
|
|
|
|
if isinstance(e, SystemExit) and e.code == 0:
|
|
|
|
return 0
|
|
|
|
sys.stderr.write("Failed to prepare guest environment\n")
|
|
|
|
traceback.print_exc()
|
|
|
|
return 2
|
|
|
|
|
2019-06-17 06:38:51 +02:00
|
|
|
exitcode = 0
|
|
|
|
if vm.ssh(*cmd) != 0:
|
|
|
|
exitcode = 3
|
2019-11-12 16:08:15 +01:00
|
|
|
if args.interactive:
|
2019-06-17 06:38:49 +02:00
|
|
|
vm.ssh()
|
2019-06-17 06:38:51 +02:00
|
|
|
|
|
|
|
if not args.snapshot:
|
|
|
|
vm.graceful_shutdown()
|
|
|
|
|
|
|
|
return exitcode
|