blob: f96414122f30c342f7447669a020837c1843ce11 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Achuith Bhandarkard8d19292016-05-03 14:32:58 -07002# 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 Frysinger666566c2016-09-21 00:00:21 -04006"""Script for VM Management."""
Achuith Bhandarkard8d19292016-05-03 14:32:58 -07007
8from __future__ import print_function
9
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010010import argparse
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010011import distutils.version
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -070012import errno
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -080013import multiprocessing
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070014import os
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010015import re
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -070016import socket
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070017
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080018from chromite.cli.cros import cros_chrome_sdk
19from chromite.lib import cache
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070020from chromite.lib import commandline
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080021from chromite.lib import constants
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070022from chromite.lib import cros_build_lib
23from chromite.lib import cros_logging as logging
Mike Frysinger10666292018-07-12 01:03:38 -040024from chromite.lib import memoize
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070025from chromite.lib import osutils
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080026from chromite.lib import path_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070027from chromite.lib import remote_access
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -070028from chromite.lib import retry_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070029
30
31class VMError(Exception):
32 """Exception for VM failures."""
33
34 def __init__(self, message):
35 super(VMError, self).__init__()
36 logging.error(message)
37
38
39class VM(object):
40 """Class for managing a VM."""
41
42 SSH_PORT = 9222
Nicolas Norvezf527cdf2018-01-26 11:55:44 -080043 IMAGE_FORMAT = 'raw'
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070044
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070045 def __init__(self, opts):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070046 """Initialize VM.
47
48 Args:
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070049 opts: command line options.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070050 """
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010051 self.qemu_path = opts.qemu_path
Ben Pastene243302c2018-09-21 16:06:08 -070052 self.qemu_img_path = opts.qemu_img_path
Achuith Bhandarkar41259652017-11-14 10:31:02 -080053 self.qemu_bios_path = opts.qemu_bios_path
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -080054 self.qemu_m = opts.qemu_m
55 self.qemu_cpu = opts.qemu_cpu
56 self.qemu_smp = opts.qemu_smp
57 if self.qemu_smp == 0:
58 self.qemu_smp = min(8, multiprocessing.cpu_count)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010059 self.enable_kvm = opts.enable_kvm
Ben Pastene243302c2018-09-21 16:06:08 -070060 self.copy_on_write = opts.copy_on_write
Achuith Bhandarkarf877da22017-09-12 12:27:39 -070061 # We don't need sudo access for software emulation or if /dev/kvm is
62 # writeable.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010063 self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK)
64 self.display = opts.display
65 self.image_path = opts.image_path
Nicolas Norvezf527cdf2018-01-26 11:55:44 -080066 self.image_format = opts.image_format
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080067 self.board = opts.board
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010068 self.ssh_port = opts.ssh_port
Achuith Bhandarkar195b9512018-08-15 17:14:32 -070069 self.private_key = opts.private_key
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010070 self.dry_run = opts.dry_run
Achuith Bhandarkar195b9512018-08-15 17:14:32 -070071 # log_level is only set if --log-level or --debug is specified.
72 self.log_level = getattr(opts, 'log_level', None)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010073
74 self.start = opts.start
75 self.stop = opts.stop
76 self.cmd = opts.args[1:] if opts.cmd else None
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070077
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +020078 self.cache_dir = os.path.abspath(opts.cache_dir)
79 assert os.path.isdir(self.cache_dir), "Cache directory doesn't exist"
80
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070081 self.vm_dir = opts.vm_dir
82 if not self.vm_dir:
83 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(),
84 'cros_vm_%d' % self.ssh_port)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -070085 self._CreateVMDir()
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070086
87 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
88 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070089 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
90 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
91 self.kvm_serial = '%s.serial' % self.kvm_monitor
92
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070093 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar195b9512018-08-15 17:14:32 -070094 port=self.ssh_port,
95 private_key=self.private_key)
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070096 self.device_addr = 'ssh://%s:%d' % (remote_access.LOCALHOST, self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070097
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070098 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
99 # moblab, etc.
100
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700101 def _RunCommand(self, *args, **kwargs):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700102 """Use SudoRunCommand or RunCommand as necessary.
103
104 Args:
105 args and kwargs: positional and optional args to RunCommand.
106
107 Returns:
108 cros_build_lib.CommandResult object.
109 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700110 if self.use_sudo:
111 return cros_build_lib.SudoRunCommand(*args, **kwargs)
112 else:
113 return cros_build_lib.RunCommand(*args, **kwargs)
114
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700115 def _CreateVMDir(self):
116 """Safely create vm_dir."""
Steven Bennettsc57ca0e2018-09-18 09:33:59 -0700117 if not osutils.SafeMakedirs(self.vm_dir):
118 # For security, ensure that vm_dir is not a symlink, and is owned by us.
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700119 error_str = ('VM state dir is misconfigured; please recreate: %s'
120 % self.vm_dir)
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700121 assert os.path.isdir(self.vm_dir), error_str
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700122 assert not os.path.islink(self.vm_dir), error_str
Steven Bennettsc57ca0e2018-09-18 09:33:59 -0700123 assert os.stat(self.vm_dir).st_uid == os.getuid(), error_str
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700124
Ben Pastene243302c2018-09-21 16:06:08 -0700125 def _CreateQcow2Image(self):
126 """Creates a qcow2-formatted image in the temporary VM dir.
127
128 This image will get removed on VM shutdown.
129 """
130 cow_image_path = os.path.join(self.vm_dir, 'qcow2.img')
131 qemu_img_args = [
132 self.qemu_img_path,
133 'create', '-f', 'qcow2',
134 '-o', 'backing_file=%s' % self.image_path,
135 cow_image_path,
136 ]
137 if not self.dry_run:
138 self._RunCommand(qemu_img_args)
139 logging.info('qcow2 image created at %s.', cow_image_path)
140 else:
141 logging.info(cros_build_lib.CmdToStr(qemu_img_args))
142 self.image_path = cow_image_path
143 self.image_format = 'qcow2'
144
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700145 def _RmVMDir(self):
146 """Cleanup vm_dir."""
Mike Frysinger97080242017-09-13 01:58:45 -0400147 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700148
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200149 def _GetCachePath(self, cache_name):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700150 """Return path to cache.
151
152 Args:
153 cache_name: Name of cache.
154
155 Returns:
156 File path of cache.
157 """
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200158 return os.path.join(self.cache_dir,
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700159 cros_chrome_sdk.COMMAND_NAME,
160 cache_name)
161
Mike Frysinger10666292018-07-12 01:03:38 -0400162 @memoize.MemoizedSingleCall
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700163 def _SDKVersion(self):
164 """Determine SDK version.
165
166 Check the environment if we're in the SDK shell, and failing that, look at
167 the misc cache.
168
169 Returns:
170 SDK version.
171 """
172 sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV)
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700173 if not sdk_version and self.board:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700174 misc_cache = cache.DiskCache(self._GetCachePath(
175 cros_chrome_sdk.SDKFetcher.MISC_CACHE))
176 with misc_cache.Lookup((self.board, 'latest')) as ref:
177 if ref.Exists(lock=True):
178 sdk_version = osutils.ReadFile(ref.path).strip()
179 return sdk_version
180
181 def _CachePathForKey(self, key):
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800182 """Get cache path for key.
183
184 Args:
185 key: cache key.
186 """
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700187 tarball_cache = cache.TarballCache(self._GetCachePath(
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800188 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700189 if self.board and self._SDKVersion():
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700190 cache_key = (self.board, self._SDKVersion(), key)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800191 with tarball_cache.Lookup(cache_key) as ref:
192 if ref.Exists():
193 return ref.path
194 return None
195
Mike Frysinger10666292018-07-12 01:03:38 -0400196 @memoize.MemoizedSingleCall
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100197 def QemuVersion(self):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700198 """Determine QEMU version.
199
200 Returns:
201 QEMU version.
202 """
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100203 version_str = self._RunCommand([self.qemu_path, '--version'],
204 capture_output=True).output
205 # version string looks like one of these:
206 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
207 # 2003-2008 Fabrice Bellard
208 #
209 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
210 #
211 # qemu-x86_64 version 2.10.1
212 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
213 m = re.search(r"version ([0-9.]+)", version_str)
214 if not m:
215 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
216 return m.group(1)
217
218 def _CheckQemuMinVersion(self):
219 """Ensure minimum QEMU version."""
220 min_qemu_version = '2.6.0'
221 logging.info('QEMU version %s', self.QemuVersion())
222 LooseVersion = distutils.version.LooseVersion
223 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
224 raise VMError('QEMU %s is the minimum supported version. You have %s.'
225 % (min_qemu_version, self.QemuVersion()))
226
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800227 def _SetQemuPath(self):
228 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800229 qemu_exe = 'qemu-system-x86_64'
230 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
231
232 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800233 if not self.qemu_path:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700234 qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800235 if qemu_dir:
236 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
237 if os.path.isfile(qemu_path):
238 self.qemu_path = qemu_path
239
240 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800241 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800242 qemu_path = os.path.join(
243 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
244 if os.path.isfile(qemu_path):
245 self.qemu_path = qemu_path
246
247 # Check system.
248 if not self.qemu_path:
249 self.qemu_path = osutils.Which(qemu_exe)
250
251 if not self.qemu_path or not os.path.isfile(self.qemu_path):
252 raise VMError('QEMU not found.')
Ben Pastene243302c2018-09-21 16:06:08 -0700253
254 if self.copy_on_write:
255 if not self.qemu_img_path:
256 # Look for qemu-img right next to qemu-system-x86_64.
257 self.qemu_img_path = os.path.join(
258 os.path.dirname(self.qemu_path), 'qemu-img')
259 if not os.path.isfile(self.qemu_img_path):
260 raise VMError('qemu-img not found. (Needed to create qcow2 image).')
261
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800262 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800263 self._CheckQemuMinVersion()
264
265 def _GetBuiltVMImagePath(self):
266 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800267 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
268 cros_build_lib.GetBoard(self.board),
269 'latest', constants.VM_IMAGE_BIN)
270 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800271
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800272 def _GetCacheVMImagePath(self):
273 """Get path of a cached VM image."""
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700274 cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800275 if cache_path:
276 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
277 if os.path.isfile(vm_image):
278 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800279 return None
280
281 def _SetVMImagePath(self):
282 """Detect VM image path in SDK and chroot."""
283 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800284 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800285 self._GetBuiltVMImagePath())
286 if not self.image_path:
287 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
288 if not os.path.isfile(self.image_path):
289 raise VMError('VM image does not exist: %s' % self.image_path)
290 logging.debug('VM image path: %s', self.image_path)
291
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700292 def _WaitForSSHPort(self):
293 """Wait for SSH port to become available."""
294 class _SSHPortInUseError(Exception):
295 """Exception for _CheckSSHPortBusy to throw."""
296
297 def _CheckSSHPortBusy(ssh_port):
298 """Check if the SSH port is in use."""
299 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
300 try:
301 sock.bind((remote_access.LOCALHOST_IP, ssh_port))
302 except socket.error as e:
303 if e.errno == errno.EADDRINUSE:
304 logging.info('SSH port %d in use...', self.ssh_port)
305 raise _SSHPortInUseError()
306 sock.close()
307
308 try:
309 retry_util.RetryException(
310 exception=_SSHPortInUseError,
311 max_retry=7,
312 functor=lambda: _CheckSSHPortBusy(self.ssh_port),
313 sleep=1)
314 except _SSHPortInUseError:
315 raise VMError('SSH port %d in use' % self.ssh_port)
316
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100317 def Run(self):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700318 """Performs an action, one of start, stop, or run a command in the VM."""
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100319 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700320 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700321
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100322 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700323 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100324 if self.cmd:
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700325 if not self.IsRunning():
326 raise VMError('VM not running.')
327 self.RemoteCommand(self.cmd, stream_output=True)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100328 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700329 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700330
331 def Start(self):
332 """Start the VM."""
333
334 self.Stop()
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700335 self._WaitForSSHPort()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700336
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700337 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800338 self._SetQemuPath()
339 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700340
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700341 self._RmVMDir()
342 self._CreateVMDir()
Ben Pastene243302c2018-09-21 16:06:08 -0700343 if self.copy_on_write:
344 self._CreateQcow2Image()
Mike Frysinger97080242017-09-13 01:58:45 -0400345 # Make sure we can read these files later on by creating them as ourselves.
346 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700347 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
Mike Frysinger0444f4c2018-08-03 15:12:46 -0400348 os.mkfifo(pipe, 0o600)
Mike Frysinger97080242017-09-13 01:58:45 -0400349 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700350
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800351 qemu_args = [self.qemu_path]
352 if self.qemu_bios_path:
353 if not os.path.isdir(self.qemu_bios_path):
354 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
355 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100356
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800357 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800358 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
359 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800360 '-pidfile', self.pidfile,
361 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
362 '-serial', 'file:%s' % self.kvm_serial,
363 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800364 # Append 'check' to warn if the requested CPU is not fully supported.
365 '-cpu', self.qemu_cpu + ',check',
Lepton Wuaa6cca42018-04-19 18:56:29 -0700366 '-device', 'virtio-net,netdev=eth0',
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700367 '-netdev', 'user,id=eth0,net=10.0.2.0/27,hostfwd=tcp:%s:%d-:22'
368 % (remote_access.LOCALHOST_IP, self.ssh_port),
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800369 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
370 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800371 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700372 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800373 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700374 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800375 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700376 logging.info('Pid file: %s', self.pidfile)
377 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800378 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800379 else:
380 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700381
382 def _GetVMPid(self):
383 """Get the pid of the VM.
384
385 Returns:
386 pid of the VM.
387 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700388 if not os.path.exists(self.vm_dir):
389 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700390 return 0
391
392 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700393 logging.info('%s does not exist.', self.pidfile)
394 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700395
Mike Frysinger97080242017-09-13 01:58:45 -0400396 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700397 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400398 # Ignore blank/empty files.
399 if pid:
400 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700401 return 0
402
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700403 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700404
405 def IsRunning(self):
406 """Returns True if there's a running VM.
407
408 Returns:
409 True if there's a running VM.
410 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700411 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700412 if not pid:
413 return False
414
415 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400416 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700417
418 def Stop(self):
419 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700420 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700421
422 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700423 if pid:
424 logging.info('Killing %d.', pid)
425 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700426 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700427 self._RmVMDir()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700428
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700429 def _WaitForProcs(self):
430 """Wait for expected processes to launch."""
431 class _TooFewPidsException(Exception):
432 """Exception for _GetRunningPids to throw."""
433
434 def _GetRunningPids(exe, numpids):
435 pids = self.remote.GetRunningPids(exe, full_path=False)
436 logging.info('%s pids: %s', exe, repr(pids))
437 if len(pids) < numpids:
438 raise _TooFewPidsException()
439
440 def _WaitForProc(exe, numpids):
441 try:
442 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700443 exception=_TooFewPidsException,
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700444 max_retry=5,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700445 functor=lambda: _GetRunningPids(exe, numpids),
446 sleep=2)
447 except _TooFewPidsException:
448 raise VMError('_WaitForProcs failed: timed out while waiting for '
449 '%d %s processes to start.' % (numpids, exe))
450
451 # We could also wait for session_manager, nacl_helper, etc, but chrome is
452 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
453 # This could potentially break with Mustash.
454 _WaitForProc('chrome', 5)
455
456 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700457 """Wait for the VM to boot up.
458
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700459 Wait for ssh connection to become active, and wait for all expected chrome
460 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700461 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700462 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700463 self.Start()
464
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700465 try:
466 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700467 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700468 max_retry=10,
469 functor=lambda: self.RemoteCommand(cmd=['echo']),
470 sleep=5)
471 except remote_access.SSHConnectionError:
472 raise VMError('WaitForBoot timed out trying to connect to VM.')
473
474 if result.returncode != 0:
475 raise VMError('WaitForBoot failed: %s.' % result.error)
476
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100477 # Chrome can take a while to start with software emulation.
478 if not self.enable_kvm:
479 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700480
Achuith Bhandarkarbad755b2018-06-09 16:05:01 -0700481 def RemoteCommand(self, cmd, stream_output=False, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700482 """Run a remote command in the VM.
483
484 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100485 cmd: command to run.
Achuith Bhandarkarbad755b2018-06-09 16:05:01 -0700486 stream_output: Stream output of long-running commands.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100487 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700488
489 Returns:
490 cros_build_lib.CommandResult object.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700491 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700492 if not self.dry_run:
Achuith Bhandarkarbad755b2018-06-09 16:05:01 -0700493 kwargs.setdefault('error_code_ok', True)
494 if stream_output:
495 kwargs.setdefault('capture_output', False)
496 else:
497 kwargs.setdefault('combine_stdout_stderr', True)
498 kwargs.setdefault('log_output', True)
499 return self.remote.RunCommand(cmd, debug_level=logging.INFO, **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700500
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100501 @staticmethod
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700502 def GetParser():
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100503 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700504
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100505 Args:
506 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700507
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100508 Returns:
509 List of parsed opts.
510 """
511 parser = commandline.ArgumentParser(description=__doc__)
512 parser.add_argument('--start', action='store_true', default=False,
513 help='Start the VM.')
514 parser.add_argument('--stop', action='store_true', default=False,
515 help='Stop the VM.')
Ben Pastene243302c2018-09-21 16:06:08 -0700516 parser.add_argument('--image-path', type='path',
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100517 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800518 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
519 help='Format of the VM image (raw, qcow2, ...).')
Ben Pastene243302c2018-09-21 16:06:08 -0700520 parser.add_argument('--qemu-path', type='path',
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100521 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800522 parser.add_argument('--qemu-m', type=str, default='8G',
523 help='Memory argument that will be passed to qemu.')
524 parser.add_argument('--qemu-smp', type=int, default='0',
525 help='SMP argument that will be passed to qemu. (0 '
526 'means auto-detection.)')
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800527 # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine
528 # running VMTest all migrate to GCE.
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800529 parser.add_argument('--qemu-cpu', type=str,
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800530 default='SandyBridge,-invpcid,-tsc-deadline',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800531 help='CPU argument that will be passed to qemu.')
Ben Pastene243302c2018-09-21 16:06:08 -0700532 parser.add_argument('--qemu-bios-path', type='path',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800533 help='Path of directory with qemu bios files.')
Ben Pastene243302c2018-09-21 16:06:08 -0700534 parser.add_argument('--copy-on-write', action='store_true', default=False,
535 help='Generates a temporary copy-on-write image backed '
536 'by the normal boot image. All filesystem changes '
537 'will instead be reflected in the temporary '
538 'image.')
539 parser.add_argument('--qemu-img-path', type='path',
540 help='Path to qemu-img binary used to create temporary '
541 'copy-on-write images.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100542 parser.add_argument('--disable-kvm', dest='enable_kvm',
543 action='store_false', default=True,
544 help='Disable KVM, use software emulation.')
545 parser.add_argument('--no-display', dest='display',
546 action='store_false', default=True,
547 help='Do not display video output.')
548 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
549 help='ssh port to communicate with VM.')
Achuith Bhandarkar195b9512018-08-15 17:14:32 -0700550 parser.add_argument('--private-key', help='Path to ssh private key.')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800551 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
552 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
Ben Pastene243302c2018-09-21 16:06:08 -0700553 parser.add_argument('--cache-dir', type='path',
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200554 default=path_util.GetCacheDir(),
555 help='Cache directory to use.')
Ben Pastene243302c2018-09-21 16:06:08 -0700556 parser.add_argument('--vm-dir', type='path',
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700557 help='Temp VM directory to use.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100558 parser.add_argument('--dry-run', action='store_true', default=False,
559 help='dry run for debugging.')
560 parser.add_argument('--cmd', action='store_true', default=False,
561 help='Run a command in the VM.')
562 parser.add_argument('args', nargs=argparse.REMAINDER,
563 help='Command to run in the VM.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700564 return parser
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700565
566def main(argv):
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700567 opts = VM.GetParser().parse_args(argv)
568 opts.Freeze()
569
570 vm = VM(opts)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100571 vm.Run()