blob: 7cfc203f2872765bb2b4460868d26fe6772d4bbc [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 Bhandarkard8d19292016-05-03 14:32:58 -070012import os
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010013import re
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070014
15from chromite.lib import commandline
16from chromite.lib import cros_build_lib
17from chromite.lib import cros_logging as logging
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070018from chromite.lib import osutils
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070019from chromite.lib import remote_access
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -070020from chromite.lib import retry_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070021
22
23class VMError(Exception):
24 """Exception for VM failures."""
25
26 def __init__(self, message):
27 super(VMError, self).__init__()
28 logging.error(message)
29
30
31class VM(object):
32 """Class for managing a VM."""
33
34 SSH_PORT = 9222
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070035
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010036 def __init__(self, argv):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070037 """Initialize VM.
38
39 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010040 argv: command line args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070041 """
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010042 opts = self._ParseArgs(argv)
43 opts.Freeze()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070044
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010045 self.qemu_path = opts.qemu_path
46 self.enable_kvm = opts.enable_kvm
Achuith Bhandarkarf877da22017-09-12 12:27:39 -070047 # We don't need sudo access for software emulation or if /dev/kvm is
48 # writeable.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010049 self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK)
50 self.display = opts.display
51 self.image_path = opts.image_path
52 self.ssh_port = opts.ssh_port
53 self.dry_run = opts.dry_run
54
55 self.start = opts.start
56 self.stop = opts.stop
57 self.cmd = opts.args[1:] if opts.cmd else None
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070058
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070059 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(), 'cros_vm')
60 if os.path.exists(self.vm_dir):
61 # For security, ensure that vm_dir is not a symlink, and is owned by us or
62 # by root.
63 assert not os.path.islink(self.vm_dir), \
64 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
65 st_uid = os.stat(self.vm_dir).st_uid
66 assert st_uid == 0 or st_uid == os.getuid(), \
67 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
68
69 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
70 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070071 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
72 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
73 self.kvm_serial = '%s.serial' % self.kvm_monitor
74
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070075 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010076 port=self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070077
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070078 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
79 # moblab, etc.
80
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070081 def _RunCommand(self, *args, **kwargs):
82 """Use SudoRunCommand or RunCommand as necessary."""
83 if self.use_sudo:
84 return cros_build_lib.SudoRunCommand(*args, **kwargs)
85 else:
86 return cros_build_lib.RunCommand(*args, **kwargs)
87
88 def _CleanupFiles(self, recreate):
89 """Cleanup vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070090
91 Args:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070092 recreate: recreate vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070093 """
Mike Frysinger97080242017-09-13 01:58:45 -040094 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070095 if recreate:
Mike Frysinger97080242017-09-13 01:58:45 -040096 osutils.SafeMakedirs(self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070097
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +010098 @cros_build_lib.MemoizedSingleCall
99 def QemuVersion(self):
100 """Determine QEMU version."""
101 version_str = self._RunCommand([self.qemu_path, '--version'],
102 capture_output=True).output
103 # version string looks like one of these:
104 # QEMU emulator version 2.0.0 (Debian 2.0.0+dfsg-2ubuntu1.36), Copyright (c)
105 # 2003-2008 Fabrice Bellard
106 #
107 # QEMU emulator version 2.6.0, Copyright (c) 2003-2008 Fabrice Bellard
108 #
109 # qemu-x86_64 version 2.10.1
110 # Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers
111 m = re.search(r"version ([0-9.]+)", version_str)
112 if not m:
113 raise VMError('Unable to determine QEMU version from:\n%s.' % version_str)
114 return m.group(1)
115
116 def _CheckQemuMinVersion(self):
117 """Ensure minimum QEMU version."""
118 min_qemu_version = '2.6.0'
119 logging.info('QEMU version %s', self.QemuVersion())
120 LooseVersion = distutils.version.LooseVersion
121 if LooseVersion(self.QemuVersion()) < LooseVersion(min_qemu_version):
122 raise VMError('QEMU %s is the minimum supported version. You have %s.'
123 % (min_qemu_version, self.QemuVersion()))
124
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100125 def Run(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700126 """Performs an action, one of start, stop, or run a command in the VM.
127
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700128 Returns:
129 cmd output.
130 """
131
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100132 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700133 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100134 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700135 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100136 if self.cmd:
137 return self.RemoteCommand(self.cmd)
138 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700139 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700140
141 def Start(self):
142 """Start the VM."""
143
144 self.Stop()
145
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700146 logging.debug('Start VM')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700147 if not self.qemu_path:
148 self.qemu_path = osutils.Which('qemu-system-x86_64')
149 if not self.qemu_path:
Achuith Bhandarkar9788efd2017-11-07 12:34:23 +0100150 raise VMError('qemu not found. Try: sudo apt-get install qemu')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700151 logging.debug('qemu path=%s', self.qemu_path)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700152
153 if not self.image_path:
154 self.image_path = os.environ.get('VM_IMAGE_PATH', '')
155 logging.debug('vm image path=%s', self.image_path)
156 if not self.image_path or not os.path.exists(self.image_path):
Achuith Bhandarkar9788efd2017-11-07 12:34:23 +0100157 raise VMError('No VM image path found. '
158 'Use cros chrome-sdk --download-vm.')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700159
160 self._CleanupFiles(recreate=True)
Mike Frysinger97080242017-09-13 01:58:45 -0400161 # Make sure we can read these files later on by creating them as ourselves.
162 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700163 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
164 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400165 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700166
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100167 self._CheckQemuMinVersion()
168
169 args = [self.qemu_path, '-m', '2G', '-smp', '4', '-vga', 'virtio',
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700170 '-daemonize',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700171 '-pidfile', self.pidfile,
172 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
173 '-serial', 'file:%s' % self.kvm_serial,
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700174 '-mon', 'chardev=control_pipe',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700175 '-net', 'nic,model=virtio',
Nicolas Norvez80329de2017-03-27 14:32:24 -0700176 '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22' % self.ssh_port,
Achuith Bhandarkar22bfedf2017-11-08 11:59:38 +0100177 '-drive', 'file=%s,index=0,media=disk,cache=unsafe,format=raw'
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700178 % self.image_path]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700179 if self.enable_kvm:
180 args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700181 if not self.display:
182 args.extend(['-display', 'none'])
Mike Frysinger97080242017-09-13 01:58:45 -0400183 logging.info(cros_build_lib.CmdToStr(args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700184 logging.info('Pid file: %s', self.pidfile)
185 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700186 self._RunCommand(args)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700187
188 def _GetVMPid(self):
189 """Get the pid of the VM.
190
191 Returns:
192 pid of the VM.
193 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700194 if not os.path.exists(self.vm_dir):
195 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700196 return 0
197
198 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700199 logging.info('%s does not exist.', self.pidfile)
200 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700201
Mike Frysinger97080242017-09-13 01:58:45 -0400202 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700203 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400204 # Ignore blank/empty files.
205 if pid:
206 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700207 return 0
208
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700209 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700210
211 def IsRunning(self):
212 """Returns True if there's a running VM.
213
214 Returns:
215 True if there's a running VM.
216 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700217 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700218 if not pid:
219 return False
220
221 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400222 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700223
224 def Stop(self):
225 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700226 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700227
228 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700229 if pid:
230 logging.info('Killing %d.', pid)
231 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700232 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700233
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700234 self._CleanupFiles(recreate=False)
235
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700236 def _WaitForProcs(self):
237 """Wait for expected processes to launch."""
238 class _TooFewPidsException(Exception):
239 """Exception for _GetRunningPids to throw."""
240
241 def _GetRunningPids(exe, numpids):
242 pids = self.remote.GetRunningPids(exe, full_path=False)
243 logging.info('%s pids: %s', exe, repr(pids))
244 if len(pids) < numpids:
245 raise _TooFewPidsException()
246
247 def _WaitForProc(exe, numpids):
248 try:
249 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700250 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700251 max_retry=20,
252 functor=lambda: _GetRunningPids(exe, numpids),
253 sleep=2)
254 except _TooFewPidsException:
255 raise VMError('_WaitForProcs failed: timed out while waiting for '
256 '%d %s processes to start.' % (numpids, exe))
257
258 # We could also wait for session_manager, nacl_helper, etc, but chrome is
259 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
260 # This could potentially break with Mustash.
261 _WaitForProc('chrome', 5)
262
263 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700264 """Wait for the VM to boot up.
265
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700266 Wait for ssh connection to become active, and wait for all expected chrome
267 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700268 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700269 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700270 self.Start()
271
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700272 try:
273 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700274 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700275 max_retry=10,
276 functor=lambda: self.RemoteCommand(cmd=['echo']),
277 sleep=5)
278 except remote_access.SSHConnectionError:
279 raise VMError('WaitForBoot timed out trying to connect to VM.')
280
281 if result.returncode != 0:
282 raise VMError('WaitForBoot failed: %s.' % result.error)
283
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100284 # Chrome can take a while to start with software emulation.
285 if not self.enable_kvm:
286 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700287
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100288 def RemoteCommand(self, cmd, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700289 """Run a remote command in the VM.
290
291 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100292 cmd: command to run.
293 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700294 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700295 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700296 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
297 combine_stdout_stderr=True,
298 log_output=True,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100299 error_code_ok=True,
300 **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700301
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100302 @staticmethod
303 def _ParseArgs(argv):
304 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700305
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100306 Args:
307 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700308
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100309 Returns:
310 List of parsed opts.
311 """
312 parser = commandline.ArgumentParser(description=__doc__)
313 parser.add_argument('--start', action='store_true', default=False,
314 help='Start the VM.')
315 parser.add_argument('--stop', action='store_true', default=False,
316 help='Stop the VM.')
317 parser.add_argument('--image-path', type='path',
318 help='Path to VM image to launch with --start.')
319 parser.add_argument('--qemu-path', type='path',
320 help='Path of qemu binary to launch with --start.')
321 parser.add_argument('--disable-kvm', dest='enable_kvm',
322 action='store_false', default=True,
323 help='Disable KVM, use software emulation.')
324 parser.add_argument('--no-display', dest='display',
325 action='store_false', default=True,
326 help='Do not display video output.')
327 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
328 help='ssh port to communicate with VM.')
329 parser.add_argument('--dry-run', action='store_true', default=False,
330 help='dry run for debugging.')
331 parser.add_argument('--cmd', action='store_true', default=False,
332 help='Run a command in the VM.')
333 parser.add_argument('args', nargs=argparse.REMAINDER,
334 help='Command to run in the VM.')
335 return parser.parse_args(argv)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700336
337def main(argv):
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100338 vm = VM(argv)
339 vm.Run()