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