blob: a33416e73d171583f74cc7b6bb297a8d6e5fa781 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Achuith Bhandarkard8d19292016-05-03 14:32:58 -07002# Copyright 2016 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Mike Frysinger666566c2016-09-21 00:00:21 -04006"""Script for VM Management."""
Achuith Bhandarkard8d19292016-05-03 14:32:58 -07007
8from __future__ import print_function
9
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010010import argparse
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010011import distutils.version
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -070012import errno
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -080013import multiprocessing
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070014import os
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010015import re
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -070016import socket
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070017
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080018from chromite.cli.cros import cros_chrome_sdk
19from chromite.lib import cache
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070020from chromite.lib import commandline
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080021from chromite.lib import constants
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070022from chromite.lib import cros_build_lib
23from chromite.lib import cros_logging as logging
Mike Frysinger10666292018-07-12 01:03:38 -040024from chromite.lib import memoize
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070025from chromite.lib import osutils
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -080026from chromite.lib import path_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070027from chromite.lib import remote_access
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -070028from chromite.lib import retry_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070029
30
31class VMError(Exception):
32 """Exception for VM failures."""
33
34 def __init__(self, message):
35 super(VMError, self).__init__()
36 logging.error(message)
37
38
39class VM(object):
40 """Class for managing a VM."""
41
42 SSH_PORT = 9222
Nicolas Norvezf527cdf2018-01-26 11:55:44 -080043 IMAGE_FORMAT = 'raw'
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070044
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070045 def __init__(self, opts):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070046 """Initialize VM.
47
48 Args:
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070049 opts: command line options.
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
Achuith Bhandarkar195b9512018-08-15 17:14:32 -070067 self.private_key = opts.private_key
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010068 self.dry_run = opts.dry_run
Achuith Bhandarkar195b9512018-08-15 17:14:32 -070069 # log_level is only set if --log-level or --debug is specified.
70 self.log_level = getattr(opts, 'log_level', None)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010071
72 self.start = opts.start
73 self.stop = opts.stop
74 self.cmd = opts.args[1:] if opts.cmd else None
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070075
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +020076 self.cache_dir = os.path.abspath(opts.cache_dir)
77 assert os.path.isdir(self.cache_dir), "Cache directory doesn't exist"
78
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070079 self.vm_dir = opts.vm_dir
80 if not self.vm_dir:
81 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(),
82 'cros_vm_%d' % self.ssh_port)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -070083 self._CreateVMDir()
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070084
85 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
86 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070087 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
88 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
89 self.kvm_serial = '%s.serial' % self.kvm_monitor
90
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070091 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar195b9512018-08-15 17:14:32 -070092 port=self.ssh_port,
93 private_key=self.private_key)
Achuith Bhandarkar2beae292018-03-26 16:44:53 -070094 self.device_addr = 'ssh://%s:%d' % (remote_access.LOCALHOST, self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070095
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070096 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
97 # moblab, etc.
98
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070099 def _RunCommand(self, *args, **kwargs):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700100 """Use SudoRunCommand or RunCommand as necessary.
101
102 Args:
103 args and kwargs: positional and optional args to RunCommand.
104
105 Returns:
106 cros_build_lib.CommandResult object.
107 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700108 if self.use_sudo:
109 return cros_build_lib.SudoRunCommand(*args, **kwargs)
110 else:
111 return cros_build_lib.RunCommand(*args, **kwargs)
112
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700113 def _CreateVMDir(self):
114 """Safely create vm_dir."""
115 if not osutils.SafeMakedirs(self.vm_dir, sudo=self.use_sudo):
116 # For security, ensure that vm_dir is not a symlink, and is owned by us or
117 # by root.
118 error_str = ('VM state dir is misconfigured; please recreate: %s'
119 % self.vm_dir)
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700120 assert os.path.isdir(self.vm_dir), error_str
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700121 assert not os.path.islink(self.vm_dir), error_str
122 st_uid = os.stat(self.vm_dir).st_uid
123 assert st_uid == 0 or st_uid == os.getuid(), error_str
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700124
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700125 def _RmVMDir(self):
126 """Cleanup vm_dir."""
Mike Frysinger97080242017-09-13 01:58:45 -0400127 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700128
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200129 def _GetCachePath(self, cache_name):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700130 """Return path to cache.
131
132 Args:
133 cache_name: Name of cache.
134
135 Returns:
136 File path of cache.
137 """
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200138 return os.path.join(self.cache_dir,
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700139 cros_chrome_sdk.COMMAND_NAME,
140 cache_name)
141
Mike Frysinger10666292018-07-12 01:03:38 -0400142 @memoize.MemoizedSingleCall
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700143 def _SDKVersion(self):
144 """Determine SDK version.
145
146 Check the environment if we're in the SDK shell, and failing that, look at
147 the misc cache.
148
149 Returns:
150 SDK version.
151 """
152 sdk_version = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_VERSION_ENV)
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700153 if not sdk_version and self.board:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700154 misc_cache = cache.DiskCache(self._GetCachePath(
155 cros_chrome_sdk.SDKFetcher.MISC_CACHE))
156 with misc_cache.Lookup((self.board, 'latest')) as ref:
157 if ref.Exists(lock=True):
158 sdk_version = osutils.ReadFile(ref.path).strip()
159 return sdk_version
160
161 def _CachePathForKey(self, key):
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800162 """Get cache path for key.
163
164 Args:
165 key: cache key.
166 """
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700167 tarball_cache = cache.TarballCache(self._GetCachePath(
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800168 cros_chrome_sdk.SDKFetcher.TARBALL_CACHE))
Achuith Bhandarkar4e367c22018-03-27 15:32:48 -0700169 if self.board and self._SDKVersion():
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700170 cache_key = (self.board, self._SDKVersion(), key)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800171 with tarball_cache.Lookup(cache_key) as ref:
172 if ref.Exists():
173 return ref.path
174 return None
175
Mike Frysinger10666292018-07-12 01:03:38 -0400176 @memoize.MemoizedSingleCall
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100177 def QemuVersion(self):
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700178 """Determine QEMU version.
179
180 Returns:
181 QEMU version.
182 """
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100183 version_str = self._RunCommand([self.qemu_path, '--version'],
184 capture_output=True).output
185 # version string looks like one of these:
186 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
187 # 2003-2008 Fabrice Bellard
188 #
189 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
190 #
191 # qemu-x86_64 version 2.10.1
192 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
193 m = re.search(r"version ([0-9.]+)", version_str)
194 if not m:
195 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
196 return m.group(1)
197
198 def _CheckQemuMinVersion(self):
199 """Ensure minimum QEMU version."""
200 min_qemu_version = '2.6.0'
201 logging.info('QEMU version %s', self.QemuVersion())
202 LooseVersion = distutils.version.LooseVersion
203 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
204 raise VMError('QEMU %s is the minimum supported version. You have %s.'
205 % (min_qemu_version, self.QemuVersion()))
206
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800207 def _SetQemuPath(self):
208 """Find a suitable Qemu executable."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800209 qemu_exe = 'qemu-system-x86_64'
210 qemu_exe_path = os.path.join('usr/bin', qemu_exe)
211
212 # Check SDK cache.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800213 if not self.qemu_path:
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700214 qemu_dir = self._CachePathForKey(cros_chrome_sdk.SDKFetcher.QEMU_BIN_KEY)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800215 if qemu_dir:
216 qemu_path = os.path.join(qemu_dir, qemu_exe_path)
217 if os.path.isfile(qemu_path):
218 self.qemu_path = qemu_path
219
220 # Check chroot.
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800221 if not self.qemu_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800222 qemu_path = os.path.join(
223 constants.SOURCE_ROOT, constants.DEFAULT_CHROOT_DIR, qemu_exe_path)
224 if os.path.isfile(qemu_path):
225 self.qemu_path = qemu_path
226
227 # Check system.
228 if not self.qemu_path:
229 self.qemu_path = osutils.Which(qemu_exe)
230
231 if not self.qemu_path or not os.path.isfile(self.qemu_path):
232 raise VMError('QEMU not found.')
233 logging.debug('QEMU path: %s', self.qemu_path)
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800234 self._CheckQemuMinVersion()
235
236 def _GetBuiltVMImagePath(self):
237 """Get path of a locally built VM image."""
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800238 vm_image_path = os.path.join(constants.SOURCE_ROOT, 'src/build/images',
239 cros_build_lib.GetBoard(self.board),
240 'latest', constants.VM_IMAGE_BIN)
241 return vm_image_path if os.path.isfile(vm_image_path) else None
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800242
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800243 def _GetCacheVMImagePath(self):
244 """Get path of a cached VM image."""
Achuith Bhandarkarf6bccdb2018-03-23 13:12:29 -0700245 cache_path = self._CachePathForKey(constants.VM_IMAGE_TAR)
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800246 if cache_path:
247 vm_image = os.path.join(cache_path, constants.VM_IMAGE_BIN)
248 if os.path.isfile(vm_image):
249 return vm_image
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800250 return None
251
252 def _SetVMImagePath(self):
253 """Detect VM image path in SDK and chroot."""
254 if not self.image_path:
Achuith Bhandarkarfc75f692018-01-10 11:33:09 -0800255 self.image_path = (self._GetCacheVMImagePath() or
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800256 self._GetBuiltVMImagePath())
257 if not self.image_path:
258 raise VMError('No VM image found. Use cros chrome-sdk --download-vm.')
259 if not os.path.isfile(self.image_path):
260 raise VMError('VM image does not exist: %s' % self.image_path)
261 logging.debug('VM image path: %s', self.image_path)
262
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700263 def _WaitForSSHPort(self):
264 """Wait for SSH port to become available."""
265 class _SSHPortInUseError(Exception):
266 """Exception for _CheckSSHPortBusy to throw."""
267
268 def _CheckSSHPortBusy(ssh_port):
269 """Check if the SSH port is in use."""
270 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
271 try:
272 sock.bind((remote_access.LOCALHOST_IP, ssh_port))
273 except socket.error as e:
274 if e.errno == errno.EADDRINUSE:
275 logging.info('SSH port %d in use...', self.ssh_port)
276 raise _SSHPortInUseError()
277 sock.close()
278
279 try:
280 retry_util.RetryException(
281 exception=_SSHPortInUseError,
282 max_retry=7,
283 functor=lambda: _CheckSSHPortBusy(self.ssh_port),
284 sleep=1)
285 except _SSHPortInUseError:
286 raise VMError('SSH port %d in use' % self.ssh_port)
287
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100288 def Run(self):
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700289 """Performs an action, one of start, stop, or run a command in the VM."""
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100290 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700291 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700292
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100293 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700294 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100295 if self.cmd:
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700296 if not self.IsRunning():
297 raise VMError('VM not running.')
298 self.RemoteCommand(self.cmd, stream_output=True)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100299 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700300 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700301
302 def Start(self):
303 """Start the VM."""
304
305 self.Stop()
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700306 self._WaitForSSHPort()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700307
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700308 logging.debug('Start VM')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800309 self._SetQemuPath()
310 self._SetVMImagePath()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700311
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700312 self._RmVMDir()
313 self._CreateVMDir()
Mike Frysinger97080242017-09-13 01:58:45 -0400314 # Make sure we can read these files later on by creating them as ourselves.
315 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700316 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
Mike Frysinger0444f4c2018-08-03 15:12:46 -0400317 os.mkfifo(pipe, 0o600)
Mike Frysinger97080242017-09-13 01:58:45 -0400318 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700319
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800320 qemu_args = [self.qemu_path]
321 if self.qemu_bios_path:
322 if not os.path.isdir(self.qemu_bios_path):
323 raise VMError('Invalid QEMU bios path: %s' % self.qemu_bios_path)
324 qemu_args += ['-L', self.qemu_bios_path]
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100325
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800326 qemu_args += [
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800327 '-m', self.qemu_m, '-smp', str(self.qemu_smp), '-vga', 'virtio',
328 '-daemonize', '-usbdevice', 'tablet',
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800329 '-pidfile', self.pidfile,
330 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
331 '-serial', 'file:%s' % self.kvm_serial,
332 '-mon', 'chardev=control_pipe',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800333 # Append 'check' to warn if the requested CPU is not fully supported.
334 '-cpu', self.qemu_cpu + ',check',
Lepton Wuaa6cca42018-04-19 18:56:29 -0700335 '-device', 'virtio-net,netdev=eth0',
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700336 '-netdev', 'user,id=eth0,net=10.0.2.0/27,hostfwd=tcp:%s:%d-:22'
337 % (remote_access.LOCALHOST_IP, self.ssh_port),
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800338 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=%s'
339 % (self.image_path, self.image_format),
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800340 ]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700341 if self.enable_kvm:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800342 qemu_args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700343 if not self.display:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800344 qemu_args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700345 logging.info('Pid file: %s', self.pidfile)
346 if not self.dry_run:
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800347 self._RunCommand(qemu_args)
Achuith Bhandarkarbe977482018-02-06 16:44:00 -0800348 else:
349 logging.info(cros_build_lib.CmdToStr(qemu_args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700350
351 def _GetVMPid(self):
352 """Get the pid of the VM.
353
354 Returns:
355 pid of the VM.
356 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700357 if not os.path.exists(self.vm_dir):
358 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700359 return 0
360
361 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700362 logging.info('%s does not exist.', self.pidfile)
363 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700364
Mike Frysinger97080242017-09-13 01:58:45 -0400365 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700366 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400367 # Ignore blank/empty files.
368 if pid:
369 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700370 return 0
371
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700372 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700373
374 def IsRunning(self):
375 """Returns True if there's a running VM.
376
377 Returns:
378 True if there's a running VM.
379 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700380 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700381 if not pid:
382 return False
383
384 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400385 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700386
387 def Stop(self):
388 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700389 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700390
391 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700392 if pid:
393 logging.info('Killing %d.', pid)
394 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700395 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkarfd5d1852018-03-26 14:50:54 -0700396 self._RmVMDir()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700397
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700398 def _WaitForProcs(self):
399 """Wait for expected processes to launch."""
400 class _TooFewPidsException(Exception):
401 """Exception for _GetRunningPids to throw."""
402
403 def _GetRunningPids(exe, numpids):
404 pids = self.remote.GetRunningPids(exe, full_path=False)
405 logging.info('%s pids: %s', exe, repr(pids))
406 if len(pids) < numpids:
407 raise _TooFewPidsException()
408
409 def _WaitForProc(exe, numpids):
410 try:
411 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700412 exception=_TooFewPidsException,
Achuith Bhandarkarb00bafc2018-09-11 16:30:13 -0700413 max_retry=5,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700414 functor=lambda: _GetRunningPids(exe, numpids),
415 sleep=2)
416 except _TooFewPidsException:
417 raise VMError('_WaitForProcs failed: timed out while waiting for '
418 '%d %s processes to start.' % (numpids, exe))
419
420 # We could also wait for session_manager, nacl_helper, etc, but chrome is
421 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
422 # This could potentially break with Mustash.
423 _WaitForProc('chrome', 5)
424
425 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700426 """Wait for the VM to boot up.
427
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700428 Wait for ssh connection to become active, and wait for all expected chrome
429 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700430 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700431 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700432 self.Start()
433
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700434 try:
435 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700436 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700437 max_retry=10,
438 functor=lambda: self.RemoteCommand(cmd=['echo']),
439 sleep=5)
440 except remote_access.SSHConnectionError:
441 raise VMError('WaitForBoot timed out trying to connect to VM.')
442
443 if result.returncode != 0:
444 raise VMError('WaitForBoot failed: %s.' % result.error)
445
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100446 # Chrome can take a while to start with software emulation.
447 if not self.enable_kvm:
448 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700449
Achuith Bhandarkarbad755b2018-06-09 16:05:01 -0700450 def RemoteCommand(self, cmd, stream_output=False, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700451 """Run a remote command in the VM.
452
453 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100454 cmd: command to run.
Achuith Bhandarkarbad755b2018-06-09 16:05:01 -0700455 stream_output: Stream output of long-running commands.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100456 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkar665a9b32018-05-17 11:39:19 -0700457
458 Returns:
459 cros_build_lib.CommandResult object.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700460 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700461 if not self.dry_run:
Achuith Bhandarkarbad755b2018-06-09 16:05:01 -0700462 kwargs.setdefault('error_code_ok', True)
463 if stream_output:
464 kwargs.setdefault('capture_output', False)
465 else:
466 kwargs.setdefault('combine_stdout_stderr', True)
467 kwargs.setdefault('log_output', True)
468 return self.remote.RunCommand(cmd, debug_level=logging.INFO, **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700469
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100470 @staticmethod
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700471 def GetParser():
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100472 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700473
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100474 Args:
475 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700476
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100477 Returns:
478 List of parsed opts.
479 """
480 parser = commandline.ArgumentParser(description=__doc__)
481 parser.add_argument('--start', action='store_true', default=False,
482 help='Start the VM.')
483 parser.add_argument('--stop', action='store_true', default=False,
484 help='Stop the VM.')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700485 parser.add_argument('--image-path', type=str,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100486 help='Path to VM image to launch with --start.')
Nicolas Norvezf527cdf2018-01-26 11:55:44 -0800487 parser.add_argument('--image-format', default=VM.IMAGE_FORMAT,
488 help='Format of the VM image (raw, qcow2, ...).')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700489 parser.add_argument('--qemu-path', type=str,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100490 help='Path of qemu binary to launch with --start.')
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800491 parser.add_argument('--qemu-m', type=str, default='8G',
492 help='Memory argument that will be passed to qemu.')
493 parser.add_argument('--qemu-smp', type=int, default='0',
494 help='SMP argument that will be passed to qemu. (0 '
495 'means auto-detection.)')
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800496 # TODO(pwang): replace SandyBridge to Haswell-noTSX once lab machine
497 # running VMTest all migrate to GCE.
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800498 parser.add_argument('--qemu-cpu', type=str,
Po-Hsien Wangc5b335f2018-02-06 18:36:16 -0800499 default='SandyBridge,-invpcid,-tsc-deadline',
Po-Hsien Wang1cec8d12018-01-25 16:36:44 -0800500 help='CPU argument that will be passed to qemu.')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700501 parser.add_argument('--qemu-bios-path', type=str,
Achuith Bhandarkar41259652017-11-14 10:31:02 -0800502 help='Path of directory with qemu bios files.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100503 parser.add_argument('--disable-kvm', dest='enable_kvm',
504 action='store_false', default=True,
505 help='Disable KVM, use software emulation.')
506 parser.add_argument('--no-display', dest='display',
507 action='store_false', default=True,
508 help='Do not display video output.')
509 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
510 help='ssh port to communicate with VM.')
Achuith Bhandarkar195b9512018-08-15 17:14:32 -0700511 parser.add_argument('--private-key', help='Path to ssh private key.')
Achuith Bhandarkar1297dcf2017-11-21 12:03:48 -0800512 sdk_board_env = os.environ.get(cros_chrome_sdk.SDKFetcher.SDK_BOARD_ENV)
513 parser.add_argument('--board', default=sdk_board_env, help='Board to use.')
Achuith Bhandarkar02ef76b2018-04-05 10:47:33 +0200514 parser.add_argument('--cache-dir', type=str,
515 default=path_util.GetCacheDir(),
516 help='Cache directory to use.')
Achuith Bhandarkar46d83872018-04-04 01:49:55 -0700517 parser.add_argument('--vm-dir', type=str,
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700518 help='Temp VM directory to use.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100519 parser.add_argument('--dry-run', action='store_true', default=False,
520 help='dry run for debugging.')
521 parser.add_argument('--cmd', action='store_true', default=False,
522 help='Run a command in the VM.')
523 parser.add_argument('args', nargs=argparse.REMAINDER,
524 help='Command to run in the VM.')
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700525 return parser
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700526
527def main(argv):
Achuith Bhandarkar2beae292018-03-26 16:44:53 -0700528 opts = VM.GetParser().parse_args(argv)
529 opts.Freeze()
530
531 vm = VM(opts)
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100532 vm.Run()