blob: 351bf410d64f77fc889e0f7eec90d0a8e4e36ea7 [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
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -070031class DeviceError(Exception):
32 """Exception for Device failures."""
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070033
34 def __init__(self, message):
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -070035 super(DeviceError, self).__init__()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070036 logging.error(message)
37
38
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -070039class Device(object):
40 """Class for managing a test device."""
41
42 def __init__(self, opts):
43 """Initialize Device.
44
45 Args:
46 opts: command line options.
47 """
48 self.device = opts.device
49 self.ssh_port = None
50 self.board = opts.board
51
52 self.cmd = opts.args[1:] if opts.cmd else None
53 self.private_key = opts.private_key
54 self.dry_run = opts.dry_run
55 # log_level is only set if --log-level or --debug is specified.
56 self.log_level = getattr(opts, 'log_level', None)
57 self.InitRemote()
58
59 def InitRemote(self):
60 """Initialize remote access."""
61 self.remote = remote_access.RemoteDevice(self.device,
62 port=self.ssh_port,
63 private_key=self.private_key)
64
65 self.device_addr = 'ssh://%s' % self.device
66 if self.ssh_port:
67 self.device_addr += ':%d' % self.ssh_port
68
69 def WaitForBoot(self):
70 """Wait for the device to boot up.
71
72 Wait for the ssh connection to become active.
73 """
74 try:
75 result = retry_util.RetryException(
76 exception=remote_access.SSHConnectionError,
77 max_retry=10,
78 functor=lambda: self.RemoteCommand(cmd=['echo']),
79 sleep=5)
80 except remote_access.SSHConnectionError:
81 raise DeviceError(
82 'WaitForBoot timed out trying to connect to the device.')
83
84 if result.returncode != 0:
85 raise DeviceError('WaitForBoot failed: %s.' % result.error)
86
87 def RemoteCommand(self, cmd, stream_output=False, **kwargs):
88 """Run a remote command.
89
90 Args:
91 cmd: command to run.
92 stream_output: Stream output of long-running commands.
93 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
94
95 Returns:
96 cros_build_lib.CommandResult object.
97 """
98 if not self.dry_run:
99 kwargs.setdefault('error_code_ok', True)
100 if stream_output:
101 kwargs.setdefault('capture_output', False)
102 else:
103 kwargs.setdefault('combine_stdout_stderr', True)
104 kwargs.setdefault('log_output', True)
105 return self.remote.RunCommand(cmd, debug_level=logging.INFO, **kwargs)
106
107 @property
108 def is_vm(self):
109 """Returns true if we're a VM."""
110 return self._IsVM(self.device)
111
112 @staticmethod
113 def _IsVM(device):
114 """VM if |device| is specified and it's not localhost."""
115 return not device or device == remote_access.LOCALHOST
116
117 @staticmethod
118 def Create(opts):
119 """Create either a Device or VM based on |opts.device|."""
120 if Device._IsVM(opts.device):
121 return VM(opts)
122 return Device(opts)
123
124 @staticmethod
125 def GetParser():
126 """Parse a list of args.
127
128 Args:
129 argv: list of command line arguments.
130
131 Returns:
132 List of parsed opts.
133 """
134 parser = commandline.ArgumentParser(description=__doc__)
135 parser.add_argument('--device', help='Hostname or Device IP.')
136 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
137 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
138 parser.add_argument('--private-key', help='Path to ssh private key.')
139 parser.add_argument('--dry-run', action='store_true', default=False,
140 help='dry run for debugging.')
141 parser.add_argument('--cmd', action='store_true', default=False,
142 help='Run a command.')
143 parser.add_argument('args', nargs=argparse.REMAINDER,
144 help='Command to run.')
145 return parser
146
147
148class VMError(DeviceError):
149 """Exception for VM failures."""
150
151
152class VM(Device):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700153 """Class for managing a VM."""
154
155 SSH_PORT = 9222
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800156 IMAGE_FORMAT = 'raw'
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700157
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700158 def __init__(self, opts):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700159 """Initialize VM.
160
161 Args:
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700162 opts: command line options.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700163 """
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -0700164 super(VM, self).__init__(opts)
165
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100166 self.qemu_path = opts.qemu_path
Ben Pastene243302c2018-09-21 16:06:08 -0700167 self.qemu_img_path = opts.qemu_img_path
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800168 self.qemu_bios_path = opts.qemu_bios_path
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800169 self.qemu_m = opts.qemu_m
170 self.qemu_cpu = opts.qemu_cpu
171 self.qemu_smp = opts.qemu_smp
172 if self.qemu_smp == 0:
173 self.qemu_smp = min(8, multiprocessing.cpu_count)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100174 self.enable_kvm = opts.enable_kvm
Ben Pastene243302c2018-09-21 16:06:08 -0700175 self.copy_on_write = opts.copy_on_write
Achuith Bhandarkarf877da22017-09-12 12:27:39 -0700176 # We don't need sudo access for software emulation or if /dev/kvm is
177 # writeable.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100178 self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK)
179 self.display = opts.display
180 self.image_path = opts.image_path
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800181 self.image_format = opts.image_format
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -0700182
183 self.device = remote_access.LOCALHOST
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100184 self.ssh_port = opts.ssh_port
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100185
186 self.start = opts.start
187 self.stop = opts.stop
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700188
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200189 self.cache_dir = os.path.abspath(opts.cache_dir)
190 assert os.path.isdir(self.cache_dir), "Cache directory doesn't exist"
191
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700192 self.vm_dir = opts.vm_dir
193 if not self.vm_dir:
194 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(),
195 'cros_vm_%d' % self.ssh_port)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700196 self._CreateVMDir()
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700197
198 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
199 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700200 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
201 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
202 self.kvm_serial = '%s.serial' % self.kvm_monitor
203
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -0700204 self.InitRemote()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700205
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700206 def _RunCommand(self, *args, **kwargs):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700207 """Use SudoRunCommand or RunCommand as necessary.
208
209 Args:
210 args and kwargs: positional and optional args to RunCommand.
211
212 Returns:
213 cros_build_lib.CommandResult object.
214 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700215 if self.use_sudo:
216 return cros_build_lib.SudoRunCommand(*args, **kwargs)
217 else:
218 return cros_build_lib.RunCommand(*args, **kwargs)
219
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700220 def _CreateVMDir(self):
221 """Safely create vm_dir."""
Steven Bennettsc57ca0e2018-09-18 09:33:59 -0700222 if not osutils.SafeMakedirs(self.vm_dir):
223 # For security, ensure that vm_dir is not a symlink, and is owned by us.
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700224 error_str = ('VM state dir is misconfigured; please recreate: %s'
225 % self.vm_dir)
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700226 assert os.path.isdir(self.vm_dir), error_str
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700227 assert not os.path.islink(self.vm_dir), error_str
Steven Bennettsc57ca0e2018-09-18 09:33:59 -0700228 assert os.stat(self.vm_dir).st_uid == os.getuid(), error_str
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700229
Ben Pastene243302c2018-09-21 16:06:08 -0700230 def _CreateQcow2Image(self):
231 """Creates a qcow2-formatted image in the temporary VM dir.
232
233 This image will get removed on VM shutdown.
234 """
235 cow_image_path = os.path.join(self.vm_dir, 'qcow2.img')
236 qemu_img_args = [
237 self.qemu_img_path,
238 'create', '-f', 'qcow2',
239 '-o', 'backing_file=%s' % self.image_path,
240 cow_image_path,
241 ]
242 if not self.dry_run:
243 self._RunCommand(qemu_img_args)
244 logging.info('qcow2 image created at %s.', cow_image_path)
245 else:
246 logging.info(cros_build_lib.CmdToStr(qemu_img_args))
247 self.image_path = cow_image_path
248 self.image_format = 'qcow2'
249
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700250 def _RmVMDir(self):
251 """Cleanup vm_dir."""
Mike Frysinger97080242017-09-13 01:58:45 -0400252 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700253
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200254 def _GetCachePath(self, cache_name):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700255 """Return path to cache.
256
257 Args:
258 cache_name: Name of cache.
259
260 Returns:
261 File path of cache.
262 """
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200263 return os.path.join(self.cache_dir,
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700264 cros_chrome_sdk.COMMAND_NAME,
265 cache_name)
266
Mike Frysinger10666292018-07-12 01:03:38 -0400267 @memoize.MemoizedSingleCall
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700268 def _SDKVersion(self):
269 """Determine SDK version.
270
271 Check the environment if we're in the SDK shell, and failing that, look at
272 the misc cache.
273
274 Returns:
275 SDK version.
276 """
277 sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV)
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700278 if not sdk_version and self.board:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700279 misc_cache = cache.DiskCache(self._GetCachePath(
280 cros_chrome_sdk.SDKFetcher.MISC_CACHE))
281 with misc_cache.Lookup((self.board, 'latest')) as ref:
282 if ref.Exists(lock=True):
283 sdk_version = osutils.ReadFile(ref.path).strip()
284 return sdk_version
285
286 def _CachePathForKey(self, key):
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800287 """Get cache path for key.
288
289 Args:
290 key: cache key.
291 """
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700292 tarball_cache = cache.TarballCache(self._GetCachePath(
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800293 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700294 if self.board and self._SDKVersion():
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700295 cache_key = (self.board, self._SDKVersion(), key)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800296 with tarball_cache.Lookup(cache_key) as ref:
297 if ref.Exists():
298 return ref.path
299 return None
300
Mike Frysinger10666292018-07-12 01:03:38 -0400301 @memoize.MemoizedSingleCall
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100302 def QemuVersion(self):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700303 """Determine QEMU version.
304
305 Returns:
306 QEMU version.
307 """
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100308 version_str = self._RunCommand([self.qemu_path, '--version'],
309 capture_output=True).output
310 # version string looks like one of these:
311 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
312 # 2003-2008 Fabrice Bellard
313 #
314 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
315 #
316 # qemu-x86_64 version 2.10.1
317 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
318 m = re.search(r"version ([0-9.]+)", version_str)
319 if not m:
320 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
321 return m.group(1)
322
323 def _CheckQemuMinVersion(self):
324 """Ensure minimum QEMU version."""
325 min_qemu_version = '2.6.0'
326 logging.info('QEMU version %s', self.QemuVersion())
327 LooseVersion = distutils.version.LooseVersion
328 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
329 raise VMError('QEMU %s is the minimum supported version. You have %s.'
330 % (min_qemu_version, self.QemuVersion()))
331
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800332 def _SetQemuPath(self):
333 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800334 qemu_exe = 'qemu-system-x86_64'
335 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
336
337 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800338 if not self.qemu_path:
Achuith Bhandarkar761322d2018-10-24 12:26:06 -0700339 qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_PATH)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800340 if qemu_dir:
341 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
342 if os.path.isfile(qemu_path):
343 self.qemu_path = qemu_path
344
345 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800346 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800347 qemu_path = os.path.join(
348 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
349 if os.path.isfile(qemu_path):
350 self.qemu_path = qemu_path
351
352 # Check system.
353 if not self.qemu_path:
354 self.qemu_path = osutils.Which(qemu_exe)
355
356 if not self.qemu_path or not os.path.isfile(self.qemu_path):
357 raise VMError('QEMU not found.')
Ben Pastene243302c2018-09-21 16:06:08 -0700358
359 if self.copy_on_write:
360 if not self.qemu_img_path:
361 # Look for qemu-img right next to qemu-system-x86_64.
362 self.qemu_img_path = os.path.join(
363 os.path.dirname(self.qemu_path), 'qemu-img')
364 if not os.path.isfile(self.qemu_img_path):
365 raise VMError('qemu-img not found. (Needed to create qcow2 image).')
366
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800367 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800368 self._CheckQemuMinVersion()
369
370 def _GetBuiltVMImagePath(self):
371 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800372 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
373 cros_build_lib.GetBoard(self.board),
374 'latest', constants.VM_IMAGE_BIN)
375 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800376
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800377 def _GetCacheVMImagePath(self):
378 """Get path of a cached VM image."""
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700379 cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800380 if cache_path:
381 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
382 if os.path.isfile(vm_image):
383 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800384 return None
385
386 def _SetVMImagePath(self):
387 """Detect VM image path in SDK and chroot."""
388 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800389 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800390 self._GetBuiltVMImagePath())
391 if not self.image_path:
392 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
393 if not os.path.isfile(self.image_path):
394 raise VMError('VM image does not exist: %s' % self.image_path)
395 logging.debug('VM image path: %s', self.image_path)
396
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700397 def _WaitForSSHPort(self):
398 """Wait for SSH port to become available."""
399 class _SSHPortInUseError(Exception):
400 """Exception for _CheckSSHPortBusy to throw."""
401
402 def _CheckSSHPortBusy(ssh_port):
403 """Check if the SSH port is in use."""
404 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
405 try:
406 sock.bind((remote_access.LOCALHOST_IP, ssh_port))
407 except socket.error as e:
408 if e.errno == errno.EADDRINUSE:
409 logging.info('SSH port %d in use...', self.ssh_port)
410 raise _SSHPortInUseError()
411 sock.close()
412
413 try:
414 retry_util.RetryException(
415 exception=_SSHPortInUseError,
416 max_retry=7,
417 functor=lambda: _CheckSSHPortBusy(self.ssh_port),
418 sleep=1)
419 except _SSHPortInUseError:
420 raise VMError('SSH port %d in use' % self.ssh_port)
421
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100422 def Run(self):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700423 """Performs an action, one of start, stop, or run a command in the VM."""
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100424 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700425 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700426
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100427 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700428 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100429 if self.cmd:
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700430 if not self.IsRunning():
431 raise VMError('VM not running.')
432 self.RemoteCommand(self.cmd, stream_output=True)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100433 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700434 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700435
436 def Start(self):
437 """Start the VM."""
438
439 self.Stop()
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700440 self._WaitForSSHPort()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700441
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700442 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800443 self._SetQemuPath()
444 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700445
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700446 self._RmVMDir()
447 self._CreateVMDir()
Ben Pastene243302c2018-09-21 16:06:08 -0700448 if self.copy_on_write:
449 self._CreateQcow2Image()
Mike Frysinger97080242017-09-13 01:58:45 -0400450 # Make sure we can read these files later on by creating them as ourselves.
451 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700452 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
Mike Frysinger0444f4c2018-08-03 15:12:46 -0400453 os.mkfifo(pipe, 0o600)
Mike Frysinger97080242017-09-13 01:58:45 -0400454 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700455
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800456 qemu_args = [self.qemu_path]
457 if self.qemu_bios_path:
458 if not os.path.isdir(self.qemu_bios_path):
459 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
460 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100461
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800462 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800463 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
464 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800465 '-pidfile', self.pidfile,
466 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
467 '-serial', 'file:%s' % self.kvm_serial,
468 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800469 # Append 'check' to warn if the requested CPU is not fully supported.
470 '-cpu', self.qemu_cpu + ',check',
Lepton Wuaa6cca42018-04-19 18:56:29 -0700471 '-device', 'virtio-net,netdev=eth0',
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700472 '-netdev', 'user,id=eth0,net=10.0.2.0/27,hostfwd=tcp:%s:%d-:22'
473 % (remote_access.LOCALHOST_IP, self.ssh_port),
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800474 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
475 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800476 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700477 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800478 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700479 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800480 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700481 logging.info('Pid file: %s', self.pidfile)
482 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800483 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800484 else:
485 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700486
487 def _GetVMPid(self):
488 """Get the pid of the VM.
489
490 Returns:
491 pid of the VM.
492 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700493 if not os.path.exists(self.vm_dir):
494 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700495 return 0
496
497 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700498 logging.info('%s does not exist.', self.pidfile)
499 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700500
Mike Frysinger97080242017-09-13 01:58:45 -0400501 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700502 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400503 # Ignore blank/empty files.
504 if pid:
505 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700506 return 0
507
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700508 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700509
510 def IsRunning(self):
511 """Returns True if there's a running VM.
512
513 Returns:
514 True if there's a running VM.
515 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700516 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700517 if not pid:
518 return False
519
520 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400521 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700522
523 def Stop(self):
524 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700525 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700526
527 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700528 if pid:
529 logging.info('Killing %d.', pid)
530 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700531 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700532 self._RmVMDir()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700533
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700534 def _WaitForProcs(self):
535 """Wait for expected processes to launch."""
536 class _TooFewPidsException(Exception):
537 """Exception for _GetRunningPids to throw."""
538
539 def _GetRunningPids(exe, numpids):
540 pids = self.remote.GetRunningPids(exe, full_path=False)
541 logging.info('%s pids: %s', exe, repr(pids))
542 if len(pids) < numpids:
543 raise _TooFewPidsException()
544
545 def _WaitForProc(exe, numpids):
546 try:
547 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700548 exception=_TooFewPidsException,
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700549 max_retry=5,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700550 functor=lambda: _GetRunningPids(exe, numpids),
551 sleep=2)
552 except _TooFewPidsException:
553 raise VMError('_WaitForProcs failed: timed out while waiting for '
554 '%d %s processes to start.' % (numpids, exe))
555
556 # We could also wait for session_manager, nacl_helper, etc, but chrome is
557 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
558 # This could potentially break with Mustash.
559 _WaitForProc('chrome', 5)
560
561 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700562 """Wait for the VM to boot up.
563
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700564 Wait for ssh connection to become active, and wait for all expected chrome
565 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700566 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700567 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700568 self.Start()
569
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -0700570 super(VM, self).WaitForBoot()
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700571
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100572 # Chrome can take a while to start with software emulation.
573 if not self.enable_kvm:
574 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700575
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100576 @staticmethod
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700577 def GetParser():
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100578 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700579
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100580 Args:
581 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700582
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100583 Returns:
584 List of parsed opts.
585 """
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -0700586 device_parser = Device.GetParser()
587 parser = commandline.ArgumentParser(description=__doc__,
588 parents=[device_parser],
589 add_help=False, logging=False)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100590 parser.add_argument('--start', action='store_true', default=False,
591 help='Start the VM.')
592 parser.add_argument('--stop', action='store_true', default=False,
593 help='Stop the VM.')
Ben Pastene243302c2018-09-21 16:06:08 -0700594 parser.add_argument('--image-path', type='path',
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100595 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800596 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
597 help='Format of the VM image (raw, qcow2, ...).')
Ben Pastene243302c2018-09-21 16:06:08 -0700598 parser.add_argument('--qemu-path', type='path',
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100599 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800600 parser.add_argument('--qemu-m', type=str, default='8G',
601 help='Memory argument that will be passed to qemu.')
602 parser.add_argument('--qemu-smp', type=int, default='0',
603 help='SMP argument that will be passed to qemu. (0 '
604 'means auto-detection.)')
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800605 # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine
606 # running VMTest all migrate to GCE.
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800607 parser.add_argument('--qemu-cpu', type=str,
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800608 default='SandyBridge,-invpcid,-tsc-deadline',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800609 help='CPU argument that will be passed to qemu.')
Ben Pastene243302c2018-09-21 16:06:08 -0700610 parser.add_argument('--qemu-bios-path', type='path',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800611 help='Path of directory with qemu bios files.')
Ben Pastene243302c2018-09-21 16:06:08 -0700612 parser.add_argument('--copy-on-write', action='store_true', default=False,
613 help='Generates a temporary copy-on-write image backed '
614 'by the normal boot image. All filesystem changes '
615 'will instead be reflected in the temporary '
616 'image.')
617 parser.add_argument('--qemu-img-path', type='path',
618 help='Path to qemu-img binary used to create temporary '
619 'copy-on-write images.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100620 parser.add_argument('--disable-kvm', dest='enable_kvm',
621 action='store_false', default=True,
622 help='Disable KVM, use software emulation.')
623 parser.add_argument('--no-display', dest='display',
624 action='store_false', default=True,
625 help='Do not display video output.')
626 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
627 help='ssh port to communicate with VM.')
Ben Pastene243302c2018-09-21 16:06:08 -0700628 parser.add_argument('--cache-dir', type='path',
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200629 default=path_util.GetCacheDir(),
630 help='Cache directory to use.')
Ben Pastene243302c2018-09-21 16:06:08 -0700631 parser.add_argument('--vm-dir', type='path',
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700632 help='Temp VM directory to use.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700633 return parser
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700634
Achuith Bhandarkar9f49aca2018-10-30 17:46:07 -0700635
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700636def main(argv):
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700637 opts = VM.GetParser().parse_args(argv)
638 opts.Freeze()
639
640 vm = VM(opts)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100641 vm.Run()