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