]> Git Repo - qemu.git/blob - scripts/qemu.py
qemu.py: Pylint/style fixes
[qemu.git] / scripts / qemu.py
1 # QEMU library
2 #
3 # Copyright (C) 2015-2016 Red Hat Inc.
4 # Copyright (C) 2012 IBM Corp.
5 #
6 # Authors:
7 #  Fam Zheng <[email protected]>
8 #
9 # This work is licensed under the terms of the GNU GPL, version 2.  See
10 # the COPYING file in the top-level directory.
11 #
12 # Based on qmp.py.
13 #
14
15 import errno
16 import string
17 import os
18 import sys
19 import subprocess
20 import qmp.qmp
21
22
23 class QEMUMachine(object):
24     '''A QEMU VM
25
26     Use this object as a context manager to ensure the QEMU process terminates::
27
28         with VM(binary) as vm:
29             ...
30         # vm is guaranteed to be shut down here
31     '''
32
33     def __init__(self, binary, args=[], wrapper=[], name=None,
34                  test_dir="/var/tmp", monitor_address=None,
35                  socket_scm_helper=None, debug=False):
36         '''
37         Initialize a QEMUMachine
38
39         @param binary: path to the qemu binary
40         @param args: list of extra arguments
41         @param wrapper: list of arguments used as prefix to qemu binary
42         @param name: prefix for socket and log file names (default: qemu-PID)
43         @param test_dir: where to create socket and log file
44         @param monitor_address: address for QMP monitor
45         @param socket_scm_helper: helper program, required for send_fd_scm()"
46         @param debug: enable debug mode
47         @note: Qemu process is not started until launch() is used.
48         '''
49         if name is None:
50             name = "qemu-%d" % os.getpid()
51         if monitor_address is None:
52             monitor_address = os.path.join(test_dir, name + "-monitor.sock")
53         self._monitor_address = monitor_address
54         self._qemu_log_path = os.path.join(test_dir, name + ".log")
55         self._popen = None
56         self._binary = binary
57         self._args = list(args)     # Force copy args in case we modify them
58         self._wrapper = wrapper
59         self._events = []
60         self._iolog = None
61         self._socket_scm_helper = socket_scm_helper
62         self._debug = debug
63         self._qmp = None
64
65     def __enter__(self):
66         return self
67
68     def __exit__(self, exc_type, exc_val, exc_tb):
69         self.shutdown()
70         return False
71
72     # This can be used to add an unused monitor instance.
73     def add_monitor_telnet(self, ip, port):
74         args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
75         self._args.append('-monitor')
76         self._args.append(args)
77
78     def add_fd(self, fd, fdset, opaque, opts=''):
79         '''Pass a file descriptor to the VM'''
80         options = ['fd=%d' % fd,
81                    'set=%d' % fdset,
82                    'opaque=%s' % opaque]
83         if opts:
84             options.append(opts)
85
86         self._args.append('-add-fd')
87         self._args.append(','.join(options))
88         return self
89
90     def send_fd_scm(self, fd_file_path):
91         # In iotest.py, the qmp should always use unix socket.
92         assert self._qmp.is_scm_available()
93         if self._socket_scm_helper is None:
94             print >>sys.stderr, "No path to socket_scm_helper set"
95             return -1
96         if not os.path.exists(self._socket_scm_helper):
97             print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
98             return -1
99         fd_param = ["%s" % self._socket_scm_helper,
100                     "%d" % self._qmp.get_sock_fd(),
101                     "%s" % fd_file_path]
102         devnull = open('/dev/null', 'rb')
103         proc = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
104                                 stderr=sys.stderr)
105         return proc.wait()
106
107     @staticmethod
108     def _remove_if_exists(path):
109         '''Remove file object at path if it exists'''
110         try:
111             os.remove(path)
112         except OSError as exception:
113             if exception.errno == errno.ENOENT:
114                 return
115             raise
116
117     def is_running(self):
118         return self._popen and (self._popen.returncode is None)
119
120     def exitcode(self):
121         if self._popen is None:
122             return None
123         return self._popen.returncode
124
125     def get_pid(self):
126         if not self.is_running():
127             return None
128         return self._popen.pid
129
130     def _load_io_log(self):
131         with open(self._qemu_log_path, "r") as iolog:
132             self._iolog = iolog.read()
133
134     def _base_args(self):
135         if isinstance(self._monitor_address, tuple):
136             moncdev = "socket,id=mon,host=%s,port=%s" % (
137                 self._monitor_address[0],
138                 self._monitor_address[1])
139         else:
140             moncdev = 'socket,id=mon,path=%s' % self._monitor_address
141         return ['-chardev', moncdev,
142                 '-mon', 'chardev=mon,mode=control',
143                 '-display', 'none', '-vga', 'none']
144
145     def _pre_launch(self):
146         self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
147                                                 server=True,
148                                                 debug=self._debug)
149
150     def _post_launch(self):
151         self._qmp.accept()
152
153     def _post_shutdown(self):
154         if not isinstance(self._monitor_address, tuple):
155             self._remove_if_exists(self._monitor_address)
156         self._remove_if_exists(self._qemu_log_path)
157
158     def launch(self):
159         '''Launch the VM and establish a QMP connection'''
160         devnull = open('/dev/null', 'rb')
161         qemulog = open(self._qemu_log_path, 'wb')
162         try:
163             self._pre_launch()
164             args = (self._wrapper + [self._binary] + self._base_args() +
165                     self._args)
166             self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
167                                            stderr=subprocess.STDOUT,
168                                            shell=False)
169             self._post_launch()
170         except:
171             if self.is_running():
172                 self._popen.kill()
173                 self._popen.wait()
174             self._load_io_log()
175             self._post_shutdown()
176             raise
177
178     def shutdown(self):
179         '''Terminate the VM and clean up'''
180         if self.is_running():
181             try:
182                 self._qmp.cmd('quit')
183                 self._qmp.close()
184             except:
185                 self._popen.kill()
186
187             exitcode = self._popen.wait()
188             if exitcode < 0:
189                 sys.stderr.write('qemu received signal %i: %s\n'
190                                  % (-exitcode, ' '.join(self._args)))
191             self._load_io_log()
192             self._post_shutdown()
193
194     underscore_to_dash = string.maketrans('_', '-')
195
196     def qmp(self, cmd, conv_keys=True, **args):
197         '''Invoke a QMP command and return the response dict'''
198         qmp_args = dict()
199         for key in args.keys():
200             if conv_keys:
201                 qmp_args[key.translate(self.underscore_to_dash)] = args[key]
202             else:
203                 qmp_args[key] = args[key]
204
205         return self._qmp.cmd(cmd, args=qmp_args)
206
207     def command(self, cmd, conv_keys=True, **args):
208         '''
209         Invoke a QMP command.
210         On success return the response dict.
211         On failure raise an exception.
212         '''
213         reply = self.qmp(cmd, conv_keys, **args)
214         if reply is None:
215             raise Exception("Monitor is closed")
216         if "error" in reply:
217             raise Exception(reply["error"]["desc"])
218         return reply["return"]
219
220     def get_qmp_event(self, wait=False):
221         '''Poll for one queued QMP events and return it'''
222         if len(self._events) > 0:
223             return self._events.pop(0)
224         return self._qmp.pull_event(wait=wait)
225
226     def get_qmp_events(self, wait=False):
227         '''Poll for queued QMP events and return a list of dicts'''
228         events = self._qmp.get_events(wait=wait)
229         events.extend(self._events)
230         del self._events[:]
231         self._qmp.clear_events()
232         return events
233
234     def event_wait(self, name, timeout=60.0, match=None):
235         '''
236         Wait for specified timeout on named event in QMP; optionally filter
237         results by match.
238
239         The 'match' is checked to be a recursive subset of the 'event'; skips
240         branch processing on match's value None
241            {"foo": {"bar": 1}} matches {"foo": None}
242            {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
243         '''
244         def event_match(event, match=None):
245             if match is None:
246                 return True
247
248             for key in match:
249                 if key in event:
250                     if isinstance(event[key], dict):
251                         if not event_match(event[key], match[key]):
252                             return False
253                     elif event[key] != match[key]:
254                         return False
255                 else:
256                     return False
257
258             return True
259
260         # Search cached events
261         for event in self._events:
262             if (event['event'] == name) and event_match(event, match):
263                 self._events.remove(event)
264                 return event
265
266         # Poll for new events
267         while True:
268             event = self._qmp.pull_event(wait=timeout)
269             if (event['event'] == name) and event_match(event, match):
270                 return event
271             self._events.append(event)
272
273         return None
274
275     def get_log(self):
276         '''
277         After self.shutdown or failed qemu execution, this returns the output
278         of the qemu process.
279         '''
280         return self._iolog
This page took 0.068689 seconds and 4 git commands to generate.