blob: 62b24dab0eb99b6a301c79c58379bd5523fc98c0 [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 Bhandarkard8d19292016-05-03 14:32:58 -070011import os
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070012
13from chromite.lib import commandline
14from chromite.lib import cros_build_lib
15from chromite.lib import cros_logging as logging
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070016from chromite.lib import osutils
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070017from chromite.lib import remote_access
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -070018from chromite.lib import retry_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070019
20
21class VMError(Exception):
22 """Exception for VM failures."""
23
24 def __init__(self, message):
25 super(VMError, self).__init__()
26 logging.error(message)
27
28
29class VM(object):
30 """Class for managing a VM."""
31
32 SSH_PORT = 9222
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070033
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010034 def __init__(self, argv):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070035 """Initialize VM.
36
37 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010038 argv: command line args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070039 """
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010040 opts = self._ParseArgs(argv)
41 opts.Freeze()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070042
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010043 self.qemu_path = opts.qemu_path
44 self.enable_kvm = opts.enable_kvm
Achuith Bhandarkarf877da22017-09-12 12:27:39 -070045 # We don't need sudo access for software emulation or if /dev/kvm is
46 # writeable.
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010047 self.use_sudo = self.enable_kvm and not os.access('/dev/kvm', os.W_OK)
48 self.display = opts.display
49 self.image_path = opts.image_path
50 self.ssh_port = opts.ssh_port
51 self.dry_run = opts.dry_run
52
53 self.start = opts.start
54 self.stop = opts.stop
55 self.cmd = opts.args[1:] if opts.cmd else None
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070056
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070057 self.vm_dir = os.path.join(osutils.GetGlobalTempDir(), 'cros_vm')
58 if os.path.exists(self.vm_dir):
59 # For security, ensure that vm_dir is not a symlink, and is owned by us or
60 # by root.
61 assert not os.path.islink(self.vm_dir), \
62 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
63 st_uid = os.stat(self.vm_dir).st_uid
64 assert st_uid == 0 or st_uid == os.getuid(), \
65 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir
66
67 self.pidfile = os.path.join(self.vm_dir, 'kvm.pid')
68 self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070069 self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM
70 self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM
71 self.kvm_serial = '%s.serial' % self.kvm_monitor
72
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070073 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010074 port=self.ssh_port)
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -070075
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070076 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
77 # moblab, etc.
78
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070079 def _RunCommand(self, *args, **kwargs):
80 """Use SudoRunCommand or RunCommand as necessary."""
81 if self.use_sudo:
82 return cros_build_lib.SudoRunCommand(*args, **kwargs)
83 else:
84 return cros_build_lib.RunCommand(*args, **kwargs)
85
86 def _CleanupFiles(self, recreate):
87 """Cleanup vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070088
89 Args:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070090 recreate: recreate vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070091 """
Mike Frysinger97080242017-09-13 01:58:45 -040092 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070093 if recreate:
Mike Frysinger97080242017-09-13 01:58:45 -040094 osutils.SafeMakedirs(self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070095
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +010096 def Run(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070097 """Performs an action, one of start, stop, or run a command in the VM.
98
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070099 Returns:
100 cmd output.
101 """
102
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100103 if not self.start and not self.stop and not self.cmd:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700104 raise VMError('Must specify one of start, stop, or cmd.')
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100105 if self.start:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700106 self.Start()
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100107 if self.cmd:
108 return self.RemoteCommand(self.cmd)
109 if self.stop:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700110 self.Stop()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700111
112 def Start(self):
113 """Start the VM."""
114
115 self.Stop()
116
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700117 logging.debug('Start VM')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700118 if not self.qemu_path:
119 self.qemu_path = osutils.Which('qemu-system-x86_64')
120 if not self.qemu_path:
Achuith Bhandarkar9788efd2017-11-07 12:34:23 +0100121 raise VMError('qemu not found. Try: sudo apt-get install qemu')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700122 logging.debug('qemu path=%s', self.qemu_path)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700123
124 if not self.image_path:
125 self.image_path = os.environ.get('VM_IMAGE_PATH', '')
126 logging.debug('vm image path=%s', self.image_path)
127 if not self.image_path or not os.path.exists(self.image_path):
Achuith Bhandarkar9788efd2017-11-07 12:34:23 +0100128 raise VMError('No VM image path found. '
129 'Use cros chrome-sdk --download-vm.')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700130
131 self._CleanupFiles(recreate=True)
Mike Frysinger97080242017-09-13 01:58:45 -0400132 # Make sure we can read these files later on by creating them as ourselves.
133 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700134 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
135 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400136 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700137
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700138 args = [self.qemu_path, '-m', '2G', '-smp', '4', '-vga', 'cirrus',
139 '-daemonize',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700140 '-pidfile', self.pidfile,
141 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
142 '-serial', 'file:%s' % self.kvm_serial,
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700143 '-mon', 'chardev=control_pipe',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700144 '-net', 'nic,model=virtio',
Nicolas Norvez80329de2017-03-27 14:32:24 -0700145 '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22' % self.ssh_port,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700146 '-drive', 'file=%s,index=0,media=disk,cache=unsafe'
147 % self.image_path]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700148 if self.enable_kvm:
149 args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700150 if not self.display:
151 args.extend(['-display', 'none'])
Mike Frysinger97080242017-09-13 01:58:45 -0400152 logging.info(cros_build_lib.CmdToStr(args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700153 logging.info('Pid file: %s', self.pidfile)
154 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700155 self._RunCommand(args)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700156
157 def _GetVMPid(self):
158 """Get the pid of the VM.
159
160 Returns:
161 pid of the VM.
162 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700163 if not os.path.exists(self.vm_dir):
164 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700165 return 0
166
167 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700168 logging.info('%s does not exist.', self.pidfile)
169 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700170
Mike Frysinger97080242017-09-13 01:58:45 -0400171 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700172 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400173 # Ignore blank/empty files.
174 if pid:
175 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700176 return 0
177
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700178 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700179
180 def IsRunning(self):
181 """Returns True if there's a running VM.
182
183 Returns:
184 True if there's a running VM.
185 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700186 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700187 if not pid:
188 return False
189
190 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400191 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700192
193 def Stop(self):
194 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700195 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700196
197 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700198 if pid:
199 logging.info('Killing %d.', pid)
200 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700201 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700202
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700203 self._CleanupFiles(recreate=False)
204
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700205 def _WaitForProcs(self):
206 """Wait for expected processes to launch."""
207 class _TooFewPidsException(Exception):
208 """Exception for _GetRunningPids to throw."""
209
210 def _GetRunningPids(exe, numpids):
211 pids = self.remote.GetRunningPids(exe, full_path=False)
212 logging.info('%s pids: %s', exe, repr(pids))
213 if len(pids) < numpids:
214 raise _TooFewPidsException()
215
216 def _WaitForProc(exe, numpids):
217 try:
218 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700219 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700220 max_retry=20,
221 functor=lambda: _GetRunningPids(exe, numpids),
222 sleep=2)
223 except _TooFewPidsException:
224 raise VMError('_WaitForProcs failed: timed out while waiting for '
225 '%d %s processes to start.' % (numpids, exe))
226
227 # We could also wait for session_manager, nacl_helper, etc, but chrome is
228 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
229 # This could potentially break with Mustash.
230 _WaitForProc('chrome', 5)
231
232 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700233 """Wait for the VM to boot up.
234
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700235 Wait for ssh connection to become active, and wait for all expected chrome
236 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700237 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700238 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700239 self.Start()
240
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700241 try:
242 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700243 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700244 max_retry=10,
245 functor=lambda: self.RemoteCommand(cmd=['echo']),
246 sleep=5)
247 except remote_access.SSHConnectionError:
248 raise VMError('WaitForBoot timed out trying to connect to VM.')
249
250 if result.returncode != 0:
251 raise VMError('WaitForBoot failed: %s.' % result.error)
252
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100253 # Chrome can take a while to start with software emulation.
254 if not self.enable_kvm:
255 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700256
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100257 def RemoteCommand(self, cmd, **kwargs):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700258 """Run a remote command in the VM.
259
260 Args:
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100261 cmd: command to run.
262 kwargs: additional args (see documentation for RemoteDevice.RunCommand).
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700263 """
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700264 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700265 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
266 combine_stdout_stderr=True,
267 log_output=True,
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100268 error_code_ok=True,
269 **kwargs)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700270
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100271 @staticmethod
272 def _ParseArgs(argv):
273 """Parse a list of args.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700274
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100275 Args:
276 argv: list of command line arguments.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700277
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100278 Returns:
279 List of parsed opts.
280 """
281 parser = commandline.ArgumentParser(description=__doc__)
282 parser.add_argument('--start', action='store_true', default=False,
283 help='Start the VM.')
284 parser.add_argument('--stop', action='store_true', default=False,
285 help='Stop the VM.')
286 parser.add_argument('--image-path', type='path',
287 help='Path to VM image to launch with --start.')
288 parser.add_argument('--qemu-path', type='path',
289 help='Path of qemu binary to launch with --start.')
290 parser.add_argument('--disable-kvm', dest='enable_kvm',
291 action='store_false', default=True,
292 help='Disable KVM, use software emulation.')
293 parser.add_argument('--no-display', dest='display',
294 action='store_false', default=True,
295 help='Do not display video output.')
296 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
297 help='ssh port to communicate with VM.')
298 parser.add_argument('--dry-run', action='store_true', default=False,
299 help='dry run for debugging.')
300 parser.add_argument('--cmd', action='store_true', default=False,
301 help='Run a command in the VM.')
302 parser.add_argument('args', nargs=argparse.REMAINDER,
303 help='Command to run in the VM.')
304 return parser.parse_args(argv)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700305
306def main(argv):
Achuith Bhandarkar2a39adf2017-10-30 10:24:45 +0100307 vm = VM(argv)
308 vm.Run()