blob: f9186a38db0687f6f992596427ce0dc2d36a06fa [file] [log] [blame]
Achuith Bhandarkard8d19292016-05-03 14:32:58 -07001# 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 Frysinger666566c2016-09-21 00:00:21 -04005"""Script for VM Management."""
Achuith Bhandarkard8d19292016-05-03 14:32:58 -07006
7from __future__ import print_function
8
9import os
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070010
11from chromite.lib import commandline
12from chromite.lib import cros_build_lib
13from chromite.lib import cros_logging as logging
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070014from chromite.lib import osutils
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070015from chromite.lib import remote_access
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -070016from chromite.lib import retry_util
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070017
18
19class VMError(Exception):
20 """Exception for VM failures."""
21
22 def __init__(self, message):
23 super(VMError, self).__init__()
24 logging.error(message)
25
26
27class VM(object):
28 """Class for managing a VM."""
29
30 SSH_PORT = 9222
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070031
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070032 def __init__(self, image_path=None, qemu_path=None, enable_kvm=True,
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -070033 display=True, ssh_port=SSH_PORT, dry_run=False):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070034 """Initialize VM.
35
36 Args:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070037 image_path: path of vm image.
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070038 qemu_path: path to qemu binary.
39 enable_kvm: enable kvm (kernel support for virtualization).
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -070040 display: display video output.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070041 ssh_port: ssh port to use.
42 dry_run: disable VM commands.
43 """
44
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070045 self.qemu_path = qemu_path
46 self.enable_kvm = 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.
49 self.use_sudo = enable_kvm and not os.access('/dev/kvm', os.W_OK)
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -070050 self.display = display
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070051 self.image_path = image_path
52 self.ssh_port = ssh_port
53 self.dry_run = dry_run
54
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070055 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 Bhandarkard8d19292016-05-03 14:32:58 -070067 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 Bhandarkar65d1a892017-05-08 14:13:12 -070071 self.remote = remote_access.RemoteDevice(remote_access.LOCALHOST,
72 port=ssh_port)
73
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070074 # TODO(achuith): support nographics, snapshot, mem_path, usb_passthrough,
75 # moblab, etc.
76
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070077
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 Bhandarkard8d19292016-05-03 14:32:58 -070087
88 Args:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070089 recreate: recreate vm_dir.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070090 """
Mike Frysinger97080242017-09-13 01:58:45 -040091 osutils.RmDir(self.vm_dir, ignore_missing=True, sudo=self.use_sudo)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070092 if recreate:
Mike Frysinger97080242017-09-13 01:58:45 -040093 osutils.SafeMakedirs(self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070094
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070095 def PerformAction(self, start=False, stop=False, cmd=None):
96 """Performs an action, one of start, stop, or run a command in the VM.
97
98 Args:
99 start: start the VM.
100 stop: stop the VM.
101 cmd: list or scalar command to run in the VM.
102
103 Returns:
104 cmd output.
105 """
106
107 if not start and not stop and not cmd:
108 raise VMError('Must specify one of start, stop, or cmd.')
109 if start:
110 self.Start()
111 if stop:
112 self.Stop()
113 if cmd:
114 return self.RemoteCommand(cmd.split())
115
116 def Start(self):
117 """Start the VM."""
118
119 self.Stop()
120
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700121 logging.debug('Start VM')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700122 if not self.qemu_path:
123 self.qemu_path = osutils.Which('qemu-system-x86_64')
124 if not self.qemu_path:
125 raise VMError('qemu not found.')
126 logging.debug('qemu path=%s', self.qemu_path)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700127
128 if not self.image_path:
129 self.image_path = os.environ.get('VM_IMAGE_PATH', '')
130 logging.debug('vm image path=%s', self.image_path)
131 if not self.image_path or not os.path.exists(self.image_path):
132 raise VMError('VM image path %s does not exist.' % self.image_path)
133
134 self._CleanupFiles(recreate=True)
Mike Frysinger97080242017-09-13 01:58:45 -0400135 # Make sure we can read these files later on by creating them as ourselves.
136 osutils.Touch(self.kvm_serial)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700137 for pipe in [self.kvm_pipe_in, self.kvm_pipe_out]:
138 os.mkfifo(pipe, 0600)
Mike Frysinger97080242017-09-13 01:58:45 -0400139 osutils.Touch(self.pidfile)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700140
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700141 args = [self.qemu_path, '-m', '2G', '-smp', '4', '-vga', 'cirrus',
142 '-daemonize',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700143 '-pidfile', self.pidfile,
144 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
145 '-serial', 'file:%s' % self.kvm_serial,
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700146 '-mon', 'chardev=control_pipe',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700147 '-net', 'nic,model=virtio',
Nicolas Norvez80329de2017-03-27 14:32:24 -0700148 '-net', 'user,hostfwd=tcp:127.0.0.1:%d-:22' % self.ssh_port,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700149 '-drive', 'file=%s,index=0,media=disk,cache=unsafe'
150 % self.image_path]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700151 if self.enable_kvm:
152 args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700153 if not self.display:
154 args.extend(['-display', 'none'])
Mike Frysinger97080242017-09-13 01:58:45 -0400155 logging.info(cros_build_lib.CmdToStr(args))
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700156 logging.info('Pid file: %s', self.pidfile)
157 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700158 self._RunCommand(args)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700159
160 def _GetVMPid(self):
161 """Get the pid of the VM.
162
163 Returns:
164 pid of the VM.
165 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700166 if not os.path.exists(self.vm_dir):
167 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700168 return 0
169
170 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700171 logging.info('%s does not exist.', self.pidfile)
172 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700173
Mike Frysinger97080242017-09-13 01:58:45 -0400174 pid = osutils.ReadFile(self.pidfile).rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700175 if not pid.isdigit():
Mike Frysinger97080242017-09-13 01:58:45 -0400176 # Ignore blank/empty files.
177 if pid:
178 logging.error('%s in %s is not a pid.', pid, self.pidfile)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700179 return 0
180
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700181 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700182
183 def IsRunning(self):
184 """Returns True if there's a running VM.
185
186 Returns:
187 True if there's a running VM.
188 """
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700189 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700190 if not pid:
191 return False
192
193 # Make sure the process actually exists.
Mike Frysinger97080242017-09-13 01:58:45 -0400194 return os.path.isdir('/proc/%i' % pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700195
196 def Stop(self):
197 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700198 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700199
200 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700201 if pid:
202 logging.info('Killing %d.', pid)
203 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700204 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700205
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700206 self._CleanupFiles(recreate=False)
207
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700208 def _WaitForProcs(self):
209 """Wait for expected processes to launch."""
210 class _TooFewPidsException(Exception):
211 """Exception for _GetRunningPids to throw."""
212
213 def _GetRunningPids(exe, numpids):
214 pids = self.remote.GetRunningPids(exe, full_path=False)
215 logging.info('%s pids: %s', exe, repr(pids))
216 if len(pids) < numpids:
217 raise _TooFewPidsException()
218
219 def _WaitForProc(exe, numpids):
220 try:
221 retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700222 exception=_TooFewPidsException,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700223 max_retry=20,
224 functor=lambda: _GetRunningPids(exe, numpids),
225 sleep=2)
226 except _TooFewPidsException:
227 raise VMError('_WaitForProcs failed: timed out while waiting for '
228 '%d %s processes to start.' % (numpids, exe))
229
230 # We could also wait for session_manager, nacl_helper, etc, but chrome is
231 # the long pole. We expect the parent, 2 zygotes, gpu-process, renderer.
232 # This could potentially break with Mustash.
233 _WaitForProc('chrome', 5)
234
235 def WaitForBoot(self):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700236 """Wait for the VM to boot up.
237
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700238 Wait for ssh connection to become active, and wait for all expected chrome
239 processes to be launched.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700240 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700241 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700242 self.Start()
243
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700244 try:
245 result = retry_util.RetryException(
Achuith Bhandarkar0e7b8502017-06-12 15:32:41 -0700246 exception=remote_access.SSHConnectionError,
Achuith Bhandarkar2f8352f2017-06-02 12:47:18 -0700247 max_retry=10,
248 functor=lambda: self.RemoteCommand(cmd=['echo']),
249 sleep=5)
250 except remote_access.SSHConnectionError:
251 raise VMError('WaitForBoot timed out trying to connect to VM.')
252
253 if result.returncode != 0:
254 raise VMError('WaitForBoot failed: %s.' % result.error)
255
256 self._WaitForProcs()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700257
258 def RemoteCommand(self, cmd):
259 """Run a remote command in the VM.
260
261 Args:
262 cmd: command to run, of list type.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700263 """
264 if not isinstance(cmd, list):
265 raise VMError('cmd must be a list.')
266
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700267 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700268 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
269 combine_stdout_stderr=True,
270 log_output=True,
271 error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700272
273def ParseCommandLine(argv):
274 """Parse the command line.
275
276 Args:
277 argv: Command arguments.
278
279 Returns:
280 List of parsed args.
281 """
282 parser = commandline.ArgumentParser(description=__doc__)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700283 parser.add_argument('--start', action='store_true', default=False,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700284 help='Start the VM.')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700285 parser.add_argument('--stop', action='store_true', default=False,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700286 help='Stop the VM.')
287 parser.add_argument('--cmd', help='Run this command in the VM.')
288 parser.add_argument('--image-path', type='path',
289 help='Path to VM image to launch with --start.')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700290 parser.add_argument('--qemu-path', type='path',
291 help='Path of qemu binary to launch with --start.')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700292 parser.add_argument('--disable-kvm', dest='enable_kvm',
293 action='store_false', default=True,
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700294 help='Disable KVM, use software emulation.')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700295 parser.add_argument('--no-display', dest='display',
296 action='store_false', default=True,
297 help='Do not display video output.')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700298 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
299 help='ssh port to communicate with VM.')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700300 parser.add_argument('--dry-run', action='store_true', default=False,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700301 help='dry run for debugging.')
302 return parser.parse_args(argv)
303
304
305def main(argv):
306 args = ParseCommandLine(argv)
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700307 vm = VM(image_path=args.image_path, qemu_path=args.qemu_path,
308 enable_kvm=args.enable_kvm, display=args.display,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700309 ssh_port=args.ssh_port, dry_run=args.dry_run)
310 vm.PerformAction(start=args.start, stop=args.stop, cmd=args.cmd)