blob: ca2d379fc2adcd0962c6439fb2adcaed2440a470 [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 Bhandarkar2a39adf2017-10-30 10:24:45 +010042 def __init__(self, argv):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070043 """Initialize VM.
44
45 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010046 argv: command line args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070047 """
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010048 opts = self._ParseArgs(argv)
49 opts.Freeze()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070050
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010051 self.qemu_path = opts.qemu_path
Achuith Bhandarkar41259652017-11-14 10:31:02 -080052 self.qemu_bios_path = opts.qemu_bios_path
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -080053 self.qemu_m = opts.qemu_m
54 self.qemu_cpu = opts.qemu_cpu
55 self.qemu_smp = opts.qemu_smp
56 if self.qemu_smp == 0:
57 self.qemu_smp = min(8, multiprocessing.cpu_count)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010058 self.enable_kvm = opts.enable_kvm
Achuith Bhandarkarf877da22017-09-12 12:27:39 -070059 # We don't need sudo access for software emulation or if /dev/kvm is
60 # writeable.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010061 self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK)
62 self.display = opts.display
63 self.image_path = opts.image_path
Nicolas Norvezf527cdf2018-01-26 11:55:44 -080064 self.image_format = opts.image_format
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080065 self.board = opts.board
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010066 self.ssh_port = opts.ssh_port
67 self.dry_run = opts.dry_run
68
69 self.start = opts.start
70 self.stop = opts.stop
71 self.cmd = opts.args[1:] if opts.cmd else None
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070072
Achuith Bhandarkare7d564a2018-01-17 10:23:52 -080073 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(),
74 'cros_vm_%d' % self.ssh_port)
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070075 if os.path.exists(self.vm_dir):
76 # For security, ensure that vm_dir is not a symlink, and is owned by us or
77 # by root.
78 assert not os.path.islink(self.vm_dir), \
79 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
80 st_uid = os.stat(self.vm_dir).st_uid
81 assert st_uid == 0 or st_uid == os.getuid(), \
82 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
83
84 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
85 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070086 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
87 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
88 self.kvm_serial = '%s.serial' % self.kvm_monitor
89
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070090 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010091 port=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 Bhandarkarfc75f692018-01-10 11:33:09 -0800113 def _GetCachePath(self, key):
114 """Get cache path for key.
115
116 Args:
117 key: cache key.
118 """
119 tarball_cache = cache.TarballCache(os.path.join(
120 path_util.GetCacheDir(),
121 cros_chrome_sdk.COMMAND_NAME,
122 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
123 lkgm = cros_chrome_sdk.SDKFetcher.GetChromeLKGM()
124 if lkgm:
125 cache_key = (self.board, lkgm, key)
126 with tarball_cache.Lookup(cache_key) as ref:
127 if ref.Exists():
128 return ref.path
129 return None
130
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100131 @cros_build_lib.MemoizedSingleCall
132 def QemuVersion(self):
133 """Determine QEMU version."""
134 version_str = self._RunCommand([self.qemu_path, '--version'],
135 capture_output=True).output
136 # version string looks like one of these:
137 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
138 # 2003-2008 Fabrice Bellard
139 #
140 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
141 #
142 # qemu-x86_64 version 2.10.1
143 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
144 m = re.search(r"version ([0-9.]+)", version_str)
145 if not m:
146 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
147 return m.group(1)
148
149 def _CheckQemuMinVersion(self):
150 """Ensure minimum QEMU version."""
151 min_qemu_version = '2.6.0'
152 logging.info('QEMU version %s', self.QemuVersion())
153 LooseVersion = distutils.version.LooseVersion
154 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
155 raise VMError('QEMU %s is the minimum supported version. You have %s.'
156 % (min_qemu_version, self.QemuVersion()))
157
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800158 def _SetQemuPath(self):
159 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800160 qemu_exe = 'qemu-system-x86_64'
161 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
162
163 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800164 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800165 qemu_dir = self._GetCachePath(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY)
166 if qemu_dir:
167 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
168 if os.path.isfile(qemu_path):
169 self.qemu_path = qemu_path
170
171 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800172 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800173 qemu_path = os.path.join(
174 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
175 if os.path.isfile(qemu_path):
176 self.qemu_path = qemu_path
177
178 # Check system.
179 if not self.qemu_path:
180 self.qemu_path = osutils.Which(qemu_exe)
181
182 if not self.qemu_path or not os.path.isfile(self.qemu_path):
183 raise VMError('QEMU not found.')
184 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800185 self._CheckQemuMinVersion()
186
187 def _GetBuiltVMImagePath(self):
188 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800189 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
190 cros_build_lib.GetBoard(self.board),
191 'latest', constants.VM_IMAGE_BIN)
192 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800193
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800194 def _GetCacheVMImagePath(self):
195 """Get path of a cached VM image."""
196 cache_path = self._GetCachePath(constants.VM_IMAGE_TAR)
197 if cache_path:
198 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
199 if os.path.isfile(vm_image):
200 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800201 return None
202
203 def _SetVMImagePath(self):
204 """Detect VM image path in SDK and chroot."""
205 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800206 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800207 self._GetBuiltVMImagePath())
208 if not self.image_path:
209 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
210 if not os.path.isfile(self.image_path):
211 raise VMError('VM image does not exist: %s' % self.image_path)
212 logging.debug('VM image path: %s', self.image_path)
213
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100214 def Run(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700215 """Performs an action, one of start, stop, or run a command in the VM.
216
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700217 Returns:
218 cmd output.
219 """
220
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100221 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700222 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100223 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700224 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100225 if self.cmd:
226 return self.RemoteCommand(self.cmd)
227 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700228 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700229
230 def Start(self):
231 """Start the VM."""
232
233 self.Stop()
234
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700235 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800236 self._SetQemuPath()
237 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700238
239 self._CleanupFiles(recreate=True)
Mike Frysinger97080242017-09-13 01:58:45 -0400240 # Make sure we can read these files later on by creating them as ourselves.
241 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700242 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
243 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400244 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700245
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800246 qemu_args = [self.qemu_path]
247 if self.qemu_bios_path:
248 if not os.path.isdir(self.qemu_bios_path):
249 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
250 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100251
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800252 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800253 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
254 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800255 '-pidfile', self.pidfile,
256 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
257 '-serial', 'file:%s' % self.kvm_serial,
258 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800259 # Append 'check' to warn if the requested CPU is not fully supported.
260 '-cpu', self.qemu_cpu + ',check',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800261 # Qemu-vlans are used by qemu to separate out network traffic on the
262 # slirp network bridge. qemu forwards traffic on a slirp vlan to all
263 # ports conected on that vlan. By default, slirp ports are on vlan
264 # 0. We explicitly set a vlan here so that another qemu VM using
265 # slirp doesn't conflict with our network traffic.
266 '-net', 'nic,model=virtio,vlan=%d' % self.ssh_port,
267 '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22,vlan=%d'
268 % (self.ssh_port, self.ssh_port),
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800269 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
270 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800271 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700272 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800273 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700274 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800275 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700276 logging.info('Pid file: %s', self.pidfile)
277 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800278 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800279 else:
280 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700281
282 def _GetVMPid(self):
283 """Get the pid of the VM.
284
285 Returns:
286 pid of the VM.
287 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700288 if not os.path.exists(self.vm_dir):
289 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700290 return 0
291
292 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700293 logging.info('%s does not exist.', self.pidfile)
294 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700295
Mike Frysinger97080242017-09-13 01:58:45 -0400296 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700297 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400298 # Ignore blank/empty files.
299 if pid:
300 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700301 return 0
302
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700303 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700304
305 def IsRunning(self):
306 """Returns True if there's a running VM.
307
308 Returns:
309 True if there's a running VM.
310 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700311 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700312 if not pid:
313 return False
314
315 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400316 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700317
318 def Stop(self):
319 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700320 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700321
322 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700323 if pid:
324 logging.info('Killing %d.', pid)
325 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700326 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700327
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700328 self._CleanupFiles(recreate=False)
329
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700330 def _WaitForProcs(self):
331 """Wait for expected processes to launch."""
332 class _TooFewPidsException(Exception):
333 """Exception for _GetRunningPids to throw."""
334
335 def _GetRunningPids(exe, numpids):
336 pids = self.remote.GetRunningPids(exe, full_path=False)
337 logging.info('%s pids: %s', exe, repr(pids))
338 if len(pids) < numpids:
339 raise _TooFewPidsException()
340
341 def _WaitForProc(exe, numpids):
342 try:
343 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700344 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700345 max_retry=20,
346 functor=lambda: _GetRunningPids(exe, numpids),
347 sleep=2)
348 except _TooFewPidsException:
349 raise VMError('_WaitForProcs failed: timed out while waiting for '
350 '%d %s processes to start.' % (numpids, exe))
351
352 # We could also wait for session_manager, nacl_helper, etc, but chrome is
353 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
354 # This could potentially break with Mustash.
355 _WaitForProc('chrome', 5)
356
357 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700358 """Wait for the VM to boot up.
359
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700360 Wait for ssh connection to become active, and wait for all expected chrome
361 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700362 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700363 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700364 self.Start()
365
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700366 try:
367 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700368 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700369 max_retry=10,
370 functor=lambda: self.RemoteCommand(cmd=['echo']),
371 sleep=5)
372 except remote_access.SSHConnectionError:
373 raise VMError('WaitForBoot timed out trying to connect to VM.')
374
375 if result.returncode != 0:
376 raise VMError('WaitForBoot failed: %s.' % result.error)
377
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100378 # Chrome can take a while to start with software emulation.
379 if not self.enable_kvm:
380 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700381
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100382 def RemoteCommand(self, cmd, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700383 """Run a remote command in the VM.
384
385 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100386 cmd: command to run.
387 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700388 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700389 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700390 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
391 combine_stdout_stderr=True,
392 log_output=True,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100393 error_code_ok=True,
394 **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700395
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100396 @staticmethod
397 def _ParseArgs(argv):
398 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700399
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100400 Args:
401 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700402
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100403 Returns:
404 List of parsed opts.
405 """
406 parser = commandline.ArgumentParser(description=__doc__)
407 parser.add_argument('--start', action='store_true', default=False,
408 help='Start the VM.')
409 parser.add_argument('--stop', action='store_true', default=False,
410 help='Stop the VM.')
411 parser.add_argument('--image-path', type='path',
412 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800413 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
414 help='Format of the VM image (raw, qcow2, ...).')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100415 parser.add_argument('--qemu-path', type='path',
416 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800417 parser.add_argument('--qemu-m', type=str, default='8G',
418 help='Memory argument that will be passed to qemu.')
419 parser.add_argument('--qemu-smp', type=int, default='0',
420 help='SMP argument that will be passed to qemu. (0 '
421 'means auto-detection.)')
422 parser.add_argument('--qemu-cpu', type=str,
423 default='Haswell-noTSX,-invpcid,-tsc-deadline',
424 help='CPU argument that will be passed to qemu.')
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800425 parser.add_argument('--qemu-bios-path', type='path',
426 help='Path of directory with qemu bios files.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100427 parser.add_argument('--disable-kvm', dest='enable_kvm',
428 action='store_false', default=True,
429 help='Disable KVM, use software emulation.')
430 parser.add_argument('--no-display', dest='display',
431 action='store_false', default=True,
432 help='Do not display video output.')
433 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
434 help='ssh port to communicate with VM.')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800435 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
436 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100437 parser.add_argument('--dry-run', action='store_true', default=False,
438 help='dry run for debugging.')
439 parser.add_argument('--cmd', action='store_true', default=False,
440 help='Run a command in the VM.')
441 parser.add_argument('args', nargs=argparse.REMAINDER,
442 help='Command to run in the VM.')
443 return parser.parse_args(argv)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700444
445def main(argv):
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100446 vm = VM(argv)
447 vm.Run()