Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 1 | # Copyright 2016 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
Mike Frysinger | 666566c | 2016-09-21 00:00:21 -0400 | [diff] [blame] | 5 | """Script for VM Management.""" |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 6 | |
| 7 | from __future__ import print_function |
| 8 | |
| 9 | import os |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 10 | |
| 11 | from chromite.lib import commandline |
| 12 | from chromite.lib import cros_build_lib |
| 13 | from chromite.lib import cros_logging as logging |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 14 | from chromite.lib import osutils |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 15 | from chromite.lib import remote_access |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 16 | from chromite.lib import retry_util |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 17 | |
| 18 | |
| 19 | class VMError(Exception): |
| 20 | """Exception for VM failures.""" |
| 21 | |
| 22 | def __init__(self, message): |
| 23 | super(VMError, self).__init__() |
| 24 | logging.error(message) |
| 25 | |
| 26 | |
| 27 | class VM(object): |
| 28 | """Class for managing a VM.""" |
| 29 | |
| 30 | SSH_PORT = 9222 |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 31 | |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 32 | def __init__(self, image_path=None, qemu_path=None, enable_kvm=True, |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 33 | display=True, ssh_port=SSH_PORT, dry_run=False): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 34 | """Initialize VM. |
| 35 | |
| 36 | Args: |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 37 | image_path: path of vm image. |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 38 | qemu_path: path to qemu binary. |
| 39 | enable_kvm: enable kvm (kernel support for virtualization). |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 40 | display: display video output. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 41 | ssh_port: ssh port to use. |
| 42 | dry_run: disable VM commands. |
| 43 | """ |
| 44 | |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 45 | self.qemu_path = qemu_path |
| 46 | self.enable_kvm = enable_kvm |
Achuith Bhandarkar | f877da2 | 2017-09-12 12:27:39 -0700 | [diff] [blame^] | 47 | # We don't need sudo access for software emulation or if /dev/kvm is |
| 48 | # writeable. |
| 49 | self.use_sudo = enable_kvm and not os.access('/dev/kvm', os.W_OK) |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 50 | self.display = display |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 51 | self.image_path = image_path |
| 52 | self.ssh_port = ssh_port |
| 53 | self.dry_run = dry_run |
| 54 | |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 55 | self.vm_dir = os.path.join(osutils.GetGlobalTempDir(), 'cros_vm') |
| 56 | if os.path.exists(self.vm_dir): |
| 57 | # For security, ensure that vm_dir is not a symlink, and is owned by us or |
| 58 | # by root. |
| 59 | assert not os.path.islink(self.vm_dir), \ |
| 60 | 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir |
| 61 | st_uid = os.stat(self.vm_dir).st_uid |
| 62 | assert st_uid == 0 or st_uid == os.getuid(), \ |
| 63 | 'VM state dir is misconfigured; please recreate: %s' % self.vm_dir |
| 64 | |
| 65 | self.pidfile = os.path.join(self.vm_dir, 'kvm.pid') |
| 66 | self.kvm_monitor = os.path.join(self.vm_dir, 'kvm.monitor') |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 67 | self.kvm_pipe_in = '%s.in' % self.kvm_monitor # to KVM |
| 68 | self.kvm_pipe_out = '%s.out' % self.kvm_monitor # from KVM |
| 69 | self.kvm_serial = '%s.serial' % self.kvm_monitor |
| 70 | |
Achuith Bhandarkar | 65d1a89 | 2017-05-08 14:13:12 -0700 | [diff] [blame] | 71 | self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST, |
| 72 | port=ssh_port) |
| 73 | |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 74 | # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough, |
| 75 | # moblab, etc. |
| 76 | |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 77 | |
| 78 | def _RunCommand(self, *args, **kwargs): |
| 79 | """Use SudoRunCommand or RunCommand as necessary.""" |
| 80 | if self.use_sudo: |
| 81 | return cros_build_lib.SudoRunCommand(*args, **kwargs) |
| 82 | else: |
| 83 | return cros_build_lib.RunCommand(*args, **kwargs) |
| 84 | |
| 85 | def _CleanupFiles(self, recreate): |
| 86 | """Cleanup vm_dir. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 87 | |
| 88 | Args: |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 89 | recreate: recreate vm_dir. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 90 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 91 | self._RunCommand(['rm', '-rf', self.vm_dir]) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 92 | if recreate: |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 93 | self._RunCommand(['mkdir', self.vm_dir]) |
| 94 | self._RunCommand(['chmod', '777', self.vm_dir]) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 95 | |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 96 | def PerformAction(self, start=False, stop=False, cmd=None): |
| 97 | """Performs an action, one of start, stop, or run a command in the VM. |
| 98 | |
| 99 | Args: |
| 100 | start: start the VM. |
| 101 | stop: stop the VM. |
| 102 | cmd: list or scalar command to run in the VM. |
| 103 | |
| 104 | Returns: |
| 105 | cmd output. |
| 106 | """ |
| 107 | |
| 108 | if not start and not stop and not cmd: |
| 109 | raise VMError('Must specify one of start, stop, or cmd.') |
| 110 | if start: |
| 111 | self.Start() |
| 112 | if stop: |
| 113 | self.Stop() |
| 114 | if cmd: |
| 115 | return self.RemoteCommand(cmd.split()) |
| 116 | |
| 117 | def Start(self): |
| 118 | """Start the VM.""" |
| 119 | |
| 120 | self.Stop() |
| 121 | |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 122 | logging.debug('Start VM') |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 123 | if not self.qemu_path: |
| 124 | self.qemu_path = osutils.Which('qemu-system-x86_64') |
| 125 | if not self.qemu_path: |
| 126 | raise VMError('qemu not found.') |
| 127 | logging.debug('qemu path=%s', self.qemu_path) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 128 | |
| 129 | if not self.image_path: |
| 130 | self.image_path = os.environ.get('VM_IMAGE_PATH', '') |
| 131 | logging.debug('vm image path=%s', self.image_path) |
| 132 | if not self.image_path or not os.path.exists(self.image_path): |
| 133 | raise VMError('VM image path %s does not exist.' % self.image_path) |
| 134 | |
| 135 | self._CleanupFiles(recreate=True) |
| 136 | open(self.kvm_serial, 'w') |
| 137 | for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]: |
| 138 | os.mkfifo(pipe, 0600) |
| 139 | |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 140 | args = [self.qemu_path, '-m', '2G', '-smp', '4', '-vga', 'cirrus', |
| 141 | '-daemonize', |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 142 | '-pidfile', self.pidfile, |
| 143 | '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor, |
| 144 | '-serial', 'file:%s' % self.kvm_serial, |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 145 | '-mon', 'chardev=control_pipe', |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 146 | '-net', 'nic,model=virtio', |
Nicolas Norvez | 80329de | 2017-03-27 14:32:24 -0700 | [diff] [blame] | 147 | '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22' % self.ssh_port, |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 148 | '-drive', 'file=%s,index=0,media=disk,cache=unsafe' |
| 149 | % self.image_path] |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 150 | if self.enable_kvm: |
| 151 | args.append('-enable-kvm') |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 152 | if not self.display: |
| 153 | args.extend(['-display', 'none']) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 154 | logging.info(' '.join(args)) |
| 155 | logging.info('Pid file: %s', self.pidfile) |
| 156 | if not self.dry_run: |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 157 | self._RunCommand(args) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 158 | |
| 159 | def _GetVMPid(self): |
| 160 | """Get the pid of the VM. |
| 161 | |
| 162 | Returns: |
| 163 | pid of the VM. |
| 164 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 165 | if not os.path.exists(self.vm_dir): |
| 166 | logging.debug('%s not present.', self.vm_dir) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 167 | return 0 |
| 168 | |
| 169 | if not os.path.exists(self.pidfile): |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 170 | logging.info('%s does not exist.', self.pidfile) |
| 171 | return 0 |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 172 | |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 173 | pid = self._RunCommand(['cat', self.pidfile], |
| 174 | redirect_stdout=True).output.rstrip() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 175 | if not pid.isdigit(): |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 176 | logging.error('%s in %s is not a pid.', pid, self.pidfile) |
| 177 | return 0 |
| 178 | |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 179 | return int(pid) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 180 | |
| 181 | def IsRunning(self): |
| 182 | """Returns True if there's a running VM. |
| 183 | |
| 184 | Returns: |
| 185 | True if there's a running VM. |
| 186 | """ |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 187 | pid = self._GetVMPid() |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 188 | if not pid: |
| 189 | return False |
| 190 | |
| 191 | # Make sure the process actually exists. |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 192 | res = self._RunCommand(['kill', '-0', str(pid)], error_code_ok=True) |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 193 | return res.returncode == 0 |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 194 | |
| 195 | def Stop(self): |
| 196 | """Stop the VM.""" |
Achuith Bhandarkar | 022d69c | 2016-10-05 14:28:14 -0700 | [diff] [blame] | 197 | logging.debug('Stop VM') |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 198 | |
| 199 | pid = self._GetVMPid() |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 200 | if pid: |
| 201 | logging.info('Killing %d.', pid) |
| 202 | if not self.dry_run: |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 203 | self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 204 | |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 205 | self._CleanupFiles(recreate=False) |
| 206 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 207 | def _WaitForProcs(self): |
| 208 | """Wait for expected processes to launch.""" |
| 209 | class _TooFewPidsException(Exception): |
| 210 | """Exception for _GetRunningPids to throw.""" |
| 211 | |
| 212 | def _GetRunningPids(exe, numpids): |
| 213 | pids = self.remote.GetRunningPids(exe, full_path=False) |
| 214 | logging.info('%s pids: %s', exe, repr(pids)) |
| 215 | if len(pids) < numpids: |
| 216 | raise _TooFewPidsException() |
| 217 | |
| 218 | def _WaitForProc(exe, numpids): |
| 219 | try: |
| 220 | retry_util.RetryException( |
Achuith Bhandarkar | 0e7b850 | 2017-06-12 15:32:41 -0700 | [diff] [blame] | 221 | exception=_TooFewPidsException, |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 222 | max_retry=20, |
| 223 | functor=lambda: _GetRunningPids(exe, numpids), |
| 224 | sleep=2) |
| 225 | except _TooFewPidsException: |
| 226 | raise VMError('_WaitForProcs failed: timed out while waiting for ' |
| 227 | '%d %s processes to start.' % (numpids, exe)) |
| 228 | |
| 229 | # We could also wait for session_manager, nacl_helper, etc, but chrome is |
| 230 | # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer. |
| 231 | # This could potentially break with Mustash. |
| 232 | _WaitForProc('chrome', 5) |
| 233 | |
| 234 | def WaitForBoot(self): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 235 | """Wait for the VM to boot up. |
| 236 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 237 | Wait for ssh connection to become active, and wait for all expected chrome |
| 238 | processes to be launched. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 239 | """ |
Achuith Bhandarkar | ee3163d | 2016-10-19 12:58:35 -0700 | [diff] [blame] | 240 | if not os.path.exists(self.vm_dir): |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 241 | self.Start() |
| 242 | |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 243 | try: |
| 244 | result = retry_util.RetryException( |
Achuith Bhandarkar | 0e7b850 | 2017-06-12 15:32:41 -0700 | [diff] [blame] | 245 | exception=remote_access.SSHConnectionError, |
Achuith Bhandarkar | 2f8352f | 2017-06-02 12:47:18 -0700 | [diff] [blame] | 246 | max_retry=10, |
| 247 | functor=lambda: self.RemoteCommand(cmd=['echo']), |
| 248 | sleep=5) |
| 249 | except remote_access.SSHConnectionError: |
| 250 | raise VMError('WaitForBoot timed out trying to connect to VM.') |
| 251 | |
| 252 | if result.returncode != 0: |
| 253 | raise VMError('WaitForBoot failed: %s.' % result.error) |
| 254 | |
| 255 | self._WaitForProcs() |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 256 | |
| 257 | def RemoteCommand(self, cmd): |
| 258 | """Run a remote command in the VM. |
| 259 | |
| 260 | Args: |
| 261 | cmd: command to run, of list type. |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 262 | """ |
| 263 | if not isinstance(cmd, list): |
| 264 | raise VMError('cmd must be a list.') |
| 265 | |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 266 | if not self.dry_run: |
Achuith Bhandarkar | 65d1a89 | 2017-05-08 14:13:12 -0700 | [diff] [blame] | 267 | return self.remote.RunCommand(cmd, debug_level=logging.INFO, |
| 268 | combine_stdout_stderr=True, |
| 269 | log_output=True, |
| 270 | error_code_ok=True) |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 271 | |
| 272 | def ParseCommandLine(argv): |
| 273 | """Parse the command line. |
| 274 | |
| 275 | Args: |
| 276 | argv: Command arguments. |
| 277 | |
| 278 | Returns: |
| 279 | List of parsed args. |
| 280 | """ |
| 281 | parser = commandline.ArgumentParser(description=__doc__) |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 282 | parser.add_argument('--start', action='store_true', default=False, |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 283 | help='Start the VM.') |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 284 | parser.add_argument('--stop', action='store_true', default=False, |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 285 | help='Stop the VM.') |
| 286 | parser.add_argument('--cmd', help='Run this command in the VM.') |
| 287 | parser.add_argument('--image-path', type='path', |
| 288 | help='Path to VM image to launch with --start.') |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 289 | parser.add_argument('--qemu-path', type='path', |
| 290 | help='Path of qemu binary to launch with --start.') |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 291 | parser.add_argument('--disable-kvm', dest='enable_kvm', |
| 292 | action='store_false', default=True, |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 293 | help='Disable KVM, use software emulation.') |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 294 | parser.add_argument('--no-display', dest='display', |
| 295 | action='store_false', default=True, |
| 296 | help='Do not display video output.') |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 297 | parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT, |
| 298 | help='ssh port to communicate with VM.') |
Achuith Bhandarkar | f4950ba | 2016-10-11 15:40:07 -0700 | [diff] [blame] | 299 | parser.add_argument('--dry-run', action='store_true', default=False, |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 300 | help='dry run for debugging.') |
| 301 | return parser.parse_args(argv) |
| 302 | |
| 303 | |
| 304 | def main(argv): |
| 305 | args = ParseCommandLine(argv) |
Achuith Bhandarkar | b891adb | 2016-10-24 18:43:22 -0700 | [diff] [blame] | 306 | vm = VM(image_path=args.image_path, qemu_path=args.qemu_path, |
| 307 | enable_kvm=args.enable_kvm, display=args.display, |
Achuith Bhandarkar | d8d1929 | 2016-05-03 14:32:58 -0700 | [diff] [blame] | 308 | ssh_port=args.ssh_port, dry_run=args.dry_run) |
| 309 | vm.PerformAction(start=args.start, stop=args.stop, cmd=args.cmd) |