-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathenv_process.py
2024 lines (1811 loc) · 77.8 KB
/
env_process.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
from __future__ import division
import copy
import glob
import logging
import multiprocessing
import os
import re
import shutil
import sys
import threading
import time
import aexpect
import six
from aexpect import remote
from avocado.core import exceptions
from avocado.utils import archive
from avocado.utils import cpu as cpu_utils
from avocado.utils import crypto
from avocado.utils import process as a_process
from six.moves import xrange
from virttest import (
arch,
cpu,
data_dir,
error_context,
ppm_utils,
qemu_monitor,
qemu_storage,
storage,
test_setup,
utils_kernel_module,
utils_libguestfs,
utils_logfile,
utils_misc,
utils_net,
utils_package,
utils_qemu,
utils_test,
virt_vm,
)
# lazy imports for dependencies that are not needed in all modes of use
from virttest._wrappers import lazy_import
from virttest.test_setup.core import SetupManager
from virttest.test_setup.gcov import ResetQemuGCov
from virttest.test_setup.libvirt_setup import LibvirtdDebugLogConfig
from virttest.test_setup.migration import MigrationEnvSetup
from virttest.test_setup.networking import (
BridgeConfig,
FirewalldService,
IPSniffer,
NetworkProxies,
)
from virttest.test_setup.os_posix import UlimitConfig
from virttest.test_setup.ppc import SwitchSMTOff
from virttest.test_setup.requirement_checks import (
CheckInstalledCMDs,
CheckRunningAsRoot,
)
from virttest.test_setup.storage import StorageConfig
from virttest.test_setup.verify import VerifyHostDMesg
from virttest.test_setup.vms import UnrequestedVMHandler
from virttest.utils_version import VersionInterval
utils_libvirtd = lazy_import("virttest.utils_libvirtd")
virsh = lazy_import("virttest.virsh")
libvirt_vm = lazy_import("virttest.libvirt_vm")
try:
import PIL.Image
except ImportError:
logging.getLogger("avocado.app").warning(
"No python imaging library installed. PPM image conversion to JPEG "
"disabled. In order to enable it, please install python-imaging or the "
"equivalent for your distro."
)
_screendump_thread = None
_screendump_thread_termination_event = None
_vm_info_thread = None
_vm_info_thread_termination_event = None
_setup_manager = SetupManager()
# default num of surplus hugepage, order to compare the values before and after
# the test when 'setup_hugepages = yes'
_pre_hugepages_surp = 0
_post_hugepages_surp = 0
#: Hooks to use for own customization stages of the virtual machines with
#: test, params. and env as supplied arguments
preprocess_vm_off_hook = None
preprocess_vm_on_hook = None
postprocess_vm_on_hook = None
postprocess_vm_off_hook = None
#: A list to handle kvm and kvm_probe modules reload with certain parameters
KVM_MODULE_HANDLERS = []
#: QEMU version regex. Attempts to extract the simple and extended version
#: information from the output produced by `qemu -version`
QEMU_VERSION_RE = r"QEMU (?:PC )?emulator version\s([0-9]+\.[0-9]+\.[0-9]+)\s?\((.*?)\)"
THREAD_ERROR = False
LOG = logging.getLogger("avocado." + __name__)
def _get_qemu_version(qemu_cmd):
"""
Return normalized qemu version
:param qemu_cmd: Path to qemu binary
"""
version_output = a_process.run("%s -version" % qemu_cmd, verbose=False).stdout_text
version_line = version_output.split("\n")[0]
matches = re.match(QEMU_VERSION_RE, version_line)
if matches:
return "%s (%s)" % matches.groups()
else:
return "Unknown"
def preprocess_image(test, params, image_name, vm_process_status=None):
"""
Preprocess a single QEMU image according to the instructions in params.
:param test: Autotest test object.
:param params: A dict containing image preprocessing parameters.
:param vm_process_status: This is needed in postprocess_image. Add it here
only for keep it work with process_images()
:note: Currently this function just creates an image if requested.
"""
base_dir = params.get("images_base_dir", data_dir.get_data_dir())
if not storage.preprocess_image_backend(base_dir, params, image_name):
LOG.error("Backend can't be prepared correctly.")
image_filename = storage.get_image_filename(params, base_dir)
create_image = False
if params.get("force_create_image") == "yes":
create_image = True
elif params.get("create_image") == "yes" and not storage.file_exists(
params, image_filename
):
create_image = True
if params.get("backup_image_before_testing", "no") == "yes":
image = qemu_storage.QemuImg(params, base_dir, image_name)
image.backup_image(params, base_dir, "backup", True, True)
if create_image:
if storage.file_exists(params, image_filename):
# As rbd image can not be covered, so need remove it if we need
# force create a new image.
storage.file_remove(params, image_filename)
image = qemu_storage.QemuImg(params, base_dir, image_name)
LOG.info("Create image on %s." % image.storage_type)
image.create(params)
def preprocess_fs_source(test, params, fs_name, vm_process_status=None):
"""
Preprocess a single QEMU filesystem source according to the
instructions in params.
:param test: Autotest test object.
:param params: A dict containing filesystem preprocessing parameters.
:param fs_name: The filesystem name.
:param vm_process_status: This is needed in postprocess_fs_source.
Add it here only for keep it work with
process_fs_sources()
"""
fs_type = params.get("fs_source_type", "mount")
fs_source_user_config = params.get("fs_source_user_config", "no")
# mount: A host directory to mount in the vm.
if fs_type == "mount":
if fs_source_user_config == "no":
fs_source = params.get("fs_source_dir")
base_dir = params.get("fs_source_base_dir", data_dir.get_data_dir())
if not os.path.isabs(fs_source):
fs_source = os.path.join(base_dir, fs_source)
create_fs_source = False
if params.get("force_create_fs_source") == "yes":
create_fs_source = True
elif params.get("create_fs_source") == "yes" and not os.path.exists(
fs_source
):
create_fs_source = True
if create_fs_source:
if os.path.exists(fs_source):
shutil.rmtree(fs_source, ignore_errors=True)
LOG.info("Create filesystem source %s." % fs_source)
os.makedirs(fs_source)
else:
test.cancel('Unsupport the type of filesystem "%s"' % fs_type)
def preprocess_vm(test, params, env, name):
"""
Preprocess a single VM object according to the instructions in params.
Start the VM if requested and get a screendump.
:param test: An Autotest test object.
:param params: A dict containing VM preprocessing parameters.
:param env: The environment (a dict-like object).
:param name: The name of the VM object.
"""
vm = env.get_vm(name)
vm_type = params.get("vm_type")
connect_uri = params.get("connect_uri")
target = params.get("target")
create_vm = False
if not vm or not isinstance(vm, virt_vm.BaseVM.lookup_vm_class(vm_type, target)):
create_vm = True
elif vm_type == "libvirt":
connect_uri = libvirt_vm.normalize_connect_uri(connect_uri)
if not vm.connect_uri == connect_uri:
create_vm = True
else:
pass
if create_vm:
# configure nested guest
if params.get("run_nested_guest_test", "no") == "yes":
current_level = params.get("nested_guest_level", "L1")
max_level = params.get("nested_guest_max_level", "L1")
if current_level != max_level:
if params.get("vm_type") == "libvirt":
params["create_vm_libvirt"] = "yes"
nested_cmdline = params.get("virtinstall_qemu_cmdline", "")
# virt-install doesn't have option, so use qemu-cmdline
if "cap-nested-hv=on" not in nested_cmdline:
params[
"virtinstall_qemu_cmdline"
] = "%s -M %s,cap-nested-hv=on" % (
nested_cmdline,
params["machine_type"],
)
elif params.get("vm_type") == "qemu":
nested_cmdline = params.get("machine_type_extra_params", "")
if "cap-nested-hv=on" not in nested_cmdline:
params["machine_type_extra_params"] = (
"%s,cap-nested-hv=on" % nested_cmdline
)
vm = env.create_vm(vm_type, target, name, params, test.bindir)
if params.get("create_vm_libvirt") == "yes" and vm_type == "libvirt":
params["medium"] = "import"
vm.create(params=params)
old_vm = copy.copy(vm)
if vm_type == "libvirt":
install_test = "unattended_install.import.import.default_install." "aio_native"
remove_test = "remove_guest.without_disk"
if not vm.exists() and (
params.get("type") != "unattended_install"
and params.get("type") != "svirt_virt_install"
):
error_msg = "Test VM %s does not exist." % name
if name == params.get("main_vm"):
error_msg += (
" Consider adding '%s' test as the first one "
"and '%s' test as last one to remove the "
"guest after testing" % (install_test, remove_test)
)
raise exceptions.TestError(error_msg)
else:
raise exceptions.TestSkipError(error_msg)
remove_vm = False
if params.get("force_remove_vm") == "yes":
remove_vm = True
if remove_vm:
vm.remove()
start_vm = False
update_virtnet = False
gracefully_kill = params.get("kill_vm_gracefully") == "yes"
if params.get("migration_mode"):
start_vm = True
elif params.get("start_vm") == "yes":
# need to deal with libvirt VM differently than qemu
if vm_type == "libvirt" or vm_type == "v2v":
if not vm.is_alive():
start_vm = True
else:
if not vm.is_alive():
start_vm = True
if params.get("check_vm_needs_restart", "yes") == "yes":
if vm.needs_restart(name=name, params=params, basedir=test.bindir):
vm.devices = None
start_vm = True
old_vm.destroy(gracefully=gracefully_kill)
update_virtnet = True
if start_vm:
if vm_type == "libvirt" and params.get("type") != "unattended_install":
vm.params = params
vm.start()
elif vm_type == "v2v":
vm.params = params
vm.start()
else:
if update_virtnet:
vm.update_vm_id()
vm.virtnet = utils_net.VirtNet(params, name, vm.instance)
# Start the VM (or restart it if it's already up)
if vm.is_alive():
vm.destroy(free_mac_addresses=False)
if params.get("reuse_previous_config", "no") == "no":
vm.create(
name,
params,
test.bindir,
timeout=int(params.get("vm_create_timeout", 90)),
migration_mode=params.get("migration_mode"),
migration_fd=params.get("migration_fd"),
migration_exec_cmd=params.get("migration_exec_cmd_dst"),
)
else:
vm.create(
timeout=int(params.get("vm_create_timeout", 90)),
migration_mode=params.get("migration_mode"),
migration_fd=params.get("migration_fd"),
migration_exec_cmd=params.get("migration_exec_cmd_dst"),
)
# Update kernel param
serial_login = params.get_boolean("kernel_extra_params_serial_login")
kernel_extra_params_add = params.get("kernel_extra_params_add", "")
kernel_extra_params_remove = params.get("kernel_extra_params_remove", "")
if params.get("disable_pci_msi"):
disable_pci_msi = params.get("disable_pci_msi")
if disable_pci_msi == "yes":
if "pci=" in kernel_extra_params_add:
kernel_extra_params_add = re.sub(
"pci=.*?\s+", "pci=nomsi ", kernel_extra_params_add
)
else:
kernel_extra_params_add += " pci=nomsi"
params["ker_remove_similar_pci"] = "yes"
else:
kernel_extra_params_remove += " pci=nomsi"
vendor = (
cpu_utils.get_vendor()
if hasattr(cpu_utils, "get_vendor")
else cpu_utils.get_cpu_vendor_name()
)
if params.get("enable_guest_iommu") and vendor == "intel":
enable_guest_iommu = params.get("enable_guest_iommu")
if enable_guest_iommu == "yes":
kernel_extra_params_add += " intel_iommu=on"
else:
kernel_extra_params_remove += " intel_iommu=on"
guest_iommu_option = params.get("guest_iommu_option")
if guest_iommu_option:
kernel_extra_params_add += " iommu=%s" % guest_iommu_option
if kernel_extra_params_add or kernel_extra_params_remove:
utils_test.update_boot_option(
vm,
args_added=kernel_extra_params_add,
args_removed=kernel_extra_params_remove,
serial_login=serial_login,
)
elif not vm.is_alive(): # VM is dead and won't be started, update params
vm.devices = None
vm.params = params
else:
# Only work when parameter 'start_vm' is no and VM is alive
if (
params.get("kill_vm_before_test") == "yes"
and params.get("start_vm") == "no"
):
old_vm.destroy(gracefully=gracefully_kill)
else:
# VM is alive and we just need to open the serial console
vm.create_serial_console()
if params.get("enable_strace") == "yes":
strace = test_setup.StraceQemu(test, params, env)
strace.start(params.objects("strace_vms"))
pause_vm = False
if params.get("paused_after_start_vm") == "yes":
pause_vm = True
# Check the status of vm
if (not vm.is_alive()) or (vm.is_paused()):
pause_vm = False
if pause_vm:
vm.pause()
if params.get("check_kernel_cmd_line_from_serial") == "yes":
debug_msg = ""
if vm.is_paused():
debug_msg += "VM is paused."
elif not vm.is_alive():
debug_msg += "VM is not alive."
elif vm.serial_console is None:
debug_msg += "There is no serial console in VM."
if debug_msg:
debug_msg += " Skip the kernel command line check."
LOG.warning(debug_msg)
return
cmd_line = params.get("kernel_cmd_line_str", "Command line:")
try:
output = vm.serial_console.read_until_output_matches(cmd_line, timeout=60)
kernel_cmd_line = re.findall("%s.*" % cmd_line, output[1])[0]
kernel_options_exist = params.get("kernel_options_exist", "")
kernel_options_not_exist = params.get("kernel_options_not_exist", "")
err_msg = ""
for kernel_option in kernel_options_exist.split():
if kernel_option not in kernel_cmd_line:
err_msg += "%s not in kernel command line" % kernel_option
err_msg += " as expect."
for kernel_option in kernel_options_not_exist.split():
if kernel_option in kernel_cmd_line:
err_msg += "%s exist in kernel command" % kernel_option
err_msg += " line."
if err_msg:
err_msg += " Kernel command line get from"
err_msg += " serial output is %s" % kernel_cmd_line
raise exceptions.TestError(err_msg)
LOG.info("Kernel command line get from serial port is as expect")
except Exception as err:
LOG.warning(
"Did not get the kernel command line from serial "
"port output. Skip the kernel command line check."
"Error is %s" % err
)
def check_image(test, params, image_name, vm_process_status=None):
"""
Check a single QEMU image according to the instructions in params.
:param test: An Autotest test object.
:param params: A dict containing image postprocessing parameters.
:param vm_process_status: (optional) vm process status like running, dead
or None for no vm exist.
"""
clone_master = params.get("clone_master", None)
base_dir = data_dir.get_data_dir()
check_image_flag = params.get("check_image") == "yes"
if not check_image_flag:
return
image = qemu_storage.QemuImg(params, base_dir, image_name)
if vm_process_status == "running" and check_image_flag:
if params.get("skip_image_check_during_running") == "yes":
LOG.debug("Guest is still running, skip the image check.")
check_image_flag = False
else:
image_info_output = image.info(force_share=True)
image_info = {}
if image_info_output is not None:
for image_info_item in image_info_output.splitlines():
option = image_info_item.split(":")
if len(option) == 2:
image_info[option[0].strip()] = option[1].strip()
else:
LOG.debug(
"Can not find matched image for selected guest "
"os, skip the image check."
)
check_image_flag = False
if (
"lazy refcounts" in image_info
and image_info["lazy refcounts"] == "true"
):
LOG.debug(
"Should not check image while guest is alive"
" when the image is create with lazy refcounts."
" Skip the image check."
)
check_image_flag = False
# Save the potential bad image when the test is not passed.
# It should before image check.
if params.get("save_image", "no") == "yes":
if vm_process_status == "dead":
hsh = utils_misc.generate_random_string(4)
name = "JOB-%s-TEST-%s-%s-%s.%s" % (
test.job.unique_id[:7],
str(test.name.uid),
image_name,
hsh,
image.image_format,
)
image.save_image(params, name)
else:
LOG.error("Not saving images, VM is not stopped.")
if check_image_flag:
try:
if clone_master is None:
image.check_image(params, base_dir, force_share=True)
elif clone_master == "yes":
if image_name in params.get("master_images_clone").split():
image.check_image(params, base_dir, force_share=True)
except Exception as e:
# FIXME: remove it from params, maybe as an img object attr
params["img_check_failed"] = "yes"
if params.get(
"skip_cluster_leak_warn"
) == "yes" and "Leaked clusters" in six.text_type(e):
LOG.warning(six.text_type(e))
else:
raise e
def postprocess_image(test, params, image_name, vm_process_status=None):
"""
Postprocess a single QEMU image according to the instructions in params.
The main operation is to remove images if instructions are given.
:param test: An Autotest test object.
:param params: A dict containing image postprocessing parameters.
:param vm_process_status: (optional) vm process status like running, dead
or None for no vm exist.
"""
if vm_process_status == "running":
LOG.warning(
"Skipped processing image '%s' since " "the VM is running!" % image_name
)
return
restored, removed = (False, False)
clone_master = params.get("clone_master", None)
base_dir = params.get("images_base_dir", data_dir.get_data_dir())
image = None
if params.get("img_check_failed") == "yes":
image = (
qemu_storage.QemuImg(params, base_dir, image_name) if not image else image
)
if params.get("restore_image_on_check_error", "no") == "yes":
image.backup_image(params, base_dir, "restore", True)
restored = True
else:
# Allow test to overwrite any pre-testing automatic backup
# with a new backup. i.e. assume pre-existing image/backup
# would not be usable after this test succeeds. The best
# example for this is when 'unattended_install' is run.
if (
params.get("backup_image_after_testing_passed", "no") == "yes"
and params.get("test_passed") == "True"
):
image = (
qemu_storage.QemuImg(params, base_dir, image_name)
if not image
else image
)
image.backup_image(params, base_dir, "backup", True)
if not restored and params.get("restore_image", "no") == "yes":
image = (
qemu_storage.QemuImg(params, base_dir, image_name) if not image else image
)
image.backup_image(params, base_dir, "restore", True)
restored = True
if not restored and params.get("restore_image_after_testing", "no") == "yes":
image = (
qemu_storage.QemuImg(params, base_dir, image_name) if not image else image
)
image.backup_image(params, base_dir, "restore", True)
if params.get("img_check_failed") == "yes":
image = (
qemu_storage.QemuImg(params, base_dir, image_name) if not image else image
)
if params.get("remove_image_on_check_error", "no") == "yes":
cl_images = params.get("master_images_clone", "")
if image_name in cl_images.split():
image.remove()
removed = True
if not removed and params.get("remove_image", "yes") == "yes":
image = (
qemu_storage.QemuImg(params, base_dir, image_name) if not image else image
)
LOG.info("Remove image on %s." % image.storage_type)
if clone_master is None:
image.remove()
elif clone_master == "yes":
if image_name in params.get("master_images_clone").split():
image.remove()
def postprocess_fs_source(test, params, fs_name, vm_process_status=None):
"""
Postprocess a single QEMU filesystem source according to the
instructions in params.
The main operation is to remove images if instructions are given.
:param test: An Autotest test object.
:param params: A dict containing filesystem postprocessing parameters.
:param fs_name: The filesystem name
:param vm_process_status: (optional) vm process status like
running, dead or None for no vm exist.
"""
if vm_process_status == "running":
LOG.warning(
"Skipped processing filesystem '%s' since " "the VM is running!" % fs_name
)
return
fs_type = params.get("fs_source_type", "mount")
if fs_type == "mount":
fs_source = params.get("fs_source_dir")
base_dir = params.get("fs_source_base_dir", data_dir.get_data_dir())
if not os.path.isabs(fs_source):
fs_source = os.path.join(base_dir, fs_source)
if params.get("remove_fs_source") == "yes":
LOG.info("Remove filesystem source %s." % fs_source)
shutil.rmtree(fs_source, ignore_errors=True)
else:
LOG.info(
"Skipped processing filesystem '%s' since "
"unsupported type '%s'." % (fs_name, fs_type)
)
def postprocess_vm(test, params, env, name):
"""
Postprocess a single VM object according to the instructions in params.
Kill the VM if requested and get a screendump.
:param test: An Autotest test object.
:param params: A dict containing VM postprocessing parameters.
:param env: The environment (a dict-like object).
:param name: The name of the VM object.
"""
vm = env.get_vm(name)
if not vm:
return
if params.get("start_vm") == "yes":
# recover the changes done to kernel params in postprocess
serial_login = params.get_boolean("kernel_extra_params_serial_login")
kernel_extra_params_add = params.get("kernel_extra_params_add", "")
kernel_extra_params_remove = params.get("kernel_extra_params_remove", "")
if params.get("enable_guest_iommu") == "yes":
kernel_extra_params_add += " intel_iommu=on"
guest_iommu_option = params.get("guest_iommu_option")
if guest_iommu_option:
kernel_extra_params_add += " iommu=%s" % guest_iommu_option
if kernel_extra_params_add or kernel_extra_params_remove:
# VM might be brought down after test
if vm and not vm.is_alive():
if params.get("vm_type") == "libvirt":
vm.start()
elif params.get("vm_type") == "qemu":
vm.create(params=params)
utils_test.update_boot_option(
vm,
args_added=kernel_extra_params_remove,
args_removed=kernel_extra_params_add,
serial_login=serial_login,
)
# Close all SSH sessions that might be active to this VM
for s in vm.remote_sessions[:]:
try:
s.close()
vm.remote_sessions.remove(s)
except Exception:
pass
utils_logfile.close_log_file()
if params.get("vm_extra_dump_paths") is not None:
vm_extra_dumps = os.path.join(test.outputdir, "vm_extra_dumps")
if not os.path.exists(vm_extra_dumps):
os.makedirs(vm_extra_dumps)
for dump_path in params.get("vm_extra_dump_paths").split(";"):
try:
vm.copy_files_from(dump_path, vm_extra_dumps)
except:
LOG.error(
"Could not copy the extra dump '%s' from the vm '%s'",
dump_path,
vm.name,
)
if params.get("kill_vm") == "yes":
kill_vm_timeout = float(params.get("kill_vm_timeout", 0))
if kill_vm_timeout:
utils_misc.wait_for(vm.is_dead, kill_vm_timeout, 0, 1)
vm.destroy(gracefully=params.get("kill_vm_gracefully") == "yes")
if (
params.get("kill_vm_libvirt") == "yes"
and params.get("vm_type") == "libvirt"
):
vm.undefine(options=params.get("kill_vm_libvirt_options"))
if vm.is_dead():
if params.get("vm_type") == "qemu":
if vm.devices is not None:
vm.devices.cleanup_daemons()
if params.get("enable_strace") == "yes":
strace = test_setup.StraceQemu(test, params, env)
strace.stop()
def process_command(test, params, env, command, command_timeout, command_noncritical):
"""
Pre- or post- custom commands to be executed before/after a test is run
:param test: An Autotest test object.
:param params: A dict containing all VM and image parameters.
:param env: The environment (a dict-like object).
:param command: Command to be run.
:param command_timeout: Timeout for command execution.
:param command_noncritical: If True test will not fail if command fails.
"""
# Export environment vars
for k in params:
os.putenv("KVM_TEST_%s" % k, str(params[k]))
# Execute commands
try:
a_process.system("cd %s; %s" % (test.bindir, command), shell=True)
except a_process.CmdError as e:
if command_noncritical:
LOG.warning(e)
else:
raise
class _CreateImages(threading.Thread):
"""
Thread which creates images. In case of failure it stores the exception
in self.exc_info
"""
def __init__(self, image_func, test, images, params, exit_event, vm_process_status):
threading.Thread.__init__(self)
self.image_func = image_func
self.test = test
self.images = images
self.params = params
self.exit_event = exit_event
self.exc_info = None
self.vm_process_status = vm_process_status
def run(self):
try:
_process_images_serial(
self.image_func,
self.test,
self.images,
self.params,
self.exit_event,
self.vm_process_status,
)
except Exception:
self.exc_info = sys.exc_info()
self.exit_event.set()
def process_images(image_func, test, params, vm_process_status=None):
"""
Wrapper which chooses the best way to process images.
:param image_func: Process function
:param test: An Autotest test object.
:param params: A dict containing all VM and image parameters.
:param vm_process_status: (optional) vm process status like running, dead
or None for no vm exist.
"""
images = params.objects("images")
if len(images) > 20: # Lets do it in parallel
_process_images_parallel(
image_func, test, params, vm_process_status=vm_process_status
)
else:
_process_images_serial(
image_func, test, images, params, vm_process_status=vm_process_status
)
def process_fs_sources(fs_source_func, test, params, vm_process_status=None):
"""
Wrapper which chooses the best way to process filesystem sources.
:param fs_source_func: Process function
:param test: An Autotest test object.
:param params: A dict containing all VM and filesystem parameters.
:param vm_process_status: (optional) vm process status like running, dead
or None for no vm exist.
"""
for filesystem in params.objects("filesystems"):
fs_params = params.object_params(filesystem)
fs_source_func(test, fs_params, filesystem, vm_process_status)
def _process_images_serial(
image_func, test, images, params, exit_event=None, vm_process_status=None
):
"""
Original process_image function, which allows custom set of images
:param image_func: Process function
:param test: An Autotest test object.
:param images: List of images (usually params.objects("images"))
:param params: A dict containing all VM and image parameters.
:param exit_event: (optional) exit event which interrupts the processing
:param vm_process_status: (optional) vm process status like running, dead
or None for no vm exist.
"""
for image_name in images:
image_params = params.object_params(image_name)
image_func(test, image_params, image_name, vm_process_status)
if exit_event and exit_event.is_set():
LOG.error("Received exit_event, stop processing of images.")
break
def _process_images_parallel(image_func, test, params, vm_process_status=None):
"""
The same as _process_images but in parallel.
:param image_func: Process function
:param test: An Autotest test object.
:param params: A dict containing all VM and image parameters.
:param vm_process_status: (optional) vm process status like running, dead
or None for no vm exist.
"""
images = params.objects("images")
no_threads = min(len(images) // 5, 2 * multiprocessing.cpu_count())
exit_event = threading.Event()
threads = []
for i in xrange(no_threads):
imgs = images[i::no_threads]
threads.append(
_CreateImages(image_func, test, imgs, params, exit_event, vm_process_status)
)
threads[-1].start()
for thread in threads:
thread.join()
if exit_event.is_set(): # Failure in some thread
LOG.error("Image processing failed:")
for thread in threads:
if thread.exc_info: # Throw the first failure
six.reraise(thread.exc_info[1], None, thread.exc_info[2])
del exit_event
del threads[:]
def process(
test, params, env, image_func, vm_func, vm_first=False, fs_source_func=None
):
"""
Pre- or post-process VMs and images according to the instructions in params.
Call image_func for each image listed in params and vm_func for each VM.
:param test: An Autotest test object.
:param params: A dict containing all VM and image parameters.
:param env: The environment (a dict-like object).
:param image_func: A function to call for each image.
:param vm_func: A function to call for each VM.
:param vm_first: Call vm_func first or not.
:param fs_source_func: A function to call for each filesystem source.
"""
def _call_vm_func():
for vm_name in params.objects("vms"):
vm_params = params.object_params(vm_name)
vm_func(test, vm_params, env, vm_name)
def _call_image_func():
if params.get("skip_image_processing") == "yes":
return
if params.objects("vms"):
for vm_name in params.objects("vms"):
vm_params = params.object_params(vm_name)
vm = env.get_vm(vm_name)
unpause_vm = False
if vm is None or vm.is_dead():
vm_process_status = "dead"
else:
vm_process_status = "running"
if vm is not None and vm.is_alive() and not vm.is_paused():
vm.pause()
unpause_vm = True
vm_params["skip_cluster_leak_warn"] = "yes"
try:
process_images(image_func, test, vm_params, vm_process_status)
finally:
if unpause_vm:
vm.resume()
else:
process_images(image_func, test, params)
def _call_fs_source_func():
if params.get("skip_fs_source_processing") == "yes":
return
if params.objects("vms"):
for vm_name in params.objects("vms"):
vm_params = params.object_params(vm_name)
if not vm_params.get("filesystems"):
continue
vm = env.get_vm(vm_name)
unpause_vm = False
if vm is None or vm.is_dead():
vm_process_status = "dead"
else:
vm_process_status = "running"
if vm is not None and vm.is_alive() and not vm.is_paused():
vm.pause()
unpause_vm = True
try:
process_fs_sources(
fs_source_func, test, vm_params, vm_process_status
)
finally:
if unpause_vm:
vm.resume()
def _call_check_image_func():
if params.get("skip_image_processing") == "yes":
return
if params.objects("vms"):
for vm_name in params.objects("vms"):
vm_params = params.object_params(vm_name)
vm = env.get_vm(vm_name)
unpause_vm = False
if vm is None or vm.is_dead():
vm_process_status = "dead"
else:
vm_process_status = "running"
if vm is not None and vm.is_alive() and not vm.is_paused():
vm.pause()
unpause_vm = True
vm_params["skip_cluster_leak_warn"] = "yes"
try:
images = params.objects("images")
_process_images_serial(
check_image,
test,
images,
vm_params,
vm_process_status=vm_process_status,
)
finally:
if unpause_vm:
vm.resume()
else:
images = params.objects("images")
_process_images_serial(check_image, test, images, params)
# preprocess
if not vm_first:
_call_image_func()
if fs_source_func:
_call_fs_source_func()
_call_vm_func()
# postprocess
if vm_first:
try:
_call_check_image_func()
finally:
_call_image_func()
if fs_source_func:
_call_fs_source_func()
@error_context.context_aware
def preprocess(test, params, env):
"""
Preprocess all VMs and images according to the instructions in params.
Also, collect some host information, such as the KVM version.