blob: 656e3044d735484d6a8082154b0401ad52c1da98 [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 Bhandarkar2beae292018-03-26 16:44:53 -070070 self.vm_dir = opts.vm_dir
71 if not self.vm_dir:
72 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(),
73 'cros_vm_%d' % self.ssh_port)
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070074 if os.path.exists(self.vm_dir):
75 # For security, ensure that vm_dir is not a symlink, and is owned by us or
76 # by root.
77 assert not os.path.islink(self.vm_dir), \
78 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
79 st_uid = os.stat(self.vm_dir).st_uid
80 assert st_uid == 0 or st_uid == os.getuid(), \
81 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
82
83 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
84 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070085 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
86 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
87 self.kvm_serial = '%s.serial' % self.kvm_monitor
88
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070089 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010090 port=self.ssh_port)
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070091 self.device_addr = 'ssh://%s:%d' % (remote_access.LOCALHOST, self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070092
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070093 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
94 # moblab, etc.
95
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070096 def _RunCommand(self, *args, **kwargs):
97 """Use SudoRunCommand or RunCommand as necessary."""
98 if self.use_sudo:
99 return cros_build_lib.SudoRunCommand(*args, **kwargs)
100 else:
101 return cros_build_lib.RunCommand(*args, **kwargs)
102
103 def _CleanupFiles(self, recreate):
104 """Cleanup vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700105
106 Args:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700107 recreate: recreate vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700108 """
Mike Frysinger97080242017-09-13 01:58:45 -0400109 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700110 if recreate:
Mike Frysinger97080242017-09-13 01:58:45 -0400111 osutils.SafeMakedirs(self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700112
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700113 @staticmethod
114 def _GetCachePath(cache_name):
115 """Return path to cache.
116
117 Args:
118 cache_name: Name of cache.
119
120 Returns:
121 File path of cache.
122 """
123 return os.path.join(path_util.GetCacheDir(),
124 cros_chrome_sdk.COMMAND_NAME,
125 cache_name)
126
127 @cros_build_lib.MemoizedSingleCall
128 def _SDKVersion(self):
129 """Determine SDK version.
130
131 Check the environment if we're in the SDK shell, and failing that, look at
132 the misc cache.
133
134 Returns:
135 SDK version.
136 """
137 sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV)
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700138 if not sdk_version and self.board:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700139 misc_cache = cache.DiskCache(self._GetCachePath(
140 cros_chrome_sdk.SDKFetcher.MISC_CACHE))
141 with misc_cache.Lookup((self.board, 'latest')) as ref:
142 if ref.Exists(lock=True):
143 sdk_version = osutils.ReadFile(ref.path).strip()
144 return sdk_version
145
146 def _CachePathForKey(self, key):
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800147 """Get cache path for key.
148
149 Args:
150 key: cache key.
151 """
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700152 tarball_cache = cache.TarballCache(self._GetCachePath(
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800153 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700154 if self.board and self._SDKVersion():
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700155 cache_key = (self.board, self._SDKVersion(), key)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800156 with tarball_cache.Lookup(cache_key) as ref:
157 if ref.Exists():
158 return ref.path
159 return None
160
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100161 @cros_build_lib.MemoizedSingleCall
162 def QemuVersion(self):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700163 """Determine QEMU version.
164
165 Returns:
166 QEMU version.
167 """
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100168 version_str = self._RunCommand([self.qemu_path, '--version'],
169 capture_output=True).output
170 # version string looks like one of these:
171 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
172 # 2003-2008 Fabrice Bellard
173 #
174 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
175 #
176 # qemu-x86_64 version 2.10.1
177 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
178 m = re.search(r"version ([0-9.]+)", version_str)
179 if not m:
180 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
181 return m.group(1)
182
183 def _CheckQemuMinVersion(self):
184 """Ensure minimum QEMU version."""
185 min_qemu_version = '2.6.0'
186 logging.info('QEMU version %s', self.QemuVersion())
187 LooseVersion = distutils.version.LooseVersion
188 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
189 raise VMError('QEMU %s is the minimum supported version. You have %s.'
190 % (min_qemu_version, self.QemuVersion()))
191
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800192 def _SetQemuPath(self):
193 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800194 qemu_exe = 'qemu-system-x86_64'
195 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
196
197 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800198 if not self.qemu_path:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700199 qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800200 if qemu_dir:
201 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
202 if os.path.isfile(qemu_path):
203 self.qemu_path = qemu_path
204
205 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800206 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800207 qemu_path = os.path.join(
208 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
209 if os.path.isfile(qemu_path):
210 self.qemu_path = qemu_path
211
212 # Check system.
213 if not self.qemu_path:
214 self.qemu_path = osutils.Which(qemu_exe)
215
216 if not self.qemu_path or not os.path.isfile(self.qemu_path):
217 raise VMError('QEMU not found.')
218 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800219 self._CheckQemuMinVersion()
220
221 def _GetBuiltVMImagePath(self):
222 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800223 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
224 cros_build_lib.GetBoard(self.board),
225 'latest', constants.VM_IMAGE_BIN)
226 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800227
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800228 def _GetCacheVMImagePath(self):
229 """Get path of a cached VM image."""
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700230 cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800231 if cache_path:
232 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
233 if os.path.isfile(vm_image):
234 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800235 return None
236
237 def _SetVMImagePath(self):
238 """Detect VM image path in SDK and chroot."""
239 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800240 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800241 self._GetBuiltVMImagePath())
242 if not self.image_path:
243 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
244 if not os.path.isfile(self.image_path):
245 raise VMError('VM image does not exist: %s' % self.image_path)
246 logging.debug('VM image path: %s', self.image_path)
247
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100248 def Run(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700249 """Performs an action, one of start, stop, or run a command in the VM.
250
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700251 Returns:
252 cmd output.
253 """
254
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100255 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700256 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100257 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700258 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100259 if self.cmd:
260 return self.RemoteCommand(self.cmd)
261 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700262 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700263
264 def Start(self):
265 """Start the VM."""
266
267 self.Stop()
268
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700269 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800270 self._SetQemuPath()
271 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700272
273 self._CleanupFiles(recreate=True)
Mike Frysinger97080242017-09-13 01:58:45 -0400274 # Make sure we can read these files later on by creating them as ourselves.
275 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700276 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
277 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400278 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700279
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800280 qemu_args = [self.qemu_path]
281 if self.qemu_bios_path:
282 if not os.path.isdir(self.qemu_bios_path):
283 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
284 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100285
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800286 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800287 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
288 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800289 '-pidfile', self.pidfile,
290 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
291 '-serial', 'file:%s' % self.kvm_serial,
292 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800293 # Append 'check' to warn if the requested CPU is not fully supported.
294 '-cpu', self.qemu_cpu + ',check',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800295 # Qemu-vlans are used by qemu to separate out network traffic on the
296 # slirp network bridge. qemu forwards traffic on a slirp vlan to all
297 # ports conected on that vlan. By default, slirp ports are on vlan
298 # 0. We explicitly set a vlan here so that another qemu VM using
299 # slirp doesn't conflict with our network traffic.
300 '-net', 'nic,model=virtio,vlan=%d' % self.ssh_port,
301 '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22,vlan=%d'
302 % (self.ssh_port, self.ssh_port),
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800303 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
304 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800305 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700306 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800307 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700308 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800309 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700310 logging.info('Pid file: %s', self.pidfile)
311 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800312 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800313 else:
314 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700315
316 def _GetVMPid(self):
317 """Get the pid of the VM.
318
319 Returns:
320 pid of the VM.
321 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700322 if not os.path.exists(self.vm_dir):
323 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700324 return 0
325
326 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700327 logging.info('%s does not exist.', self.pidfile)
328 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700329
Mike Frysinger97080242017-09-13 01:58:45 -0400330 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700331 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400332 # Ignore blank/empty files.
333 if pid:
334 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700335 return 0
336
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700337 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700338
339 def IsRunning(self):
340 """Returns True if there's a running VM.
341
342 Returns:
343 True if there's a running VM.
344 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700345 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700346 if not pid:
347 return False
348
349 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400350 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700351
352 def Stop(self):
353 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700354 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700355
356 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700357 if pid:
358 logging.info('Killing %d.', pid)
359 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700360 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700361
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700362 self._CleanupFiles(recreate=False)
363
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700364 def _WaitForProcs(self):
365 """Wait for expected processes to launch."""
366 class _TooFewPidsException(Exception):
367 """Exception for _GetRunningPids to throw."""
368
369 def _GetRunningPids(exe, numpids):
370 pids = self.remote.GetRunningPids(exe, full_path=False)
371 logging.info('%s pids: %s', exe, repr(pids))
372 if len(pids) < numpids:
373 raise _TooFewPidsException()
374
375 def _WaitForProc(exe, numpids):
376 try:
377 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700378 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700379 max_retry=20,
380 functor=lambda: _GetRunningPids(exe, numpids),
381 sleep=2)
382 except _TooFewPidsException:
383 raise VMError('_WaitForProcs failed: timed out while waiting for '
384 '%d %s processes to start.' % (numpids, exe))
385
386 # We could also wait for session_manager, nacl_helper, etc, but chrome is
387 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
388 # This could potentially break with Mustash.
389 _WaitForProc('chrome', 5)
390
391 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700392 """Wait for the VM to boot up.
393
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700394 Wait for ssh connection to become active, and wait for all expected chrome
395 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700396 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700397 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700398 self.Start()
399
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700400 try:
401 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700402 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700403 max_retry=10,
404 functor=lambda: self.RemoteCommand(cmd=['echo']),
405 sleep=5)
406 except remote_access.SSHConnectionError:
407 raise VMError('WaitForBoot timed out trying to connect to VM.')
408
409 if result.returncode != 0:
410 raise VMError('WaitForBoot failed: %s.' % result.error)
411
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100412 # Chrome can take a while to start with software emulation.
413 if not self.enable_kvm:
414 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700415
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100416 def RemoteCommand(self, cmd, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700417 """Run a remote command in the VM.
418
419 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100420 cmd: command to run.
421 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700422 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700423 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700424 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
425 combine_stdout_stderr=True,
426 log_output=True,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100427 error_code_ok=True,
428 **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700429
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100430 @staticmethod
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700431 def GetParser():
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100432 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700433
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100434 Args:
435 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700436
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100437 Returns:
438 List of parsed opts.
439 """
440 parser = commandline.ArgumentParser(description=__doc__)
441 parser.add_argument('--start', action='store_true', default=False,
442 help='Start the VM.')
443 parser.add_argument('--stop', action='store_true', default=False,
444 help='Stop the VM.')
445 parser.add_argument('--image-path', type='path',
446 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800447 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
448 help='Format of the VM image (raw, qcow2, ...).')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100449 parser.add_argument('--qemu-path', type='path',
450 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800451 parser.add_argument('--qemu-m', type=str, default='8G',
452 help='Memory argument that will be passed to qemu.')
453 parser.add_argument('--qemu-smp', type=int, default='0',
454 help='SMP argument that will be passed to qemu. (0 '
455 'means auto-detection.)')
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800456 # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine
457 # running VMTest all migrate to GCE.
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800458 parser.add_argument('--qemu-cpu', type=str,
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800459 default='SandyBridge,-invpcid,-tsc-deadline',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800460 help='CPU argument that will be passed to qemu.')
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800461 parser.add_argument('--qemu-bios-path', type='path',
462 help='Path of directory with qemu bios files.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100463 parser.add_argument('--disable-kvm', dest='enable_kvm',
464 action='store_false', default=True,
465 help='Disable KVM, use software emulation.')
466 parser.add_argument('--no-display', dest='display',
467 action='store_false', default=True,
468 help='Do not display video output.')
469 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
470 help='ssh port to communicate with VM.')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800471 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
472 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700473 parser.add_argument('--vm-dir', type='path',
474 help='Temp VM directory to use.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100475 parser.add_argument('--dry-run', action='store_true', default=False,
476 help='dry run for debugging.')
477 parser.add_argument('--cmd', action='store_true', default=False,
478 help='Run a command in the VM.')
479 parser.add_argument('args', nargs=argparse.REMAINDER,
480 help='Command to run in the VM.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700481 return parser
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700482
483def main(argv):
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700484 opts = VM.GetParser().parse_args(argv)
485 opts.Freeze()
486
487 vm = VM(opts)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100488 vm.Run()