basevm.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. #
  2. # VM testing base class
  3. #
  4. # Copyright 2017-2019 Red Hat Inc.
  5. #
  6. # Authors:
  7. # Fam Zheng <famz@redhat.com>
  8. # Gerd Hoffmann <kraxel@redhat.com>
  9. #
  10. # This code is licensed under the GPL version 2 or later. See
  11. # the COPYING file in the top-level directory.
  12. #
  13. import os
  14. import re
  15. import sys
  16. import socket
  17. import logging
  18. import time
  19. import datetime
  20. import subprocess
  21. import hashlib
  22. import argparse
  23. import atexit
  24. import tempfile
  25. import shutil
  26. import multiprocessing
  27. import traceback
  28. import shlex
  29. import json
  30. from qemu.machine import QEMUMachine
  31. from qemu.utils import get_info_usernet_hostfwd_port, kvm_available
  32. SSH_KEY_FILE = os.path.join(os.path.dirname(__file__),
  33. "..", "keys", "id_rsa")
  34. SSH_PUB_KEY_FILE = os.path.join(os.path.dirname(__file__),
  35. "..", "keys", "id_rsa.pub")
  36. # This is the standard configuration.
  37. # Any or all of these can be overridden by
  38. # passing in a config argument to the VM constructor.
  39. DEFAULT_CONFIG = {
  40. 'cpu' : "max",
  41. 'machine' : 'pc',
  42. 'guest_user' : "qemu",
  43. 'guest_pass' : "qemupass",
  44. 'root_user' : "root",
  45. 'root_pass' : "qemupass",
  46. 'ssh_key_file' : SSH_KEY_FILE,
  47. 'ssh_pub_key_file': SSH_PUB_KEY_FILE,
  48. 'memory' : "4G",
  49. 'extra_args' : [],
  50. 'qemu_args' : "",
  51. 'dns' : "",
  52. 'ssh_port' : 0,
  53. 'install_cmds' : "",
  54. 'boot_dev_type' : "block",
  55. 'ssh_timeout' : 1,
  56. }
  57. BOOT_DEVICE = {
  58. 'block' : "-drive file={},if=none,id=drive0,cache=writeback "\
  59. "-device virtio-blk,drive=drive0,bootindex=0",
  60. 'scsi' : "-device virtio-scsi-device,id=scsi "\
  61. "-drive file={},format=raw,if=none,id=hd0 "\
  62. "-device scsi-hd,drive=hd0,bootindex=0",
  63. }
  64. class BaseVM(object):
  65. envvars = [
  66. "https_proxy",
  67. "http_proxy",
  68. "ftp_proxy",
  69. "no_proxy",
  70. ]
  71. # The script to run in the guest that builds QEMU
  72. BUILD_SCRIPT = ""
  73. # The guest name, to be overridden by subclasses
  74. name = "#base"
  75. # The guest architecture, to be overridden by subclasses
  76. arch = "#arch"
  77. # command to halt the guest, can be overridden by subclasses
  78. poweroff = "poweroff"
  79. # Time to wait for shutdown to finish.
  80. shutdown_timeout_default = 90
  81. # enable IPv6 networking
  82. ipv6 = True
  83. # This is the timeout on the wait for console bytes.
  84. socket_timeout = 120
  85. # Scale up some timeouts under TCG.
  86. # 4 is arbitrary, but greater than 2,
  87. # since we found we need to wait more than twice as long.
  88. tcg_timeout_multiplier = 4
  89. def __init__(self, args, config=None):
  90. self._guest = None
  91. self._genisoimage = args.genisoimage
  92. self._build_path = args.build_path
  93. self._efi_aarch64 = args.efi_aarch64
  94. self._source_path = args.source_path
  95. # Allow input config to override defaults.
  96. self._config = DEFAULT_CONFIG.copy()
  97. # 1GB per core, minimum of 4. This is only a default.
  98. mem = max(4, args.jobs)
  99. self._config['memory'] = f"{mem}G"
  100. if config != None:
  101. self._config.update(config)
  102. self.validate_ssh_keys()
  103. self._tmpdir = os.path.realpath(tempfile.mkdtemp(prefix="vm-test-",
  104. suffix=".tmp",
  105. dir="."))
  106. atexit.register(shutil.rmtree, self._tmpdir)
  107. # Copy the key files to a temporary directory.
  108. # Also chmod the key file to agree with ssh requirements.
  109. self._config['ssh_key'] = \
  110. open(self._config['ssh_key_file']).read().rstrip()
  111. self._config['ssh_pub_key'] = \
  112. open(self._config['ssh_pub_key_file']).read().rstrip()
  113. self._ssh_tmp_key_file = os.path.join(self._tmpdir, "id_rsa")
  114. open(self._ssh_tmp_key_file, "w").write(self._config['ssh_key'])
  115. subprocess.check_call(["chmod", "600", self._ssh_tmp_key_file])
  116. self._ssh_tmp_pub_key_file = os.path.join(self._tmpdir, "id_rsa.pub")
  117. open(self._ssh_tmp_pub_key_file,
  118. "w").write(self._config['ssh_pub_key'])
  119. self.debug = args.debug
  120. self._console_log_path = None
  121. if args.log_console:
  122. self._console_log_path = \
  123. os.path.join(os.path.expanduser("~/.cache/qemu-vm"),
  124. "{}.install.log".format(self.name))
  125. self._stderr = sys.stderr
  126. self._devnull = open(os.devnull, "w")
  127. if self.debug:
  128. self._stdout = sys.stdout
  129. else:
  130. self._stdout = self._devnull
  131. netdev = "user,id=vnet,hostfwd=:127.0.0.1:{}-:22"
  132. self._args = [ \
  133. "-nodefaults", "-m", self._config['memory'],
  134. "-cpu", self._config['cpu'],
  135. "-netdev",
  136. netdev.format(self._config['ssh_port']) +
  137. (",ipv6=no" if not self.ipv6 else "") +
  138. (",dns=" + self._config['dns'] if self._config['dns'] else ""),
  139. "-device", "virtio-net-pci,netdev=vnet",
  140. "-vnc", "127.0.0.1:0,to=20"]
  141. if args.jobs and args.jobs > 1:
  142. self._args += ["-smp", "%d" % args.jobs]
  143. if kvm_available(self.arch):
  144. self._shutdown_timeout = self.shutdown_timeout_default
  145. self._args += ["-enable-kvm"]
  146. else:
  147. logging.info("KVM not available, not using -enable-kvm")
  148. self._shutdown_timeout = \
  149. self.shutdown_timeout_default * self.tcg_timeout_multiplier
  150. self._data_args = []
  151. if self._config['qemu_args'] != None:
  152. qemu_args = self._config['qemu_args']
  153. qemu_args = qemu_args.replace('\n',' ').replace('\r','')
  154. # shlex groups quoted arguments together
  155. # we need this to keep the quoted args together for when
  156. # the QEMU command is issued later.
  157. args = shlex.split(qemu_args)
  158. self._config['extra_args'] = []
  159. for arg in args:
  160. if arg:
  161. # Preserve quotes around arguments.
  162. # shlex above takes them out, so add them in.
  163. if " " in arg:
  164. arg = '"{}"'.format(arg)
  165. self._config['extra_args'].append(arg)
  166. def validate_ssh_keys(self):
  167. """Check to see if the ssh key files exist."""
  168. if 'ssh_key_file' not in self._config or\
  169. not os.path.exists(self._config['ssh_key_file']):
  170. raise Exception("ssh key file not found.")
  171. if 'ssh_pub_key_file' not in self._config or\
  172. not os.path.exists(self._config['ssh_pub_key_file']):
  173. raise Exception("ssh pub key file not found.")
  174. def wait_boot(self, wait_string=None):
  175. """Wait for the standard string we expect
  176. on completion of a normal boot.
  177. The user can also choose to override with an
  178. alternate string to wait for."""
  179. if wait_string is None:
  180. if self.login_prompt is None:
  181. raise Exception("self.login_prompt not defined")
  182. wait_string = self.login_prompt
  183. # Intentionally bump up the default timeout under TCG,
  184. # since the console wait below takes longer.
  185. timeout = self.socket_timeout
  186. if not kvm_available(self.arch):
  187. timeout *= 8
  188. self.console_init(timeout=timeout)
  189. self.console_wait(wait_string)
  190. def _download_with_cache(self, url, sha256sum=None, sha512sum=None):
  191. def check_sha256sum(fname):
  192. if not sha256sum:
  193. return True
  194. checksum = subprocess.check_output(["sha256sum", fname]).split()[0]
  195. return sha256sum == checksum.decode("utf-8")
  196. def check_sha512sum(fname):
  197. if not sha512sum:
  198. return True
  199. checksum = subprocess.check_output(["sha512sum", fname]).split()[0]
  200. return sha512sum == checksum.decode("utf-8")
  201. cache_dir = os.path.expanduser("~/.cache/qemu-vm/download")
  202. if not os.path.exists(cache_dir):
  203. os.makedirs(cache_dir)
  204. fname = os.path.join(cache_dir,
  205. hashlib.sha1(url.encode("utf-8")).hexdigest())
  206. if os.path.exists(fname) and check_sha256sum(fname) and check_sha512sum(fname):
  207. return fname
  208. logging.debug("Downloading %s to %s...", url, fname)
  209. subprocess.check_call(["wget", "-c", url, "-O", fname + ".download"],
  210. stdout=self._stdout, stderr=self._stderr)
  211. os.rename(fname + ".download", fname)
  212. return fname
  213. def _ssh_do(self, user, cmd, check):
  214. ssh_cmd = ["ssh",
  215. "-t",
  216. "-o", "StrictHostKeyChecking=no",
  217. "-o", "UserKnownHostsFile=" + os.devnull,
  218. "-o",
  219. "ConnectTimeout={}".format(self._config["ssh_timeout"]),
  220. "-p", str(self.ssh_port), "-i", self._ssh_tmp_key_file,
  221. "-o", "IdentitiesOnly=yes"]
  222. # If not in debug mode, set ssh to quiet mode to
  223. # avoid printing the results of commands.
  224. if not self.debug:
  225. ssh_cmd.append("-q")
  226. for var in self.envvars:
  227. ssh_cmd += ['-o', "SendEnv=%s" % var ]
  228. assert not isinstance(cmd, str)
  229. ssh_cmd += ["%s@127.0.0.1" % user] + list(cmd)
  230. logging.debug("ssh_cmd: %s", " ".join(ssh_cmd))
  231. r = subprocess.call(ssh_cmd)
  232. if check and r != 0:
  233. raise Exception("SSH command failed: %s" % cmd)
  234. return r
  235. def ssh(self, *cmd):
  236. return self._ssh_do(self._config["guest_user"], cmd, False)
  237. def ssh_root(self, *cmd):
  238. return self._ssh_do(self._config["root_user"], cmd, False)
  239. def ssh_check(self, *cmd):
  240. self._ssh_do(self._config["guest_user"], cmd, True)
  241. def ssh_root_check(self, *cmd):
  242. self._ssh_do(self._config["root_user"], cmd, True)
  243. def build_image(self, img):
  244. raise NotImplementedError
  245. def exec_qemu_img(self, *args):
  246. cmd = [os.environ.get("QEMU_IMG", "qemu-img")]
  247. cmd.extend(list(args))
  248. subprocess.check_call(cmd)
  249. def add_source_dir(self, src_dir):
  250. name = "data-" + hashlib.sha1(src_dir.encode("utf-8")).hexdigest()[:5]
  251. tarfile = os.path.join(self._tmpdir, name + ".tar")
  252. logging.debug("Creating archive %s for src_dir dir: %s", tarfile, src_dir)
  253. subprocess.check_call(["./scripts/archive-source.sh", tarfile],
  254. cwd=src_dir, stdin=self._devnull,
  255. stdout=self._stdout, stderr=self._stderr)
  256. self._data_args += ["-drive",
  257. "file=%s,if=none,id=%s,cache=writeback,format=raw" % \
  258. (tarfile, name),
  259. "-device",
  260. "virtio-blk,drive=%s,serial=%s,bootindex=1" % (name, name)]
  261. def boot(self, img, extra_args=[]):
  262. boot_dev = BOOT_DEVICE[self._config['boot_dev_type']]
  263. boot_params = boot_dev.format(img)
  264. args = self._args + boot_params.split(' ')
  265. args += self._data_args + extra_args + self._config['extra_args']
  266. logging.debug("QEMU args: %s", " ".join(args))
  267. qemu_path = get_qemu_path(self.arch, self._build_path)
  268. # Since console_log_path is only set when the user provides the
  269. # log_console option, we will set drain_console=True so the
  270. # console is always drained.
  271. guest = QEMUMachine(binary=qemu_path, args=args,
  272. console_log=self._console_log_path,
  273. drain_console=True)
  274. guest.set_machine(self._config['machine'])
  275. guest.set_console()
  276. try:
  277. guest.launch()
  278. except:
  279. logging.error("Failed to launch QEMU, command line:")
  280. logging.error(" ".join([qemu_path] + args))
  281. logging.error("Log:")
  282. logging.error(guest.get_log())
  283. logging.error("QEMU version >= 2.10 is required")
  284. raise
  285. atexit.register(self.shutdown)
  286. self._guest = guest
  287. # Init console so we can start consuming the chars.
  288. self.console_init()
  289. usernet_info = guest.cmd("human-monitor-command",
  290. command_line="info usernet")
  291. self.ssh_port = get_info_usernet_hostfwd_port(usernet_info)
  292. if not self.ssh_port:
  293. raise Exception("Cannot find ssh port from 'info usernet':\n%s" % \
  294. usernet_info)
  295. def console_init(self, timeout = None):
  296. if timeout == None:
  297. timeout = self.socket_timeout
  298. vm = self._guest
  299. vm.console_socket.settimeout(timeout)
  300. self.console_raw_path = os.path.join(vm._temp_dir,
  301. vm._name + "-console.raw")
  302. self.console_raw_file = open(self.console_raw_path, 'wb')
  303. def console_log(self, text):
  304. for line in re.split("[\r\n]", text):
  305. # filter out terminal escape sequences
  306. line = re.sub("\x1b\\[[0-9;?]*[a-zA-Z]", "", line)
  307. line = re.sub("\x1b\\([0-9;?]*[a-zA-Z]", "", line)
  308. # replace unprintable chars
  309. line = re.sub("\x1b", "<esc>", line)
  310. line = re.sub("[\x00-\x1f]", ".", line)
  311. line = re.sub("[\x80-\xff]", ".", line)
  312. if line == "":
  313. continue
  314. # log console line
  315. sys.stderr.write("con recv: %s\n" % line)
  316. def console_wait(self, expect, expectalt = None):
  317. vm = self._guest
  318. output = ""
  319. while True:
  320. try:
  321. chars = vm.console_socket.recv(1)
  322. if self.console_raw_file:
  323. self.console_raw_file.write(chars)
  324. self.console_raw_file.flush()
  325. except socket.timeout:
  326. sys.stderr.write("console: *** read timeout ***\n")
  327. sys.stderr.write("console: waiting for: '%s'\n" % expect)
  328. if not expectalt is None:
  329. sys.stderr.write("console: waiting for: '%s' (alt)\n" % expectalt)
  330. sys.stderr.write("console: line buffer:\n")
  331. sys.stderr.write("\n")
  332. self.console_log(output.rstrip())
  333. sys.stderr.write("\n")
  334. raise
  335. output += chars.decode("latin1")
  336. if expect in output:
  337. break
  338. if not expectalt is None and expectalt in output:
  339. break
  340. if "\r" in output or "\n" in output:
  341. lines = re.split("[\r\n]", output)
  342. output = lines.pop()
  343. if self.debug:
  344. self.console_log("\n".join(lines))
  345. if self.debug:
  346. self.console_log(output)
  347. if not expectalt is None and expectalt in output:
  348. return False
  349. return True
  350. def console_consume(self):
  351. vm = self._guest
  352. output = ""
  353. vm.console_socket.setblocking(0)
  354. while True:
  355. try:
  356. chars = vm.console_socket.recv(1)
  357. except:
  358. break
  359. output += chars.decode("latin1")
  360. if "\r" in output or "\n" in output:
  361. lines = re.split("[\r\n]", output)
  362. output = lines.pop()
  363. if self.debug:
  364. self.console_log("\n".join(lines))
  365. if self.debug:
  366. self.console_log(output)
  367. vm.console_socket.setblocking(1)
  368. def console_send(self, command):
  369. vm = self._guest
  370. if self.debug:
  371. logline = re.sub("\n", "<enter>", command)
  372. logline = re.sub("[\x00-\x1f]", ".", logline)
  373. sys.stderr.write("con send: %s\n" % logline)
  374. for char in list(command):
  375. vm.console_socket.send(char.encode("utf-8"))
  376. time.sleep(0.01)
  377. def console_wait_send(self, wait, command):
  378. self.console_wait(wait)
  379. self.console_send(command)
  380. def console_ssh_init(self, prompt, user, pw):
  381. sshkey_cmd = "echo '%s' > .ssh/authorized_keys\n" \
  382. % self._config['ssh_pub_key'].rstrip()
  383. self.console_wait_send("login:", "%s\n" % user)
  384. self.console_wait_send("Password:", "%s\n" % pw)
  385. self.console_wait_send(prompt, "mkdir .ssh\n")
  386. self.console_wait_send(prompt, sshkey_cmd)
  387. self.console_wait_send(prompt, "chmod 755 .ssh\n")
  388. self.console_wait_send(prompt, "chmod 644 .ssh/authorized_keys\n")
  389. def console_sshd_config(self, prompt):
  390. self.console_wait(prompt)
  391. self.console_send("echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config\n")
  392. self.console_wait(prompt)
  393. self.console_send("echo 'UseDNS no' >> /etc/ssh/sshd_config\n")
  394. for var in self.envvars:
  395. self.console_wait(prompt)
  396. self.console_send("echo 'AcceptEnv %s' >> /etc/ssh/sshd_config\n" % var)
  397. def print_step(self, text):
  398. sys.stderr.write("### %s ...\n" % text)
  399. def wait_ssh(self, wait_root=False, seconds=300, cmd="exit 0"):
  400. # Allow more time for VM to boot under TCG.
  401. if not kvm_available(self.arch):
  402. seconds *= self.tcg_timeout_multiplier
  403. starttime = datetime.datetime.now()
  404. endtime = starttime + datetime.timedelta(seconds=seconds)
  405. cmd_success = False
  406. while datetime.datetime.now() < endtime:
  407. if wait_root and self.ssh_root(cmd) == 0:
  408. cmd_success = True
  409. break
  410. elif self.ssh(cmd) == 0:
  411. cmd_success = True
  412. break
  413. seconds = (endtime - datetime.datetime.now()).total_seconds()
  414. logging.debug("%ds before timeout", seconds)
  415. time.sleep(1)
  416. if not cmd_success:
  417. raise Exception("Timeout while waiting for guest ssh")
  418. def shutdown(self):
  419. self._guest.shutdown(timeout=self._shutdown_timeout)
  420. def wait(self):
  421. self._guest.wait(timeout=self._shutdown_timeout)
  422. def graceful_shutdown(self):
  423. self.ssh_root(self.poweroff)
  424. self._guest.wait(timeout=self._shutdown_timeout)
  425. def qmp(self, *args, **kwargs):
  426. return self._guest.qmp(*args, **kwargs)
  427. def gen_cloud_init_iso(self):
  428. cidir = self._tmpdir
  429. mdata = open(os.path.join(cidir, "meta-data"), "w")
  430. name = self.name.replace(".","-")
  431. mdata.writelines(["instance-id: {}-vm-0\n".format(name),
  432. "local-hostname: {}-guest\n".format(name)])
  433. mdata.close()
  434. udata = open(os.path.join(cidir, "user-data"), "w")
  435. print("guest user:pw {}:{}".format(self._config['guest_user'],
  436. self._config['guest_pass']))
  437. udata.writelines(["#cloud-config\n",
  438. "chpasswd:\n",
  439. " list: |\n",
  440. " root:%s\n" % self._config['root_pass'],
  441. " %s:%s\n" % (self._config['guest_user'],
  442. self._config['guest_pass']),
  443. " expire: False\n",
  444. "users:\n",
  445. " - name: %s\n" % self._config['guest_user'],
  446. " sudo: ALL=(ALL) NOPASSWD:ALL\n",
  447. " ssh-authorized-keys:\n",
  448. " - %s\n" % self._config['ssh_pub_key'],
  449. " - name: root\n",
  450. " ssh-authorized-keys:\n",
  451. " - %s\n" % self._config['ssh_pub_key'],
  452. "locale: en_US.UTF-8\n"])
  453. proxy = os.environ.get("http_proxy")
  454. if not proxy is None:
  455. udata.writelines(["apt:\n",
  456. " proxy: %s" % proxy])
  457. udata.close()
  458. subprocess.check_call([self._genisoimage, "-output", "cloud-init.iso",
  459. "-volid", "cidata", "-joliet", "-rock",
  460. "user-data", "meta-data"],
  461. cwd=cidir,
  462. stdin=self._devnull, stdout=self._stdout,
  463. stderr=self._stdout)
  464. return os.path.join(cidir, "cloud-init.iso")
  465. def get_qemu_packages_from_lcitool_json(self, json_path=None):
  466. """Parse a lcitool variables json file and return the PKGS list."""
  467. if json_path is None:
  468. json_path = os.path.join(
  469. os.path.dirname(__file__), "generated", self.name + ".json"
  470. )
  471. with open(json_path, "r") as fh:
  472. return json.load(fh)["pkgs"]
  473. def get_qemu_path(arch, build_path=None):
  474. """Fetch the path to the qemu binary."""
  475. # If QEMU environment variable set, it takes precedence
  476. if "QEMU" in os.environ:
  477. qemu_path = os.environ["QEMU"]
  478. elif build_path:
  479. qemu_path = os.path.join(build_path, "qemu-system-" + arch)
  480. else:
  481. # Default is to use system path for qemu.
  482. qemu_path = "qemu-system-" + arch
  483. return qemu_path
  484. def get_qemu_version(qemu_path):
  485. """Get the version number from the current QEMU,
  486. and return the major number."""
  487. output = subprocess.check_output([qemu_path, '--version'])
  488. version_line = output.decode("utf-8")
  489. version_num = re.split(r' |\(', version_line)[3].split('.')[0]
  490. return int(version_num)
  491. def parse_config(config, args):
  492. """ Parse yaml config and populate our config structure.
  493. The yaml config allows the user to override the
  494. defaults for VM parameters. In many cases these
  495. defaults can be overridden without rebuilding the VM."""
  496. if args.config:
  497. config_file = args.config
  498. elif 'QEMU_CONFIG' in os.environ:
  499. config_file = os.environ['QEMU_CONFIG']
  500. else:
  501. return config
  502. if not os.path.exists(config_file):
  503. raise Exception("config file {} does not exist".format(config_file))
  504. # We gracefully handle importing the yaml module
  505. # since it might not be installed.
  506. # If we are here it means the user supplied a .yml file,
  507. # so if the yaml module is not installed we will exit with error.
  508. try:
  509. import yaml
  510. except ImportError:
  511. print("The python3-yaml package is needed "\
  512. "to support config.yaml files")
  513. # Instead of raising an exception we exit to avoid
  514. # a raft of messy (expected) errors to stdout.
  515. exit(1)
  516. with open(config_file) as f:
  517. yaml_dict = yaml.safe_load(f)
  518. if 'qemu-conf' in yaml_dict:
  519. config.update(yaml_dict['qemu-conf'])
  520. else:
  521. raise Exception("config file {} is not valid"\
  522. " missing qemu-conf".format(config_file))
  523. return config
  524. def parse_args(vmcls):
  525. def get_default_jobs():
  526. if multiprocessing.cpu_count() > 1:
  527. if kvm_available(vmcls.arch):
  528. return multiprocessing.cpu_count() // 2
  529. elif os.uname().machine == "x86_64" and \
  530. vmcls.arch in ["aarch64", "x86_64", "i386"]:
  531. # MTTCG is available on these arches and we can allow
  532. # more cores. but only up to a reasonable limit. User
  533. # can always override these limits with --jobs.
  534. return min(multiprocessing.cpu_count() // 2, 8)
  535. return 1
  536. parser = argparse.ArgumentParser(
  537. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  538. description="Utility for provisioning VMs and running builds",
  539. epilog="""Remaining arguments are passed to the command.
  540. Exit codes: 0 = success, 1 = command line error,
  541. 2 = environment initialization failed,
  542. 3 = test command failed""")
  543. parser.add_argument("--debug", "-D", action="store_true",
  544. help="enable debug output")
  545. parser.add_argument("--image", "-i", default="%s.img" % vmcls.name,
  546. help="image file name")
  547. parser.add_argument("--force", "-f", action="store_true",
  548. help="force build image even if image exists")
  549. parser.add_argument("--jobs", type=int, default=get_default_jobs(),
  550. help="number of virtual CPUs")
  551. parser.add_argument("--verbose", "-V", action="store_true",
  552. help="Pass V=1 to builds within the guest")
  553. parser.add_argument("--build-image", "-b", action="store_true",
  554. help="build image")
  555. parser.add_argument("--build-qemu",
  556. help="build QEMU from source in guest")
  557. parser.add_argument("--build-target",
  558. help="QEMU build target", default="all check")
  559. parser.add_argument("--build-path", default=None,
  560. help="Path of build directory, "\
  561. "for using build tree QEMU binary. ")
  562. parser.add_argument("--source-path", default=None,
  563. help="Path of source directory, "\
  564. "for finding additional files. ")
  565. int_ops = parser.add_mutually_exclusive_group()
  566. int_ops.add_argument("--interactive", "-I", action="store_true",
  567. help="Interactively run command")
  568. int_ops.add_argument("--interactive-root", action="store_true",
  569. help="Interactively run command as root")
  570. parser.add_argument("--snapshot", "-s", action="store_true",
  571. help="run tests with a snapshot")
  572. parser.add_argument("--genisoimage", default="genisoimage",
  573. help="iso imaging tool")
  574. parser.add_argument("--config", "-c", default=None,
  575. help="Provide config yaml for configuration. "\
  576. "See config_example.yaml for example.")
  577. parser.add_argument("--efi-aarch64",
  578. default="/usr/share/qemu-efi-aarch64/QEMU_EFI.fd",
  579. help="Path to efi image for aarch64 VMs.")
  580. parser.add_argument("--log-console", action="store_true",
  581. help="Log console to file.")
  582. parser.add_argument("commands", nargs="*", help="""Remaining
  583. commands after -- are passed to command inside the VM""")
  584. return parser.parse_args()
  585. def main(vmcls, config=None):
  586. try:
  587. if config == None:
  588. config = DEFAULT_CONFIG
  589. args = parse_args(vmcls)
  590. if not args.commands and not args.build_qemu and not args.build_image:
  591. print("Nothing to do?")
  592. return 1
  593. config = parse_config(config, args)
  594. logging.basicConfig(level=(logging.DEBUG if args.debug
  595. else logging.WARN))
  596. vm = vmcls(args, config=config)
  597. if args.build_image:
  598. if os.path.exists(args.image) and not args.force:
  599. sys.stderr.writelines(["Image file exists, skipping build: %s\n" % args.image,
  600. "Use --force option to overwrite\n"])
  601. return 0
  602. return vm.build_image(args.image)
  603. if args.build_qemu:
  604. vm.add_source_dir(args.build_qemu)
  605. cmd = [vm.BUILD_SCRIPT.format(
  606. configure_opts = " ".join(args.commands),
  607. jobs=int(args.jobs),
  608. target=args.build_target,
  609. verbose = "V=1" if args.verbose else "")]
  610. else:
  611. cmd = args.commands
  612. img = args.image
  613. if args.snapshot:
  614. img += ",snapshot=on"
  615. vm.boot(img)
  616. vm.wait_ssh()
  617. except Exception as e:
  618. if isinstance(e, SystemExit) and e.code == 0:
  619. return 0
  620. sys.stderr.write("Failed to prepare guest environment\n")
  621. traceback.print_exc()
  622. return 2
  623. exitcode = 0
  624. if vm.ssh(*cmd) != 0:
  625. exitcode = 3
  626. if args.interactive:
  627. vm.ssh()
  628. elif args.interactive_root:
  629. vm.ssh_root()
  630. if not args.snapshot:
  631. vm.graceful_shutdown()
  632. return exitcode