forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqemu_vm.py
3644 lines (3147 loc) · 149 KB
/
qemu_vm.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
"""
Utility classes and functions to handle Virtual Machine creation using qemu.
@copyright: 2008-2009 Red Hat Inc.
"""
import time, os, logging, fcntl, re, commands
from autotest.client.shared import error
from autotest.client import utils
import utils_misc, virt_vm, test_setup, storage, qemu_monitor, aexpect
import qemu_virtio_port, remote, data_dir, utils_net, qemu_devices
class QemuSegFaultError(virt_vm.VMError):
def __init__(self, crash_message):
virt_vm.VMError.__init__(self, crash_message)
self.crash_message = crash_message
def __str__(self):
return ("Qemu crashed: %s" % self.crash_message)
class VMMigrateProtoUnsupportedError(virt_vm.VMMigrateProtoUnknownError):
"""
When QEMU tells us it doesn't know about a given migration protocol.
This usually happens when we're testing older QEMU. It makes sense to
skip the test in this situation.
"""
def __init__(self, protocol, output):
self.protocol = protocol
self.output = output
def __str__(self):
return ("QEMU reports it doesn't know migration protocol '%s'. "
"QEMU output: %s" % self.protocol, self.output)
class KVMInternalError(virt_vm.VMError):
pass
class ImageUnbootableError(virt_vm.VMError):
def __init__(self, name):
virt_vm.VMError.__init__(self, name)
self.name = name
def __str__(self):
return ("VM '%s' can't bootup from image,"
" check your boot disk image file." % self.name)
class VM(virt_vm.BaseVM):
"""
This class handles all basic VM operations.
"""
MIGRATION_PROTOS = ['rdma', 'x-rdma', 'tcp', 'unix', 'exec', 'fd']
# By default we inherit all timeouts from the base VM class except...
CLOSE_SESSION_TIMEOUT = 30
# Because we've seen qemu taking longer than 5 seconds to initialize
# itself completely, including creating the monitor sockets files
# which are used on create(), this timeout is considerably larger
# than the one on the base vm class
CREATE_TIMEOUT = 20
def __init__(self, name, params, root_dir, address_cache, state=None):
"""
Initialize the object and set a few attributes.
@param name: The name of the object
@param params: A dict containing VM params
(see method make_qemu_command for a full description)
@param root_dir: Base directory for relative filenames
@param address_cache: A dict that maps MAC addresses to IP addresses
@param state: If provided, use this as self.__dict__
"""
if state:
self.__dict__ = state
else:
self.process = None
self.serial_console = None
self.redirs = {}
self.spice_options = {}
self.vnc_port = 5900
self.monitors = []
self.virtio_ports = [] # virtio_console / virtio_serialport
self.pci_assignable = None
self.uuid = None
self.vcpu_threads = []
self.vhost_threads = []
self.devices = None
self.name = name
self.params = params
self.root_dir = root_dir
self.address_cache = address_cache
self.index_in_use = {}
# This usb_dev_dict member stores usb controller and device info,
# It's dict, each key is an id of usb controller,
# and key's value is a list, contains usb devices' ids which
# attach to this controller.
# A filled usb_dev_dict may look like:
# { "usb1" : ["stg1", "stg2", "stg3", "stg4", "stg5", "stg6"],
# "usb2" : ["stg7", "stg8"],
# ...
# }
# This structure can used in usb hotplug/unplug test.
self.usb_dev_dict = {}
self.logs = {}
self.logsessions = {}
self.driver_type = 'qemu'
self.params['driver_type_' + self.name] = self.driver_type
# virtnet init depends on vm_type/driver_type being set w/in params
super(VM, self).__init__(name, params)
# un-overwrite instance attribute, virtnet db lookups depend on this
if state:
self.instance = state['instance']
self.qemu_command = ''
self.start_time = 0.0
def verify_alive(self):
"""
Make sure the VM is alive and that the main monitor is responsive.
@raise VMDeadError: If the VM is dead
@raise: Various monitor exceptions if the monitor is unresponsive
"""
self.verify_disk_image_bootable()
self.verify_userspace_crash()
self.verify_kernel_crash()
self.verify_illegal_instruction()
self.verify_kvm_internal_error()
try:
virt_vm.BaseVM.verify_alive(self)
if self.monitor:
self.monitor.verify_responsive()
except virt_vm.VMDeadError:
raise virt_vm.VMDeadError(self.process.get_status(),
self.process.get_output())
def is_alive(self):
"""
Return True if the VM is alive and its monitor is responsive.
"""
return not self.is_dead() and (not self.monitor or
self.monitor.is_responsive())
def is_dead(self):
"""
Return True if the qemu process is dead.
"""
return not self.process or not self.process.is_alive()
def is_paused(self):
"""
Return True if the qemu process is paused ('stop'ed)
"""
if self.is_dead():
return False
try:
self.verify_status("paused")
return True
except virt_vm.VMStatusError:
return False
def verify_status(self, status):
"""
Check VM status
@param status: Optional VM status, 'running' or 'paused'
@raise VMStatusError: If the VM status is not same as parameter
"""
if not self.monitor.verify_status(status):
raise virt_vm.VMStatusError('Unexpected VM status: "%s"' %
self.monitor.get_status())
def verify_userspace_crash(self):
"""
Verify if the userspace component (qemu) crashed.
"""
if "(core dumped)" in self.process.get_output():
for line in self.process.get_output().splitlines():
if "(core dumped)" in line:
raise QemuSegFaultError(line)
def verify_kvm_internal_error(self):
"""
Verify KVM internal error.
"""
if "KVM internal error." in self.process.get_output():
out = self.process.get_output()
out = out[out.find("KVM internal error."):]
raise KVMInternalError(out)
def verify_disk_image_bootable(self):
if self.params.get("image_verify_bootable") == "yes":
pattern = self.params.get("image_unbootable_pattern")
if not pattern:
raise virt_vm.VMConfigMissingError(self.name,
"image_unbootable_pattern")
try:
seabios_log = self.logsessions['seabios'].get_output()
if re.search(pattern, seabios_log, re.S):
logging.error("Can't boot guest from image.")
# Set 'shutdown_command' to None to force autotest
# shuts down guest with monitor.
self.params["shutdown_command"] = None
raise ImageUnbootableError(self.name)
except KeyError:
pass
def __usb_get_controllers(self, controller_type):
ctl_list = []
for usb in self.params.objects("usbs"):
usb_params = self.params.object_params(usb)
usb_type = usb_params.get("usb_type")
if usb_type.find(controller_type) != -1:
ctl_list.append(usb)
if not ctl_list:
raise virt_vm.VMUSBControllerMissingError(self.name,
controller_type)
return ctl_list
def __usb_verify_controller(self, controller):
if controller not in self.params.objects("usbs"):
raise virt_vm.VMUSBControllerError("No USB controller called"
" '%s'" % controller)
def __usb_get_dev_in_port(self, controller, port, hub_port=None):
usb_dev_list = self.usb_dev_dict.get(controller)
if hub_port is None:
try:
return usb_dev_list[port]
except IndexError:
raise virt_vm.VMUSBControllerError("USB controller '%s'"
" doesn't provide port '%d'" % (controller, port))
else:
try:
return usb_dev_list[port][hub_port]
except IndexError:
raise virt_vm.VMUSBControllerError("usb hub on port '%d' of"
" controller '%s' doesn't provide"
" port '%d'" % (port, controller, hub_port))
def usb_assign_dev_to_port(self, usb_dev, controller, port, is_hub=False):
"""
Assign an USB device to a port.
@param usb_dev: The usb device which is needed to be assigned a port.
@param controller: the usb controller which this usb device will be
attached to.
@param port: The usb port this usb device will be attached to.
@return: The usb port number.
"""
self.__usb_verify_controller(controller)
hub_port = None
if "." in str(port):
# We get a device on usb hub here.
port, hub_port = port.split(".")
# Usb port starts from 1 besides python list starting from 0.
# minus 1 in port to make them equal.
hub_port = int(hub_port) - 1
port = int(port) - 1
dev = self.__usb_get_dev_in_port(controller, port, hub_port)
if dev is not None:
raise virt_vm.VMUSBPortInUseError(self.name, controller, port)
usb_dev_list = self.usb_dev_dict.get(controller)
if is_hub:
if not hub_port:
# usb hub has extra 8 ports.
usb_dev_list[port] = [None] * 8
else:
usb_dev_list[port][hub_port] = [None] * 8
else:
if not hub_port:
usb_dev_list[port] = usb_dev
else:
usb_dev_list[port][hub_port] = usb_dev
def usb_get_free_port(self, usb_dev, controller_type, is_hub=False):
"""
Find an available USB port.
@param usb_dev: The usb device which is needed to be assigned a port.
@param controller_type: Usb controller type which this usb device needs.
@return: A tuple with a free usb_bus id and port number.
"""
usb_bus = None
usb_port = None
for usb in self.__usb_get_controllers(controller_type):
usb_params = self.params.object_params(usb)
max_port_num = int(usb_params.get("usb_max_port", 6))
usb_bus = "%s.0" % usb
# Find a free port on this controller.
for port_num in range(max_port_num):
# Usb port starts from 1, so add 1 directly here.
port_num += 1
try:
self.usb_assign_dev_to_port(usb_dev, usb, port_num, is_hub)
usb_port = port_num
break
except virt_vm.VMUSBPortInUseError:
continue
# Exit for-loop if we find a free port.
if usb_port:
break
if not usb_port:
raise virt_vm.VMUSBControllerPortFullError(self.name,
self.usb_dev_dict)
return (usb_bus, str(usb_port))
def clone(self, name=None, params=None, root_dir=None, address_cache=None,
copy_state=False):
"""
Return a clone of the VM object with optionally modified parameters.
The clone is initially not alive and needs to be started using create().
Any parameters not passed to this function are copied from the source
VM.
@param name: Optional new VM name
@param params: Optional new VM creation parameters
@param root_dir: Optional new base directory for relative filenames
@param address_cache: A dict that maps MAC addresses to IP addresses
@param copy_state: If True, copy the original VM's state to the clone.
Mainly useful for make_qemu_command().
"""
if name is None:
name = self.name
if params is None:
params = self.params.copy()
if root_dir is None:
root_dir = self.root_dir
if address_cache is None:
address_cache = self.address_cache
if copy_state:
state = self.__dict__.copy()
else:
state = None
return VM(name, params, root_dir, address_cache, state)
def get_serial_console_filename(self, name=None):
"""
Return the serial console filename.
@param name: The serial port name.
"""
if name:
return "/tmp/serial-%s-%s" % (name, self.instance)
return "/tmp/serial-%s" % self.instance
def get_serial_console_filenames(self):
"""
Return a list of all serial console filenames
(as specified in the VM's params).
"""
return [self.get_serial_console_filename(_) for _ in
self.params.objects("isa_serials")]
def make_create_command(self, name=None, params=None, root_dir=None):
"""
Generate a qemu command line. All parameters are optional. If a
parameter is not supplied, the corresponding value stored in the
class attributes is used.
@param name: The name of the object
@param params: A dict containing VM params
@param root_dir: Base directory for relative filenames
@note: The params dict should contain:
mem -- memory size in MBs
cdrom -- ISO filename to use with the qemu -cdrom parameter
extra_params -- a string to append to the qemu command
shell_port -- port of the remote shell daemon on the guest
(SSH, Telnet or the home-made Remote Shell Server)
shell_client -- client program to use for connecting to the
remote shell daemon on the guest (ssh, telnet or nc)
x11_display -- if specified, the DISPLAY environment variable
will be be set to this value for the qemu process (useful for
SDL rendering)
images -- a list of image object names, separated by spaces
nics -- a list of NIC object names, separated by spaces
For each image in images:
drive_format -- string to pass as 'if' parameter for this
image (e.g. ide, scsi)
image_snapshot -- if yes, pass 'snapshot=on' to qemu for
this image
image_boot -- if yes, pass 'boot=on' to qemu for this image
In addition, all parameters required by get_image_filename.
For each NIC in nics:
nic_model -- string to pass as 'model' parameter for this
NIC (e.g. e1000)
"""
# Helper function for command line option wrappers
def _add_option(option, value, option_type=None, first=False):
"""
Add option to qemu parameters.
"""
if first:
fmt = " %s=%s"
else:
fmt = ",%s=%s"
if option_type is bool:
# Decode value for bool parameter (supports True, False, None)
if value in ['yes', 'on', True]:
return fmt % (option, "on")
elif value in ['no', 'off', False]:
return fmt % (option, "off")
elif value and isinstance(value, bool):
return fmt % (option, "on")
elif value and isinstance(value, str):
# "EMPTY_STRING" and "NULL_STRING" is used for testing illegal
# foramt of option.
# "EMPTY_STRING": set option as a empty string "".
# "NO_EQUAL_STRING": set option as a option string only,
# even without "=".
# (In most case, qemu-kvm should recognize it as "<null>")
if value == "NO_EQUAL_STRING":
return ",%s" % option
if value == "EMPTY_STRING":
value = '""'
return fmt % (option, str(value))
return ""
# Wrappers for all supported qemu command line parameters.
# This is meant to allow support for multiple qemu versions.
# Each of these functions receives the output of 'qemu -help'
# as a parameter, and should add the requested command line
# option accordingly.
def add_name(devices, name):
return " -name '%s'" % name
def add_human_monitor(devices, monitor_name, filename):
if not devices.has_option("chardev"):
return " -monitor unix:'%s',server,nowait" % filename
monitor_id = "hmp_id_%s" % monitor_name
cmd = " -chardev socket"
cmd += _add_option("id", monitor_id)
cmd += _add_option("path", filename)
cmd += _add_option("server", "NO_EQUAL_STRING")
cmd += _add_option("nowait", "NO_EQUAL_STRING")
cmd += " -mon chardev=%s" % monitor_id
cmd += _add_option("mode", "readline")
return cmd
def add_qmp_monitor(devices, monitor_name, filename):
if not devices.has_option("qmp"):
logging.warn("Fallback to human monitor since qmp is"
" unsupported")
return add_human_monitor(devices, monitor_name, filename)
if not devices.has_option("chardev"):
return " -qmp unix:'%s',server,nowait" % filename
monitor_id = "qmp_id_%s" % monitor_name
cmd = " -chardev socket"
cmd += _add_option("id", monitor_id)
cmd += _add_option("path", filename)
cmd += _add_option("server", "NO_EQUAL_STRING")
cmd += _add_option("nowait", "NO_EQUAL_STRING")
cmd += " -mon chardev=%s" % monitor_id
cmd += _add_option("mode", "control")
return cmd
def add_serial(devices, name, filename):
if not devices.has_option("chardev"):
return " -serial unix:'%s',server,nowait" % filename
serial_id = "serial_id_%s" % name
cmd = " -chardev socket"
cmd += _add_option("id", serial_id)
cmd += _add_option("path", filename)
cmd += _add_option("server", "NO_EQUAL_STRING")
cmd += _add_option("nowait", "NO_EQUAL_STRING")
cmd += " -device isa-serial"
cmd += _add_option("chardev", serial_id)
return cmd
def add_virtio_port(devices, name, bus, filename, porttype, chardev,
name_prefix=None, index=None, extra_params=""):
"""
Appends virtio_serialport or virtio_console device to cmdline.
@param help: qemu -h output
@param name: Name of the port
@param bus: Which virtio-serial-pci device use
@param filename: Path to chardev filename
@param porttype: Type of the port (*serialport, console)
@param chardev: Which chardev to use (*socket, spicevmc)
@param name_prefix: Custom name prefix (port index is appended)
@param index: Index of the current virtio_port
@param extra_params: Space sepparated chardev params
"""
cmd = ''
# host chardev
if chardev == "spicevmc": # SPICE
cmd += " -chardev spicevmc,id=dev%s,name=%s" % (name, name)
else: # SOCKET
cmd = (" -chardev socket,id=dev%s,path=%s,server,nowait"
% (name, filename))
# virtport device
if porttype in ("console", "virtio_console"):
cmd += " -device virtconsole"
else:
cmd += " -device virtserialport"
if name_prefix: # used by spiceagent (com.redhat.spice.*)
port_name = "%s%d" % (name_prefix, index)
else:
port_name = name
cmd += ",chardev=dev%s,name=%s,id=%s" % (name, port_name, name)
cmd += _add_option("bus", bus)
# Space sepparated chardev params
_params = ""
for parm in extra_params.split():
_params += ',' + parm
cmd += _params
return cmd
def add_log_seabios(devices):
if not devices.has_device("isa-debugcon"):
return ""
default_id = "seabioslog_id_%s" % self.instance
filename = "/tmp/seabios-%s" % self.instance
self.logs["seabios"] = filename
cmd = " -chardev socket"
cmd += _add_option("id", default_id)
cmd += _add_option("path", filename)
cmd += _add_option("server", "NO_EQUAL_STRING")
cmd += _add_option("nowait", "NO_EQUAL_STRING")
cmd += " -device isa-debugcon"
cmd += _add_option("chardev", default_id)
cmd += _add_option("iobase", "0x402")
return cmd
def add_log_anaconda(devices):
chardev_id = "anacondalog_chardev_%s" % self.instance
vioser_id = "anacondalog_vioser_%s" % self.instance
filename = "/tmp/anaconda-%s" % self.instance
self.logs["anaconda"] = filename
dev = qemu_devices.QCustomDevice('chardev')
dev.set_param('backend', 'socket')
dev.set_param('id', chardev_id)
dev.set_param("path", filename)
dev.set_param("server", 'NO_EQUAL_STRING')
dev.set_param("nowait", 'NO_EQUAL_STRING')
devices.insert(dev)
dev = QDevice('virtio-serial-pci', parent_bus={'type': 'pci'})
dev.set_param("id", vioser_id)
devices.insert(dev)
dev = QDevice('virtserialport')
dev.set_param("bus", "%s.0" % vioser_id)
dev.set_param("chardev", chardev_id)
dev.set_param("name", "org.fedoraproject.anaconda.log.0")
devices.insert(dev)
def add_mem(devices, mem):
return " -m %s" % mem
def add_smp(devices):
smp_str = " -smp %d" % self.cpuinfo.smp
smp_pattern = "smp n\[,maxcpus=cpus\].*"
if devices.has_option(smp_pattern):
smp_str += ",maxcpus=%d" % self.cpuinfo.maxcpus
smp_str += ",cores=%d" % self.cpuinfo.cores
smp_str += ",threads=%d" % self.cpuinfo.threads
smp_str += ",sockets=%d" % self.cpuinfo.sockets
return smp_str
def add_cdrom(devices, filename, index=None, fmt=None, bus=None,
port=None):
if devices.has_option("drive"):
name = None;
dev = "";
if fmt == "ahci":
name = "ahci%s" % index
dev += " -device ide-drive,bus=ahci.%s,drive=%s" % (index,
name)
fmt = "none"
index = None
if fmt in ['usb1', 'usb2', 'usb3']:
name = "%s.%s" % (fmt, index)
dev += " -device usb-storage"
dev += _add_option("bus", bus)
dev += _add_option("port", port)
dev += _add_option("drive", name)
fmt = "none"
index = None
if fmt is not None and fmt.startswith("scsi-"):
# handles scsi-{hd, cd, disk, block, generic} targets
name = "virtio-scsi-cd%s" % index
dev += (" -device %s,drive=%s" %
(fmt, name))
dev += _add_option("bus", "virtio_scsi_pci%d.0" % bus)
fmt = "none"
index = None
cmd = " -drive file='%s',media=cdrom" % filename
if index is not None:
cmd += ",index=%s" % index
if fmt:
cmd += ",if=%s" % fmt
if name:
cmd += ",id=%s" % name
return cmd + dev
else:
return " -cdrom '%s'" % filename
def add_drive(devices, filename, index=None, fmt=None, cache=None,
werror=None, rerror=None, serial=None, snapshot=None,
boot=None, blkdebug=None, bus=None, port=None,
bootindex=None, removable=None, min_io_size=None,
opt_io_size=None, physical_block_size=None,
logical_block_size=None, readonly=None, scsiid=None,
lun=None, imgfmt="raw", aio=None, media="disk",
ide_bus=None, ide_unit=None, vdisk=0, scsi_disk=None,
pci_addr=None, scsi=None, x_data_plane=None,
blk_extra_params=None):
dev_format = {"virtio" : "virtio-blk-pci",
"ide" : "ide-drive",
"usb2": "usb-storage"}
name = ""
if fmt == "ide":
name = "ide0-%s-%s" % (ide_bus, ide_unit)
ide_bus = "ide." + str(ide_bus)
elif fmt == "virtio":
if media == "disk":
vdisk += 1
blkdev_id = "virtio-disk%s" % vdisk
name = "virtio-disk%s" % vdisk
elif fmt == "usb2":
name = "usb2.%s" % (index or utils_misc.generate_random_id())
elif media == "cdrom":
readonly = True
if not devices.has_option("device"):
name = None
if name:
blkdev_id = "drive-%s" % name
else:
blkdev_id = None
if ",aio=" not in devices.get_help_text():
aio = None
dev = None
if fmt == "ahci":
tmp = "ahci%s" % (index or utils_misc.generate_random_id())
blkdev_id = tmp
dev = QDevice('ide-drive')
dev.set_param('bus', 'ahci.%s' % index)
dev.set_param('drive', blkdev_id)
dev.set_param("id", name)
fmt = "none"
index = None
elif fmt in ['usb1', 'usb2', 'usb3']:
tmp = index or utils_misc.generate_random_id()
blkdev_id = "%s.%s" % (fmt, tmp)
dev = QDevice('usb-storage')
dev.set_param("bus", bus)
dev.set_param("port", port)
dev.set_param("serial", serial)
dev.set_param("bootindex", bootindex, bool)
dev.set_param("removable", removable, bool)
dev.set_param("min_io_size", min_io_size)
dev.set_param("opt_io_size", opt_io_size)
dev.set_param("physical_block_size", physical_block_size)
dev.set_param("logical_block_size", logical_block_size)
dev.set_param("drive", blkdev_id)
dev.set_param("id", "usb-disk%s" % tmp)
fmt = "none"
index = None
elif fmt and fmt.startswith("scsi-"):
# handles scsi-{hd, cd, disk, block, generic} targets
blkdev_id = "virtio-scsi%s-id%s" % ((index or ""), scsi_disk)
dev = QDevice(fmt)
dev.set_param("id", name)
dev.set_param("logical_block_size", logical_block_size)
dev.set_param("physical_block_size", physical_block_size)
dev.set_param("min_io_size", min_io_size)
dev.set_param("opt_io_size", opt_io_size)
dev.set_param("bootindex", bootindex)
dev.set_param("serial", serial)
dev.set_param("removable", removable, bool)
if bus:
dev.set_param("bus", "virtio_scsi_pci%d.0" % bus)
if scsiid:
dev.set_param("scsi-id", scsiid)
if lun:
dev.set_param("lun", lun)
fmt = "none"
dev.set_param("drive", blkdev_id)
index = None
elif (devices.has_option("device") and
fmt not in ("floppy", "scsi")):
dev = QDevice(dev_format[fmt])
if fmt == "ide":
dev.set_param("bus", str(ide_bus))
dev.set_param("unit", str(ide_unit))
elif fmt == "virtio":
dev.parent_bus = {'type': 'pci'}
dev.set_param('addr', pci_addr)
dev.set_param("physical_block_size", physical_block_size)
dev.set_param("logical_block_size", logical_block_size)
# This 'scsi' option only affect on RHEL6.later host.
# RHBZ 756677.
dev.set_param("scsi", scsi, bool)
dev.set_param("drive", blkdev_id)
dev.set_param("id", name)
dev.set_param("x-data-plane", x_data_plane, bool)
dev.set_param("bootindex", bootindex)
fmt = "none"
if fmt == "floppy":
drivelist = ['driveA', 'driveB']
blkdev_id = "fdc0-0-%s" % index
fmt = "none"
dev = qemu_devices.QCustomDevice('global')
dev.set_param("isa-fdc.%s" % drivelist[index], blkdev_id)
index = None
if dev and blk_extra_params:
for key, value in re.findall(r'(%s)=(%s)', blk_extra_params):
dev.set_param(key, value)
# -drive part
drive = qemu_devices.QCustomDevice('drive')
if blkdebug is not None:
drive.set_param('file', 'blkdebug:%s:%s' % (blkdebug, filename))
else:
drive.set_param('file', filename, 'NEED_QUOTE')
drive.set_param("index", index)
drive.set_param("if", fmt)
drive.set_param("id", blkdev_id)
drive.set_param("media", media)
drive.set_param("cache", cache)
drive.set_param("rerror", rerror)
drive.set_param("werror", werror)
drive.set_param("serial", serial)
drive.set_param("snapshot", snapshot, bool)
# Only add boot=on/off if necessary (deprecated in newer qemu)
if boot != "unused":
drive.set_param("boot", boot, bool)
drive.set_param("readonly", readonly, bool)
drive.set_param("format", imgfmt)
drive.set_param("aio", aio)
devices.insert(drive)
if dev:
devices.insert(dev)
def add_nic(devices, vlan, model=None, mac=None, device_id=None,
netdev_id=None, nic_extra_params=None, pci_addr=None,
bootindex=None):
if model == 'none':
return
if devices.has_option("device"):
if not model:
model = "rtl8139"
elif model == "virtio":
model = "virtio-net-pci"
dev = QDevice(model)
dev.set_param('mac', mac)
# only pci domain=0,bus=0,function=0 is supported for now.
#
# libvirt gains the pci_slot, free_pci_addr here,
# value by parsing the xml file, i.e. counting all the
# pci devices and store the number.
if model != 'spapr-vlan':
dev.parent_bus = {'type': 'pci'}
dev.set_param('addr', pci_addr)
if nic_extra_params:
for key, val in re.findall(r'(%s)=(%s)', nic_extra_params):
dev.set_param(key, val)
dev.set_param("bootindex", bootindex)
else:
dev = qemu_devices.QCustomDevice('net')
dev.set_param('type', 'nic')
dev.set_param('model', model)
dev.set_param('macaddr', mac, 'NEED_QUOTE')
dev.set_param('id', device_id, 'NEED_QUOTE')
if devices.has_option("netdev"):
dev.set_param('netdev', netdev_id)
else:
dev.set_param('vlan', vlan)
devices.insert(dev)
def add_net(devices, vlan, nettype, ifname=None, tftp=None,
bootfile=None, hostfwd=[], netdev_id=None,
netdev_extra_params=None, tapfds=None, script=None,
downscript=None, vhost=None, queues=None):
mode = None
if nettype in ['bridge', 'network', 'macvtap']:
mode = 'tap'
elif nettype == 'user':
mode = 'user'
else:
logging.warning("Unknown/unsupported nettype %s" % nettype)
return ''
if devices.has_option("netdev"):
cmd = " -netdev %s,id=%s" % (mode, netdev_id)
if vhost:
cmd += ",%s" % vhost
enable_vhostfd = params.get("enable_vhostfd", "yes")
if vhost == 'vhost=on' and enable_vhostfd == 'yes':
vhostfd = os.open("/dev/vhost-net", os.O_RDWR)
cmd += ",vhostfd=%s" % vhostfd
if netdev_extra_params:
cmd += "%s" % netdev_extra_params
else:
cmd = " -net %s,vlan=%d" % (mode, vlan)
if mode == "tap" and tapfds:
if (int(queues)) > 1 and ',fds=' in devices.get_help_text():
cmd += ",fds=%s" % tapfds
else:
cmd += ",fd=%s" % tapfds
elif mode == "user":
if tftp and "[,tftp=" in devices.get_help_text():
cmd += ",tftp='%s'" % tftp
if bootfile and "[,bootfile=" in devices.get_help_text():
cmd += ",bootfile='%s'" % bootfile
if "[,hostfwd=" in devices.get_help_text():
for host_port, guest_port in hostfwd:
cmd += ",hostfwd=tcp::%s-:%s" % (host_port, guest_port)
else:
if ifname:
cmd += ",ifname='%s'" % ifname
if script:
cmd += ",script='%s'" % script
cmd += ",downscript='%s'" % (downscript or "no")
return cmd
def add_floppy(devices, filename, index):
cmd_list = [" -fda '%s'", " -fdb '%s'"]
return cmd_list[index] % filename
def add_tftp(devices, filename):
# If the new syntax is supported, don't add -tftp
if "[,tftp=" in devices.get_help_text():
return ""
else:
return " -tftp '%s'" % filename
def add_bootp(devices, filename):
# If the new syntax is supported, don't add -bootp
if "[,bootfile=" in devices.get_help_text():
return ""
else:
return " -bootp '%s'" % filename
def add_tcp_redir(devices, host_port, guest_port):
# If the new syntax is supported, don't add -redir
if "[,hostfwd=" in devices.get_help_text():
return ""
else:
return " -redir tcp:%s::%s" % (host_port, guest_port)
def add_vnc(devices, vnc_port, vnc_password='no', extra_params=None):
vnc_cmd = " -vnc :%d" % (vnc_port - 5900)
if vnc_password == "yes":
vnc_cmd += ",password"
if extra_params:
vnc_cmd += ",%s" % extra_params
return vnc_cmd
def add_sdl(devices):
if devices.has_option("sdl"):
return " -sdl"
else:
return ""
def add_nographic(devices):
return " -nographic"
def add_uuid(devices, uuid):
return " -uuid '%s'" % uuid
def add_pcidevice(devices, host, params):
if devices.has_device('pci-assign'):
dev = QDevice('pci-assign', parent_bus={'type': 'pci'})
else:
dev = QDevice('pcidevice', parent_bus={'type': 'pci'})
help_cmd = "%s -device pci-assign,\\? 2>&1" % qemu_binary
pcidevice_help = utils.system_output(help_cmd)
dev.set_param('host', host)
dev.set_param('id', 'id_%s' % host)
fail_param = []
for param in params.get("pci-assign_params", "").split():
value = params.get(param)
if value:
if bool(re.search(param, pcidevice_help, re.M)):
dev.set_param(param, value)
else:
fail_param.append(param)
if fail_param:
msg = ("parameter %s is not support in device pci-assign."
" It only support following paramter:\n %s" %
(param, pcidevice_help))
logging.warn(msg)
devices.insert(dev)
def add_spice_rhel5(devices, spice_params, port_range=(3100, 3199)):
"""
processes spice parameters on rhel5 host.
@param spice_options - dict with spice keys/values
@param port_range - tuple with port range, default: (3000, 3199)
"""
if devices.has_option("spice"):
cmd = " -spice"
else:
return ""
spice_help = ""
if devices.has_option("spice-help"):
spice_help = commands.getoutput("%s -device \\?" % qemu_binary)
s_port = str(utils_misc.find_free_port(*port_range))
self.spice_options['spice_port'] = s_port
cmd += " port=%s" % s_port
for param in spice_params.split():
value = params.get(param)
if value:
if bool(re.search(param, spice_help, re.M)):
cmd += ",%s=%s" % (param, value)
else:
msg = ("parameter %s is not supported in spice. It "
"only supports the following parameters:\n %s"
% (param, spice_help))
logging.warn(msg)
else:
cmd += ",%s" % param
if devices.has_option("qxl"):
qxl_dev_nr = params.get("qxl_dev_nr", 1)
cmd += " -qxl %s" % qxl_dev_nr
return cmd
def add_spice(port_range=(3000, 3199),
tls_port_range=(3200, 3399)):
"""
processes spice parameters
@param port_range - tuple with port range, default: (3000, 3199)
@param tls_port_range - tuple with tls port range,
default: (3200, 3399)
"""
spice_opts = [] # will be used for ",".join()
tmp = None
def optget(opt):
"""a helper function"""
return self.spice_options.get(opt)
def set_yes_no_value(key, yes_value=None, no_value=None):