forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirt_vm.py
1263 lines (1004 loc) · 41.9 KB
/
virt_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
import logging, time, glob, os, re
from autotest.client.shared import error
import utils_misc, utils_net, remote
class VMError(Exception):
pass
class VMCreateError(VMError):
def __init__(self, cmd, status, output):
VMError.__init__(self, cmd, status, output)
self.cmd = cmd
self.status = status
self.output = output
def __str__(self):
return ("VM creation command failed: %r (status: %s, "
"output: %r)" % (self.cmd, self.status, self.output))
class VMStartError(VMError):
def __init__(self, name, reason=None):
VMError.__init__(self, name, reason)
self.name = name
self.reason = reason
def __str__(self):
msg = "VM '%s' failed to start" % self.name
if self.reason is not None:
msg += ": %s" % self.reason
return msg
class VMConfigMissingError(VMError):
def __init__(self, name, config):
VMError.__init__(self, name, config)
self.name = name
self.config = config
def __str__(self):
return "Missing config '%s' for VM %s" % (self.config, self.name)
class VMHashMismatchError(VMError):
def __init__(self, actual, expected):
VMError.__init__(self, actual, expected)
self.actual_hash = actual
self.expected_hash = expected
def __str__(self):
return ("CD image hash (%s) differs from expected one (%s)" %
(self.actual_hash, self.expected_hash))
class VMImageMissingError(VMError):
def __init__(self, filename):
VMError.__init__(self, filename)
self.filename = filename
def __str__(self):
return "CD image file not found: %r" % self.filename
class VMImageCheckError(VMError):
def __init__(self, filename):
VMError.__init__(self, filename)
self.filename = filename
def __str__(self):
return "Errors found on image: %r" % self.filename
class VMBadPATypeError(VMError):
def __init__(self, pa_type):
VMError.__init__(self, pa_type)
self.pa_type = pa_type
def __str__(self):
return "Unsupported PCI assignable type: %r" % self.pa_type
class VMPAError(VMError):
def __init__(self, pa_type):
VMError.__init__(self, pa_type)
self.pa_type = pa_type
def __str__(self):
return ("No PCI assignable devices could be assigned "
"(pci_assignable=%r)" % self.pa_type)
class VMPostCreateError(VMError):
def __init__(self, cmd, output):
VMError.__init__(self, cmd, output)
self.cmd = cmd
self.output = output
class VMHugePageError(VMPostCreateError):
def __str__(self):
return ("Cannot allocate hugepage memory (command: %r, "
"output: %r)" % (self.cmd, self.output))
class VMKVMInitError(VMPostCreateError):
def __str__(self):
return ("Cannot initialize KVM (command: %r, output: %r)" %
(self.cmd, self.output))
class VMDeadError(VMError):
def __init__(self, reason='', detail=''):
VMError.__init__(self)
self.reason = reason
self.detail = detail
def __str__(self):
msg = "VM is dead"
if self.reason:
msg += " reason: %s" % self.reason
if self.detail:
msg += " detail: %r" % self.detail
return (msg)
class VMDeadKernelCrashError(VMError):
def __init__(self, kernel_crash):
VMError.__init__(self, kernel_crash)
self.kernel_crash = kernel_crash
def __str__(self):
return ("VM is dead due to a kernel crash:\n%s" % self.kernel_crash)
class VMInvalidInstructionCode(VMError):
def __init__(self, invalid_code):
VMError.__init__(self, invalid_code)
self.invalid_code = invalid_code
def __str__(self):
error = ""
for invalid_code in self.invalid_code:
error += "%s" % (invalid_code)
return ("Invalid instruction was executed on VM:\n%s" % error)
class VMAddressError(VMError):
pass
class VMPortNotRedirectedError(VMAddressError):
def __init__(self, port):
VMAddressError.__init__(self, port)
self.port = port
def __str__(self):
return "Port not redirected: %s" % self.port
class VMAddressVerificationError(VMAddressError):
def __init__(self, mac, ip):
VMAddressError.__init__(self, mac, ip)
self.mac = mac
self.ip = ip
def __str__(self):
return ("Could not verify DHCP lease: "
"%s --> %s" % (self.mac, self.ip))
class VMMACAddressMissingError(VMAddressError):
def __init__(self, nic_index):
VMAddressError.__init__(self, nic_index)
self.nic_index = nic_index
def __str__(self):
return "No MAC defined for NIC #%s" % self.nic_index
class VMIPAddressMissingError(VMAddressError):
def __init__(self, mac):
VMAddressError.__init__(self, mac)
self.mac = mac
def __str__(self):
return "No DHCP lease for MAC %s" % self.mac
class VMUnknownNetTypeError(VMError):
def __init__(self, vmname, nicname, nettype):
super(VMUnknownNetTypeError, self).__init__()
self.vmname = vmname
self.nicname = nicname
self.nettype = nettype
def __str__(self):
return "Unknown nettype '%s' requested for NIC %s on VM %s" % (
self.nettype, self.nicname, self.vmname)
class VMAddNetDevError(VMError):
pass
class VMDelNetDevError(VMError):
pass
class VMAddNicError(VMError):
pass
class VMDelNicError(VMError):
pass
class VMMigrateError(VMError):
pass
class VMMigrateTimeoutError(VMMigrateError):
pass
class VMMigrateCancelError(VMMigrateError):
pass
class VMMigrateFailedError(VMMigrateError):
pass
class VMMigrateProtoUnknownError(error.TestNAError):
def __init__(self, protocol):
self.protocol = protocol
def __str__(self):
return ("Virt Test doesn't know migration protocol '%s'. "
"You would have to add it to the list of known protocols" %
self.protocol)
class VMMigrateStateMismatchError(VMMigrateError):
def __init__(self):
VMMigrateError.__init__(self)
def __str__(self):
return ("Mismatch of VM state before and after migration")
class VMRebootError(VMError):
pass
class VMStatusError(VMError):
pass
class VMRemoveError(VMError):
pass
class VMDeviceError(VMError):
pass
class VMDeviceNotSupportedError(VMDeviceError):
def __init__(self, name, device):
VMDeviceError.__init__(self, name, device)
self.name = name
self.device = device
def __str__(self):
return ("Device '%s' is not supported for vm '%s' on this Host." %
(self.device, self.name))
class VMPCIDeviceError(VMDeviceError):
pass
class VMPCISlotInUseError(VMPCIDeviceError):
def __init__(self, name, slot):
VMPCIDeviceError.__init__(self, name, slot)
self.name = name
self.slot = slot
def __str__(self):
return ("PCI slot '0x%s' is already in use on vm '%s'. Please assign"
" another slot in config file." % (self.slot, self.name))
class VMPCIOutOfRangeError(VMPCIDeviceError):
def __init__(self, name, max_dev_num):
VMPCIDeviceError.__init__(self, name, max_dev_num)
self.name = name
self.max_dev_num = max_dev_num
def __str__(self):
return ("Too many PCI devices added on vm '%s', max supported '%s'" %
(self.name, str(self.max_dev_num)))
class VMUSBError(VMError):
pass
class VMUSBControllerError(VMUSBError):
pass
class VMUSBControllerMissingError(VMUSBControllerError):
def __init__(self, name, controller_type):
VMUSBControllerError.__init__(self, name, controller_type)
self.name = name
self.controller_type = controller_type
def __str__(self):
return ("Could not find '%s' USB Controller on vm '%s'. Please "
"check config files." % (self.controller_type, self.name))
class VMUSBControllerPortFullError(VMUSBControllerError):
def __init__(self, name, usb_dev_dict):
VMUSBControllerError.__init__(self, name, usb_dev_dict)
self.name = name
self.usb_dev_dict = usb_dev_dict
def __str__(self):
output = ""
try:
for ctl, dev_list in self.usb_dev_dict.iteritems():
output += "%s: %s\n" %(ctl, dev_list)
except Exception:
pass
return ("No available USB port left on VM %s.\n"
"USB devices map is: \n%s" % (self.name, output))
class VMUSBPortInUseError(VMUSBError):
def __init__(self, vm_name, controller, port):
VMUSBError.__init__(self, vm_name, controller, port)
self.vm_name = vm_name
self.controller = controller
self.port = port
def __str__(self):
return ("USB port '%d' of controller '%s' is already in use on vm"
" '%s'. Please assign another port in config file." %
(self.port, self.controller, self.vm_name))
class VMScreenInactiveError(VMError):
def __init__(self, vm, inactive_time):
VMError.__init__(self)
self.vm = vm
self.inactive_time = inactive_time
def __str__(self):
msg = ("%s screen is inactive for %d s (%d min)" %
(self.vm.name, self.inactive_time, self.inactive_time/60))
return msg
class CpuInfo(object):
"""
A class for VM's cpu information.
"""
def __init__(self, model=None, vendor=None, flags=None, family=None,
smp=0, maxcpus=0, sockets=0, cores=0, threads=0):
"""
@param model: CPU Model of VM (use 'qemu -cpu ?' for list)
@param vendor: CPU Vendor of VM
@param flags: CPU Flags of VM
@param flags: CPU Family of VM
@param smp: set the number of CPUs to 'n' [default=1]
@param maxcpus: maximum number of total cpus, including
offline CPUs for hotplug, etc
@param cores: number of CPU cores on one socket
@param threads: number of threads on one CPU core
@param sockets: number of discrete sockets in the system
"""
self.model = model
self.vendor = vendor
self.flags = flags
self.family = family
self.smp = smp
self.maxcpus = maxcpus
self.sockets = sockets
self.cores = cores
self.threads = threads
class BaseVM(object):
"""
Base class for all hypervisor specific VM subclasses.
This class should not be used directly, that is, do not attempt to
instantiate and use this class. Instead, one should implement a subclass
that implements, at the very least, all methods defined right after the
the comment blocks that are marked with:
"Public API - *must* be reimplemented with virt specific code"
and
"Protected API - *must* be reimplemented with virt specific classes"
The current proposal regarding methods naming convention is:
- Public API methods: named in the usual way, consumed by tests
- Protected API methods: name begins with a single underline, to be
consumed only by BaseVM and subclasses
- Private API methods: name begins with double underline, to be consumed
only by the VM subclass itself (usually implements virt specific
functionality: example: __make_qemu_command())
So called "protected" methods are intended to be used only by VM classes,
and not be consumed by tests. Theses should respect a naming convention
and always be preceeded by a single underline.
Currently most (if not all) methods are public and appears to be consumed
by tests. It is a ongoing task to determine whether methods should be
"public" or "protected".
"""
#
# Assuming that all low-level hypervisor have at least migration via tcp
# (true for xen & kvm). Also true for libvirt (using xen and kvm drivers)
#
MIGRATION_PROTOS = ['tcp', ]
#
# Timeout definition. This is being kept inside the base class so that
# sub classes can change the default just for themselves
#
LOGIN_TIMEOUT = 10
LOGIN_WAIT_TIMEOUT = 240
COPY_FILES_TIMEOUT = 600
MIGRATE_TIMEOUT = 3600
REBOOT_TIMEOUT = 240
CREATE_TIMEOUT = 5
def __init__(self, name, params):
self.name = name
self.params = params
#
# Assuming all low-level hypervisors will have a serial (like) console
# connection to the guest. libvirt also supports serial (like) consoles
# (virDomainOpenConsole). subclasses should set this to an object that
# is or behaves like aexpect.ShellSession.
#
self.serial_console = None
self.remote_sessions = []
# Create instance if not already set
if not hasattr(self, 'instance'):
self._generate_unique_id()
# Don't overwrite existing state, update from params
if hasattr(self, 'virtnet'):
# Direct reference to self.virtnet makes pylint complain
# note: virtnet.__init__() supports being called anytime
getattr(self, 'virtnet').__init__(self.params,
self.name,
self.instance)
else: # Create new
self.virtnet = utils_net.VirtNet(self.params,
self.name,
self.instance)
if not hasattr(self, 'cpuinfo'):
self.cpuinfo = CpuInfo()
def _generate_unique_id(self):
"""
Generate a unique identifier for this VM
"""
while True:
self.instance = (time.strftime("%Y%m%d-%H%M%S-") +
utils_misc.generate_random_string(8))
if not glob.glob("/tmp/*%s" % self.instance):
break
@staticmethod
def lookup_vm_class(vm_type, target):
if vm_type == 'qemu':
import qemu_vm
return qemu_vm.VM
if vm_type == 'libvirt':
import libvirt_vm
return libvirt_vm.VM
if vm_type == 'v2v':
if target == 'libvirt' or target is None:
import libvirt_vm
return libvirt_vm.VM
if target == 'ovirt':
import ovirt
return ovirt.VMManager
#
# Public API - could be reimplemented with virt specific code
#
def needs_restart(self, name, params, basedir):
"""
Verifies whether the current virt_install commandline matches the
requested one, based on the test parameters.
"""
try:
need_restart = (self.make_create_command() !=
self.make_create_command(name, params, basedir))
except Exception:
need_restart = True
if need_restart:
logging.debug("VM params in env don't match requested, restarting.")
return True
else:
# Command-line encoded state doesn't include all params
# TODO: Check more than just networking
other_virtnet = utils_net.VirtNet(params, name, self.instance)
if self.virtnet != other_virtnet:
logging.debug("VM params in env match, but network differs, "
"restarting")
logging.debug("\t" + str(self.virtnet))
logging.debug("\t!=")
logging.debug("\t" + str(other_virtnet))
return True
else:
logging.debug("VM params in env do match requested, continuing.")
return False
def verify_alive(self):
"""
Make sure the VM is alive and that the main monitor is responsive.
Can be subclassed to provide better information on why the VM is
not alive (reason, detail)
@raise VMDeadError: If the VM is dead
@raise: Various monitor exceptions if the monitor is unresponsive
"""
if self.is_dead():
raise VMDeadError
def get_mac_address(self, nic_index=0):
"""
Return the MAC address of a NIC.
@param nic_index: Index of the NIC
@raise VMMACAddressMissingError: If no MAC address is defined for the
requested NIC
"""
try:
mac = self.virtnet[nic_index].mac
return mac
except KeyError:
raise VMMACAddressMissingError(nic_index)
def get_address(self, index=0):
"""
Return the IP address of a NIC or guest (in host space).
@param index: Name or index of the NIC whose address is requested.
@return: 'localhost': Port redirection is in use
@return: IP address of NIC if valid in arp cache.
@raise VMMACAddressMissingError: If no MAC address is defined for the
requested NIC
@raise VMIPAddressMissingError: If no IP address is found for the the
NIC's MAC address
@raise VMAddressVerificationError: If the MAC-IP address mapping cannot
be verified (using arping)
"""
nic = self.virtnet[index]
# TODO: Determine port redirection in use w/o checking nettype
if nic.nettype not in ['bridge', 'macvtap']:
return "localhost"
if not nic.has_key('mac') and self.params.get('vm_type') == 'libvirt':
# Look it up from xml
nic.mac = self.get_virsh_mac_address(index)
# else TODO: Look up mac from existing qemu-kvm process
if not nic.has_key('mac'):
raise VMMACAddressMissingError(index)
# Get the IP address from arp cache, try upper and lower case
arp_ip = self.address_cache.get(nic.mac.upper())
if not arp_ip:
arp_ip = self.address_cache.get(nic.mac.lower())
if not arp_ip and os.geteuid() != 0:
# For non-root, tcpdump won't work for finding IP address, try arp
ip_map = utils_net.parse_arp()
arp_ip = ip_map.get(nic.mac.lower())
if arp_ip:
self.address_cache[nic.mac.lower()] = arp_ip
if not arp_ip:
raise VMIPAddressMissingError(nic.mac)
# Make sure the IP address is assigned to one or more macs
# for this guest
macs = self.virtnet.mac_list()
if not utils_net.verify_ip_address_ownership(arp_ip, macs):
raise VMAddressVerificationError(nic.mac, arp_ip)
logging.debug('Found/Verified IP %s for VM %s NIC %s' % (
arp_ip, self.name, str(index)))
return arp_ip
def fill_addrs(self, addrs):
"""
Fill VM's nic address to the virtnet structure based on VM's address
structure addrs.
@param addrs: Dict of interfaces and address
{"if_name":{"mac":['addrs',],
"ipv4":['addrs',],
"ipv6":['addrs',]},
...}
"""
for virtnet in self.virtnet:
for iface_name, iface in addrs.iteritems():
if virtnet.mac in iface["mac"]:
virtnet.ip = {"ipv4": iface["ipv4"],
"ipv6": iface["ipv6"]}
virtnet.g_nic_name = iface_name
def get_port(self, port, nic_index=0):
"""
Return the port in host space corresponding to port in guest space.
@param port: Port number in host space.
@param nic_index: Index of the NIC.
@return: If port redirection is used, return the host port redirected
to guest port port. Otherwise return port.
@raise VMPortNotRedirectedError: If an unredirected port is requested
in user mode
"""
nic_nettype = self.virtnet[nic_index].nettype
if nic_nettype in ["bridge", "macvtap"]:
return port
else:
try:
return self.redirs[port]
except KeyError:
raise VMPortNotRedirectedError(port)
def free_mac_address(self, nic_index_or_name=0):
"""
Free a NIC's MAC address.
@param nic_index: Index of the NIC
"""
self.virtnet.free_mac_address(nic_index_or_name)
@error.context_aware
def wait_for_get_address(self, nic_index_or_name, timeout=30, internal_timeout=1):
"""
Wait for a nic to acquire an IP address, then return it.
"""
# Don't let VMIPAddressMissingError/VMAddressVerificationError through
def _get_address():
try:
return self.get_address(nic_index_or_name)
except (VMIPAddressMissingError, VMAddressVerificationError):
return False
if not utils_misc.wait_for(_get_address, timeout, internal_timeout):
raise VMIPAddressMissingError(self.virtnet[nic_index_or_name].mac)
return self.get_address(nic_index_or_name)
# Adding/setup networking devices methods split between 'add_*' for
# setting up virtnet, and 'activate_' for performing actions based
# on settings.
def add_nic(self, **params):
"""
Add new or setup existing NIC with optional model type and mac address
@param: **params: Additional NIC parameters to set.
@param: nic_name: Name for device
@param: mac: Optional MAC address, None to randomly generate.
@param: ip: Optional IP address to register in address_cache
@return: Dict with new NIC's info.
"""
if not params.has_key('nic_name'):
params['nic_name'] = utils_misc.generate_random_id()
nic_name = params['nic_name']
if nic_name in self.virtnet.nic_name_list():
self.virtnet[nic_name].update(**params)
else:
self.virtnet.append(params)
nic = self.virtnet[nic_name]
if not nic.has_key('mac'): # generate random mac
logging.debug("Generating random mac address for nic")
self.virtnet.generate_mac_address(nic_name)
# mac of '' or invaid format results in not setting a mac
if nic.has_key('ip') and nic.has_key('mac'):
if not self.address_cache.has_key(nic.mac):
logging.debug("(address cache) Adding static "
"cache entry: %s ---> %s" % (nic.mac, nic.ip))
else:
logging.debug("(address cache) Updating static "
"cache entry from: %s ---> %s"
" to: %s ---> %s" % (nic.mac,
self.address_cache[nic.mac], nic.mac, nic.ip))
self.address_cache[nic.mac] = nic.ip
return nic
def del_nic(self, nic_index_or_name):
"""
Remove the nic specified by name, or index number
"""
nic = self.virtnet[nic_index_or_name]
nic_mac = nic.mac.lower()
self.free_mac_address(nic_index_or_name)
try:
del self.virtnet[nic_index_or_name]
del self.address_cache[nic_mac]
except IndexError:
pass # continue to not exist
except KeyError:
pass # continue to not exist
def verify_kernel_crash(self):
"""
Find kernel crash message on the VM serial console.
@raise: VMDeadKernelCrashError, in case a kernel crash message was
found.
"""
panic_re = [r"BUG:.*---\[ end trace .* \]---"]
panic_re.append(r"----------\[ cut here.* BUG .*\[ end trace .* \]---")
panic_re.append(r"general protection fault:.* RSP.*>")
panic_re = "|".join(panic_re)
if self.serial_console is not None:
data = self.serial_console.get_output()
match = re.search(panic_re, data, re.DOTALL|re.MULTILINE|re.I)
if match is not None:
raise VMDeadKernelCrashError(match.group(0))
def verify_illegal_instruction(self):
"""
Find illegal instruction code on VM serial console output.
@raise: VMInvalidInstructionCode, in case a wrong instruction code.
"""
if self.serial_console is not None:
data = self.serial_console.get_output()
match = re.findall(r".*trap invalid opcode.*\n", data,
re.MULTILINE)
if match:
raise VMInvalidInstructionCode(match)
def get_params(self):
"""
Return the VM's params dict. Most modified params take effect only
upon VM.create().
"""
return self.params
def get_testlog_filename(self):
"""
Return the testlog filename.
"""
return "/tmp/testlog-%s" % self.instance
def get_virtio_port_filename(self, port_name):
"""
Return the filename corresponding to a givven monitor name.
"""
return "/tmp/virtio_port-%s-%s" % (port_name, self.instance)
def get_virtio_port_filenames(self):
"""
Return a list of all virtio port filenames (as specified in the VM's
params).
"""
return [self.get_virtio_port_filename(v) for v in
self.params.objects("virtio_ports")]
@error.context_aware
def login(self, nic_index=0, timeout=LOGIN_TIMEOUT,
username=None, password=None):
"""
Log into the guest via SSH/Telnet/Netcat.
If timeout expires while waiting for output from the guest (e.g. a
password prompt or a shell prompt) -- fail.
@param nic_index: The index of the NIC to connect to.
@param timeout: Time (seconds) before giving up logging into the
guest.
@return: A ShellSession object.
"""
error.context("logging into '%s'" % self.name)
if not username:
username = self.params.get("username", "")
if not password:
password = self.params.get("password", "")
prompt = self.params.get("shell_prompt", "[\#\$]")
linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n"))
client = self.params.get("shell_client")
address = self.get_address(nic_index)
port = self.get_port(int(self.params.get("shell_port")))
log_filename = ("session-%s-%s.log" %
(self.name, utils_misc.generate_random_string(4)))
session = remote.remote_login(client, address, port, username,
password, prompt, linesep,
log_filename, timeout)
session.set_status_test_command(self.params.get("status_test_command",
""))
self.remote_sessions.append(session)
return session
def remote_login(self, nic_index=0, timeout=LOGIN_TIMEOUT,
username=None, password=None):
"""
Alias for login() for backward compatibility.
"""
return self.login(nic_index, timeout, username, password)
def wait_for_login(self, nic_index=0, timeout=LOGIN_WAIT_TIMEOUT,
internal_timeout=LOGIN_TIMEOUT,
serial=False, restart_network=False,
username=None, password=None):
"""
Make multiple attempts to log into the guest via SSH/Telnet/Netcat.
@param nic_index: The index of the NIC to connect to.
@param timeout: Time (seconds) to keep trying to log in.
@param internal_timeout: Timeout to pass to login().
@param serial: Whether to use a serial connection when remote login
(ssh, rss) failed.
@param restart_network: Whether to try to restart guest's network.
@return: A ShellSession object.
"""
error_messages = []
logging.debug("Attempting to log into '%s' (timeout %ds)", self.name,
timeout)
end_time = time.time() + timeout
while time.time() < end_time:
try:
return self.login(nic_index, internal_timeout,
username, password)
except (remote.LoginError, VMError), e:
self.verify_alive()
e = str(e)
if e not in error_messages:
logging.debug(e)
error_messages.append(e)
time.sleep(2)
# Timeout expired
if serial or restart_network:
# Try to login via serila console
return self.wait_for_serial_login(timeout, internal_timeout,
restart_network,
username, password)
else:
# Try one more time but don't catch exceptions
return self.login(nic_index, internal_timeout, username, password)
@error.context_aware
def copy_files_to(self, host_path, guest_path, nic_index=0, limit="",
verbose=False, timeout=COPY_FILES_TIMEOUT,
username=None, password=None):
"""
Transfer files to the remote host(guest).
@param host_path: Host path
@param guest_path: Guest path
@param nic_index: The index of the NIC to connect to.
@param limit: Speed limit of file transfer.
@param verbose: If True, log some stats using logging.debug (RSS only)
@param timeout: Time (seconds) before giving up on doing the remote
copy.
"""
error.context("sending file(s) to '%s'" % self.name)
if not username:
username = self.params.get("username", "")
if not password:
password = self.params.get("password", "")
client = self.params.get("file_transfer_client")
address = self.get_address(nic_index)
port = self.get_port(int(self.params.get("file_transfer_port")))
log_filename = ("transfer-%s-to-%s-%s.log" %
(self.name, address,
utils_misc.generate_random_string(4)))
remote.copy_files_to(address, client, username, password, port,
host_path, guest_path, limit, log_filename,
verbose, timeout)
utils_misc.close_log_file(log_filename)
@error.context_aware
def copy_files_from(self, guest_path, host_path, nic_index=0, limit="",
verbose=False, timeout=COPY_FILES_TIMEOUT,
username=None,password=None):
"""
Transfer files from the guest.
@param host_path: Guest path
@param guest_path: Host path
@param nic_index: The index of the NIC to connect to.
@param limit: Speed limit of file transfer.
@param verbose: If True, log some stats using logging.debug (RSS only)
@param timeout: Time (seconds) before giving up on doing the remote
copy.
"""
error.context("receiving file(s) from '%s'" % self.name)
if not username:
username = self.params.get("username", "")
if not password:
password = self.params.get("password", "")
client = self.params.get("file_transfer_client")
address = self.get_address(nic_index)
port = self.get_port(int(self.params.get("file_transfer_port")))
log_filename = ("transfer-%s-from-%s-%s.log" %
(self.name, address,
utils_misc.generate_random_string(4)))
remote.copy_files_from(address, client, username, password, port,
guest_path, host_path, limit, log_filename,
verbose, timeout)
utils_misc.close_log_file(log_filename)
@error.context_aware
def serial_login(self, timeout=LOGIN_TIMEOUT,
username=None, password=None):
"""
Log into the guest via the serial console.
If timeout expires while waiting for output from the guest (e.g. a
password prompt or a shell prompt) -- fail.
@param timeout: Time (seconds) before giving up logging into the guest.
@return: ShellSession object on success and None on failure.
"""
error.context("logging into '%s' via serial console" % self.name)
if not username:
username = self.params.get("username", "")
if not password:
password = self.params.get("password", "")
prompt = self.params.get("shell_prompt", "[\#\$]")
linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n"))
status_test_command = self.params.get("status_test_command", "")
self.serial_console.set_linesep(linesep)
self.serial_console.set_status_test_command(status_test_command)
# Try to get a login prompt
self.serial_console.sendline()
remote.handle_prompts(self.serial_console, username, password,
prompt, timeout)
return self.serial_console
def wait_for_serial_login(self, timeout=LOGIN_WAIT_TIMEOUT,
internal_timeout=LOGIN_TIMEOUT,
restart_network=False,
username=None, password=None):
"""
Make multiple attempts to log into the guest via serial console.
@param timeout: Time (seconds) to keep trying to log in.
@param internal_timeout: Timeout to pass to serial_login().
@param restart_network: Whether try to restart guest's network.
@return: A ShellSession object.
"""
error_messages = []
logging.debug("Attempting to log into '%s' via serial console "
"(timeout %ds)", self.name, timeout)
end_time = time.time() + timeout
while time.time() < end_time:
try:
session = self.serial_login(internal_timeout)
if restart_network:
try:
utils_net.restart_guest_network(session)
except Exception:
pass
return session
except remote.LoginError, e:
self.verify_alive()
e = str(e)
if e not in error_messages:
logging.debug(e)
error_messages.append(e)
time.sleep(2)
# Timeout expired; try one more time but don't catch exceptions
return self.serial_login(internal_timeout, username, password)