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