-
Notifications
You must be signed in to change notification settings - Fork 353
/
kvm_vm.py
2746 lines (2379 loc) · 112 KB
/
kvm_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, errno
from autotest.client.shared import error
from autotest.client import utils
import utils_misc, virt_vm, test_setup, storage, kvm_monitor, aexpect
import kvm_virtio_port
import remote
class VM(virt_vm.BaseVM):
"""
This class handles all basic VM operations.
"""
MIGRATION_PROTOS = ['tcp', 'unix', 'exec', 'fd']
#
# By default we inherit all timeouts from the base VM class
#
LOGIN_TIMEOUT = virt_vm.BaseVM.LOGIN_TIMEOUT
LOGIN_WAIT_TIMEOUT = virt_vm.BaseVM.LOGIN_WAIT_TIMEOUT
COPY_FILES_TIMEOUT = virt_vm.BaseVM.COPY_FILES_TIMEOUT
MIGRATE_TIMEOUT = virt_vm.BaseVM.MIGRATE_TIMEOUT
REBOOT_TIMEOUT = virt_vm.BaseVM.REBOOT_TIMEOUT
CREATE_TIMEOUT = virt_vm.BaseVM.CREATE_TIMEOUT
CLOSE_SESSION_TIMEOUT = 30
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.init_pci_addr = int(params.get("init_pci_addr", 4))
self.name = name
self.params = params
self.root_dir = root_dir
# We need this to get to the blkdebug files
self.virt_dir = os.path.abspath(os.path.join(root_dir, "..", "..", "virt"))
self.address_cache = address_cache
# 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 = 'kvm'
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 = ''
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
"""
try:
virt_vm.BaseVM.verify_alive(self)
if self.monitors:
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.monitors 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 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 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 __make_qemu_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 has_option(hlp, option):
return bool(re.search(r"^-%s(\s|$)" % option, hlp, re.MULTILINE))
# 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 get_free_pci_addr(pci_addr=None):
"""
return *hex* format free pci addr.
@param pci_addr: *decimal* formated, desired pci_add
"""
if pci_addr is None:
pci_addr = self.init_pci_addr
while True:
# actually when pci_addr > 20? errors may happen
if pci_addr > 31:
raise virt_vm.VMPCIOutOfRangeError(self.name, 31)
if pci_addr in self.pci_addr_list:
pci_addr += 1
else:
self.pci_addr_list.append(pci_addr)
return hex(pci_addr)
elif int(pci_addr) in self.pci_addr_list:
raise virt_vm.VMPCISlotInUseError(self.name, pci_addr)
else:
self.pci_addr_list.append(int(pci_addr))
return hex(int(pci_addr))
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 ""
def get_free_usb_port(dev, controller_type):
# Find an available USB port.
bus = None
port = None
controller = None
for usb in params.objects("usbs"):
usb_params = params.object_params(usb)
usb_type = usb_params.get("usb_type")
usb_dev = self.usb_dev_dict.get(usb)
if usb_type.find(controller_type) != -1:
controller = usb
max_port = int(usb_params.get("usb_max_port", 6))
if len(usb_dev) < max_port:
bus = "%s.0" % usb
self.usb_dev_dict[usb].append(dev)
# Usb port starts from 1, so add 1 directly here.
port = self.usb_dev_dict[usb].index(dev) + 1
break
if controller is None:
raise virt_vm.VMUSBControllerMissingError(self.name,
controller_type)
elif bus is None:
raise virt_vm.VMUSBControllerPortFullError(self.name)
return (bus, str(port))
def add_name(hlp, name):
return " -name '%s'" % name
def add_human_monitor(hlp, monitor_name, filename):
if not has_option(hlp, "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(hlp, monitor_name, filename):
if not has_option(hlp, "qmp"):
logging.warn("Fallback to human monitor since qmp is"
" unsupported")
return add_human_monitor(hlp, monitor_name, filename)
if not has_option(hlp, "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(hlp, filename):
if not has_option(hlp, "chardev"):
return " -serial unix:'%s',server,nowait" % filename
default_id = "serial_id_%s" % self.instance
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-serial"
cmd += _add_option("chardev", default_id)
return cmd
def add_virtio_port(hlp, name, bus, filename, porttype, chardev,
name_prefix=None, index=None):
"""
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)
"""
cmd = ''
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))
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)
return cmd
def add_log_seabios(hlp):
device_help = commands.getoutput("%s -device \\?" % qemu_binary)
if not bool(re.search("isa-debugcon", device_help, re.M)):
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(hlp):
chardev_id = "anacondalog_chardev_%s" % self.instance
vioser_id = "anacondalog_vioser_%s" % self.instance
filename = "/tmp/anaconda-%s" % self.instance
self.logs["anaconda"] = filename
cmd = " -chardev socket"
cmd += _add_option("id", chardev_id)
cmd += _add_option("path", filename)
cmd += _add_option("server", "NO_EQUAL_STRING")
cmd += _add_option("nowait", "NO_EQUAL_STRING")
cmd += " -device virtio-serial-pci"
cmd += _add_option("id", vioser_id)
cmd += " -device virtserialport"
cmd += _add_option("bus", "%s.0" % vioser_id)
cmd += _add_option("chardev", chardev_id)
cmd += _add_option("name", "org.fedoraproject.anaconda.log.0")
return cmd
def add_mem(hlp, mem):
return " -m %s" % mem
def add_smp(hlp):
smp_str = " -smp %d" % self.cpuinfo.smp
if has_option(hlp, "maxcpus=cpus"):
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(hlp, filename, index=None, fmt=None, bus=None,
port=None):
if has_option(hlp, "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(hlp, filename, index=None, fmt=None, cache=None,
werror=None, rerror=None, serial=None, snapshot=False,
boot=False, 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=False, scsiid=None,
lun=None):
name = None
dev = ""
if not re.search("boot=on\|off", hlp, re.MULTILINE):
if boot in ['yes', 'on', True]:
bootindex = "1"
boot = "unused"
if fmt == "ahci":
name = "ahci%s" % index
dev += " -device ide-drive,bus=ahci.%s,drive=%s" % (index, name)
dev += _add_option("bootindex", bootindex)
fmt = "none"
index = None
if fmt == "virtio":
if has_option(hlp, "device"):
name = "virtio%s" % index
dev += " -device virtio-blk-pci"
dev += _add_option("drive", name)
fmt = "none"
dev += _add_option("bootindex", bootindex)
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("serial", serial)
dev += _add_option("bootindex", bootindex)
dev += _add_option("removable", removable)
dev += _add_option("min_io_size", min_io_size)
dev += _add_option("opt_io_size", opt_io_size)
dev += _add_option("physical_block_size", physical_block_size)
dev += _add_option("logical_block_size", logical_block_size)
dev += _add_option("drive", name)
fmt = "none"
index = None
if fmt.startswith("scsi-"):
# handles scsi-{hd, cd, disk, block, generic} targets
name = "virtio-scsi%s" % index
dev += " -device %s" % fmt
dev += _add_option("logical_block_size", logical_block_size)
dev += _add_option("physical_block_size", physical_block_size)
dev += _add_option("min_io_size", min_io_size)
dev += _add_option("opt_io_size", opt_io_size)
dev += _add_option("bootindex", bootindex)
dev += _add_option("serial", serial)
dev += _add_option("removable", removable)
if bus:
name += "-b%s" % bus
dev += _add_option("bus", "virtio_scsi_pci%d.0" % bus)
if scsiid:
name += "-i%s" % scsiid
dev += _add_option("scsi-id", scsiid)
if lun:
name += "-l%s" % lun
dev += _add_option("lun", lun)
fmt = "none"
dev += _add_option("drive", name)
index = None
if fmt == "floppy":
drivelist = ['driveA','driveB']
name ="fdc0-0-%s" % index
fmt = "none"
dev += " -global"
dev += _add_option("isa-fdc.%s" % drivelist[index], name,
first=True)
if blkdebug is not None:
cmd = " -drive file=blkdebug:%s:%s" % (blkdebug, filename)
else:
cmd = " -drive file='%s'" % filename
cmd += _add_option("index", index)
cmd += _add_option("if", fmt)
cmd += _add_option("cache", cache)
cmd += _add_option("rerror", rerror)
cmd += _add_option("werror", werror)
cmd += _add_option("serial", serial)
cmd += _add_option("snapshot", snapshot, bool)
# Only add boot=on/off if necessary (deprecated in newer qemu)
if boot != "unused":
cmd += _add_option("boot", boot, bool)
cmd += _add_option("id", name)
cmd += _add_option("readonly", readonly, bool)
return cmd + dev
def add_nic(hlp, vlan, model=None, mac=None, device_id=None, netdev_id=None,
nic_extra_params=None):
if model == 'none':
return ''
if has_option(hlp, "netdev"):
netdev_vlan_str = ",netdev=%s" % netdev_id
else:
netdev_vlan_str = ",vlan=%d" % vlan
if has_option(hlp, "device"):
if not model:
model = "rtl8139"
elif model == "virtio":
model = "virtio-net-pci"
cmd = " -device %s" % model + netdev_vlan_str
if mac:
cmd += ",mac='%s'" % mac
if nic_extra_params:
cmd += ",%s" % nic_extra_params
else:
cmd = " -net nic" + netdev_vlan_str
if model:
cmd += ",model=%s" % model
if mac:
cmd += ",macaddr='%s'" % mac
if device_id:
cmd += ",id='%s'" % device_id
return cmd
def add_net(hlp, vlan, nettype, ifname=None, tftp=None, bootfile=None,
hostfwd=[], netdev_id=None, netdev_extra_params=None,
tapfd=None):
mode = None
if nettype == 'bridge':
mode = 'tap'
elif nettype == 'network':
mode = 'tap'
elif nettype == 'user':
mode = 'user'
else:
logging.warning("Unknown/unsupported nettype %s" % nettype)
return ''
if has_option(hlp, "netdev"):
cmd = " -netdev %s,id=%s" % (mode, netdev_id)
if netdev_extra_params:
cmd += ",%s" % netdev_extra_params
else:
cmd = " -net %s,vlan=%d" % (mode, vlan)
if mode == "tap" and tapfd:
cmd += ",fd=%d" % tapfd
elif mode == "user":
if tftp and "[,tftp=" in hlp:
cmd += ",tftp='%s'" % tftp
if bootfile and "[,bootfile=" in hlp:
cmd += ",bootfile='%s'" % bootfile
if "[,hostfwd=" in hlp:
for host_port, guest_port in hostfwd:
cmd += ",hostfwd=tcp::%s-:%s" % (host_port, guest_port)
return cmd
def add_floppy(hlp, filename, index):
cmd_list = [" -fda '%s'"," -fdb '%s'"]
return cmd_list[index] % filename
def add_tftp(hlp, filename):
# If the new syntax is supported, don't add -tftp
if "[,tftp=" in hlp:
return ""
else:
return " -tftp '%s'" % filename
def add_bootp(hlp, filename):
# If the new syntax is supported, don't add -bootp
if "[,bootfile=" in hlp:
return ""
else:
return " -bootp '%s'" % filename
def add_tcp_redir(hlp, host_port, guest_port):
# If the new syntax is supported, don't add -redir
if "[,hostfwd=" in hlp:
return ""
else:
return " -redir tcp:%s::%s" % (host_port, guest_port)
def add_vnc(hlp, 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(hlp):
if has_option(hlp, "sdl"):
return " -sdl"
else:
return ""
def add_nographic(hlp):
return " -nographic"
def add_uuid(hlp, uuid):
return " -uuid '%s'" % uuid
def add_pcidevice(hlp, host):
return " -pcidevice host='%s'" % host
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):
"""just a helper function"""
tmp = optget(key)
if tmp == "no" and no_value:
spice_opts.append(no_value)
elif tmp == "yes" and yes_value:
spice_opts.append(yes_value)
def set_value(opt_string, key, fallback=None):
"""just a helper function"""
tmp = optget(key)
if tmp:
spice_opts.append(opt_string % tmp)
elif fallback:
spice_opts.append(fallback)
s_port = str(utils_misc.find_free_port(*port_range))
set_value("port=%s", "spice_port", "port=%s" % s_port)
if optget("spice_port") == None:
self.spice_options['spice_port'] = s_port
set_value("password=%s", "spice_password", "disable-ticketing")
set_value("addr=%s", "spice_addr")
if optget("spice_ssl") == "yes":
# SSL only part
t_port = str(utils_misc.find_free_port(*tls_port_range))
set_value("tls-port=%s", "spice_tls_port",
"tls-port=%s" % t_port)
if optget("spice_tls_port") == None:
self.spice_options['spice_tls_port'] = t_port
prefix = optget("spice_x509_prefix")
if (not os.path.exists(prefix) and
(optget("spice_gen_x509") == "yes")):
# Generate spice_x509_* is not always necessary,
# Regenerate them will make your existing VM
# not longer accessiable via encrypted spice.
c_subj = optget("spice_x509_cacert_subj")
s_subj = optget("spice_x509_server_subj")
passwd = optget("spice_x509_key_password")
secure = optget("spice_x509_secure")
utils_misc.create_x509_dir(prefix, c_subj, s_subj, passwd,
secure)
tmp = optget("spice_x509_dir")
if tmp == "yes":
spice_opts.append("x509-dir=%s" % (prefix))
elif tmp == "no":
cacert = optget("spice_x509_cacert_file")
server_key = optget("spice_x509_key_file")
server_cert = optget("spice_x509_cert_file")
keyfile_str = ("x509-key-file=%s,x509-cacert-file=%s,"
"x509-cert-file=%s" %
(os.path.join(prefix, server_key),
os.path.join(prefix, cacert),
os.path.join(prefix, server_cert)))
spice_opts.append(keyfile_str)
set_yes_no_value("spice_x509_secure",
yes_value="x509-key-password=%s" %
(optget("spice_x509_key_password")))
tmp = optget("spice_secure_channels")
if tmp:
for item in tmp.split(","):
spice_opts.append("tls-channel=%s" % (item.strip()))
# Less common options
set_value("image-compression=%s", "spice_image_compression")
set_value("jpeg-wan-compression=%s", "spice_jpeg_wan_compression")
set_value("zlib-glz-wan-compression=%s",
"spice_zlib_glz_wan_compression")
set_value("streaming-video=%s", "spice_streaming_video")
set_value("agent-mouse=%s", "spice_agent_mouse")
set_value("playback-compression=%s", "spice_playback_compression")
set_yes_no_value("spice_ipv4", yes_value="ipv4")
set_yes_no_value("spice_ipv6", yes_value="ipv6")
return " -spice %s" % (",".join(spice_opts))
def add_qxl(qxl_nr, qxl_memory=None):
"""
adds extra qxl devices + sets memory to -vga qxl and extra qxls
@param qxl_nr total number of qxl devices
@param qxl_memory sets memory to individual devices
"""
qxl_str = ""
vram_help = ""
if qxl_memory:
vram_help = "vram_size=%d" % qxl_memory
qxl_str += " -global qxl-vga.%s" % (vram_help)
for index in range(1, qxl_nr):
qxl_str += " -device qxl,id=video%d,%s"\
% (index, vram_help)
return qxl_str
def add_vga(vga):
return " -vga %s" % vga
def add_kernel(hlp, filename):
return " -kernel '%s'" % filename
def add_initrd(hlp, filename):
return " -initrd '%s'" % filename
def add_rtc(hlp):
# Pay attention that rtc-td-hack is for early version
# if "rtc " in help:
if has_option(hlp, "rtc"):
cmd = " -rtc base=%s" % params.get("rtc_base", "utc")
cmd += _add_option("clock", params.get("rtc_clock", "host"))
cmd += _add_option("driftfix", params.get("rtc_drift", "none"))
return cmd
elif has_option(hlp, "rtc-td-hack"):
return " -rtc-td-hack"
else:
return ""
def add_kernel_cmdline(hlp, cmdline):
return " -append '%s'" % cmdline
def add_testdev(hlp, filename):
return (" -chardev file,id=testlog,path=%s"
" -device testdev,chardev=testlog" % filename)
def add_no_hpet(hlp):
if has_option(hlp, "no-hpet"):
return " -no-hpet"
else:
return ""
def add_cpu_flags(hlp, cpu_model, flags=None, vendor_id=None,
family=None):
if has_option(hlp, 'cpu'):
cmd = " -cpu '%s'" % cpu_model
if vendor_id:
cmd += ",vendor=\"%s\"" % vendor_id
if flags:
cmd += ",%s" % flags
if family is not None:
cmd += ",family=%s" % family
return cmd
else:
return ""
def add_boot(hlp, boot_order, boot_once, boot_menu):
cmd = " -boot"
pattern = "boot \[order=drives\]\[,once=drives\]\[,menu=on\|off\]"
if has_option(hlp, "boot \[a\|c\|d\|n\]"):
cmd += " %s" % boot_once
elif has_option(hlp, pattern):
cmd += (" order=%s,once=%s,menu=%s" %
(boot_order, boot_once, boot_menu))
else:
cmd = ""
return cmd
def add_machine_type(hlp, machine_type):
if has_option(hlp, "machine") or has_option(hlp, "M"):
return " -M %s" % machine_type
else:
return ""
def add_usb(hlp, usb_id, usb_type):
if not has_option(hlp, "device"):
# Okay, for the archaic qemu which has not device parameter,
# just return a usb uhci controller.
# If choose this kind of usb controller, it has no name/id,
# and only can be created once, so give it a special name.
self.usb_dev_dict["OLDVERSION_usb0"] = []
return " -usb"
device_help = commands.getoutput("%s -device \\?" % qemu_binary)
if not bool(re.search(usb_type, device_help, re.M)):
raise virt_vm.VMDeviceNotSupportedError(self.name, usb_type)
cmd = " -device %s" % usb_type
cmd += _add_option("id", usb_id)
if usb_type == "ich9-usb-ehci1":
common = ",multifunction=on,masterbus=%s.0" % usb_id
uhci1 = " -device ich9-usb-uhci1,addr=1d.0,firstport=0"
uhci2 = " -device ich9-usb-uhci2,addr=1d.1,firstport=2"
uhci3 = " -device ich9-usb-uhci3,addr=1d.2,firstport=4"
cmd += ",addr=1d.7,multifunction=on"
cmd += uhci1 + common
cmd += uhci2 + common
cmd += uhci3 + common
# register this usb controller.
self.usb_dev_dict[usb_id] = []
return cmd
def add_usbdevice(hlp, usb_dev, usb_type, controller_type,
bus=None, port=None):
"""
This function is used to add usb device except for usb storage.
"""
cmd = ""
if has_option(hlp, "device"):
cmd = " -device %s" % usb_type
cmd += _add_option("id", "usb-%s" % usb_dev)
cmd += _add_option("bus", bus)
cmd += _add_option("port", port)
else:
if "tablet" in usb_type:
cmd = " -usbdevice %s" % usb_type
else:
logging.error("This version of host only support"
" tablet device")
return cmd
def add_sga(hlp):
if not has_option(hlp, "device"):
return ""
return " -device sga"
# End of command line option wrappers
if name is None:
name = self.name
if params is None:
params = self.params
if root_dir is None:
root_dir = self.root_dir
have_ahci = False
virtio_scsi_pcis = []
# Clone this VM using the new params
vm = self.clone(name, params, root_dir, copy_state=True)
# init value by default.
# PCI addr 0,1,2 are taken by PCI/ISA/IDE bridge and the sound device.
self.pci_addr_list = [0, 1, 2]
qemu_binary = utils_misc.get_path(root_dir, params.get("qemu_binary",
"qemu"))
self.qemu_binary = qemu_binary
hlp = commands.getoutput("%s -help" % qemu_binary)
support_cpu_model = commands.getoutput("%s -cpu ?list" % qemu_binary)
# Start constructing the qemu command
qemu_cmd = ""
# Enable the use of glibc's malloc_perturb feature
if params.get("malloc_perturb", "no") == "yes":
qemu_cmd += "MALLOC_PERTURB_=1 "
# Set the X11 display parameter if requested
if params.get("x11_display"):
qemu_cmd += "DISPLAY=%s " % params.get("x11_display")
# Update LD_LIBRARY_PATH for built libraries (libspice-server)
library_path = os.path.join(self.root_dir, 'build', 'lib')
if os.path.isdir(library_path):
library_path = os.path.abspath(library_path)
qemu_cmd += "LD_LIBRARY_PATH=%s " % library_path
if params.get("qemu_audio_drv"):
qemu_cmd += "QEMU_AUDIO_DRV=%s " % params.get("qemu_audio_drv")
# Add command prefix for qemu-kvm. like taskset, valgrind and so on
if params.get("qemu_command_prefix"):
qemu_command_prefix = params.get("qemu_command_prefix")
qemu_cmd += "%s " % qemu_command_prefix
# Add numa memory cmd to pin guest memory to numa node
if params.get("numa_node"):
numa_node = int(params.get("numa_node"))
if numa_node < 0:
p = utils_misc.NumaNode(numa_node)
n = int(p.get_node_num()) + numa_node
qemu_cmd += "numactl -m %s " % n
else:
n = numa_node - 1
qemu_cmd += "numactl -m %s " % n
# Add the qemu binary
qemu_cmd += qemu_binary
qemu_cmd += " -S"
# Add the VM's name
qemu_cmd += add_name(hlp, name)
# no automagic devices please
defaults = params.get("defaults", "no")
if has_option(hlp,"nodefaults") and defaults != "yes":
qemu_cmd += " -nodefaults"
# Add monitors
for monitor_name in params.objects("monitors"):
monitor_params = params.object_params(monitor_name)
monitor_filename = vm.get_monitor_filename(monitor_name)
if monitor_params.get("monitor_type") == "qmp":
qemu_cmd += add_qmp_monitor(hlp, monitor_name,
monitor_filename)
else:
qemu_cmd += add_human_monitor(hlp, monitor_name,
monitor_filename)
# Add serial console redirection
qemu_cmd += add_serial(hlp, vm.get_serial_console_filename())
# Add virtio_serial ports
i = 0
virtio_serial_pcis = []
virtio_port_spread = int(params.get('virtio_port_spread', 2))
for port_name in params.objects("virtio_ports"):
port_params = params.object_params(port_name)