Mike Frysinger | e58c0e2 | 2017-10-04 15:43:30 -0400 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 2 | # Copyright 2016 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
Mike Frysinger | 666566c | 2016-09-21 00:00:21 -0400 | [diff] [blame] | 6 | """Script for VM Management.""" |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 7 | |
| 8 | from __future__ import print_function |
| 9 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 10 | import argparse |
Achuith Bhandarkar | 22bfedf | 2017-11-08 11:59:38 +0100 | [diff] [blame] | 11 | import distutils.version |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 12 | import multiprocessing |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 13 | import os |
Achuith Bhandarkar | 22bfedf | 2017-11-08 11:59:38 +0100 | [diff] [blame] | 14 | import re |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 15 | |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 16 | from chromite.cli.cros import cros_chrome_sdk |
| 17 | from chromite.lib import cache |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 18 | from chromite.lib import commandline |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 19 | from chromite.lib import constants |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 20 | from chromite.lib import cros_build_lib |
| 21 | from chromite.lib import cros_logging as logging |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 22 | from chromite.lib import osutils |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 23 | from chromite.lib import path_util |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 24 | from chromite.lib import remote_access |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 25 | from chromite.lib import retry_util |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 26 | |
| 27 | |
| 28 | class VMError(Exception): |
| 29 | """Exception for VM failures.""" |
| 30 | |
| 31 | def __init__(self, message): |
| 32 | super(VMError, self).__init__() |
| 33 | logging.error(message) |
| 34 | |
| 35 | |
| 36 | class VM(object): |
| 37 | """Class for managing a VM.""" |
| 38 | |
| 39 | SSH_PORT = 9222 |
Nicolas Norvez | f527cdf | 2018-01-26 11:55:44 -0800 | [diff] [blame] | 40 | IMAGE_FORMAT = 'raw' |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 41 | |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 42 | def __init__(self, opts): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 43 | """Initialize VM. |
| 44 | |
| 45 | Args: |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 46 | opts: command line options. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 47 | """ |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 48 | self.qemu_path = opts.qemu_path |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 49 | self.qemu_bios_path = opts.qemu_bios_path |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 50 | self.qemu_m = opts.qemu_m |
| 51 | self.qemu_cpu = opts.qemu_cpu |
| 52 | self.qemu_smp = opts.qemu_smp |
| 53 | if self.qemu_smp == 0: |
| 54 | self.qemu_smp = min(8, multiprocessing.cpu_count) |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 55 | self.enable_kvm = opts.enable_kvm |
Achuith Bhandarkar | f877da2 | 2017-09-12 12:27:39 -0700 | [diff] [blame] | 56 | # We don't need sudo access for software emulation or if /dev/kvm is |
| 57 | # writeable. |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 58 | self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK) |
| 59 | self.display = opts.display |
| 60 | self.image_path = opts.image_path |
Nicolas Norvez | f527cdf | 2018-01-26 11:55:44 -0800 | [diff] [blame] | 61 | self.image_format = opts.image_format |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 62 | self.board = opts.board |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 63 | self.ssh_port = opts.ssh_port |
| 64 | self.dry_run = opts.dry_run |
| 65 | |
| 66 | self.start = opts.start |
| 67 | self.stop = opts.stop |
| 68 | self.cmd = opts.args[1:] if opts.cmd else None |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 69 | |
Achuith Bhandarkar | 02ef76b | 2018-04-05 10:47:33 +0200 | [diff] [blame^] | 70 | self.cache_dir = os.path.abspath(opts.cache_dir) |
| 71 | assert os.path.isdir(self.cache_dir), "Cache directory doesn't exist" |
| 72 | |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 73 | self.vm_dir = opts.vm_dir |
| 74 | if not self.vm_dir: |
| 75 | self.vm_dir = os.path.join(osutils.GetGlobalTempDir(), |
| 76 | 'cros_vm_%d' % self.ssh_port) |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 77 | self._CreateVMDir() |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 78 | |
| 79 | self.pidfile = os.path.join(self.vm_dir, 'kvm.pid') |
| 80 | self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor') |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 81 | self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM |
| 82 | self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM |
| 83 | self.kvm_serial = '%s.serial' % self.kvm_monitor |
| 84 | |
Achuith Bhandarkar | 65d1a89 | 2017-05-08 14:13:12 -0700 | [diff] [blame] | 85 | self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST, |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 86 | port=self.ssh_port) |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 87 | self.device_addr = 'ssh://%s:%d' % (remote_access.LOCALHOST, self.ssh_port) |
Achuith Bhandarkar | 65d1a89 | 2017-05-08 14:13:12 -0700 | [diff] [blame] | 88 | |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 89 | # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough, |
| 90 | # moblab, etc. |
| 91 | |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 92 | def _RunCommand(self, *args, **kwargs): |
| 93 | """Use SudoRunCommand or RunCommand as necessary.""" |
| 94 | if self.use_sudo: |
| 95 | return cros_build_lib.SudoRunCommand(*args, **kwargs) |
| 96 | else: |
| 97 | return cros_build_lib.RunCommand(*args, **kwargs) |
| 98 | |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 99 | def _CreateVMDir(self): |
| 100 | """Safely create vm_dir.""" |
| 101 | if not osutils.SafeMakedirs(self.vm_dir, sudo=self.use_sudo): |
| 102 | # For security, ensure that vm_dir is not a symlink, and is owned by us or |
| 103 | # by root. |
| 104 | error_str = ('VM state dir is misconfigured; please recreate: %s' |
| 105 | % self.vm_dir) |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 106 | assert os.path.isdir(self.vm_dir), error_str |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 107 | assert not os.path.islink(self.vm_dir), error_str |
| 108 | st_uid = os.stat(self.vm_dir).st_uid |
| 109 | assert st_uid == 0 or st_uid == os.getuid(), error_str |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 110 | |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 111 | def _RmVMDir(self): |
| 112 | """Cleanup vm_dir.""" |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 113 | osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 114 | |
Achuith Bhandarkar | 02ef76b | 2018-04-05 10:47:33 +0200 | [diff] [blame^] | 115 | def _GetCachePath(self, cache_name): |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 116 | """Return path to cache. |
| 117 | |
| 118 | Args: |
| 119 | cache_name: Name of cache. |
| 120 | |
| 121 | Returns: |
| 122 | File path of cache. |
| 123 | """ |
Achuith Bhandarkar | 02ef76b | 2018-04-05 10:47:33 +0200 | [diff] [blame^] | 124 | return os.path.join(self.cache_dir, |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 125 | cros_chrome_sdk.COMMAND_NAME, |
| 126 | cache_name) |
| 127 | |
| 128 | @cros_build_lib.MemoizedSingleCall |
| 129 | def _SDKVersion(self): |
| 130 | """Determine SDK version. |
| 131 | |
| 132 | Check the environment if we're in the SDK shell, and failing that, look at |
| 133 | the misc cache. |
| 134 | |
| 135 | Returns: |
| 136 | SDK version. |
| 137 | """ |
| 138 | sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV) |
Achuith Bhandarkar | 4e367c2 | 2018-03-27 15:32:48 -0700 | [diff] [blame] | 139 | if not sdk_version and self.board: |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 140 | misc_cache = cache.DiskCache(self._GetCachePath( |
| 141 | cros_chrome_sdk.SDKFetcher.MISC_CACHE)) |
| 142 | with misc_cache.Lookup((self.board, 'latest')) as ref: |
| 143 | if ref.Exists(lock=True): |
| 144 | sdk_version = osutils.ReadFile(ref.path).strip() |
| 145 | return sdk_version |
| 146 | |
| 147 | def _CachePathForKey(self, key): |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 148 | """Get cache path for key. |
| 149 | |
| 150 | Args: |
| 151 | key: cache key. |
| 152 | """ |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 153 | tarball_cache = cache.TarballCache(self._GetCachePath( |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 154 | cros_chrome_sdk.SDKFetcher.TARBALL_CACHE)) |
Achuith Bhandarkar | 4e367c2 | 2018-03-27 15:32:48 -0700 | [diff] [blame] | 155 | if self.board and self._SDKVersion(): |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 156 | cache_key = (self.board, self._SDKVersion(), key) |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 157 | with tarball_cache.Lookup(cache_key) as ref: |
| 158 | if ref.Exists(): |
| 159 | return ref.path |
| 160 | return None |
| 161 | |
Achuith Bhandarkar | 22bfedf | 2017-11-08 11:59:38 +0100 | [diff] [blame] | 162 | @cros_build_lib.MemoizedSingleCall |
| 163 | def QemuVersion(self): |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 164 | """Determine QEMU version. |
| 165 | |
| 166 | Returns: |
| 167 | QEMU version. |
| 168 | """ |
Achuith Bhandarkar | 22bfedf | 2017-11-08 11:59:38 +0100 | [diff] [blame] | 169 | version_str = self._RunCommand([self.qemu_path, '--version'], |
| 170 | capture_output=True).output |
| 171 | # version string looks like one of these: |
| 172 | # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c) |
| 173 | # 2003-2008 Fabrice Bellard |
| 174 | # |
| 175 | # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard |
| 176 | # |
| 177 | # qemu-x86_64 version 2.10.1 |
| 178 | # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers |
| 179 | m = re.search(r"version ([0-9.]+)", version_str) |
| 180 | if not m: |
| 181 | raise VMError('Unable to determine QEMU version from:\n%s.' % version_str) |
| 182 | return m.group(1) |
| 183 | |
| 184 | def _CheckQemuMinVersion(self): |
| 185 | """Ensure minimum QEMU version.""" |
| 186 | min_qemu_version = '2.6.0' |
| 187 | logging.info('QEMU version %s', self.QemuVersion()) |
| 188 | LooseVersion = distutils.version.LooseVersion |
| 189 | if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version): |
| 190 | raise VMError('QEMU %s is the minimum supported version. You have %s.' |
| 191 | % (min_qemu_version, self.QemuVersion())) |
| 192 | |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 193 | def _SetQemuPath(self): |
| 194 | """Find a suitable Qemu executable.""" |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 195 | qemu_exe = 'qemu-system-x86_64' |
| 196 | qemu_exe_path = os.path.join('usr/bin', qemu_exe) |
| 197 | |
| 198 | # Check SDK cache. |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 199 | if not self.qemu_path: |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 200 | qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY) |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 201 | if qemu_dir: |
| 202 | qemu_path = os.path.join(qemu_dir, qemu_exe_path) |
| 203 | if os.path.isfile(qemu_path): |
| 204 | self.qemu_path = qemu_path |
| 205 | |
| 206 | # Check chroot. |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 207 | if not self.qemu_path: |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 208 | qemu_path = os.path.join( |
| 209 | constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path) |
| 210 | if os.path.isfile(qemu_path): |
| 211 | self.qemu_path = qemu_path |
| 212 | |
| 213 | # Check system. |
| 214 | if not self.qemu_path: |
| 215 | self.qemu_path = osutils.Which(qemu_exe) |
| 216 | |
| 217 | if not self.qemu_path or not os.path.isfile(self.qemu_path): |
| 218 | raise VMError('QEMU not found.') |
| 219 | logging.debug('QEMU path: %s', self.qemu_path) |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 220 | self._CheckQemuMinVersion() |
| 221 | |
| 222 | def _GetBuiltVMImagePath(self): |
| 223 | """Get path of a locally built VM image.""" |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 224 | vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images', |
| 225 | cros_build_lib.GetBoard(self.board), |
| 226 | 'latest', constants.VM_IMAGE_BIN) |
| 227 | return vm_image_path if os.path.isfile(vm_image_path) else None |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 228 | |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 229 | def _GetCacheVMImagePath(self): |
| 230 | """Get path of a cached VM image.""" |
Achuith Bhandarkar | f6bccdb | 2018-03-23 13:12:29 -0700 | [diff] [blame] | 231 | cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR) |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 232 | if cache_path: |
| 233 | vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN) |
| 234 | if os.path.isfile(vm_image): |
| 235 | return vm_image |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 236 | return None |
| 237 | |
| 238 | def _SetVMImagePath(self): |
| 239 | """Detect VM image path in SDK and chroot.""" |
| 240 | if not self.image_path: |
Achuith Bhandarkar | fc75f69 | 2018-01-10 11:33:09 -0800 | [diff] [blame] | 241 | self.image_path = (self._GetCacheVMImagePath() or |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 242 | self._GetBuiltVMImagePath()) |
| 243 | if not self.image_path: |
| 244 | raise VMError('No VM image found. Use cros chrome-sdk --download-vm.') |
| 245 | if not os.path.isfile(self.image_path): |
| 246 | raise VMError('VM image does not exist: %s' % self.image_path) |
| 247 | logging.debug('VM image path: %s', self.image_path) |
| 248 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 249 | def Run(self): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 250 | """Performs an action, one of start, stop, or run a command in the VM. |
| 251 | |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 252 | Returns: |
| 253 | cmd output. |
| 254 | """ |
| 255 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 256 | if not self.start and not self.stop and not self.cmd: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 257 | raise VMError('Must specify one of start, stop, or cmd.') |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 258 | if self.start: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 259 | self.Start() |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 260 | if self.cmd: |
| 261 | return self.RemoteCommand(self.cmd) |
| 262 | if self.stop: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 263 | self.Stop() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 264 | |
| 265 | def Start(self): |
| 266 | """Start the VM.""" |
| 267 | |
| 268 | self.Stop() |
| 269 | |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 270 | logging.debug('Start VM') |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 271 | self._SetQemuPath() |
| 272 | self._SetVMImagePath() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 273 | |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 274 | self._RmVMDir() |
| 275 | self._CreateVMDir() |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 276 | # Make sure we can read these files later on by creating them as ourselves. |
| 277 | osutils.Touch(self.kvm_serial) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 278 | for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]: |
| 279 | os.mkfifo(pipe, 0600) |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 280 | osutils.Touch(self.pidfile) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 281 | |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 282 | qemu_args = [self.qemu_path] |
| 283 | if self.qemu_bios_path: |
| 284 | if not os.path.isdir(self.qemu_bios_path): |
| 285 | raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path) |
| 286 | qemu_args += ['-L', self.qemu_bios_path] |
Achuith Bhandarkar | 22bfedf | 2017-11-08 11:59:38 +0100 | [diff] [blame] | 287 | |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 288 | qemu_args += [ |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 289 | '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio', |
| 290 | '-daemonize', '-usbdevice', 'tablet', |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 291 | '-pidfile', self.pidfile, |
| 292 | '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor, |
| 293 | '-serial', 'file:%s' % self.kvm_serial, |
| 294 | '-mon', 'chardev=control_pipe', |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 295 | # Append 'check' to warn if the requested CPU is not fully supported. |
| 296 | '-cpu', self.qemu_cpu + ',check', |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 297 | # Qemu-vlans are used by qemu to separate out network traffic on the |
| 298 | # slirp network bridge. qemu forwards traffic on a slirp vlan to all |
| 299 | # ports conected on that vlan. By default, slirp ports are on vlan |
| 300 | # 0. We explicitly set a vlan here so that another qemu VM using |
| 301 | # slirp doesn't conflict with our network traffic. |
| 302 | '-net', 'nic,model=virtio,vlan=%d' % self.ssh_port, |
| 303 | '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22,vlan=%d' |
| 304 | % (self.ssh_port, self.ssh_port), |
Nicolas Norvez | f527cdf | 2018-01-26 11:55:44 -0800 | [diff] [blame] | 305 | '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s' |
| 306 | % (self.image_path, self.image_format), |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 307 | ] |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 308 | if self.enable_kvm: |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 309 | qemu_args.append('-enable-kvm') |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 310 | if not self.display: |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 311 | qemu_args.extend(['-display', 'none']) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 312 | logging.info('Pid file: %s', self.pidfile) |
| 313 | if not self.dry_run: |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 314 | self._RunCommand(qemu_args) |
Achuith Bhandarkar | be97748 | 2018-02-06 16:44:00 -0800 | [diff] [blame] | 315 | else: |
| 316 | logging.info(cros_build_lib.CmdToStr(qemu_args)) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 317 | |
| 318 | def _GetVMPid(self): |
| 319 | """Get the pid of the VM. |
| 320 | |
| 321 | Returns: |
| 322 | pid of the VM. |
| 323 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 324 | if not os.path.exists(self.vm_dir): |
| 325 | logging.debug('%s not present.', self.vm_dir) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 326 | return 0 |
| 327 | |
| 328 | if not os.path.exists(self.pidfile): |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 329 | logging.info('%s does not exist.', self.pidfile) |
| 330 | return 0 |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 331 | |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 332 | pid = osutils.ReadFile(self.pidfile).rstrip() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 333 | if not pid.isdigit(): |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 334 | # Ignore blank/empty files. |
| 335 | if pid: |
| 336 | logging.error('%s in %s is not a pid.', pid, self.pidfile) |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 337 | return 0 |
| 338 | |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 339 | return int(pid) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 340 | |
| 341 | def IsRunning(self): |
| 342 | """Returns True if there's a running VM. |
| 343 | |
| 344 | Returns: |
| 345 | True if there's a running VM. |
| 346 | """ |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 347 | pid = self._GetVMPid() |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 348 | if not pid: |
| 349 | return False |
| 350 | |
| 351 | # Make sure the process actually exists. |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 352 | return os.path.isdir('/proc/%i' % pid) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 353 | |
| 354 | def Stop(self): |
| 355 | """Stop the VM.""" |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 356 | logging.debug('Stop VM') |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 357 | |
| 358 | pid = self._GetVMPid() |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 359 | if pid: |
| 360 | logging.info('Killing %d.', pid) |
| 361 | if not self.dry_run: |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 362 | self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True) |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 363 | self._RmVMDir() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 364 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 365 | def _WaitForProcs(self): |
| 366 | """Wait for expected processes to launch.""" |
| 367 | class _TooFewPidsException(Exception): |
| 368 | """Exception for _GetRunningPids to throw.""" |
| 369 | |
| 370 | def _GetRunningPids(exe, numpids): |
| 371 | pids = self.remote.GetRunningPids(exe, full_path=False) |
| 372 | logging.info('%s pids: %s', exe, repr(pids)) |
| 373 | if len(pids) < numpids: |
| 374 | raise _TooFewPidsException() |
| 375 | |
| 376 | def _WaitForProc(exe, numpids): |
| 377 | try: |
| 378 | retry_util.RetryException( |
Achuith Bhandarkar | 0e7b850 | 2017-06-12 15:32:41 -0700 | [diff] [blame] | 379 | exception=_TooFewPidsException, |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 380 | max_retry=20, |
| 381 | functor=lambda: _GetRunningPids(exe, numpids), |
| 382 | sleep=2) |
| 383 | except _TooFewPidsException: |
| 384 | raise VMError('_WaitForProcs failed: timed out while waiting for ' |
| 385 | '%d %s processes to start.' % (numpids, exe)) |
| 386 | |
| 387 | # We could also wait for session_manager, nacl_helper, etc, but chrome is |
| 388 | # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer. |
| 389 | # This could potentially break with Mustash. |
| 390 | _WaitForProc('chrome', 5) |
| 391 | |
| 392 | def WaitForBoot(self): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 393 | """Wait for the VM to boot up. |
| 394 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 395 | Wait for ssh connection to become active, and wait for all expected chrome |
| 396 | processes to be launched. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 397 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 398 | if not os.path.exists(self.vm_dir): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 399 | self.Start() |
| 400 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 401 | try: |
| 402 | result = retry_util.RetryException( |
Achuith Bhandarkar | 0e7b850 | 2017-06-12 15:32:41 -0700 | [diff] [blame] | 403 | exception=remote_access.SSHConnectionError, |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 404 | max_retry=10, |
| 405 | functor=lambda: self.RemoteCommand(cmd=['echo']), |
| 406 | sleep=5) |
| 407 | except remote_access.SSHConnectionError: |
| 408 | raise VMError('WaitForBoot timed out trying to connect to VM.') |
| 409 | |
| 410 | if result.returncode != 0: |
| 411 | raise VMError('WaitForBoot failed: %s.' % result.error) |
| 412 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 413 | # Chrome can take a while to start with software emulation. |
| 414 | if not self.enable_kvm: |
| 415 | self._WaitForProcs() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 416 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 417 | def RemoteCommand(self, cmd, **kwargs): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 418 | """Run a remote command in the VM. |
| 419 | |
| 420 | Args: |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 421 | cmd: command to run. |
| 422 | kwargs: additional args (see documentation for RemoteDevice.RunCommand). |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 423 | """ |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 424 | if not self.dry_run: |
Achuith Bhandarkar | 65d1a89 | 2017-05-08 14:13:12 -0700 | [diff] [blame] | 425 | return self.remote.RunCommand(cmd, debug_level=logging.INFO, |
| 426 | combine_stdout_stderr=True, |
| 427 | log_output=True, |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 428 | error_code_ok=True, |
| 429 | **kwargs) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 430 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 431 | @staticmethod |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 432 | def GetParser(): |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 433 | """Parse a list of args. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 434 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 435 | Args: |
| 436 | argv: list of command line arguments. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 437 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 438 | Returns: |
| 439 | List of parsed opts. |
| 440 | """ |
| 441 | parser = commandline.ArgumentParser(description=__doc__) |
| 442 | parser.add_argument('--start', action='store_true', default=False, |
| 443 | help='Start the VM.') |
| 444 | parser.add_argument('--stop', action='store_true', default=False, |
| 445 | help='Stop the VM.') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 446 | parser.add_argument('--image-path', type=str, |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 447 | help='Path to VM image to launch with --start.') |
Nicolas Norvez | f527cdf | 2018-01-26 11:55:44 -0800 | [diff] [blame] | 448 | parser.add_argument('--image-format', default=VM.IMAGE_FORMAT, |
| 449 | help='Format of the VM image (raw, qcow2, ...).') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 450 | parser.add_argument('--qemu-path', type=str, |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 451 | help='Path of qemu binary to launch with --start.') |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 452 | parser.add_argument('--qemu-m', type=str, default='8G', |
| 453 | help='Memory argument that will be passed to qemu.') |
| 454 | parser.add_argument('--qemu-smp', type=int, default='0', |
| 455 | help='SMP argument that will be passed to qemu. (0 ' |
| 456 | 'means auto-detection.)') |
Po-Hsien Wang | c5b335f | 2018-02-06 18:36:16 -0800 | [diff] [blame] | 457 | # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine |
| 458 | # running VMTest all migrate to GCE. |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 459 | parser.add_argument('--qemu-cpu', type=str, |
Po-Hsien Wang | c5b335f | 2018-02-06 18:36:16 -0800 | [diff] [blame] | 460 | default='SandyBridge,-invpcid,-tsc-deadline', |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 461 | help='CPU argument that will be passed to qemu.') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 462 | parser.add_argument('--qemu-bios-path', type=str, |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 463 | help='Path of directory with qemu bios files.') |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 464 | parser.add_argument('--disable-kvm', dest='enable_kvm', |
| 465 | action='store_false', default=True, |
| 466 | help='Disable KVM, use software emulation.') |
| 467 | parser.add_argument('--no-display', dest='display', |
| 468 | action='store_false', default=True, |
| 469 | help='Do not display video output.') |
| 470 | parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT, |
| 471 | help='ssh port to communicate with VM.') |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 472 | sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV) |
| 473 | parser.add_argument('--board', default=sdk_board_env, help='Board to use.') |
Achuith Bhandarkar | 02ef76b | 2018-04-05 10:47:33 +0200 | [diff] [blame^] | 474 | parser.add_argument('--cache-dir', type=str, |
| 475 | default=path_util.GetCacheDir(), |
| 476 | help='Cache directory to use.') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 477 | parser.add_argument('--vm-dir', type=str, |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 478 | help='Temp VM directory to use.') |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 479 | parser.add_argument('--dry-run', action='store_true', default=False, |
| 480 | help='dry run for debugging.') |
| 481 | parser.add_argument('--cmd', action='store_true', default=False, |
| 482 | help='Run a command in the VM.') |
| 483 | parser.add_argument('args', nargs=argparse.REMAINDER, |
| 484 | help='Command to run in the VM.') |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 485 | return parser |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 486 | |
| 487 | def main(argv): |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 488 | opts = VM.GetParser().parse_args(argv) |
| 489 | opts.Freeze() |
| 490 | |
| 491 | vm = VM(opts) |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 492 | vm.Run() |