1 # QEMU Monitor Protocol Python class
3 # Copyright (C) 2009, 2010 Red Hat Inc.
6 # Luiz Capitulino <lcapitulino@redhat.com>
8 # This work is licensed under the terms of the GNU GPL, version 2. See
9 # the COPYING file in the top-level directory.
15 class QMPError(Exception):
18 class QMPConnectError(QMPError
):
21 class QMPCapabilitiesError(QMPError
):
24 class QEMUMonitorProtocol
:
25 def __init__(self
, address
):
27 Create a QEMUMonitorProtocol class.
29 @param address: QEMU address, can be either a unix socket path (string)
30 or a tuple in the form ( address, port ) for a TCP
32 @note No connection is established, this is done by the connect() method
35 self
.__address
= address
36 self
.__sock
= self
.__get
_sock
()
37 self
.__sockfile
= self
.__sock
.makefile()
40 if isinstance(self
.__address
, tuple):
41 family
= socket
.AF_INET
43 family
= socket
.AF_UNIX
44 return socket
.socket(family
, socket
.SOCK_STREAM
)
46 def __json_read(self
):
48 data
= self
.__sockfile
.readline()
51 resp
= json
.loads(data
)
53 self
.__events
.append(resp
)
61 Connect to the QMP Monitor and perform capabilities negotiation.
63 @return QMP greeting dict
64 @raise socket.error on socket connection errors
65 @raise QMPConnectError if the greeting is not received
66 @raise QMPCapabilitiesError if fails to negotiate capabilities
68 self
.__sock
.connect(self
.__address
)
69 greeting
= self
.__json
_read
()
70 if greeting
is None or not greeting
.has_key('QMP'):
72 # Greeting seems ok, negotiate capabilities
73 resp
= self
.cmd('qmp_capabilities')
76 raise QMPCapabilitiesError
78 def cmd_obj(self
, qmp_cmd
):
80 Send a QMP command to the QMP Monitor.
82 @param qmp_cmd: QMP command to be sent as a Python dict
83 @return QMP response as a Python dict or None if the connection has
87 self
.__sock
.sendall(json
.dumps(qmp_cmd
))
88 except socket
.error
, err
:
89 if err
[0] == errno
.EPIPE
:
91 raise socket
.error(err
)
92 return self
.__json
_read
()
94 def cmd(self
, name
, args
=None, id=None):
96 Build a QMP command and send it to the QMP Monitor.
98 @param name: command name (string)
99 @param args: command arguments (dict)
100 @param id: command id (dict, list, string or int)
102 qmp_cmd
= { 'execute': name
}
104 qmp_cmd
['arguments'] = args
107 return self
.cmd_obj(qmp_cmd
)
109 def get_events(self
):
111 Get a list of available QMP events.
113 self
.__sock
.setblocking(0)
116 except socket
.error
, err
:
117 if err
[0] == errno
.EAGAIN
:
120 self
.__sock
.setblocking(1)
123 def clear_events(self
):
125 Clear current list of pending events.
131 self
.__sockfile
.close()