blob: d9c5dd306f40abd7c834b3bf671a5ca6dfc18683 [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 Bhandarkarfd5d1852018-03-26 14:50:54 -070074 self._CreateVMDir()
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070075
76 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
77 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070078 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
79 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
80 self.kvm_serial = '%s.serial' % self.kvm_monitor
81
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070082 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010083 port=self.ssh_port)
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070084 self.device_addr = 'ssh://%s:%d' % (remote_access.LOCALHOST, self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070085
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070086 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
87 # moblab, etc.
88
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070089 def _RunCommand(self, *args, **kwargs):
90 """Use SudoRunCommand or RunCommand as necessary."""
91 if self.use_sudo:
92 return cros_build_lib.SudoRunCommand(*args, **kwargs)
93 else:
94 return cros_build_lib.RunCommand(*args, **kwargs)
95
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -070096 def _CreateVMDir(self):
97 """Safely create vm_dir."""
98 if not osutils.SafeMakedirs(self.vm_dir, sudo=self.use_sudo):
99 # For security, ensure that vm_dir is not a symlink, and is owned by us or
100 # by root.
101 error_str = ('VM state dir is misconfigured; please recreate: %s'
102 % self.vm_dir)
103 assert not os.path.islink(self.vm_dir), error_str
104 st_uid = os.stat(self.vm_dir).st_uid
105 assert st_uid == 0 or st_uid == os.getuid(), error_str
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700106
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700107 def _RmVMDir(self):
108 """Cleanup vm_dir."""
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
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700111 @staticmethod
112 def _GetCachePath(cache_name):
113 """Return path to cache.
114
115 Args:
116 cache_name: Name of cache.
117
118 Returns:
119 File path of cache.
120 """
121 return os.path.join(path_util.GetCacheDir(),
122 cros_chrome_sdk.COMMAND_NAME,
123 cache_name)
124
125 @cros_build_lib.MemoizedSingleCall
126 def _SDKVersion(self):
127 """Determine SDK version.
128
129 Check the environment if we're in the SDK shell, and failing that, look at
130 the misc cache.
131
132 Returns:
133 SDK version.
134 """
135 sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV)
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700136 if not sdk_version and self.board:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700137 misc_cache = cache.DiskCache(self._GetCachePath(
138 cros_chrome_sdk.SDKFetcher.MISC_CACHE))
139 with misc_cache.Lookup((self.board, 'latest')) as ref:
140 if ref.Exists(lock=True):
141 sdk_version = osutils.ReadFile(ref.path).strip()
142 return sdk_version
143
144 def _CachePathForKey(self, key):
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800145 """Get cache path for key.
146
147 Args:
148 key: cache key.
149 """
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700150 tarball_cache = cache.TarballCache(self._GetCachePath(
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800151 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700152 if self.board and self._SDKVersion():
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700153 cache_key = (self.board, self._SDKVersion(), key)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800154 with tarball_cache.Lookup(cache_key) as ref:
155 if ref.Exists():
156 return ref.path
157 return None
158
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100159 @cros_build_lib.MemoizedSingleCall
160 def QemuVersion(self):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700161 """Determine QEMU version.
162
163 Returns:
164 QEMU version.
165 """
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100166 version_str = self._RunCommand([self.qemu_path, '--version'],
167 capture_output=True).output
168 # version string looks like one of these:
169 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
170 # 2003-2008 Fabrice Bellard
171 #
172 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
173 #
174 # qemu-x86_64 version 2.10.1
175 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
176 m = re.search(r"version ([0-9.]+)", version_str)
177 if not m:
178 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
179 return m.group(1)
180
181 def _CheckQemuMinVersion(self):
182 """Ensure minimum QEMU version."""
183 min_qemu_version = '2.6.0'
184 logging.info('QEMU version %s', self.QemuVersion())
185 LooseVersion = distutils.version.LooseVersion
186 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
187 raise VMError('QEMU %s is the minimum supported version. You have %s.'
188 % (min_qemu_version, self.QemuVersion()))
189
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800190 def _SetQemuPath(self):
191 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800192 qemu_exe = 'qemu-system-x86_64'
193 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
194
195 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800196 if not self.qemu_path:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700197 qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800198 if qemu_dir:
199 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
200 if os.path.isfile(qemu_path):
201 self.qemu_path = qemu_path
202
203 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800204 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800205 qemu_path = os.path.join(
206 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
207 if os.path.isfile(qemu_path):
208 self.qemu_path = qemu_path
209
210 # Check system.
211 if not self.qemu_path:
212 self.qemu_path = osutils.Which(qemu_exe)
213
214 if not self.qemu_path or not os.path.isfile(self.qemu_path):
215 raise VMError('QEMU not found.')
216 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800217 self._CheckQemuMinVersion()
218
219 def _GetBuiltVMImagePath(self):
220 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800221 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
222 cros_build_lib.GetBoard(self.board),
223 'latest', constants.VM_IMAGE_BIN)
224 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800225
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800226 def _GetCacheVMImagePath(self):
227 """Get path of a cached VM image."""
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700228 cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800229 if cache_path:
230 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
231 if os.path.isfile(vm_image):
232 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800233 return None
234
235 def _SetVMImagePath(self):
236 """Detect VM image path in SDK and chroot."""
237 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800238 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800239 self._GetBuiltVMImagePath())
240 if not self.image_path:
241 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
242 if not os.path.isfile(self.image_path):
243 raise VMError('VM image does not exist: %s' % self.image_path)
244 logging.debug('VM image path: %s', self.image_path)
245
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100246 def Run(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700247 """Performs an action, one of start, stop, or run a command in the VM.
248
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700249 Returns:
250 cmd output.
251 """
252
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100253 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700254 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100255 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700256 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100257 if self.cmd:
258 return self.RemoteCommand(self.cmd)
259 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700260 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700261
262 def Start(self):
263 """Start the VM."""
264
265 self.Stop()
266
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700267 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800268 self._SetQemuPath()
269 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700270
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700271 self._RmVMDir()
272 self._CreateVMDir()
Mike Frysinger97080242017-09-13 01:58:45 -0400273 # Make sure we can read these files later on by creating them as ourselves.
274 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700275 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
276 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400277 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700278
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800279 qemu_args = [self.qemu_path]
280 if self.qemu_bios_path:
281 if not os.path.isdir(self.qemu_bios_path):
282 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
283 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100284
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800285 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800286 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
287 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800288 '-pidfile', self.pidfile,
289 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
290 '-serial', 'file:%s' % self.kvm_serial,
291 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800292 # Append 'check' to warn if the requested CPU is not fully supported.
293 '-cpu', self.qemu_cpu + ',check',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800294 # Qemu-vlans are used by qemu to separate out network traffic on the
295 # slirp network bridge. qemu forwards traffic on a slirp vlan to all
296 # ports conected on that vlan. By default, slirp ports are on vlan
297 # 0. We explicitly set a vlan here so that another qemu VM using
298 # slirp doesn't conflict with our network traffic.
299 '-net', 'nic,model=virtio,vlan=%d' % self.ssh_port,
300 '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22,vlan=%d'
301 % (self.ssh_port, self.ssh_port),
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800302 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
303 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800304 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700305 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800306 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700307 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800308 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700309 logging.info('Pid file: %s', self.pidfile)
310 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800311 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800312 else:
313 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700314
315 def _GetVMPid(self):
316 """Get the pid of the VM.
317
318 Returns:
319 pid of the VM.
320 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700321 if not os.path.exists(self.vm_dir):
322 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700323 return 0
324
325 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700326 logging.info('%s does not exist.', self.pidfile)
327 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700328
Mike Frysinger97080242017-09-13 01:58:45 -0400329 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700330 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400331 # Ignore blank/empty files.
332 if pid:
333 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700334 return 0
335
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700336 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700337
338 def IsRunning(self):
339 """Returns True if there's a running VM.
340
341 Returns:
342 True if there's a running VM.
343 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700344 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700345 if not pid:
346 return False
347
348 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400349 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700350
351 def Stop(self):
352 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700353 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700354
355 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700356 if pid:
357 logging.info('Killing %d.', pid)
358 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700359 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700360 self._RmVMDir()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700361
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700362 def _WaitForProcs(self):
363 """Wait for expected processes to launch."""
364 class _TooFewPidsException(Exception):
365 """Exception for _GetRunningPids to throw."""
366
367 def _GetRunningPids(exe, numpids):
368 pids = self.remote.GetRunningPids(exe, full_path=False)
369 logging.info('%s pids: %s', exe, repr(pids))
370 if len(pids) < numpids:
371 raise _TooFewPidsException()
372
373 def _WaitForProc(exe, numpids):
374 try:
375 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700376 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700377 max_retry=20,
378 functor=lambda: _GetRunningPids(exe, numpids),
379 sleep=2)
380 except _TooFewPidsException:
381 raise VMError('_WaitForProcs failed: timed out while waiting for '
382 '%d %s processes to start.' % (numpids, exe))
383
384 # We could also wait for session_manager, nacl_helper, etc, but chrome is
385 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
386 # This could potentially break with Mustash.
387 _WaitForProc('chrome', 5)
388
389 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700390 """Wait for the VM to boot up.
391
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700392 Wait for ssh connection to become active, and wait for all expected chrome
393 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700394 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700395 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700396 self.Start()
397
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700398 try:
399 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700400 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700401 max_retry=10,
402 functor=lambda: self.RemoteCommand(cmd=['echo']),
403 sleep=5)
404 except remote_access.SSHConnectionError:
405 raise VMError('WaitForBoot timed out trying to connect to VM.')
406
407 if result.returncode != 0:
408 raise VMError('WaitForBoot failed: %s.' % result.error)
409
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100410 # Chrome can take a while to start with software emulation.
411 if not self.enable_kvm:
412 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700413
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100414 def RemoteCommand(self, cmd, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700415 """Run a remote command in the VM.
416
417 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100418 cmd: command to run.
419 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700420 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700421 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700422 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
423 combine_stdout_stderr=True,
424 log_output=True,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100425 error_code_ok=True,
426 **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700427
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100428 @staticmethod
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700429 def GetParser():
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100430 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700431
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100432 Args:
433 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700434
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100435 Returns:
436 List of parsed opts.
437 """
438 parser = commandline.ArgumentParser(description=__doc__)
439 parser.add_argument('--start', action='store_true', default=False,
440 help='Start the VM.')
441 parser.add_argument('--stop', action='store_true', default=False,
442 help='Stop the VM.')
443 parser.add_argument('--image-path', type='path',
444 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800445 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
446 help='Format of the VM image (raw, qcow2, ...).')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100447 parser.add_argument('--qemu-path', type='path',
448 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800449 parser.add_argument('--qemu-m', type=str, default='8G',
450 help='Memory argument that will be passed to qemu.')
451 parser.add_argument('--qemu-smp', type=int, default='0',
452 help='SMP argument that will be passed to qemu. (0 '
453 'means auto-detection.)')
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800454 # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine
455 # running VMTest all migrate to GCE.
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800456 parser.add_argument('--qemu-cpu', type=str,
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800457 default='SandyBridge,-invpcid,-tsc-deadline',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800458 help='CPU argument that will be passed to qemu.')
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800459 parser.add_argument('--qemu-bios-path', type='path',
460 help='Path of directory with qemu bios files.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100461 parser.add_argument('--disable-kvm', dest='enable_kvm',
462 action='store_false', default=True,
463 help='Disable KVM, use software emulation.')
464 parser.add_argument('--no-display', dest='display',
465 action='store_false', default=True,
466 help='Do not display video output.')
467 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
468 help='ssh port to communicate with VM.')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800469 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
470 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700471 parser.add_argument('--vm-dir', type='path',
472 help='Temp VM directory to use.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100473 parser.add_argument('--dry-run', action='store_true', default=False,
474 help='dry run for debugging.')
475 parser.add_argument('--cmd', action='store_true', default=False,
476 help='Run a command in the VM.')
477 parser.add_argument('args', nargs=argparse.REMAINDER,
478 help='Command to run in the VM.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700479 return parser
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700480
481def main(argv):
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700482 opts = VM.GetParser().parse_args(argv)
483 opts.Freeze()
484
485 vm = VM(opts)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100486 vm.Run()