blob: 1669cc0d2037fca727a9d1b9d91f6eb114b54d0d [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
10import time
11
12from chromite.lib import commandline
13from chromite.lib import cros_build_lib
14from chromite.lib import cros_logging as logging
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070015from chromite.lib import osutils
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070016from chromite.lib import remote_access
17
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
32
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070033 def __init__(self, image_path=None, qemu_path=None, enable_kvm=True,
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -070034 display=True, ssh_port=SSH_PORT, dry_run=False):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070035 """Initialize VM.
36
37 Args:
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070038 image_path: path of vm image.
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070039 qemu_path: path to qemu binary.
40 enable_kvm: enable kvm (kernel support for virtualization).
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -070041 display: display video output.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070042 ssh_port: ssh port to use.
43 dry_run: disable VM commands.
44 """
45
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -070046 self.qemu_path = qemu_path
47 self.enable_kvm = enable_kvm
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070048 # Software emulation doesn't need sudo access.
49 self.use_sudo = enable_kvm
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 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070091 self._RunCommand(['rm', '-rf', self.vm_dir])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070092 if recreate:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -070093 self._RunCommand(['mkdir', self.vm_dir])
94 self._RunCommand(['chmod', '777', self.vm_dir])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070095
Achuith Bhandarkard8d19292016-05-03 14:32:58 -070096 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 Bhandarkar022d69c2016-10-05 14:28:14 -0700122 logging.debug('Start VM')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700123 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 Bhandarkard8d19292016-05-03 14:32:58 -0700128
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 Bhandarkarf4950ba2016-10-11 15:40:07 -0700140 args = [self.qemu_path, '-m', '2G', '-smp', '4', '-vga', 'cirrus',
141 '-daemonize',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700142 '-pidfile', self.pidfile,
143 '-chardev', 'pipe,id=control_pipe,path=%s' % self.kvm_monitor,
144 '-serial', 'file:%s' % self.kvm_serial,
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700145 '-mon', 'chardev=control_pipe',
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700146 '-net', 'nic,model=virtio',
147 '-net', 'user,hostfwd=tcp::%d-:22' % self.ssh_port,
148 '-drive', 'file=%s,index=0,media=disk,cache=unsafe'
149 % self.image_path]
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700150 if self.enable_kvm:
151 args.append('-enable-kvm')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700152 if not self.display:
153 args.extend(['-display', 'none'])
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700154 logging.info(' '.join(args))
155 logging.info('Pid file: %s', self.pidfile)
156 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700157 self._RunCommand(args)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700158
159 def _GetVMPid(self):
160 """Get the pid of the VM.
161
162 Returns:
163 pid of the VM.
164 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700165 if not os.path.exists(self.vm_dir):
166 logging.debug('%s not present.', self.vm_dir)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700167 return 0
168
169 if not os.path.exists(self.pidfile):
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700170 logging.info('%s does not exist.', self.pidfile)
171 return 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700172
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700173 pid = self._RunCommand(['cat', self.pidfile],
174 redirect_stdout=True).output.rstrip()
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700175 if not pid.isdigit():
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700176 logging.error('%s in %s is not a pid.', pid, self.pidfile)
177 return 0
178
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700179 return int(pid)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700180
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 Bhandarkarf4950ba2016-10-11 15:40:07 -0700187 pid = self._GetVMPid()
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700188 if not pid:
189 return False
190
191 # Make sure the process actually exists.
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700192 res = self._RunCommand(['kill', '-0', str(pid)], error_code_ok=True)
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700193 return res.returncode == 0
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700194
195 def Stop(self):
196 """Stop the VM."""
Achuith Bhandarkar022d69c2016-10-05 14:28:14 -0700197 logging.debug('Stop VM')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700198
199 pid = self._GetVMPid()
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700200 if pid:
201 logging.info('Killing %d.', pid)
202 if not self.dry_run:
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700203 self._RunCommand(['kill', '-9', str(pid)], error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700204
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700205 self._CleanupFiles(recreate=False)
206
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700207 def WaitForBoot(self, timeout=180, poll_interval=1):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700208 """Wait for the VM to boot up.
209
210 If there is no VM running, start one.
211
212 Args:
213 timeout: maxiumum time to wait before raising an exception.
214 poll_interval: interval between checks.
215 """
Achuith Bhandarkaree3163d2016-10-19 12:58:35 -0700216 if not os.path.exists(self.vm_dir):
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700217 self.Start()
218
219 start_time = time.time()
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700220 error = 'timed out after %d sec' % timeout
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700221 while time.time() - start_time < timeout:
222 result = self.RemoteCommand(cmd=['echo'])
223 if result.returncode == 255:
224 time.sleep(poll_interval)
225 continue
226 elif result.returncode == 0:
227 return
228 else:
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700229 error = self.error
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700230 break
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700231 raise VMError('WaitForBoot failed: %s.' % error)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700232
233 def RemoteCommand(self, cmd):
234 """Run a remote command in the VM.
235
236 Args:
237 cmd: command to run, of list type.
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700238 """
239 if not isinstance(cmd, list):
240 raise VMError('cmd must be a list.')
241
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700242 if not self.dry_run:
Achuith Bhandarkar65d1a892017-05-08 14:13:12 -0700243 return self.remote.RunCommand(cmd, debug_level=logging.INFO,
244 combine_stdout_stderr=True,
245 log_output=True,
246 error_code_ok=True)
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700247
248def ParseCommandLine(argv):
249 """Parse the command line.
250
251 Args:
252 argv: Command arguments.
253
254 Returns:
255 List of parsed args.
256 """
257 parser = commandline.ArgumentParser(description=__doc__)
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700258 parser.add_argument('--start', action='store_true', default=False,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700259 help='Start the VM.')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700260 parser.add_argument('--stop', action='store_true', default=False,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700261 help='Stop the VM.')
262 parser.add_argument('--cmd', help='Run this command in the VM.')
263 parser.add_argument('--image-path', type='path',
264 help='Path to VM image to launch with --start.')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700265 parser.add_argument('--qemu-path', type='path',
266 help='Path of qemu binary to launch with --start.')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700267 parser.add_argument('--disable-kvm', dest='enable_kvm',
268 action='store_false', default=True,
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700269 help='Disable KVM, use software emulation.')
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700270 parser.add_argument('--no-display', dest='display',
271 action='store_false', default=True,
272 help='Do not display video output.')
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700273 parser.add_argument('--ssh-port', type=int, default=VM.SSH_PORT,
274 help='ssh port to communicate with VM.')
Achuith Bhandarkarf4950ba2016-10-11 15:40:07 -0700275 parser.add_argument('--dry-run', action='store_true', default=False,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700276 help='dry run for debugging.')
277 return parser.parse_args(argv)
278
279
280def main(argv):
281 args = ParseCommandLine(argv)
Achuith Bhandarkarb891adb2016-10-24 18:43:22 -0700282 vm = VM(image_path=args.image_path, qemu_path=args.qemu_path,
283 enable_kvm=args.enable_kvm, display=args.display,
Achuith Bhandarkard8d19292016-05-03 14:32:58 -0700284 ssh_port=args.ssh_port, dry_run=args.dry_run)
285 vm.PerformAction(start=args.start, stop=args.stop, cmd=args.cmd)