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.""" |
Steven Bennetts | c57ca0e | 2018-09-18 09:33:59 -0700 | [diff] [blame^] | 115 | if not osutils.SafeMakedirs(self.vm_dir): |
| 116 | # For security, ensure that vm_dir is not a symlink, and is owned by us. |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 117 | error_str = ('VM state dir is misconfigured; please recreate: %s' |
| 118 | % self.vm_dir) |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 119 | assert os.path.isdir(self.vm_dir), error_str |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 120 | assert not os.path.islink(self.vm_dir), error_str |
Steven Bennetts | c57ca0e | 2018-09-18 09:33:59 -0700 | [diff] [blame^] | 121 | assert os.stat(self.vm_dir).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 | b00bafc | 2018-09-11 16:30:13 -0700 | [diff] [blame] | 261 | def _WaitForSSHPort(self): |
| 262 | """Wait for SSH port to become available.""" |
| 263 | class _SSHPortInUseError(Exception): |
| 264 | """Exception for _CheckSSHPortBusy to throw.""" |
| 265 | |
| 266 | def _CheckSSHPortBusy(ssh_port): |
| 267 | """Check if the SSH port is in use.""" |
| 268 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 269 | try: |
| 270 | sock.bind((remote_access.LOCALHOST_IP, ssh_port)) |
| 271 | except socket.error as e: |
| 272 | if e.errno == errno.EADDRINUSE: |
| 273 | logging.info('SSH port %d in use...', self.ssh_port) |
| 274 | raise _SSHPortInUseError() |
| 275 | sock.close() |
| 276 | |
| 277 | try: |
| 278 | retry_util.RetryException( |
| 279 | exception=_SSHPortInUseError, |
| 280 | max_retry=7, |
| 281 | functor=lambda: _CheckSSHPortBusy(self.ssh_port), |
| 282 | sleep=1) |
| 283 | except _SSHPortInUseError: |
| 284 | raise VMError('SSH port %d in use' % self.ssh_port) |
| 285 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 286 | def Run(self): |
Achuith Bhandarkar | 665a9b3 | 2018-05-17 11:39:19 -0700 | [diff] [blame] | 287 | """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] | 288 | if not self.start and not self.stop and not self.cmd: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 289 | raise VMError('Must specify one of start, stop, or cmd.') |
Achuith Bhandarkar | 665a9b3 | 2018-05-17 11:39:19 -0700 | [diff] [blame] | 290 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 291 | if self.start: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 292 | self.Start() |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 293 | if self.cmd: |
Achuith Bhandarkar | 665a9b3 | 2018-05-17 11:39:19 -0700 | [diff] [blame] | 294 | if not self.IsRunning(): |
| 295 | raise VMError('VM not running.') |
| 296 | self.RemoteCommand(self.cmd, stream_output=True) |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 297 | if self.stop: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 298 | self.Stop() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 299 | |
| 300 | def Start(self): |
| 301 | """Start the VM.""" |
| 302 | |
| 303 | self.Stop() |
Achuith Bhandarkar | b00bafc | 2018-09-11 16:30:13 -0700 | [diff] [blame] | 304 | self._WaitForSSHPort() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 305 | |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 306 | logging.debug('Start VM') |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 307 | self._SetQemuPath() |
| 308 | self._SetVMImagePath() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 309 | |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 310 | self._RmVMDir() |
| 311 | self._CreateVMDir() |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 312 | # Make sure we can read these files later on by creating them as ourselves. |
| 313 | osutils.Touch(self.kvm_serial) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 314 | for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]: |
Mike Frysinger | 0444f4c | 2018-08-03 15:12:46 -0400 | [diff] [blame] | 315 | os.mkfifo(pipe, 0o600) |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 316 | osutils.Touch(self.pidfile) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 317 | |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 318 | qemu_args = [self.qemu_path] |
| 319 | if self.qemu_bios_path: |
| 320 | if not os.path.isdir(self.qemu_bios_path): |
| 321 | raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path) |
| 322 | qemu_args += ['-L', self.qemu_bios_path] |
Achuith Bhandarkar | 22bfedf | 2017-11-08 11:59:38 +0100 | [diff] [blame] | 323 | |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 324 | qemu_args += [ |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 325 | '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio', |
| 326 | '-daemonize', '-usbdevice', 'tablet', |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 327 | '-pidfile', self.pidfile, |
| 328 | '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor, |
| 329 | '-serial', 'file:%s' % self.kvm_serial, |
| 330 | '-mon', 'chardev=control_pipe', |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 331 | # Append 'check' to warn if the requested CPU is not fully supported. |
| 332 | '-cpu', self.qemu_cpu + ',check', |
Lepton Wu | aa6cca4 | 2018-04-19 18:56:29 -0700 | [diff] [blame] | 333 | '-device', 'virtio-net,netdev=eth0', |
Achuith Bhandarkar | b00bafc | 2018-09-11 16:30:13 -0700 | [diff] [blame] | 334 | '-netdev', 'user,id=eth0,net=10.0.2.0/27,hostfwd=tcp:%s:%d-:22' |
| 335 | % (remote_access.LOCALHOST_IP, self.ssh_port), |
Nicolas Norvez | f527cdf | 2018-01-26 11:55:44 -0800 | [diff] [blame] | 336 | '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s' |
| 337 | % (self.image_path, self.image_format), |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 338 | ] |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 339 | if self.enable_kvm: |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 340 | qemu_args.append('-enable-kvm') |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 341 | if not self.display: |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 342 | qemu_args.extend(['-display', 'none']) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 343 | logging.info('Pid file: %s', self.pidfile) |
| 344 | if not self.dry_run: |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 345 | self._RunCommand(qemu_args) |
Achuith Bhandarkar | be97748 | 2018-02-06 16:44:00 -0800 | [diff] [blame] | 346 | else: |
| 347 | logging.info(cros_build_lib.CmdToStr(qemu_args)) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 348 | |
| 349 | def _GetVMPid(self): |
| 350 | """Get the pid of the VM. |
| 351 | |
| 352 | Returns: |
| 353 | pid of the VM. |
| 354 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 355 | if not os.path.exists(self.vm_dir): |
| 356 | logging.debug('%s not present.', self.vm_dir) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 357 | return 0 |
| 358 | |
| 359 | if not os.path.exists(self.pidfile): |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 360 | logging.info('%s does not exist.', self.pidfile) |
| 361 | return 0 |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 362 | |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 363 | pid = osutils.ReadFile(self.pidfile).rstrip() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 364 | if not pid.isdigit(): |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 365 | # Ignore blank/empty files. |
| 366 | if pid: |
| 367 | logging.error('%s in %s is not a pid.', pid, self.pidfile) |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 368 | return 0 |
| 369 | |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 370 | return int(pid) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 371 | |
| 372 | def IsRunning(self): |
| 373 | """Returns True if there's a running VM. |
| 374 | |
| 375 | Returns: |
| 376 | True if there's a running VM. |
| 377 | """ |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 378 | pid = self._GetVMPid() |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 379 | if not pid: |
| 380 | return False |
| 381 | |
| 382 | # Make sure the process actually exists. |
Mike Frysinger | 9708024 | 2017-09-13 01:58:45 -0400 | [diff] [blame] | 383 | return os.path.isdir('/proc/%i' % pid) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 384 | |
| 385 | def Stop(self): |
| 386 | """Stop the VM.""" |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 387 | logging.debug('Stop VM') |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 388 | |
| 389 | pid = self._GetVMPid() |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 390 | if pid: |
| 391 | logging.info('Killing %d.', pid) |
| 392 | if not self.dry_run: |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 393 | self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True) |
Achuith Bhandarkar | fd5d185 | 2018-03-26 14:50:54 -0700 | [diff] [blame] | 394 | self._RmVMDir() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 395 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 396 | def _WaitForProcs(self): |
| 397 | """Wait for expected processes to launch.""" |
| 398 | class _TooFewPidsException(Exception): |
| 399 | """Exception for _GetRunningPids to throw.""" |
| 400 | |
| 401 | def _GetRunningPids(exe, numpids): |
| 402 | pids = self.remote.GetRunningPids(exe, full_path=False) |
| 403 | logging.info('%s pids: %s', exe, repr(pids)) |
| 404 | if len(pids) < numpids: |
| 405 | raise _TooFewPidsException() |
| 406 | |
| 407 | def _WaitForProc(exe, numpids): |
| 408 | try: |
| 409 | retry_util.RetryException( |
Achuith Bhandarkar | 0e7b850 | 2017-06-12 15:32:41 -0700 | [diff] [blame] | 410 | exception=_TooFewPidsException, |
Achuith Bhandarkar | b00bafc | 2018-09-11 16:30:13 -0700 | [diff] [blame] | 411 | max_retry=5, |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 412 | functor=lambda: _GetRunningPids(exe, numpids), |
| 413 | sleep=2) |
| 414 | except _TooFewPidsException: |
| 415 | raise VMError('_WaitForProcs failed: timed out while waiting for ' |
| 416 | '%d %s processes to start.' % (numpids, exe)) |
| 417 | |
| 418 | # We could also wait for session_manager, nacl_helper, etc, but chrome is |
| 419 | # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer. |
| 420 | # This could potentially break with Mustash. |
| 421 | _WaitForProc('chrome', 5) |
| 422 | |
| 423 | def WaitForBoot(self): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 424 | """Wait for the VM to boot up. |
| 425 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 426 | Wait for ssh connection to become active, and wait for all expected chrome |
| 427 | processes to be launched. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 428 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 429 | if not os.path.exists(self.vm_dir): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 430 | self.Start() |
| 431 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 432 | try: |
| 433 | result = retry_util.RetryException( |
Achuith Bhandarkar | 0e7b850 | 2017-06-12 15:32:41 -0700 | [diff] [blame] | 434 | exception=remote_access.SSHConnectionError, |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 435 | max_retry=10, |
| 436 | functor=lambda: self.RemoteCommand(cmd=['echo']), |
| 437 | sleep=5) |
| 438 | except remote_access.SSHConnectionError: |
| 439 | raise VMError('WaitForBoot timed out trying to connect to VM.') |
| 440 | |
| 441 | if result.returncode != 0: |
| 442 | raise VMError('WaitForBoot failed: %s.' % result.error) |
| 443 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 444 | # Chrome can take a while to start with software emulation. |
| 445 | if not self.enable_kvm: |
| 446 | self._WaitForProcs() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 447 | |
Achuith Bhandarkar | bad755b | 2018-06-09 16:05:01 -0700 | [diff] [blame] | 448 | def RemoteCommand(self, cmd, stream_output=False, **kwargs): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 449 | """Run a remote command in the VM. |
| 450 | |
| 451 | Args: |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 452 | cmd: command to run. |
Achuith Bhandarkar | bad755b | 2018-06-09 16:05:01 -0700 | [diff] [blame] | 453 | stream_output: Stream output of long-running commands. |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 454 | kwargs: additional args (see documentation for RemoteDevice.RunCommand). |
Achuith Bhandarkar | 665a9b3 | 2018-05-17 11:39:19 -0700 | [diff] [blame] | 455 | |
| 456 | Returns: |
| 457 | cros_build_lib.CommandResult object. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 458 | """ |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 459 | if not self.dry_run: |
Achuith Bhandarkar | bad755b | 2018-06-09 16:05:01 -0700 | [diff] [blame] | 460 | kwargs.setdefault('error_code_ok', True) |
| 461 | if stream_output: |
| 462 | kwargs.setdefault('capture_output', False) |
| 463 | else: |
| 464 | kwargs.setdefault('combine_stdout_stderr', True) |
| 465 | kwargs.setdefault('log_output', True) |
| 466 | return self.remote.RunCommand(cmd, debug_level=logging.INFO, **kwargs) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 467 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 468 | @staticmethod |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 469 | def GetParser(): |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 470 | """Parse a list of args. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 471 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 472 | Args: |
| 473 | argv: list of command line arguments. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 474 | |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 475 | Returns: |
| 476 | List of parsed opts. |
| 477 | """ |
| 478 | parser = commandline.ArgumentParser(description=__doc__) |
| 479 | parser.add_argument('--start', action='store_true', default=False, |
| 480 | help='Start the VM.') |
| 481 | parser.add_argument('--stop', action='store_true', default=False, |
| 482 | help='Stop the VM.') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 483 | parser.add_argument('--image-path', type=str, |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 484 | help='Path to VM image to launch with --start.') |
Nicolas Norvez | f527cdf | 2018-01-26 11:55:44 -0800 | [diff] [blame] | 485 | parser.add_argument('--image-format', default=VM.IMAGE_FORMAT, |
| 486 | help='Format of the VM image (raw, qcow2, ...).') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 487 | parser.add_argument('--qemu-path', type=str, |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 488 | help='Path of qemu binary to launch with --start.') |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 489 | parser.add_argument('--qemu-m', type=str, default='8G', |
| 490 | help='Memory argument that will be passed to qemu.') |
| 491 | parser.add_argument('--qemu-smp', type=int, default='0', |
| 492 | help='SMP argument that will be passed to qemu. (0 ' |
| 493 | 'means auto-detection.)') |
Po-Hsien Wang | c5b335f | 2018-02-06 18:36:16 -0800 | [diff] [blame] | 494 | # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine |
| 495 | # running VMTest all migrate to GCE. |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 496 | parser.add_argument('--qemu-cpu', type=str, |
Po-Hsien Wang | c5b335f | 2018-02-06 18:36:16 -0800 | [diff] [blame] | 497 | default='SandyBridge,-invpcid,-tsc-deadline', |
Po-Hsien Wang | 1cec8d1 | 2018-01-25 16:36:44 -0800 | [diff] [blame] | 498 | help='CPU argument that will be passed to qemu.') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 499 | parser.add_argument('--qemu-bios-path', type=str, |
Achuith Bhandarkar | 4125965 | 2017-11-14 10:31:02 -0800 | [diff] [blame] | 500 | help='Path of directory with qemu bios files.') |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 501 | parser.add_argument('--disable-kvm', dest='enable_kvm', |
| 502 | action='store_false', default=True, |
| 503 | help='Disable KVM, use software emulation.') |
| 504 | parser.add_argument('--no-display', dest='display', |
| 505 | action='store_false', default=True, |
| 506 | help='Do not display video output.') |
| 507 | parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT, |
| 508 | help='ssh port to communicate with VM.') |
Achuith Bhandarkar | 195b951 | 2018-08-15 17:14:32 -0700 | [diff] [blame] | 509 | parser.add_argument('--private-key', help='Path to ssh private key.') |
Achuith Bhandarkar | 1297dcf | 2017-11-21 12:03:48 -0800 | [diff] [blame] | 510 | sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV) |
| 511 | parser.add_argument('--board', default=sdk_board_env, help='Board to use.') |
Achuith Bhandarkar | 02ef76b | 2018-04-05 10:47:33 +0200 | [diff] [blame] | 512 | parser.add_argument('--cache-dir', type=str, |
| 513 | default=path_util.GetCacheDir(), |
| 514 | help='Cache directory to use.') |
Achuith Bhandarkar | 46d8387 | 2018-04-04 01:49:55 -0700 | [diff] [blame] | 515 | parser.add_argument('--vm-dir', type=str, |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 516 | help='Temp VM directory to use.') |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 517 | parser.add_argument('--dry-run', action='store_true', default=False, |
| 518 | help='dry run for debugging.') |
| 519 | parser.add_argument('--cmd', action='store_true', default=False, |
| 520 | help='Run a command in the VM.') |
| 521 | parser.add_argument('args', nargs=argparse.REMAINDER, |
| 522 | help='Command to run in the VM.') |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 523 | return parser |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 524 | |
| 525 | def main(argv): |
Achuith Bhandarkar | 2beae29 | 2018-03-26 16:44:53 -0700 | [diff] [blame] | 526 | opts = VM.GetParser().parse_args(argv) |
| 527 | opts.Freeze() |
| 528 | |
| 529 | vm = VM(opts) |
Achuith Bhandarkar | 2a39adf | 2017-10-30 10:24:45 +0100 | [diff] [blame] | 530 | vm.Run() |