migration: Create load_setup()/cleanup() methods
[qemu/ar7.git] / scripts / qemu.py
blob880e3e8219c90a41c2e4e3d1d58f805ab7e87869
1 # QEMU library
3 # Copyright (C) 2015-2016 Red Hat Inc.
4 # Copyright (C) 2012 IBM Corp.
6 # Authors:
7 # Fam Zheng <famz@redhat.com>
9 # This work is licensed under the terms of the GNU GPL, version 2. See
10 # the COPYING file in the top-level directory.
12 # Based on qmp.py.
15 import errno
16 import string
17 import os
18 import sys
19 import subprocess
20 import qmp.qmp
23 class QEMUMachine(object):
24 '''A QEMU VM'''
26 def __init__(self, binary, args=[], wrapper=[], name=None, test_dir="/var/tmp",
27 monitor_address=None, socket_scm_helper=None, debug=False):
28 if name is None:
29 name = "qemu-%d" % os.getpid()
30 if monitor_address is None:
31 monitor_address = os.path.join(test_dir, name + "-monitor.sock")
32 self._monitor_address = monitor_address
33 self._qemu_log_path = os.path.join(test_dir, name + ".log")
34 self._popen = None
35 self._binary = binary
36 self._args = list(args) # Force copy args in case we modify them
37 self._wrapper = wrapper
38 self._events = []
39 self._iolog = None
40 self._socket_scm_helper = socket_scm_helper
41 self._debug = debug
43 # This can be used to add an unused monitor instance.
44 def add_monitor_telnet(self, ip, port):
45 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
46 self._args.append('-monitor')
47 self._args.append(args)
49 def add_fd(self, fd, fdset, opaque, opts=''):
50 '''Pass a file descriptor to the VM'''
51 options = ['fd=%d' % fd,
52 'set=%d' % fdset,
53 'opaque=%s' % opaque]
54 if opts:
55 options.append(opts)
57 self._args.append('-add-fd')
58 self._args.append(','.join(options))
59 return self
61 def send_fd_scm(self, fd_file_path):
62 # In iotest.py, the qmp should always use unix socket.
63 assert self._qmp.is_scm_available()
64 if self._socket_scm_helper is None:
65 print >>sys.stderr, "No path to socket_scm_helper set"
66 return -1
67 if os.path.exists(self._socket_scm_helper) == False:
68 print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
69 return -1
70 fd_param = ["%s" % self._socket_scm_helper,
71 "%d" % self._qmp.get_sock_fd(),
72 "%s" % fd_file_path]
73 devnull = open('/dev/null', 'rb')
74 p = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
75 stderr=sys.stderr)
76 return p.wait()
78 @staticmethod
79 def _remove_if_exists(path):
80 '''Remove file object at path if it exists'''
81 try:
82 os.remove(path)
83 except OSError as exception:
84 if exception.errno == errno.ENOENT:
85 return
86 raise
88 def is_running(self):
89 return self._popen and (self._popen.returncode is None)
91 def exitcode(self):
92 if self._popen is None:
93 return None
94 return self._popen.returncode
96 def get_pid(self):
97 if not self.is_running():
98 return None
99 return self._popen.pid
101 def _load_io_log(self):
102 with open(self._qemu_log_path, "r") as fh:
103 self._iolog = fh.read()
105 def _base_args(self):
106 if isinstance(self._monitor_address, tuple):
107 moncdev = "socket,id=mon,host=%s,port=%s" % (
108 self._monitor_address[0],
109 self._monitor_address[1])
110 else:
111 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
112 return ['-chardev', moncdev,
113 '-mon', 'chardev=mon,mode=control',
114 '-display', 'none', '-vga', 'none']
116 def _pre_launch(self):
117 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address, server=True,
118 debug=self._debug)
120 def _post_launch(self):
121 self._qmp.accept()
123 def _post_shutdown(self):
124 if not isinstance(self._monitor_address, tuple):
125 self._remove_if_exists(self._monitor_address)
126 self._remove_if_exists(self._qemu_log_path)
128 def launch(self):
129 '''Launch the VM and establish a QMP connection'''
130 devnull = open('/dev/null', 'rb')
131 qemulog = open(self._qemu_log_path, 'wb')
132 try:
133 self._pre_launch()
134 args = self._wrapper + [self._binary] + self._base_args() + self._args
135 self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
136 stderr=subprocess.STDOUT, shell=False)
137 self._post_launch()
138 except:
139 if self.is_running():
140 self._popen.kill()
141 self._popen.wait()
142 self._load_io_log()
143 self._post_shutdown()
144 raise
146 def shutdown(self):
147 '''Terminate the VM and clean up'''
148 if self.is_running():
149 try:
150 self._qmp.cmd('quit')
151 self._qmp.close()
152 except:
153 self._popen.kill()
155 exitcode = self._popen.wait()
156 if exitcode < 0:
157 sys.stderr.write('qemu received signal %i: %s\n' % (-exitcode, ' '.join(self._args)))
158 self._load_io_log()
159 self._post_shutdown()
161 underscore_to_dash = string.maketrans('_', '-')
162 def qmp(self, cmd, conv_keys=True, **args):
163 '''Invoke a QMP command and return the result dict'''
164 qmp_args = dict()
165 for k in args.keys():
166 if conv_keys:
167 qmp_args[k.translate(self.underscore_to_dash)] = args[k]
168 else:
169 qmp_args[k] = args[k]
171 return self._qmp.cmd(cmd, args=qmp_args)
173 def command(self, cmd, conv_keys=True, **args):
174 reply = self.qmp(cmd, conv_keys, **args)
175 if reply is None:
176 raise Exception("Monitor is closed")
177 if "error" in reply:
178 raise Exception(reply["error"]["desc"])
179 return reply["return"]
181 def get_qmp_event(self, wait=False):
182 '''Poll for one queued QMP events and return it'''
183 if len(self._events) > 0:
184 return self._events.pop(0)
185 return self._qmp.pull_event(wait=wait)
187 def get_qmp_events(self, wait=False):
188 '''Poll for queued QMP events and return a list of dicts'''
189 events = self._qmp.get_events(wait=wait)
190 events.extend(self._events)
191 del self._events[:]
192 self._qmp.clear_events()
193 return events
195 def event_wait(self, name, timeout=60.0, match=None):
196 # Test if 'match' is a recursive subset of 'event'
197 def event_match(event, match=None):
198 if match is None:
199 return True
201 for key in match:
202 if key in event:
203 if isinstance(event[key], dict):
204 if not event_match(event[key], match[key]):
205 return False
206 elif event[key] != match[key]:
207 return False
208 else:
209 return False
211 return True
213 # Search cached events
214 for event in self._events:
215 if (event['event'] == name) and event_match(event, match):
216 self._events.remove(event)
217 return event
219 # Poll for new events
220 while True:
221 event = self._qmp.pull_event(wait=timeout)
222 if (event['event'] == name) and event_match(event, match):
223 return event
224 self._events.append(event)
226 return None
228 def get_log(self):
229 return self._iolog