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