forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqemu_monitor.py
1794 lines (1423 loc) · 56 KB
/
qemu_monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Interfaces to the QEMU monitor.
@copyright: 2008-2010 Red Hat Inc.
"""
import socket, time, threading, logging, select, re, os
import utils_misc, passfd_setup
from autotest.client.shared import utils
try:
import json
except ImportError:
logging.warning("Could not import json module. "
"QMP monitor functionality disabled.")
class MonitorError(Exception):
pass
class MonitorConnectError(MonitorError):
def __init__(self, monitor_name):
MonitorError.__init__(self)
self.monitor_name = monitor_name
def __str__(self):
return "Could not connect to monitor '%s'" % self.monitor_name
class MonitorSocketError(MonitorError):
def __init__(self, msg, e):
Exception.__init__(self, msg, e)
self.msg = msg
self.e = e
def __str__(self):
return "%s (%s)" % (self.msg, self.e)
class MonitorLockError(MonitorError):
pass
class MonitorProtocolError(MonitorError):
pass
class MonitorNotSupportedError(MonitorError):
pass
class MonitorNotSupportedCmdError(MonitorNotSupportedError):
def __init__(self, monitor, cmd):
MonitorError.__init__(self)
self.monitor = monitor
self.cmd = cmd
def __str__(self):
return ("Not supported cmd '%s' in monitor '%s'" %
(self.cmd, self.monitor))
class QMPCmdError(MonitorError):
def __init__(self, cmd, qmp_args, data):
MonitorError.__init__(self, cmd, qmp_args, data)
self.cmd = cmd
self.qmp_args = qmp_args
self.data = data
def __str__(self):
return ("QMP command %r failed (arguments: %r, "
"error message: %r)" % (self.cmd, self.qmp_args, self.data))
def get_monitor_filename(vm, monitor_name):
"""
Return the filename corresponding to a given monitor name.
@param vm: The VM object which has the monitor.
@param monitor_name: The monitor name.
@return: The string of socket file name for qemu monitor.
"""
return "/tmp/monitor-%s-%s" % (monitor_name, vm.instance)
def get_monitor_filenames(vm):
"""
Return a list of all monitor filenames (as specified in the VM's
params).
@param vm: The VM object which has the monitors.
"""
return [get_monitor_filename(vm, m) for m in vm.params.objects("monitors")]
def create_monitor(vm, monitor_name, monitor_params):
"""
Create monitor object and connect to the monitor socket.
@param vm: The VM object which has the monitor.
@param monitor_name: The name of this monitor object.
@param monitor_params: The dict for creating this monitor object.
"""
monitor_creator = HumanMonitor
if monitor_params.get("monitor_type") == "qmp":
monitor_creator = QMPMonitor
if not utils_misc.qemu_has_option("qmp", vm.qemu_binary):
# Add a "human" monitor on non-qmp version of qemu.
logging.warn("QMP monitor is unsupported by this version of qemu,"
" creating human monitor instead.")
monitor_creator = HumanMonitor
monitor_filename = get_monitor_filename(vm, monitor_name)
monitor = monitor_creator(vm, monitor_name, monitor_filename)
monitor.verify_responsive()
return monitor
def wait_for_create_monitor(vm, monitor_name, monitor_params, timeout):
"""
Wait for the progress of creating monitor object. This function will
retry to create the Monitor object until timeout.
@param vm: The VM object which has the monitor.
@param monitor_name: The name of this monitor object.
@param monitor_params: The dict for creating this monitor object.
@param timeout: Time to wait for creating this monitor object.
"""
# Wait for monitor connection to succeed
end_time = time.time() + timeout
while time.time() < end_time:
try:
return create_monitor(vm, monitor_name, monitor_params)
except MonitorError, e:
logging.warn(e)
time.sleep(1)
else:
raise MonitorConnectError(monitor_name)
class Monitor:
"""
Common code for monitor classes.
"""
ACQUIRE_LOCK_TIMEOUT = 20
DATA_AVAILABLE_TIMEOUT = 0
CONNECT_TIMEOUT = 30
def __init__(self, vm, name, filename):
"""
Initialize the instance.
@param vm: The VM which this monitor belongs to.
@param name: Monitor identifier (a string)
@param filename: Monitor socket filename
@raise MonitorConnectError: Raised if the connection fails
"""
self.vm = vm
self.name = name
self.filename = filename
self._lock = threading.RLock()
self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._socket.settimeout(self.CONNECT_TIMEOUT)
self._passfd = None
self._supported_cmds = []
self.debug_log = False
self.log_file = os.path.basename(self.filename + ".log")
try:
self._socket.connect(filename)
except socket.error, details:
raise MonitorConnectError("Could not connect to monitor socket: %s"
% details)
def __del__(self):
# Automatically close the connection when the instance is garbage
# collected
self._close_sock()
utils_misc.close_log_file(self.log_file)
# The following two functions are defined to make sure the state is set
# exclusively by the constructor call as specified in __getinitargs__().
def __getstate__(self):
pass
def __setstate__(self, state):
pass
def __getinitargs__(self):
# Save some information when pickling -- will be passed to the
# constructor upon unpickling
return self.vm, self.name, self.filename, True
def _close_sock(self):
try:
self._socket.shutdown(socket.SHUT_RDWR)
except socket.error:
pass
self._socket.close()
def _acquire_lock(self, timeout=ACQUIRE_LOCK_TIMEOUT):
end_time = time.time() + timeout
while time.time() < end_time:
if self._lock.acquire(False):
return True
time.sleep(0.05)
return False
def _data_available(self, timeout=DATA_AVAILABLE_TIMEOUT):
timeout = max(0, timeout)
try:
return bool(select.select([self._socket], [], [], timeout)[0])
except socket.error, e:
raise MonitorSocketError("Verifying data on monitor socket", e)
def _recvall(self):
s = ""
while self._data_available():
try:
data = self._socket.recv(1024)
except socket.error, e:
raise MonitorSocketError("Could not receive data from monitor",
e)
if not data:
break
s += data
return s
def _has_command(self, cmd):
"""
Check wheter kvm monitor support 'cmd'.
@param cmd: command string which will be checked.
@return: True if cmd is supported, False if not supported.
"""
if cmd and cmd in self._supported_cmds:
return True
return False
def _log_command(self, cmd, debug=True, extra_str=""):
"""
Print log message beening sent.
@param cmd: Command string.
@param debug: Whether to print the commands.
@param extra_str: Extra string would be printed in log.
"""
if self.debug_log or debug:
logging.debug("(monitor %s) Sending command '%s' %s",
self.name, cmd, extra_str)
def _log_lines(self, log_str):
"""
Record monitor cmd/output in log file.
"""
try:
for l in log_str.splitlines():
utils_misc.log_line(self.log_file, l)
except Exception:
pass
def is_responsive(self):
"""
Return True iff the monitor is responsive.
"""
try:
self.verify_responsive()
return True
except MonitorError:
return False
def verify_supported_cmd(self, cmd):
"""
Verify whether cmd is supported by monitor. If not, raise a
MonitorNotSupportedCmdError Exception.
@param cmd: The cmd string need to verify.
"""
if not self._has_command(cmd):
raise MonitorNotSupportedCmdError(self.name, cmd)
# Methods that may be implemented by subclasses:
def human_monitor_cmd(self, cmd="", timeout=None,
debug=True, fd=None):
"""
Send HMP command
This method allows code to send HMP commands without the need to check
if ther monitor is QMPMonitor or HumanMonitor.
@param cmd: human monitor command.
@param timeout: Time duration to wait for response
@param debug: Whether to print the commands being sent and responses
@param fd: file object or file descriptor to pass
@return: The response to the command
"""
raise NotImplementedError
# Methods that should work on both classes, as long as human_monitor_cmd()
# works:
re_numa_nodes = re.compile(r"^([0-9]+) nodes$", re.M)
re_numa_node_info = re.compile(r"^node ([0-9]+) (cpus|size): (.*)$", re.M)
@classmethod
def parse_info_numa(cls, r):
"""
Parse 'info numa' output
See info_numa() for information about the return value.
"""
nodes = cls.re_numa_nodes.search(r)
if nodes is None:
raise Exception("Couldn't get number of nodes from 'info numa' output")
nodes = int(nodes.group(1))
data = [[0, set()] for i in range(nodes)]
for nodenr,field,value in cls.re_numa_node_info.findall(r):
nodenr = int(nodenr)
if nodenr > nodes:
raise Exception("Invalid node number on 'info numa' output: %d", nodenr)
if field == 'size':
if not value.endswith(' MB'):
raise Exception("Unexpected size value: %s", value)
megabytes = int(value[:-3])
data[nodenr][0] = megabytes
elif field == 'cpus':
cpus = set([int(v) for v in value.split()])
data[nodenr][1] = cpus
data = [tuple(i) for i in data]
return data
def info_numa(self):
"""
Run 'info numa' command and parse returned information
@return: An array of (ram, cpus) tuples, where ram is the RAM size in
MB and cpus is a set of CPU numbers
"""
r = self.human_monitor_cmd("info numa")
return self.parse_info_numa(r)
def close(self):
"""
Close the connection to the monitor and its log file.
"""
self._close_sock()
utils_misc.close_log_file(self.log_file)
class HumanMonitor(Monitor):
"""
Wraps "human monitor" commands.
"""
PROMPT_TIMEOUT = 60
CMD_TIMEOUT = 60
def __init__(self, vm, name, filename, suppress_exceptions=False):
"""
Connect to the monitor socket and find the (qemu) prompt.
@param vm: The VM which this monitor belongs to.
@param name: Monitor identifier (a string)
@param filename: Monitor socket filename
@raise MonitorConnectError: Raised if the connection fails and
suppress_exceptions is False
@raise MonitorProtocolError: Raised if the initial (qemu) prompt isn't
found and suppress_exceptions is False
@note: Other exceptions may be raised. See cmd()'s
docstring.
"""
try:
Monitor.__init__(self, vm, name, filename)
self.protocol = "human"
# Find the initial (qemu) prompt
s, o = self._read_up_to_qemu_prompt()
if not s:
raise MonitorProtocolError("Could not find (qemu) prompt "
"after connecting to monitor. "
"Output so far: %r" % o)
self._get_supported_cmds()
except MonitorError, e:
self._close_sock()
if suppress_exceptions:
logging.warn(e)
else:
raise
# Private methods
def _read_up_to_qemu_prompt(self, timeout=PROMPT_TIMEOUT):
s = ""
end_time = time.time() + timeout
while self._data_available(end_time - time.time()):
data = self._recvall()
if not data:
break
s += data
try:
lines = s.splitlines()
if lines[-1].split()[-1] == "(qemu)":
self._log_lines("\n".join(lines[1:]))
return True, "\n".join(lines[:-1])
except IndexError:
continue
if s:
try:
self._log_lines(s.splitlines()[1:])
except IndexError:
pass
return False, "\n".join(s.splitlines())
def _send(self, cmd):
"""
Send a command without waiting for output.
@param cmd: Command to send
@raise MonitorLockError: Raised if the lock cannot be acquired
@raise MonitorSocketError: Raised if a socket error occurs
"""
if not self._acquire_lock():
raise MonitorLockError("Could not acquire exclusive lock to send "
"monitor command '%s'" % cmd)
try:
try:
self._socket.sendall(cmd + "\n")
self._log_lines(cmd)
except socket.error, e:
raise MonitorSocketError("Could not send monitor command %r" %
cmd, e)
finally:
self._lock.release()
def _get_supported_cmds(self):
"""
Get supported human monitor cmds list.
"""
cmds = self.cmd("help", debug=False)
if cmds:
cmd_list = re.findall("^(.*?) ", cmds, re.M)
self._supported_cmds = [c for c in cmd_list if c]
if not self._supported_cmds:
logging.warn("Could not get supported monitor cmds list")
def _log_response(self, cmd, resp, debug=True):
"""
Print log message for monitor cmd's response.
@param cmd: Command string.
@param resp: Response from monitor command.
@param debug: Whether to print the commands.
"""
if self.debug_log or debug:
logging.debug("(monitor %s) Response to '%s'", self.name, cmd)
for l in resp.splitlines():
logging.debug("(monitor %s) %s", self.name, l)
# Public methods
def cmd(self, cmd, timeout=CMD_TIMEOUT, debug=True, fd=None):
"""
Send command to the monitor.
@param cmd: Command to send to the monitor
@param timeout: Time duration to wait for the (qemu) prompt to return
@param debug: Whether to print the commands being sent and responses
@return: Output received from the monitor
@raise MonitorLockError: Raised if the lock cannot be acquired
@raise MonitorSocketError: Raised if a socket error occurs
@raise MonitorProtocolError: Raised if the (qemu) prompt cannot be
found after sending the command
"""
self._log_command(cmd, debug)
if not self._acquire_lock():
raise MonitorLockError("Could not acquire exclusive lock to send "
"monitor command '%s'" % cmd)
try:
# Read any data that might be available
self._recvall()
if fd is not None:
if self._passfd is None:
self._passfd = passfd_setup.import_passfd()
# If command includes a file descriptor, use passfd module
self._passfd.sendfd(self._socket, fd, "%s\n" % cmd)
else:
# Send command
if debug:
logging.debug("Send command: %s" % cmd)
self._send(cmd)
# Read output
s, o = self._read_up_to_qemu_prompt(timeout)
# Remove command echo from output
o = "\n".join(o.splitlines()[1:])
# Report success/failure
if s:
if o:
self._log_response(cmd, o, debug)
return o
else:
msg = ("Could not find (qemu) prompt after command '%s'. "
"Output so far: %r" % (cmd, o))
raise MonitorProtocolError(msg)
finally:
self._lock.release()
def human_monitor_cmd(self, cmd="", timeout=CMD_TIMEOUT,
debug=True, fd=None):
"""
Send human monitor command directly
@param cmd: human monitor command.
@param timeout: Time duration to wait for response
@param debug: Whether to print the commands being sent and responses
@param fd: file object or file descriptor to pass
@return: The response to the command
"""
return self.cmd(cmd, timeout, debug, fd)
def verify_responsive(self):
"""
Make sure the monitor is responsive by sending a command.
"""
self.cmd("info status", debug=False)
def get_status(self):
return self.cmd("info status", debug=False)
def verify_status(self, status):
"""
Verify VM status
@param status: Optional VM status, 'running' or 'paused'
@return: return True if VM status is same as we expected
"""
return (status in self.get_status())
# Command wrappers
# Notes:
# - All of the following commands raise exceptions in a similar manner to
# cmd().
# - A command wrapper should use self._has_command if it requires
# information about the monitor's capabilities.
def send_args_cmd(self, cmdlines, timeout=CMD_TIMEOUT, convert=True):
"""
Send a command with/without parameters and return its output.
Have same effect with cmd function.
Implemented under the same name for both the human and QMP monitors.
Command with parameters should in following format e.g.:
'memsave val=0 size=10240 filename=memsave'
Command without parameter: 'sendkey ctrl-alt-f1'
@param cmdlines: Commands send to qemu which is seperated by ";". For
command with parameters command should send in a string
with this format:
$command $arg_name=$arg_value $arg_name=$arg_value
@param timeout: Time duration to wait for (qemu) prompt after command
@param convert: If command need to convert. For commands such as:
$command $arg_value
@return: The output of the command
@raise MonitorLockError: Raised if the lock cannot be acquired
@raise MonitorSendError: Raised if the command cannot be sent
@raise MonitorProtocolError: Raised if the (qemu) prompt cannot be
found after sending the command
"""
cmd_output = []
for cmdline in cmdlines.split(";"):
if not convert:
return self.cmd(cmdline, timeout)
if "=" in cmdline:
command = cmdline.split()[0]
cmdargs = " ".join(cmdline.split()[1:]).split(",")
for arg in cmdargs:
command += " " + arg.split("=")[-1]
else:
command = cmdline
cmd_output.append(self.cmd(command, timeout))
if len(cmd_output) == 1:
return cmd_output[0]
return cmd_output
def quit(self):
"""
Send "quit" without waiting for output.
"""
self._send("quit")
def info(self, what, debug=True):
"""
Request info about something and return the output.
@param debug: Whether to print the commands being sent and responses
"""
return self.cmd("info %s" % what, debug=debug)
def query(self, what):
"""
Alias for info.
"""
return self.info(what)
def screendump(self, filename, debug=True):
"""
Request a screendump.
@param filename: Location for the screendump
@return: The command's output
"""
return self.cmd(cmd="screendump %s" % filename, debug=debug)
def set_link(self, name, up):
"""
Set link up/down.
@param name: Link name
@param up: Bool value, True=set up this link, False=Set down this link
@return: The response to the command
"""
set_link_cmd = "set_link"
# set_link in RHEL5 host use "up|down" instead of "on|off" which is
# used in RHEL6 host and Fedora host. So here find out the string
# this monitor accept.
o = self.cmd("help %s" % set_link_cmd)
try:
on_str, off_str = re.findall("(\w+)\|(\w+)", o)[0]
except IndexError:
# take a default value if can't get on/off string from monitor.
on_str, off_str = "on", "off"
status = off_str
if up:
status = on_str
return self.cmd("%s %s %s" % (set_link_cmd, name, status))
def live_snapshot(self, device, snapshot_file, snapshot_format="qcow2"):
"""
Take a live disk snapshot.
@param device: device id of base image
@param snapshot_file: image file name of snapshot
@param snapshot_format: image format of snapshot
@return: The response to the command
"""
cmd = ("snapshot_blkdev %s %s %s" %
(device, snapshot_file, snapshot_format))
return self.cmd(cmd)
def block_stream(self, device, speed=None, base=None):
"""
Start block-stream job;
@param device: device ID
@param speed: int type, lmited speed(B/s)
@param base: base file
@return: The command's output
"""
cmd = "block_stream %s" % device
if speed is not None:
cmd = "%s %sB" % (cmd, speed)
if base:
cmd = "%s %s" % (cmd, base)
return self.cmd(cmd)
def set_block_job_speed(self, device, speed=0):
"""
Set limited speed for runnig job on the device
@param device: device ID
@param speed: int type, limited speed(B/s)
@return: The command's output
"""
cmd = "block-job-set-speed %s %sB" % (device, speed)
return self.cmd(cmd)
def cancel_block_job(self, device):
"""
Cancel running block stream/mirror job on the device
@param device: device ID
@return: The command's output
"""
return self.send_args_cmd("block-job-cancel %s" % device)
def query_block_job(self, device):
"""
Get block job status on the device
@param device: device ID
@return: dict about job info, return empty dict if no active job
"""
job = dict()
output = str(self.info("block-jobs"))
for line in output.split("\n"):
if "No" in re.match("\w+",output).group(0):
continue
if device in line:
if "Streaming" in re.match("\w+", output).group(0):
job["type"] = "stream"
else:
job["type"] = "mirror"
job["device"] = device
job["offset"] = int(re.findall("\d+", output)[-3])
job["len"] = int(re.findall("\d+", output)[-2])
job["speed"] = int(re.findall("\d+", output)[-1])
break
return job
def get_backingfile(self, device):
"""
Return "backing_file" path of the device
@param device: device ID
@return: string, backing_file path
"""
backing_file = None
block_info = self.query("block")
try:
pattern = "%s:.*backing_file=([^\s]*)" % device
backing_file = re.search(pattern, block_info, re.M).group(1)
except Exception:
pass
return backing_file
def block_mirror(self, device, target, speed, sync, format, mode,
cmd="__com.redhat_drive-mirror"):
"""
Start mirror type block device copy job
@param device: device ID
@param target: target image
@param speed: limited speed, unit is B/s
@param sync: full copy to target image(unsupport in human monitor)
@param mode: target image create mode, 'absolute-paths' or 'existing'
@param format: target image format
@param cmd: block mirror command
@return: The command's output
"""
self.verify_supported_cmd(cmd)
args = " ".join([device, target, format])
if cmd.startswith("__com.redhat"):
if mode == "existing":
args = "-n %s" % args
if sync == "full":
args ="-f %s" % args
else:
if speed:
args = "%s %sB" % (args, speed)
cmd = "%s %s" % (cmd, args)
return self.cmd(cmd)
def block_reopen(self, device, new_image_file, image_format,
cmd="__com.redhat_drive-reopen"):
"""
Reopen new target image
@param device: device ID
@param new_image_file: new image file name
@param image_format: new image file format
@param cmd: image reopen command
@return: The command's output
"""
self.verify_supported_cmd(cmd)
args = device
if cmd.startswith("__com.redhat"):
args += " ".join([new_image_file, image_format])
cmd = "%s %s" % (cmd, args)
return self.cmd(cmd)
def migrate(self, uri, full_copy=False, incremental_copy=False, wait=False):
"""
Migrate.
@param uri: destination URI
@param full_copy: If true, migrate with full disk copy
@param incremental_copy: If true, migrate with incremental disk copy
@param wait: If true, wait for completion
@return: The command's output
"""
cmd = "migrate"
if not wait:
cmd += " -d"
if full_copy:
cmd += " -b"
if incremental_copy:
cmd += " -i"
cmd += " %s" % uri
return self.cmd(cmd)
def migrate_set_speed(self, value):
"""
Set maximum speed (in bytes/sec) for migrations.
@param value: Speed in bytes/sec
@return: The command's output
"""
return self.cmd("migrate_set_speed %s" % value)
def migrate_set_downtime(self, value):
"""
Set maximum tolerated downtime (in seconds) for migration.
@param: value: maximum downtime (in seconds)
@return: The command's output
"""
return self.cmd("migrate_set_downtime %s" % value)
def sendkey(self, keystr, hold_time=1):
"""
Send key combination to VM.
@param keystr: Key combination string
@param hold_time: Hold time in ms (should normally stay 1 ms)
@return: The command's output
"""
return self.cmd("sendkey %s %s" % (keystr, hold_time))
def mouse_move(self, dx, dy):
"""
Move mouse.
@param dx: X amount
@param dy: Y amount
@return: The command's output
"""
return self.cmd("mouse_move %s %s" % (dx, dy))
def mouse_button(self, state):
"""
Set mouse button state.
@param state: Button state (1=L, 2=M, 4=R)
@return: The command's output
"""
return self.cmd("mouse_button %s" % state)
def getfd(self, fd, name):
"""
Receives a file descriptor
@param fd: File descriptor to pass to QEMU
@param name: File descriptor name (internal to QEMU)
@return: The command's output
"""
return self.cmd("getfd %s" % name, fd=fd)
def system_wakeup(self):
"""
Wakeup suspended guest.
"""
cmd = "system_wakeup"
self.verify_supported_cmd(cmd)
return self.cmd(cmd)
def nmi(self):
"""
Inject a NMI on all guest's CPUs.
"""
return self.cmd("nmi")
def block_resize(self, device, size):
"""
Resize the block device size
@param device: Block device name
@param size: Block device size need to set to. To keep the same with
qmp monitor will use bytes as unit for the block size
@return: Command output
"""
size = int(size) / 1024 / 1024
cmd = "block_resize device=%s,size=%s" % (device, size)
return self.send_args_cmd(cmd)
class QMPMonitor(Monitor):
"""
Wraps QMP monitor commands.
"""
READ_OBJECTS_TIMEOUT = 5
CMD_TIMEOUT = 60
RESPONSE_TIMEOUT = 60
PROMPT_TIMEOUT = 60
def __init__(self, vm, name, filename, suppress_exceptions=False):
"""
Connect to the monitor socket, read the greeting message and issue the
qmp_capabilities command. Also make sure the json module is available.
@param vm: The VM which this monitor belongs to.
@param name: Monitor identifier (a string)
@param filename: Monitor socket filename
@raise MonitorConnectError: Raised if the connection fails and
suppress_exceptions is False
@raise MonitorProtocolError: Raised if the no QMP greeting message is
received and suppress_exceptions is False
@raise MonitorNotSupportedError: Raised if json isn't available and
suppress_exceptions is False
@note: Other exceptions may be raised if the qmp_capabilities command
fails. See cmd()'s docstring.
"""
try:
Monitor.__init__(self, vm, name, filename)
self.protocol = "qmp"
self._greeting = None
self._events = []
self._supported_hmp_cmds = []
# Make sure json is available
try:
json
except NameError:
raise MonitorNotSupportedError("QMP requires the json module "
"(Python 2.6 and up)")
# Read greeting message
end_time = time.time() + 20
while time.time() < end_time:
for obj in self._read_objects():
if "QMP" in obj:
self._greeting = obj
break
if self._greeting:
break
time.sleep(0.1)