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