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