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