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