forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibvirt_vm.py
1583 lines (1350 loc) · 59.6 KB
/
libvirt_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 libvirt.
@copyright: 2011 Red Hat Inc.
"""
import time, os, logging, fcntl, re, shutil, tempfile
from autotest.client.shared import error
from autotest.client import utils
import utils_misc, virt_vm, storage, aexpect, remote, virsh, libvirt_xml
import data_dir, xml_utils
def normalize_connect_uri(connect_uri):
"""
Processes connect_uri Cartesian into something virsh can use
@param: connect_uri: Cartesian Params setting
@return: Normalized connect_uri
"""
if connect_uri == 'default':
return None
else: # Validate and canonicalize uri early to catch problems
result = virsh.canonical_uri(uri=connect_uri)
if not result:
raise ValueError("Normalizing connect_uri %s failed" % connect_uri)
return result
def complete_uri(ip_address):
"""
Return a complete URI with the combination of ip_address and local uri.
It is useful when you need to connect remote hypervisor.
@param ip_address: an ip address or a hostname
@return: a complete uri
"""
# Allow to raise CmdError if canonical_uri is failed
uri = virsh.canonical_uri(ignore_status=False)
driver = uri.split(":")[0]
# The libvirtd daemon's mode(system or session on qemu)
daemon_mode = uri.split("/")[-1]
complete_uri = "%s+ssh://%s/%s" % (driver, ip_address, daemon_mode)
return complete_uri
def get_uri_with_transport(uri_type='qemu', transport="", dest_ip=""):
"""
Return a URI to connect driver on dest with a specificed transport.
@param origin_uri: The URI on dest used to connect itself directly.
@param transport: The transport type connect to dest.
@param dest_ip: The ip of destination.
"""
_type2uri_ = {'qemu':"qemu:///system",
'qemu_system':"qemu:///system",
'qemu_session':"qemu:///session",
'lxc':"lxc:///",
'xen':"xen:///"}
try:
origin_uri = _type2uri_[uri_type]
except KeyError:
raise ValueError("Param uri_type = %s is not supported." % (uri_type))
#For example:
# ("qemu:///system")-->("qemu", ":", "///system")
origin_uri_partitions = origin_uri.partition(":")
origin_uri_driver = origin_uri_partitions[0]
origin_uri_colon = origin_uri_partitions[1]
origin_uri_dest = origin_uri_partitions[2]
transport_uri_driver = ("%s+%s" % (origin_uri_driver, transport))
transport_uri_colon = origin_uri_colon
#For example:
# ("///system")-->("", "//", "/system")
transport_dest_partitions = origin_uri_dest.partition("//")
transport_uri_dest = (transport_dest_partitions[0]+transport_dest_partitions[1]+
dest_ip+transport_dest_partitions[2])
return ("%s%s%s" % (transport_uri_driver, transport_uri_colon, transport_uri_dest))
class VM(virt_vm.BaseVM):
"""
This class handles all basic VM operations for libvirt.
"""
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_create_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.vnc_port = None
self.vnc_autoport = True
self.pci_assignable = None
self.netdev_id = []
self.device_id = []
self.pci_devices = []
self.uuid = None
self.spice_port = 8000
self.name = name
self.params = params
self.root_dir = root_dir
self.address_cache = address_cache
self.vnclisten = "0.0.0.0"
self.connect_uri = normalize_connect_uri( params.get("connect_uri",
"default") )
if self.connect_uri:
self.driver_type = virsh.driver(uri = self.connect_uri)
else:
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)
logging.info("Libvirt VM '%s', driver '%s', uri '%s'",
self.name, self.driver_type, self.connect_uri)
def verify_alive(self):
"""
Make sure the VM is alive.
@raise VMDeadError: If the VM is dead
"""
if not self.is_alive():
raise virt_vm.VMDeadError("Domain %s is inactive" % self.name,
self.state())
def is_alive(self):
"""
Return True if VM is alive.
"""
return virsh.is_alive(self.name, uri=self.connect_uri)
def is_dead(self):
"""
Return True if VM is dead.
"""
return virsh.is_dead(self.name, uri=self.connect_uri)
def is_paused(self):
"""
Return True if VM is paused.
"""
return (self.state() == "paused")
def is_persistent(self):
"""
Return True if VM is persistent.
"""
try:
return bool(re.search(r"^Persistent:\s+[Yy]es",
virsh.dominfo(self.name, uri=self.connect_uri).stdout.strip(),
re.MULTILINE))
except error.CmdError:
return False
def exists(self):
"""
Return True if VM exists.
"""
return virsh.domain_exists(self.name, uri=self.connect_uri)
def undefine(self):
"""
Undefine the VM.
"""
try:
virsh.undefine(self.name, uri=self.connect_uri,
ignore_status=False)
except error.CmdError, detail:
logging.error("Undefined VM %s failed:\n%s", self.name, detail)
return False
return True
def define(self, xml_file):
"""
Define the VM.
"""
if not os.path.exists(xml_file):
logging.error("File %s not found." % xml_file)
return False
try:
virsh.define(xml_file, uri=self.connect_uri,
ignore_status=False)
except error.CmdError, detail:
logging.error("Defined VM from %s failed:\n%s", xml_file, detail)
return False
return True
def state(self):
"""
Return domain state.
"""
return virsh.domstate(self.name, uri=self.connect_uri).stdout.strip()
def get_id(self):
"""
Return VM's ID.
"""
return virsh.domid(self.name, uri=self.connect_uri).stdout.strip()
def get_xml(self):
"""
Return VM's xml file.
"""
return virsh.dumpxml(self.name, uri=self.connect_uri)
def backup_xml(self):
"""
Backup the guest's xmlfile.
"""
# Since backup_xml() is not a function for testing,
# we have to handle the exception here.
try:
xml_file = tempfile.mktemp(dir="/tmp")
virsh.dumpxml(self.name, to_file=xml_file, uri=self.connect_uri)
return xml_file
except Exception, detail:
if os.path.exists(xml_file):
os.remove(xml_file)
logging.error("Failed to backup xml file:\n%s", detail)
return ""
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_create_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_create_command(self, name=None, params=None, root_dir=None):
"""
Generate a libvirt 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(help_text, option):
return bool(re.search(r"--%s" % option, help_text, re.MULTILINE))
# Wrappers for all supported libvirt command line parameters.
# This is meant to allow support for multiple libvirt versions.
# Each of these functions receives the output of 'libvirt --help' as a
# parameter, and should add the requested command line option
# accordingly.
def add_name(help_text, name):
return " --name '%s'" % name
def add_machine_type(help_text, machine_type):
if has_option(help_text, "machine"):
return " --machine %s" % machine_type
else:
return ""
def add_hvm_or_pv(help_text, hvm_or_pv):
if hvm_or_pv == "hvm":
return " --hvm --accelerate"
elif hvm_or_pv == "pv":
return " --paravirt"
else:
logging.warning("Unknown virt type hvm_or_pv, using default.")
return ""
def add_mem(help_text, mem):
return " --ram=%s" % mem
def add_check_cpu(help_text):
if has_option(help_text, "check-cpu"):
return " --check-cpu"
else:
return ""
def add_smp(help_text, smp):
return " --vcpu=%s" % smp
def add_location(help_text, location):
if has_option(help_text, "location"):
return " --location %s" % location
else:
return ""
def add_cdrom(help_text, filename, index=None):
if has_option(help_text, "cdrom"):
return " --cdrom %s" % filename
else:
return ""
def add_pxe(help_text):
if has_option(help_text, "pxe"):
return " --pxe"
else:
return ""
def add_import(help_text):
if has_option(help_text, "import"):
return " --import"
else:
return ""
def add_drive(help_text, filename, pool=None, vol=None, device=None,
bus=None, perms=None, size=None, sparse=False,
cache=None, fmt=None):
cmd = " --disk"
if filename:
cmd += " path=%s" % filename
elif pool:
if vol:
cmd += " vol=%s/%s" % (pool, vol)
else:
cmd += " pool=%s" % pool
if device:
cmd += ",device=%s" % device
if bus:
cmd += ",bus=%s" % bus
if perms:
cmd += ",%s" % perms
if size:
cmd += ",size=%s" % size.rstrip("Gg")
if sparse:
cmd += ",sparse=false"
if fmt:
cmd += ",format=%s" % fmt
if cache:
cmd += ",cache=%s" % cache
return cmd
def add_floppy(help_text, filename):
return " --disk path=%s,device=floppy,ro" % filename
def add_vnc(help_text, vnc_port=None):
if vnc_port:
return " --vnc --vncport=%d" % (vnc_port)
else:
return " --vnc"
def add_vnclisten(help_text, vnclisten):
if has_option(help_text, "vnclisten"):
return " --vnclisten=%s" % (vnclisten)
else:
return ""
def add_sdl(help_text):
if has_option(help_text, "sdl"):
return " --sdl"
else:
return ""
def add_nographic(help_text):
return " --nographics"
def add_video(help_text, video_device):
if has_option(help_text, "video"):
return " --video=%s" % (video_device)
else:
return ""
def add_uuid(help_text, uuid):
if has_option(help_text, "uuid"):
return " --uuid %s" % uuid
else:
return ""
def add_os_type(help_text, os_type):
if has_option(help_text, "os-type"):
return " --os-type %s" % os_type
else:
return ""
def add_os_variant(help_text, os_variant):
if has_option(help_text, "os-variant"):
return " --os-variant %s" % os_variant
else:
return ""
def add_pcidevice(help_text, pci_device):
if has_option(help_text, "host-device"):
return " --host-device %s" % pci_device
else:
return ""
def add_soundhw(help_text, sound_device):
if has_option(help_text, "soundhw"):
return " --soundhw %s" % sound_device
else:
return ""
def add_serial(help_text):
if has_option(help_text, "serial"):
return " --serial pty"
def add_kernel_cmdline(help_text, cmdline):
return " -append %s" % cmdline
def add_connect_uri(help_text, uri):
if uri and has_option(help_text, "connect"):
return " --connect=%s" % uri
else:
return ""
def add_nic(help_text, nic_params):
"""
Return additional command line params based on dict-like nic_params
"""
mac = nic_params.get('mac')
nettype = nic_params.get('nettype')
netdst = nic_params.get('netdst')
nic_model = nic_params.get('nic_model')
if nettype:
result = " --network=%s" % nettype
else:
result = ""
if has_option(help_text, "bridge"):
# older libvirt (--network=NATdev --bridge=bridgename --mac=mac)
if nettype != 'user':
result += ':%s' % netdst
if mac: # possible to specify --mac w/o --network
result += " --mac=%s" % mac
else:
# newer libvirt (--network=mynet,model=virtio,mac=00:11)
if nettype != 'user':
result += '=%s' % netdst
if nettype and nic_model: # only supported along with nettype
result += ",model=%s" % nic_model
if nettype and mac:
result += ',mac=%s' % mac
elif mac: # possible to specify --mac w/o --network
result += " --mac=%s" % mac
logging.debug("vm.make_create_command.add_nic returning: %s"
% result)
return result
# 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
# Clone this VM using the new params
vm = self.clone(name, params, root_dir, copy_state=True)
virt_install_binary = utils_misc.get_path(
root_dir,
params.get("virt_install_binary",
"virt-install"))
help_text = utils.system_output("%s --help" % virt_install_binary)
# Find all supported machine types, so we can rule out an unsupported
# machine type option passed in the configuration.
hvm_or_pv = params.get("hvm_or_pv", "hvm")
# default to 'uname -m' output
arch_name = params.get("vm_arch_name", utils.get_current_kernel_arch())
capabs = libvirt_xml.CapabilityXML()
support_machine_type = capabs.os_arch_machine_map[hvm_or_pv][arch_name]
logging.debug("Machine types supported for %s\%s: %s" % (hvm_or_pv,
arch_name, support_machine_type))
# Start constructing the qemu command
virt_install_cmd = ""
# Set the X11 display parameter if requested
if params.get("x11_display"):
virt_install_cmd += "DISPLAY=%s " % params.get("x11_display")
# Add the qemu binary
virt_install_cmd += virt_install_binary
# set connect uri
virt_install_cmd += add_connect_uri(help_text, self.connect_uri)
# hvm or pv specificed by libvirt switch (pv used by Xen only)
if hvm_or_pv:
virt_install_cmd += add_hvm_or_pv(help_text, hvm_or_pv)
# Add the VM's name
virt_install_cmd += add_name(help_text, name)
machine_type = params.get("machine_type")
if machine_type:
if machine_type in support_machine_type:
virt_install_cmd += add_machine_type(help_text, machine_type)
else:
raise error.TestNAError("Unsupported machine type %s." %
(machine_type))
mem = params.get("mem")
if mem:
virt_install_cmd += add_mem(help_text, mem)
# TODO: should we do the check before we call ? negative case ?
check_cpu = params.get("use_check_cpu")
if check_cpu:
virt_install_cmd += add_check_cpu(help_text)
smp = params.get("smp")
if smp:
virt_install_cmd += add_smp(help_text, smp)
# TODO: directory location for vmlinuz/kernel for cdrom install ?
location = None
if params.get("medium") == 'url':
location = params.get('url')
elif params.get("medium") == 'kernel_initrd':
# directory location of kernel/initrd pair (directory layout must
# be in format libvirt will recognize)
location = params.get("image_dir")
elif params.get("medium") == 'nfs':
location = "nfs:%s:%s" % (params.get("nfs_server"),
params.get("nfs_dir"))
elif params.get("medium") == 'cdrom':
if params.get("use_libvirt_cdrom_switch") == 'yes':
virt_install_cmd += add_cdrom(help_text, params.get("cdrom_cd1"))
elif params.get("unattended_delivery_method") == "integrated":
virt_install_cmd += add_cdrom(help_text,
os.path.join(
data_dir.get_data_dir(),
params.get("cdrom_unattended")
))
else:
location = data_dir.get_data_dir()
kernel_dir = os.path.dirname(params.get("kernel"))
kernel_parent_dir = os.path.dirname(kernel_dir)
pxeboot_link = os.path.join(kernel_parent_dir, "pxeboot")
if os.path.islink(pxeboot_link):
os.unlink(pxeboot_link)
if os.path.isdir(pxeboot_link):
logging.info("Removed old %s leftover directory",
pxeboot_link)
shutil.rmtree(pxeboot_link)
os.symlink(kernel_dir, pxeboot_link)
elif params.get("medium") == "import":
virt_install_cmd += add_import(help_text)
if location:
virt_install_cmd += add_location(help_text, location)
if params.get("display") == "vnc":
if params.get("vnc_autoport") == "yes":
vm.vnc_autoport = True
else:
vm.vnc_autoport = False
if not vm.vnc_autoport and params.get("vnc_port"):
vm.vnc_port = int(params.get("vnc_port"))
virt_install_cmd += add_vnc(help_text, vm.vnc_port)
if params.get("vnclisten"):
vm.vnclisten = params.get("vnclisten")
virt_install_cmd += add_vnclisten(help_text, vm.vnclisten)
elif params.get("display") == "sdl":
virt_install_cmd += add_sdl(help_text)
elif params.get("display") == "nographic":
virt_install_cmd += add_nographic(help_text)
video_device = params.get("video_device")
if video_device:
virt_install_cmd += add_video(help_text, video_device)
sound_device = params.get("sound_device")
if sound_device:
virt_install_cmd += add_soundhw(help_text, sound_device)
# if none is given a random UUID will be generated by libvirt
if params.get("uuid"):
virt_install_cmd += add_uuid(help_text, params.get("uuid"))
# selectable OS type
if params.get("use_os_type") == "yes":
virt_install_cmd += add_os_type(help_text, params.get("os_type"))
# selectable OS variant
if params.get("use_os_variant") == "yes":
virt_install_cmd += add_os_variant(help_text, params.get("os_variant"))
# Add serial console
virt_install_cmd += add_serial(help_text)
# If the PCI assignment step went OK, add each one of the PCI assigned
# devices to the command line.
if self.pci_devices:
for pci_id in self.pci_devices:
virt_install_cmd += add_pcidevice(help_text, pci_id)
for image_name in params.objects("images"):
image_params = params.object_params(image_name)
base_dir = image_params.get("images_base_dir",
data_dir.get_data_dir())
filename = storage.get_image_filename(image_params,
base_dir)
if image_params.get("use_storage_pool") == "yes":
filename = None
virt_install_cmd += add_drive(help_text,
filename,
image_params.get("image_pool"),
image_params.get("image_vol"),
image_params.get("image_device"),
image_params.get("image_bus"),
image_params.get("image_perms"),
image_params.get("image_size"),
image_params.get("drive_sparse"),
image_params.get("drive_cache"),
image_params.get("image_format"))
if image_params.get("boot_drive") == "no":
continue
if filename:
virt_install_cmd += add_drive(help_text,
filename,
None,
None,
None,
image_params.get("drive_format"),
None,
image_params.get("image_size"),
image_params.get("drive_sparse"),
image_params.get("drive_cache"),
image_params.get("image_format"))
if (params.get('unattended_delivery_method') != 'integrated' and
not (self.driver_type == 'xen' and params.get('hvm_or_pv') == 'pv')):
for cdrom in params.objects("cdroms"):
cdrom_params = params.object_params(cdrom)
iso = cdrom_params.get("cdrom")
if params.get("use_libvirt_cdrom_switch") == 'yes':
# we don't want to skip the winutils iso
if not cdrom == 'winutils':
logging.debug("Using --cdrom instead of --disk for install")
logging.debug("Skipping CDROM:%s:%s", cdrom, iso)
continue
if params.get("medium") == 'cdrom_no_kernel_initrd':
if iso == params.get("cdrom_cd1"):
logging.debug("Using cdrom or url for install")
logging.debug("Skipping CDROM: %s", iso)
continue
if iso:
virt_install_cmd += add_drive(help_text,
utils_misc.get_path(root_dir, iso),
image_params.get("iso_image_pool"),
image_params.get("iso_image_vol"),
'cdrom',
None,
None,
None,
None,
None,
None)
# We may want to add {floppy_otps} parameter for -fda
# {fat:floppy:}/path/. However vvfat is not usually recommended.
# Only support to add the main floppy if you want to add the second
# one please modify this part.
floppy = params.get("floppy_name")
if floppy:
floppy = utils_misc.get_path(data_dir.get_data_dir(), floppy)
virt_install_cmd += add_drive(help_text, floppy,
None,
None,
'floppy',
None,
None,
None,
None,
None,
None)
# setup networking parameters
for nic in vm.virtnet:
# make_create_command can be called w/o vm.create()
nic = vm.add_nic(**dict(nic))
logging.debug("make_create_command() setting up command for"
" nic: %s" % str(nic))
virt_install_cmd += add_nic(help_text, nic)
if params.get("use_no_reboot") == "yes":
virt_install_cmd += " --noreboot"
if params.get("use_autostart") == "yes":
virt_install_cmd += " --autostart"
if params.get("virt_install_debug") == "yes":
virt_install_cmd += " --debug"
# bz still open, not fully functional yet
if params.get("use_virt_install_wait") == "yes":
virt_install_cmd += (" --wait %s" %
params.get("virt_install_wait_time"))
kernel_params = params.get("kernel_params")
if kernel_params:
virt_install_cmd += " --extra-args '%s'" % kernel_params
virt_install_cmd += " --noautoconsole"
return virt_install_cmd
def setup_serial_console(self):
self.serial_console = aexpect.ShellSession(
"virsh console %s" % self.name, auto_close=False)
def set_root_serial_console(self, device, remove=False):
"""
Allow or ban root to login through serial console.
@param device: device to set root login
@param allow_root: do remove operation
"""
try:
session = self.login()
except (remote.LoginError, virt_vm.VMError), e:
logging.debug(e)
else:
try:
securetty_output = session.cmd_output("cat /etc/securetty")
devices = str(securetty_output).strip().splitlines()
if device not in devices:
if not remove:
session.sendline("echo %s >> /etc/securetty" % device)
else:
if remove:
session.sendline("sed -i -e /%s/d /etc/securetty"
% device)
logging.debug("Set root login for %s successfuly.", device)
return True
finally:
session.close()
logging.debug("Set root login for %s failed.", device)
return False
def set_kernel_console(self, device, speed=None, remove=False):
"""
Set kernel parameter for given console device.
@param device: a console device
@param speed: speed of serial console
@param remove: do remove operation
"""
try:
session = self.login()
except (remote.LoginError, virt_vm.VMError), e:
logging.debug(e)
else:
try:
grub = "/etc/grub.cfg"
if session.cmd_status("ls /etc/grub2.cfg"):
grub = "/etc/grub2.cfg"
kernel_params = "console=%s" % device
if speed is not None:
kernel_params += ",%s" % speed
output = session.cmd_output("cat %s" % grub)
if not re.search("console=%s" % device, output):
if not remove:
session.sendline("sed -i -e \'s/vmlinuz-.*/& %s/g\' %s"
% (kernel_params, grub))
else:
if remove:
session.sendline("sed -i -e \'s/console=%s\w*\s//g\'"
" %s" % (device, grub))
logging.debug("Set kernel params for %s successfully.", device)
return True
finally:
session.close()
logging.debug("Set kernel params for %s failed.", device)
return False
def set_console_getty(self, device, getty="mgetty", remove=False):
"""
Set getty for given console device.
@param device: a console device
@param getty: getty type: agetty, mgetty and so on.
@param remove: do remove operation
"""
try:
session = self.login()
except (remote.LoginError, virt_vm.VMError), e:
logging.debug(e)
else:
try:
# Only configurate RHEL5 and below
regex = "gettys are handled by"
output = session.cmd_output("cat /etc/inittab")
if re.search(regex, output):
logging.debug("Skip setting inittab for %s", device)
return True
getty_str = "co:2345:respawn:/sbin/%s %s" % (getty, device)
matched_str = "respawn:/sbin/*getty %s" % device
if not re.search(matched_str, output):
if not remove:
session.sendline("echo %s >> /etc/inittab" % getty_str)
else:
if remove:
session.sendline("sed -i -e /%s/d "
"/etc/inittab" % matched_str)
logging.debug("Set inittab for %s successfuly.", device)
return True
finally:
session.close()
logging.debug("Set inittab for %s failed.", device)
return False
@error.context_aware
def create(self, name=None, params=None, root_dir=None, timeout=5.0,
migration_mode=None, mac_source=None, autoconsole=True):
"""
Start the VM by running a qemu command.
All parameters are optional. If name, params or root_dir are not
supplied, the respective values stored as class attributes are used.
@param name: The name of the object
@param params: A dict containing VM params
@param root_dir: Base directory for relative filenames
@param migration_mode: If supplied, start VM for incoming migration
using this protocol (either 'tcp', 'unix' or 'exec')
@param migration_exec_cmd: Command to embed in '-incoming "exec: ..."'
(e.g. 'gzip -c -d filename') if migration_mode is 'exec'
@param mac_source: A VM object from which to copy MAC addresses. If not
specified, new addresses will be generated.
@raise VMCreateError: If qemu terminates unexpectedly
@raise VMKVMInitError: If KVM initialization fails
@raise VMHugePageError: If hugepage initialization fails
@raise VMImageMissingError: If a CD image is missing
@raise VMHashMismatchError: If a CD image hash has doesn't match the
expected hash
@raise VMBadPATypeError: If an unsupported PCI assignment type is
requested
@raise VMPAError: If no PCI assignable devices could be assigned
"""
error.context("creating '%s'" % self.name)
self.destroy(free_mac_addresses=False)
if name is not None:
self.name = name
if params is not None:
self.params = params
if root_dir is not None:
self.root_dir = root_dir
name = self.name
params = self.params
root_dir = self.root_dir
# Verify the md5sum of the ISO images
for cdrom in params.objects("cdroms"):
if params.get("medium") == "import":
break
cdrom_params = params.object_params(cdrom)
iso = cdrom_params.get("cdrom")
if ((self.driver_type == 'xen') and
(params.get('hvm_or_pv') == 'pv') and
(os.path.basename(iso) == 'ks.iso')):
continue
if iso:
iso = utils_misc.get_path(data_dir.get_data_dir(), iso)
if not os.path.exists(iso):
raise virt_vm.VMImageMissingError(iso)
compare = False
if cdrom_params.get("md5sum_1m"):
logging.debug("Comparing expected MD5 sum with MD5 sum of "
"first MB of ISO file...")
actual_hash = utils.hash_file(iso, 1048576, method="md5")
expected_hash = cdrom_params.get("md5sum_1m")
compare = True
elif cdrom_params.get("md5sum"):
logging.debug("Comparing expected MD5 sum with MD5 sum of "
"ISO file...")
actual_hash = utils.hash_file(iso, method="md5")
expected_hash = cdrom_params.get("md5sum")
compare = True
elif cdrom_params.get("sha1sum"):
logging.debug("Comparing expected SHA1 sum with SHA1 sum "
"of ISO file...")
actual_hash = utils.hash_file(iso, method="sha1")
expected_hash = cdrom_params.get("sha1sum")
compare = True
if compare:
if actual_hash == expected_hash:
logging.debug("Hashes match")
else:
raise virt_vm.VMHashMismatchError(actual_hash,
expected_hash)
# Make sure the following code is not executed by more than one thread
# at the same time
lockfile = open("/tmp/libvirt-autotest-vm-create.lock", "w+")
fcntl.lockf(lockfile, fcntl.LOCK_EX)
try:
# Handle port redirections
redir_names = params.objects("redirs")
host_ports = utils_misc.find_free_ports(5000, 6000, len(redir_names))
self.redirs = {}
for i in range(len(redir_names)):
redir_params = params.object_params(redir_names[i])
guest_port = int(redir_params.get("guest_port"))
self.redirs[guest_port] = host_ports[i]
# Find available PCI devices
self.pci_devices = []
for device in params.objects("pci_devices"):
self.pci_devices.append(device)
# Find available VNC port, if needed
if params.get("display") == "vnc":
if params.get("vnc_autoport") == "yes":
self.vnc_port = None
self.vnc_autoport = True
else: