blob: 7da6628a6247ba0784b9ff0888e1450b45772992 [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
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -080012import multiprocessing
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070013import os
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010014import re
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070015
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080016from chromite.cli.cros import cros_chrome_sdk
17from chromite.lib import cache
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070018from chromite.lib import commandline
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080019from chromite.lib import constants
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070020from chromite.lib import cros_build_lib
21from chromite.lib import cros_logging as logging
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070022from chromite.lib import osutils
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080023from chromite.lib import path_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070024from chromite.lib import remote_access
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -070025from chromite.lib import retry_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070026
27
28class VMError(Exception):
29 """Exception for VM failures."""
30
31 def __init__(self, message):
32 super(VMError, self).__init__()
33 logging.error(message)
34
35
36class VM(object):
37 """Class for managing a VM."""
38
39 SSH_PORT = 9222
Nicolas Norvezf527cdf2018-01-26 11:55:44 -080040 IMAGE_FORMAT = 'raw'
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070041
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070042 def __init__(self, opts):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070043 """Initialize VM.
44
45 Args:
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070046 opts: command line options.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070047 """
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010048 self.qemu_path = opts.qemu_path
Achuith Bhandarkar41259652017-11-14 10:31:02 -080049 self.qemu_bios_path = opts.qemu_bios_path
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -080050 self.qemu_m = opts.qemu_m
51 self.qemu_cpu = opts.qemu_cpu
52 self.qemu_smp = opts.qemu_smp
53 if self.qemu_smp == 0:
54 self.qemu_smp = min(8, multiprocessing.cpu_count)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010055 self.enable_kvm = opts.enable_kvm
Achuith Bhandarkarf877da22017-09-12 12:27:39 -070056 # We don't need sudo access for software emulation or if /dev/kvm is
57 # writeable.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010058 self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK)
59 self.display = opts.display
60 self.image_path = opts.image_path
Nicolas Norvezf527cdf2018-01-26 11:55:44 -080061 self.image_format = opts.image_format
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080062 self.board = opts.board
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010063 self.ssh_port = opts.ssh_port
64 self.dry_run = opts.dry_run
65
66 self.start = opts.start
67 self.stop = opts.stop
68 self.cmd = opts.args[1:] if opts.cmd else None
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070069
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +020070 self.cache_dir = os.path.abspath(opts.cache_dir)
71 assert os.path.isdir(self.cache_dir), "Cache directory doesn't exist"
72
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070073 self.vm_dir = opts.vm_dir
74 if not self.vm_dir:
75 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(),
76 'cros_vm_%d' % self.ssh_port)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -070077 self._CreateVMDir()
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070078
79 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
80 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070081 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
82 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
83 self.kvm_serial = '%s.serial' % self.kvm_monitor
84
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070085 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010086 port=self.ssh_port)
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070087 self.device_addr = 'ssh://%s:%d' % (remote_access.LOCALHOST, self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070088
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070089 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
90 # moblab, etc.
91
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070092 def _RunCommand(self, *args, **kwargs):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -070093 """Use SudoRunCommand or RunCommand as necessary.
94
95 Args:
96 args and kwargs: positional and optional args to RunCommand.
97
98 Returns:
99 cros_build_lib.CommandResult object.
100 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700101 if self.use_sudo:
102 return cros_build_lib.SudoRunCommand(*args, **kwargs)
103 else:
104 return cros_build_lib.RunCommand(*args, **kwargs)
105
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700106 def _CreateVMDir(self):
107 """Safely create vm_dir."""
108 if not osutils.SafeMakedirs(self.vm_dir, sudo=self.use_sudo):
109 # For security, ensure that vm_dir is not a symlink, and is owned by us or
110 # by root.
111 error_str = ('VM state dir is misconfigured; please recreate: %s'
112 % self.vm_dir)
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700113 assert os.path.isdir(self.vm_dir), error_str
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700114 assert not os.path.islink(self.vm_dir), error_str
115 st_uid = os.stat(self.vm_dir).st_uid
116 assert st_uid == 0 or st_uid == os.getuid(), error_str
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700117
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700118 def _RmVMDir(self):
119 """Cleanup vm_dir."""
Mike Frysinger97080242017-09-13 01:58:45 -0400120 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700121
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200122 def _GetCachePath(self, cache_name):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700123 """Return path to cache.
124
125 Args:
126 cache_name: Name of cache.
127
128 Returns:
129 File path of cache.
130 """
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200131 return os.path.join(self.cache_dir,
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700132 cros_chrome_sdk.COMMAND_NAME,
133 cache_name)
134
135 @cros_build_lib.MemoizedSingleCall
136 def _SDKVersion(self):
137 """Determine SDK version.
138
139 Check the environment if we're in the SDK shell, and failing that, look at
140 the misc cache.
141
142 Returns:
143 SDK version.
144 """
145 sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV)
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700146 if not sdk_version and self.board:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700147 misc_cache = cache.DiskCache(self._GetCachePath(
148 cros_chrome_sdk.SDKFetcher.MISC_CACHE))
149 with misc_cache.Lookup((self.board, 'latest')) as ref:
150 if ref.Exists(lock=True):
151 sdk_version = osutils.ReadFile(ref.path).strip()
152 return sdk_version
153
154 def _CachePathForKey(self, key):
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800155 """Get cache path for key.
156
157 Args:
158 key: cache key.
159 """
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700160 tarball_cache = cache.TarballCache(self._GetCachePath(
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800161 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700162 if self.board and self._SDKVersion():
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700163 cache_key = (self.board, self._SDKVersion(), key)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800164 with tarball_cache.Lookup(cache_key) as ref:
165 if ref.Exists():
166 return ref.path
167 return None
168
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100169 @cros_build_lib.MemoizedSingleCall
170 def QemuVersion(self):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700171 """Determine QEMU version.
172
173 Returns:
174 QEMU version.
175 """
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100176 version_str = self._RunCommand([self.qemu_path, '--version'],
177 capture_output=True).output
178 # version string looks like one of these:
179 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
180 # 2003-2008 Fabrice Bellard
181 #
182 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
183 #
184 # qemu-x86_64 version 2.10.1
185 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
186 m = re.search(r"version ([0-9.]+)", version_str)
187 if not m:
188 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
189 return m.group(1)
190
191 def _CheckQemuMinVersion(self):
192 """Ensure minimum QEMU version."""
193 min_qemu_version = '2.6.0'
194 logging.info('QEMU version %s', self.QemuVersion())
195 LooseVersion = distutils.version.LooseVersion
196 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
197 raise VMError('QEMU %s is the minimum supported version. You have %s.'
198 % (min_qemu_version, self.QemuVersion()))
199
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800200 def _SetQemuPath(self):
201 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800202 qemu_exe = 'qemu-system-x86_64'
203 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
204
205 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800206 if not self.qemu_path:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700207 qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800208 if qemu_dir:
209 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
210 if os.path.isfile(qemu_path):
211 self.qemu_path = qemu_path
212
213 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800214 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800215 qemu_path = os.path.join(
216 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
217 if os.path.isfile(qemu_path):
218 self.qemu_path = qemu_path
219
220 # Check system.
221 if not self.qemu_path:
222 self.qemu_path = osutils.Which(qemu_exe)
223
224 if not self.qemu_path or not os.path.isfile(self.qemu_path):
225 raise VMError('QEMU not found.')
226 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800227 self._CheckQemuMinVersion()
228
229 def _GetBuiltVMImagePath(self):
230 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800231 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
232 cros_build_lib.GetBoard(self.board),
233 'latest', constants.VM_IMAGE_BIN)
234 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800235
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800236 def _GetCacheVMImagePath(self):
237 """Get path of a cached VM image."""
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700238 cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800239 if cache_path:
240 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
241 if os.path.isfile(vm_image):
242 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800243 return None
244
245 def _SetVMImagePath(self):
246 """Detect VM image path in SDK and chroot."""
247 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800248 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800249 self._GetBuiltVMImagePath())
250 if not self.image_path:
251 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
252 if not os.path.isfile(self.image_path):
253 raise VMError('VM image does not exist: %s' % self.image_path)
254 logging.debug('VM image path: %s', self.image_path)
255
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100256 def Run(self):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700257 """Performs an action, one of start, stop, or run a command in the VM."""
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100258 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700259 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700260
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100261 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700262 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100263 if self.cmd:
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700264 if not self.IsRunning():
265 raise VMError('VM not running.')
266 self.RemoteCommand(self.cmd, stream_output=True)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100267 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700268 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700269
270 def Start(self):
271 """Start the VM."""
272
273 self.Stop()
274
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700275 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800276 self._SetQemuPath()
277 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700278
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700279 self._RmVMDir()
280 self._CreateVMDir()
Mike Frysinger97080242017-09-13 01:58:45 -0400281 # Make sure we can read these files later on by creating them as ourselves.
282 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700283 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
284 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400285 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700286
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800287 qemu_args = [self.qemu_path]
288 if self.qemu_bios_path:
289 if not os.path.isdir(self.qemu_bios_path):
290 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
291 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100292
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800293 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800294 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
295 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800296 '-pidfile', self.pidfile,
297 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
298 '-serial', 'file:%s' % self.kvm_serial,
299 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800300 # Append 'check' to warn if the requested CPU is not fully supported.
301 '-cpu', self.qemu_cpu + ',check',
Lepton Wuaa6cca42018-04-19 18:56:29 -0700302 '-device', 'virtio-net,netdev=eth0',
303 '-netdev', 'user,id=eth0,net=10.0.2.0/27,hostfwd=tcp:127.0.0.1:%d-:22'
304 % self.ssh_port,
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800305 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
306 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800307 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700308 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800309 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700310 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800311 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700312 logging.info('Pid file: %s', self.pidfile)
313 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800314 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800315 else:
316 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700317
318 def _GetVMPid(self):
319 """Get the pid of the VM.
320
321 Returns:
322 pid of the VM.
323 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700324 if not os.path.exists(self.vm_dir):
325 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700326 return 0
327
328 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700329 logging.info('%s does not exist.', self.pidfile)
330 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700331
Mike Frysinger97080242017-09-13 01:58:45 -0400332 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700333 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400334 # Ignore blank/empty files.
335 if pid:
336 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700337 return 0
338
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700339 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700340
341 def IsRunning(self):
342 """Returns True if there's a running VM.
343
344 Returns:
345 True if there's a running VM.
346 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700347 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700348 if not pid:
349 return False
350
351 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400352 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700353
354 def Stop(self):
355 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700356 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700357
358 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700359 if pid:
360 logging.info('Killing %d.', pid)
361 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700362 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700363 self._RmVMDir()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700364
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700365 def _WaitForProcs(self):
366 """Wait for expected processes to launch."""
367 class _TooFewPidsException(Exception):
368 """Exception for _GetRunningPids to throw."""
369
370 def _GetRunningPids(exe, numpids):
371 pids = self.remote.GetRunningPids(exe, full_path=False)
372 logging.info('%s pids: %s', exe, repr(pids))
373 if len(pids) < numpids:
374 raise _TooFewPidsException()
375
376 def _WaitForProc(exe, numpids):
377 try:
378 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700379 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700380 max_retry=20,
381 functor=lambda: _GetRunningPids(exe, numpids),
382 sleep=2)
383 except _TooFewPidsException:
384 raise VMError('_WaitForProcs failed: timed out while waiting for '
385 '%d %s processes to start.' % (numpids, exe))
386
387 # We could also wait for session_manager, nacl_helper, etc, but chrome is
388 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
389 # This could potentially break with Mustash.
390 _WaitForProc('chrome', 5)
391
392 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700393 """Wait for the VM to boot up.
394
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700395 Wait for ssh connection to become active, and wait for all expected chrome
396 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700397 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700398 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700399 self.Start()
400
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700401 try:
402 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700403 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700404 max_retry=10,
405 functor=lambda: self.RemoteCommand(cmd=['echo']),
406 sleep=5)
407 except remote_access.SSHConnectionError:
408 raise VMError('WaitForBoot timed out trying to connect to VM.')
409
410 if result.returncode != 0:
411 raise VMError('WaitForBoot failed: %s.' % result.error)
412
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100413 # Chrome can take a while to start with software emulation.
414 if not self.enable_kvm:
415 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700416
Alec Thileniuscc35c592018-06-07 21:57:07 +0000417 def RemoteCommand(self, cmd, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700418 """Run a remote command in the VM.
419
420 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100421 cmd: command to run.
422 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700423
424 Returns:
425 cros_build_lib.CommandResult object.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700426 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700427 if not self.dry_run:
Alec Thileniuscc35c592018-06-07 21:57:07 +0000428 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
429 combine_stdout_stderr=True,
430 log_output=True,
431 error_code_ok=True,
432 **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700433
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100434 @staticmethod
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700435 def GetParser():
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100436 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700437
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100438 Args:
439 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700440
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100441 Returns:
442 List of parsed opts.
443 """
444 parser = commandline.ArgumentParser(description=__doc__)
445 parser.add_argument('--start', action='store_true', default=False,
446 help='Start the VM.')
447 parser.add_argument('--stop', action='store_true', default=False,
448 help='Stop the VM.')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700449 parser.add_argument('--image-path', type=str,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100450 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800451 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
452 help='Format of the VM image (raw, qcow2, ...).')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700453 parser.add_argument('--qemu-path', type=str,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100454 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800455 parser.add_argument('--qemu-m', type=str, default='8G',
456 help='Memory argument that will be passed to qemu.')
457 parser.add_argument('--qemu-smp', type=int, default='0',
458 help='SMP argument that will be passed to qemu. (0 '
459 'means auto-detection.)')
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800460 # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine
461 # running VMTest all migrate to GCE.
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800462 parser.add_argument('--qemu-cpu', type=str,
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800463 default='SandyBridge,-invpcid,-tsc-deadline',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800464 help='CPU argument that will be passed to qemu.')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700465 parser.add_argument('--qemu-bios-path', type=str,
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800466 help='Path of directory with qemu bios files.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100467 parser.add_argument('--disable-kvm', dest='enable_kvm',
468 action='store_false', default=True,
469 help='Disable KVM, use software emulation.')
470 parser.add_argument('--no-display', dest='display',
471 action='store_false', default=True,
472 help='Do not display video output.')
473 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
474 help='ssh port to communicate with VM.')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800475 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
476 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200477 parser.add_argument('--cache-dir', type=str,
478 default=path_util.GetCacheDir(),
479 help='Cache directory to use.')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700480 parser.add_argument('--vm-dir', type=str,
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700481 help='Temp VM directory to use.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100482 parser.add_argument('--dry-run', action='store_true', default=False,
483 help='dry run for debugging.')
484 parser.add_argument('--cmd', action='store_true', default=False,
485 help='Run a command in the VM.')
486 parser.add_argument('args', nargs=argparse.REMAINDER,
487 help='Command to run in the VM.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700488 return parser
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700489
490def main(argv):
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700491 opts = VM.GetParser().parse_args(argv)
492 opts.Freeze()
493
494 vm = VM(opts)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100495 vm.Run()