forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_misc.py
1623 lines (1325 loc) · 50.6 KB
/
utils_misc.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
"""
Virtualization test utility functions.
@copyright: 2008-2009 Red Hat Inc.
"""
import time, string, random, socket, os, signal, re, logging, commands
import fcntl, sys, inspect, tarfile, shutil, getpass
from autotest.client import utils, os_dep
from autotest.client.shared import error, logging_config
from autotest.client.shared import git
import utils_koji, data_dir
import platform
ARCH = platform.machine()
class UnsupportedCPU(error.TestError):
pass
# TODO: remove this import when log_last_traceback is moved to autotest
import traceback
# TODO: this function is being moved into autotest. For compatibility
# reasons keep it here too but new code should use the one from base_utils.
def log_last_traceback(msg=None, log=logging.error):
"""
@warning: This function is being moved into autotest and your code should
use autotest.client.shared.base_utils function instead.
Writes last traceback into specified log.
@param msg: Override the default message. ["Original traceback"]
@param log: Where to log the traceback [logging.error]
"""
if not log:
log = logging.error
if msg:
log(msg)
exc_type, exc_value, exc_traceback = sys.exc_info()
if not exc_traceback:
log('Requested log_last_traceback but no exception was raised.')
return
log("Original " +
"".join(traceback.format_exception(exc_type, exc_value,
exc_traceback)))
def lock_file(filename, mode=fcntl.LOCK_EX):
f = open(filename, "w")
fcntl.lockf(f, mode)
return f
def unlock_file(f):
fcntl.lockf(f, fcntl.LOCK_UN)
f.close()
# Utility functions for dealing with external processes
def unique(llist):
"""
Return a list of the elements in list, but without duplicates.
@param list: List with values.
@return: List with non duplicate elements.
"""
n = len(llist)
if n == 0:
return []
u = {}
try:
for x in llist:
u[x] = 1
except TypeError:
return None
else:
return u.keys()
def find_command(cmd):
"""
Try to find a command in the PATH, paranoid version.
@param cmd: Command to be found.
@raise: ValueError in case the command was not found.
"""
common_bin_paths = ["/usr/libexec", "/usr/local/sbin", "/usr/local/bin",
"/usr/sbin", "/usr/bin", "/sbin", "/bin"]
try:
path_paths = os.environ['PATH'].split(":")
except IndexError:
path_paths = []
path_paths = unique(common_bin_paths + path_paths)
for dir_path in path_paths:
cmd_path = os.path.join(dir_path, cmd)
if os.path.isfile(cmd_path):
return os.path.abspath(cmd_path)
raise ValueError('Missing command: %s' % cmd)
def pid_exists(pid):
"""
Return True if a given PID exists.
@param pid: Process ID number.
"""
try:
os.kill(pid, 0)
return True
except Exception:
return False
def safe_kill(pid, signal):
"""
Attempt to send a signal to a given process that may or may not exist.
@param signal: Signal number.
"""
try:
os.kill(pid, signal)
return True
except Exception:
return False
def kill_process_tree(pid, sig=signal.SIGKILL):
"""Signal a process and all of its children.
If the process does not exist -- return.
@param pid: The pid of the process to signal.
@param sig: The signal to send to the processes.
"""
if not safe_kill(pid, signal.SIGSTOP):
return
children = commands.getoutput("ps --ppid=%d -o pid=" % pid).split()
for child in children:
kill_process_tree(int(child), sig)
safe_kill(pid, sig)
safe_kill(pid, signal.SIGCONT)
# The following are utility functions related to ports.
def is_port_free(port, address):
"""
Return True if the given port is available for use.
@param port: Port number
"""
try:
s = socket.socket()
#s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if address == "localhost":
s.bind(("localhost", port))
free = True
else:
s.connect((address, port))
free = False
except socket.error:
if address == "localhost":
free = False
else:
free = True
s.close()
return free
def find_free_port(start_port, end_port, address="localhost"):
"""
Return a host free port in the range [start_port, end_port].
@param start_port: First port that will be checked.
@param end_port: Port immediately after the last one that will be checked.
"""
for i in range(start_port, end_port):
if is_port_free(i, address):
return i
return None
def find_free_ports(start_port, end_port, count, address="localhost"):
"""
Return count of host free ports in the range [start_port, end_port].
@count: Initial number of ports known to be free in the range.
@param start_port: First port that will be checked.
@param end_port: Port immediately after the last one that will be checked.
"""
ports = []
i = start_port
while i < end_port and count > 0:
if is_port_free(i, address):
ports.append(i)
count -= 1
i += 1
return ports
# An easy way to log lines to files when the logging system can't be used
_open_log_files = {}
_log_file_dir = "/tmp"
def log_line(filename, line):
"""
Write a line to a file. '\n' is appended to the line.
@param filename: Path of file to write to, either absolute or relative to
the dir set by set_log_file_dir().
@param line: Line to write.
"""
global _open_log_files, _log_file_dir
path = get_path(_log_file_dir, filename)
if path not in _open_log_files:
# First, let's close the log files opened in old directories
close_log_file(filename)
# Then, let's open the new file
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass
_open_log_files[path] = open(path, "w")
timestr = time.strftime("%Y-%m-%d %H:%M:%S")
_open_log_files[path].write("%s: %s\n" % (timestr, line))
_open_log_files[path].flush()
def set_log_file_dir(directory):
"""
Set the base directory for log files created by log_line().
@param dir: Directory for log files.
"""
global _log_file_dir
_log_file_dir = directory
def close_log_file(filename):
global _open_log_files, _log_file_dir
remove = []
for k in _open_log_files:
if os.path.basename(k) == filename:
f = _open_log_files[k]
f.close()
remove.append(k)
if remove:
for key_to_remove in remove:
_open_log_files.pop(key_to_remove)
# The following are miscellaneous utility functions.
def get_path(base_path, user_path):
"""
Translate a user specified path to a real path.
If user_path is relative, append it to base_path.
If user_path is absolute, return it as is.
@param base_path: The base path of relative user specified paths.
@param user_path: The user specified path.
"""
if os.path.isabs(user_path):
return user_path
else:
return os.path.join(base_path, user_path)
def generate_random_string(length, ignore_str=string.punctuation,
convert_str=""):
"""
Return a random string using alphanumeric characters.
@param length: Length of the string that will be generated.
@param ignore_str: Characters that will not include in generated string.
@param convert_str: Characters that need to be escaped (prepend "\\").
@return: The generated random string.
"""
r = random.SystemRandom()
sr = ""
chars = string.letters + string.digits + string.punctuation
if not ignore_str:
ignore_str = ""
for i in ignore_str:
chars = chars.replace(i, "")
while length > 0:
tmp = r.choice(chars)
if convert_str and (tmp in convert_str):
tmp = "\\%s" % tmp
sr += tmp
length -= 1
return sr
def generate_random_id():
"""
Return a random string suitable for use as a qemu id.
"""
return "id" + generate_random_string(6)
def generate_tmp_file_name(file_name, ext=None, directory='/tmp/'):
"""
Returns a temporary file name. The file is not created.
"""
while True:
file_name = (file_name + '-' + time.strftime("%Y%m%d-%H%M%S-") +
generate_random_string(4))
if ext:
file_name += '.' + ext
file_name = os.path.join(directory, file_name)
if not os.path.exists(file_name):
break
return file_name
def format_str_for_message(sr):
"""
Format str so that it can be appended to a message.
If str consists of one line, prefix it with a space.
If str consists of multiple lines, prefix it with a newline.
@param str: string that will be formatted.
"""
lines = str.splitlines()
num_lines = len(lines)
sr = "\n".join(lines)
if num_lines == 0:
return ""
elif num_lines == 1:
return " " + sr
else:
return "\n" + sr
def wait_for(func, timeout, first=0.0, step=1.0, text=None):
"""
If func() evaluates to True before timeout expires, return the
value of func(). Otherwise return None.
@brief: Wait until func() evaluates to True.
@param timeout: Timeout in seconds
@param first: Time to sleep before first attempt
@param steps: Time to sleep between attempts in seconds
@param text: Text to print while waiting, for debug purposes
"""
start_time = time.time()
end_time = time.time() + timeout
time.sleep(first)
while time.time() < end_time:
if text:
logging.debug("%s (%f secs)", text, (time.time() - start_time))
output = func()
if output:
return output
time.sleep(step)
return None
def get_hash_from_file(hash_path, dvd_basename):
"""
Get the a hash from a given DVD image from a hash file
(Hash files are usually named MD5SUM or SHA1SUM and are located inside the
download directories of the DVDs)
@param hash_path: Local path to a hash file.
@param cd_image: Basename of a CD image
"""
hash_file = open(hash_path, 'r')
for line in hash_file.readlines():
if dvd_basename in line:
return line.split()[0]
def run_tests(parser, job):
"""
Runs the sequence of KVM tests based on the list of dictionaries
generated by the configuration system, handling dependencies.
@param parser: Config parser object.
@param job: Autotest job object.
@return: True, if all tests ran passed, False if any of them failed.
"""
last_index = -1
for i, d in enumerate(parser.get_dicts()):
logging.info("Test %4d: %s" % (i + 1, d["shortname"]))
last_index += 1
status_dict = {}
failed = False
# Add the parameter decide if setup host env in the test case
# For some special tests we only setup host in the first and last case
# When we need to setup host env we need the host_setup_flag as following:
# 0(00): do nothing
# 1(01): setup env
# 2(10): cleanup env
# 3(11): setup and cleanup env
index = 0
setup_flag = 1
cleanup_flag = 2
for param_dict in parser.get_dicts():
if index == 0:
if param_dict.get("host_setup_flag", None) is not None:
flag = int(param_dict["host_setup_flag"])
param_dict["host_setup_flag"] = flag | setup_flag
else:
param_dict["host_setup_flag"] = setup_flag
if index == last_index:
if param_dict.get("host_setup_flag", None) is not None:
flag = int(param_dict["host_setup_flag"])
param_dict["host_setup_flag"] = flag | cleanup_flag
else:
param_dict["host_setup_flag"] = cleanup_flag
index += 1
# Add kvm module status
sysfs_dir = param_dict.get("sysfs_dir", "sys")
param_dict["kvm_default"] = get_module_params(sysfs_dir, 'kvm')
if param_dict.get("skip") == "yes":
continue
dependencies_satisfied = True
for dep in param_dict.get("dep"):
for test_name in status_dict.keys():
if not dep in test_name:
continue
# So the only really non-fatal state is WARN,
# All the others make it not safe to proceed with dependency
# execution
if status_dict[test_name] not in ['GOOD', 'WARN']:
dependencies_satisfied = False
break
test_iterations = int(param_dict.get("iterations", 1))
test_tag = param_dict.get("vm_type") + "." + param_dict.get("shortname")
if dependencies_satisfied:
# Setting up profilers during test execution.
profilers = param_dict.get("profilers", "").split()
for profiler in profilers:
job.profilers.add(profiler, **param_dict)
# We need only one execution, profiled, hence we're passing
# the profile_only parameter to job.run_test().
profile_only = bool(profilers) or None
test_timeout = int(param_dict.get("test_timeout", 14400))
current_status = job.run_test_detail("virt",
params=param_dict,
tag=test_tag,
iterations=test_iterations,
profile_only=profile_only,
timeout=test_timeout)
for profiler in profilers:
job.profilers.delete(profiler)
else:
# We will force the test to fail as TestNA during preprocessing
param_dict['dependency_failed'] = 'yes'
current_status = job.run_test_detail("virt",
params=param_dict,
tag=test_tag,
iterations=test_iterations)
if not current_status:
failed = True
status_dict[param_dict.get("name")] = current_status
return not failed
def display_attributes(instance):
"""
Inspects a given class instance attributes and displays them, convenient
for debugging.
"""
logging.debug("Attributes set:")
for member in inspect.getmembers(instance):
name, value = member
attribute = getattr(instance, name)
if not (name.startswith("__") or callable(attribute) or not value):
logging.debug(" %s: %s", name, value)
def get_full_pci_id(pci_id):
"""
Get full PCI ID of pci_id.
@param pci_id: PCI ID of a device.
"""
cmd = "lspci -D | awk '/%s/ {print $1}'" % pci_id
status, full_id = commands.getstatusoutput(cmd)
if status != 0:
return None
return full_id
def get_vendor_from_pci_id(pci_id):
"""
Check out the device vendor ID according to pci_id.
@param pci_id: PCI ID of a device.
"""
cmd = "lspci -n | awk '/%s/ {print $3}'" % pci_id
return re.sub(":", " ", commands.getoutput(cmd))
class Flag(str):
"""
Class for easy merge cpuflags.
"""
aliases = {}
def __new__(cls, flag):
if flag in Flag.aliases:
flag = Flag.aliases[flag]
return str.__new__(cls, flag)
def __eq__(self, other):
s = set(self.split("|"))
o = set(other.split("|"))
if s & o:
return True
else:
return False
def __str__(self):
return self.split("|")[0]
def __repr__(self):
return self.split("|")[0]
def __hash__(self, *args, **kwargs):
return 0
kvm_map_flags_to_test = {
Flag('avx') :set(['avx']),
Flag('sse3|pni') :set(['sse3']),
Flag('ssse3') :set(['ssse3']),
Flag('sse4.1|sse4_1|sse4.2|sse4_2'):set(['sse4']),
Flag('aes') :set(['aes','pclmul']),
Flag('pclmuldq') :set(['pclmul']),
Flag('pclmulqdq') :set(['pclmul']),
Flag('rdrand') :set(['rdrand']),
Flag('sse4a') :set(['sse4a']),
Flag('fma4') :set(['fma4']),
Flag('xop') :set(['xop']),
}
kvm_map_flags_aliases = {
'sse4_1' :'sse4.1',
'sse4_2' :'sse4.2',
'pclmuldq' :'pclmulqdq',
'sse3' :'pni',
'ffxsr' :'fxsr_opt',
'xd' :'nx',
'i64' :'lm',
'psn' :'pn',
'clfsh' :'clflush',
'dts' :'ds',
'htt' :'ht',
'CMPXCHG8B' :'cx8',
'Page1GB' :'pdpe1gb',
'LahfSahf' :'lahf_lm',
'ExtApicSpace' :'extapic',
'AltMovCr8' :'cr8_legacy',
'cr8legacy' :'cr8_legacy'
}
def kvm_flags_to_stresstests(flags):
"""
Covert [cpu flags] to [tests]
@param cpuflags: list of cpuflags
@return: Return tests like string.
"""
tests = set([])
for f in flags:
tests |= kvm_map_flags_to_test[f]
param = ""
for f in tests:
param += ","+f
return param
def get_cpu_flags():
"""
Returns a list of the CPU flags
"""
flags_re = re.compile(r'^flags\s*:(.*)')
for line in open('/proc/cpuinfo').readlines():
match = flags_re.match(line)
if match:
return match.groups()[0].split()
return []
def get_cpu_vendor(cpu_flags=[], verbose=True):
"""
Returns the name of the CPU vendor, either intel, amd or unknown
"""
if not cpu_flags:
cpu_flags = get_cpu_flags()
if 'vmx' in cpu_flags:
vendor = 'intel'
elif 'svm' in cpu_flags:
vendor = 'amd'
elif ARCH == 'ppc64':
vendor = 'ibm'
else:
vendor = 'unknown'
if verbose:
logging.debug("Detected CPU vendor as '%s'", vendor)
return vendor
def get_support_machine_type(qemu_binary="/usr/libexec/qemu-kvm"):
"""
Get the machine type the host support,return a list of machine type
"""
o = utils.system_output("%s -M ?" % qemu_binary)
s = re.findall("(\S*)\s*RHEL\s", o)
c = re.findall("(RHEL.*PC)", o)
return (s, c)
def get_cpu_model():
"""
Get cpu model from host cpuinfo
"""
def _make_up_pattern(flags):
"""
Update the check pattern to a certain order and format
"""
pattern_list = re.split(",", flags.strip())
pattern_list.sort()
pattern = r"(\b%s\b)" % pattern_list[0]
for i in pattern_list[1:]:
pattern += r".+(\b%s\b)" % i
return pattern
cpu_types = {"amd": ["Opteron_G5", "Opteron_G4", "Opteron_G3",
"Opteron_G2", "Opteron_G1"],
"intel": ["Haswell", "SandyBridge", "Westmere",
"Nehalem", "Penryn", "Conroe"]}
cpu_type_re = {"Opteron_G5":
"f16c,fma,tbm",
"Opteron_G4":
"avx,xsave,aes,sse4.2|sse4_2,sse4.1|sse4_1,cx16,ssse3,sse4a",
"Opteron_G3": "cx16,sse4a",
"Opteron_G2": "cx16",
"Opteron_G1": "",
"Haswell":
"fsgsbase,bmi1,hle,avx2,smep,bmi2,erms,invpcid,rtm",
"SandyBridge":
"avx,xsave,aes,sse4_2|sse4.2,sse4.1|sse4_1,cx16,ssse3",
"Westmere": "aes,sse4.2|sse4_2,sse4.1|sse4_1,cx16,ssse3",
"Nehalem": "sse4.2|sse4_2,sse4.1|sse4_1,cx16,ssse3",
"Penryn": "sse4.1|sse4_1,cx16,ssse3",
"Conroe": "ssse3"}
flags = get_cpu_flags()
flags.sort()
cpu_flags = " ".join(flags)
vendor = get_cpu_vendor(flags)
cpu_model = ""
if cpu_flags:
for cpu_type in cpu_types.get(vendor):
pattern = _make_up_pattern(cpu_type_re.get(cpu_type))
if re.findall(pattern, cpu_flags):
cpu_model = cpu_type
break
else:
logging.warn("Can not get cpu flags from cpuinfo")
if cpu_model:
cpu_type_list = cpu_types.get(vendor)
cpu_support_model = cpu_type_list[cpu_type_list.index(cpu_model):]
cpu_model = ",".join(cpu_support_model)
return cpu_model
def get_archive_tarball_name(source_dir, tarball_name, compression):
'''
Get the name for a tarball file, based on source, name and compression
'''
if tarball_name is None:
tarball_name = os.path.basename(source_dir)
if not tarball_name.endswith('.tar'):
tarball_name = '%s.tar' % tarball_name
if compression and not tarball_name.endswith('.%s' % compression):
tarball_name = '%s.%s' % (tarball_name, compression)
return tarball_name
def archive_as_tarball(source_dir, dest_dir, tarball_name=None,
compression='bz2', verbose=True):
'''
Saves the given source directory to the given destination as a tarball
If the name of the archive is omitted, it will be taken from the
source_dir. If it is an absolute path, dest_dir will be ignored. But,
if both the destination directory and tarball anem is given, and the
latter is not an absolute path, they will be combined.
For archiving directory '/tmp' in '/net/server/backup' as file
'tmp.tar.bz2', simply use:
>>> utils_misc.archive_as_tarball('/tmp', '/net/server/backup')
To save the file it with a different name, say 'host1-tmp.tar.bz2'
and save it under '/net/server/backup', use:
>>> utils_misc.archive_as_tarball('/tmp', '/net/server/backup',
'host1-tmp')
To save with gzip compression instead (resulting in the file
'/net/server/backup/host1-tmp.tar.gz'), use:
>>> utils_misc.archive_as_tarball('/tmp', '/net/server/backup',
'host1-tmp', 'gz')
'''
tarball_name = get_archive_tarball_name(source_dir,
tarball_name,
compression)
if not os.path.isabs(tarball_name):
tarball_path = os.path.join(dest_dir, tarball_name)
else:
tarball_path = tarball_name
if verbose:
logging.debug('Archiving %s as %s' % (source_dir,
tarball_path))
os.chdir(os.path.dirname(source_dir))
tarball = tarfile.TarFile(name=tarball_path, mode='w')
tarball = tarball.open(name=tarball_path, mode='w:%s' % compression)
tarball.add(os.path.basename(source_dir))
tarball.close()
def parallel(targets):
"""
Run multiple functions in parallel.
@param targets: A sequence of tuples or functions. If it's a sequence of
tuples, each tuple will be interpreted as (target, args, kwargs) or
(target, args) or (target,) depending on its length. If it's a
sequence of functions, the functions will be called without
arguments.
@return: A list of the values returned by the functions called.
"""
threads = []
for target in targets:
if isinstance(target, tuple) or isinstance(target, list):
t = utils.InterruptedThread(*target)
else:
t = utils.InterruptedThread(target)
threads.append(t)
t.start()
return [t.join() for t in threads]
class VirtLoggingConfig(logging_config.LoggingConfig):
"""
Used with the sole purpose of providing convenient logging setup
for the KVM test auxiliary programs.
"""
def configure_logging(self, results_dir=None, verbose=False):
super(VirtLoggingConfig, self).configure_logging(use_console=True,
verbose=verbose)
def umount(src, mount_point, fstype):
"""
Umount the src mounted in mount_point.
@src: mount source
@mount_point: mount point
@type: file system type
"""
mount_string = "%s %s %s" % (src, mount_point, fstype)
if mount_string in file("/etc/mtab").read():
umount_cmd = "umount %s" % mount_point
try:
utils.system(umount_cmd)
return True
except error.CmdError:
return False
else:
logging.debug("%s is not mounted under %s", src, mount_point)
return True
def mount(src, mount_point, fstype, perm="rw"):
"""
Mount the src into mount_point of the host.
@src: mount source
@mount_point: mount point
@fstype: file system type
@perm: mount premission
"""
umount(src, mount_point, fstype)
mount_string = "%s %s %s %s" % (src, mount_point, fstype, perm)
if mount_string in file("/etc/mtab").read():
logging.debug("%s is already mounted in %s with %s",
src, mount_point, perm)
return True
mount_cmd = "mount -t %s %s %s -o %s" % (fstype, src, mount_point, perm)
try:
utils.system(mount_cmd)
except error.CmdError:
return False
logging.debug("Verify the mount through /etc/mtab")
if mount_string in file("/etc/mtab").read():
logging.debug("%s is successfully mounted", src)
return True
else:
logging.error("Can't find mounted NFS share - /etc/mtab contents \n%s",
file("/etc/mtab").read())
return False
def install_host_kernel(job, params):
"""
Install a host kernel, given the appropriate params.
@param job: Job object.
@param params: Dict with host kernel install params.
"""
install_type = params.get('host_kernel_install_type')
if install_type == 'rpm':
logging.info('Installing host kernel through rpm')
rpm_url = params.get('host_kernel_rpm_url')
k_basename = os.path.basename(rpm_url)
dst = os.path.join("/var/tmp", k_basename)
k = utils.get_file(rpm_url, dst)
host_kernel = job.kernel(k)
host_kernel.install(install_vmlinux=False)
utils.write_keyval(job.resultdir,
{'software_version_kernel': k_basename})
host_kernel.boot()
elif install_type in ['koji', 'brew']:
logging.info('Installing host kernel through koji/brew')
koji_cmd = params.get('host_kernel_koji_cmd')
koji_build = params.get('host_kernel_koji_build')
koji_tag = params.get('host_kernel_koji_tag')
k_deps = utils_koji.KojiPkgSpec(tag=koji_tag, build=koji_build,
package='kernel',
subpackages=['kernel-devel', 'kernel-firmware'])
k = utils_koji.KojiPkgSpec(tag=koji_tag, build=koji_build,
package='kernel', subpackages=['kernel'])
c = utils_koji.KojiClient(koji_cmd)
logging.info('Fetching kernel dependencies (-devel, -firmware)')
c.get_pkgs(k_deps, job.tmpdir)
logging.info('Installing kernel dependencies (-devel, -firmware) '
'through %s', install_type)
k_deps_rpm_file_names = [os.path.join(job.tmpdir, rpm_file_name) for
rpm_file_name in c.get_pkg_rpm_file_names(k_deps)]
utils.run('rpm -U --force %s' % " ".join(k_deps_rpm_file_names))
c.get_pkgs(k, job.tmpdir)
k_rpm = os.path.join(job.tmpdir,
c.get_pkg_rpm_file_names(k)[0])
host_kernel = job.kernel(k_rpm)
host_kernel.install(install_vmlinux=False)
utils.write_keyval(job.resultdir,
{'software_version_kernel':
" ".join(c.get_pkg_rpm_file_names(k_deps))})
host_kernel.boot()
elif install_type == 'git':
logging.info('Chose to install host kernel through git, proceeding')
repo = params.get('host_kernel_git_repo')
repo_base = params.get('host_kernel_git_repo_base', None)
branch = params.get('host_kernel_git_branch')
commit = params.get('host_kernel_git_commit')
patch_list = params.get('host_kernel_patch_list')
if patch_list:
patch_list = patch_list.split()
kernel_config = params.get('host_kernel_config', None)
repodir = os.path.join("/tmp", 'kernel_src')
r = git.GitRepoHelper(uri=repo, branch=branch, destination_dir=repodir,
commit=commit, base_uri=repo_base)
r.execute()
host_kernel = job.kernel(r.destination_dir)
if patch_list:
host_kernel.patch(patch_list)
if kernel_config:
host_kernel.config(kernel_config)
host_kernel.build()
host_kernel.install()
git_repo_version = '%s:%s:%s' % (r.uri, r.branch, r.get_top_commit())
utils.write_keyval(job.resultdir,
{'software_version_kernel': git_repo_version})
host_kernel.boot()
else:
logging.info('Chose %s, using the current kernel for the host',
install_type)
k_version = utils.system_output('uname -r', ignore_status=True)
utils.write_keyval(job.resultdir,
{'software_version_kernel': k_version})
def install_cpuflags_util_on_vm(test, vm, dst_dir, extra_flags=None):
"""
Install stress to vm.
@param vm: virtual machine.
@param dst_dir: Installation path.
@param extra_flags: Extraflags for gcc compiler.
"""
if not extra_flags:
extra_flags = ""
cpuflags_src = os.path.join(test.virtdir, "deps", "test_cpu_flags")
cpuflags_dst = os.path.join(dst_dir, "test_cpu_flags")
session = vm.wait_for_login()
session.cmd("rm -rf %s" %
(cpuflags_dst))
session.cmd("sync")
vm.copy_files_to(cpuflags_src, dst_dir)
session.cmd("sync")
session.cmd("cd %s; make EXTRA_FLAGS='%s';" %
(cpuflags_dst, extra_flags))
session.cmd("sync")
session.close()
def install_disktest_on_vm(test, vm, src_dir, dst_dir):
"""
Install stress to vm.
@param vm: virtual machine.
@param src_dir: Source path.
@param dst_dir: Instaltation path.
"""
disktest_src = src_dir
disktest_dst = os.path.join(dst_dir, "disktest")
session = vm.wait_for_login()
session.cmd("rm -rf %s" % (disktest_dst))
session.cmd("mkdir -p %s" % (disktest_dst))
session.cmd("sync")
vm.copy_files_to(disktest_src, disktest_dst)
session.cmd("sync")
session.cmd("cd %s; make;" %
(os.path.join(disktest_dst, "src")))
session.cmd("sync")
session.close()
def qemu_has_option(option, qemu_path="/usr/bin/qemu-kvm"):
"""
Helper function for command line option wrappers
@param option: Option need check.
@param qemu_path: Path for qemu-kvm.
"""
hlp = commands.getoutput("%s -help" % qemu_path)
return bool(re.search(r"^-%s(\s|$)" % option, hlp, re.MULTILINE))
def bitlist_to_string(data):
"""
Transform from bit list to ASCII string.