-
Notifications
You must be signed in to change notification settings - Fork 418
/
sub_test.py
executable file
·2394 lines (2075 loc) · 99.1 KB
/
sub_test.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
#!/usr/bin/env python3
#
# Rewrite of sub_test by Sung-Eun Choi (sungeun@cray.com)
# sub_test is used by start_test in the Chapel Testing system
# August 2009
#
# This script can be overridden with a script by the same name
# placed in the test directory.
#
# The use and behavior of the various environment variables,
# settings, and files were copied straight from sub_test. They
# were added/modified to sub_test over the years, and their use
# is inconsistent and a bit of a mess. I like to think that this
# is due to the fact that the original sub_test was written in csh,
# which was probably pretty novel at the time but is quite limited
# by today's standards. In addition, I implemented the timeout
# mechanism directly rather than calling out to the timedexec
# (perl) script.
#
# For compatibility reasons, I have maintained the behavior of the
# original sub_test. Any new features (e.g., internal timeout
# mechanism) or modified behaviors (e.g., multiple .compopts,
# multiple .execopts, custom .good files) will not interfere with
# the expected behavior of tests that do not use the features or
# behaviors.
#
#
# ENVIRONMENT VARIABLES:
#
# CHPL_HOME: Grabbed from the environment or deduced based on the path to
# the compiler.
# CHPL_TEST_VGRND_COMP: Use valgrind on the compiler
# CHPL_TEST_VGRND_EXE: Use valgrind on the test program
# CHPL_VALGRIND_OPTS: Options to valgrind
# CHPL_TEST_FUTURES: 2 == test futures only
# 1 == test futures and non-futures
# 0 == test non-futures only
# CHPL_TEST_NOTESTS: Test the tests that are marked "notest" (see below)
# LAUNCHCMD: Uses this command to launch the test program
# CHPL_TEST_INTERP: DEPRECATED
# CHPL_TEST_PERF: Run as a performance test (same as -performance flag)
# CHPL_TEST_PERF_LABEL: The performance label, e.g. "perf"
# CHPL_TEST_PERF_DIR: Scratch directory for performance data
# CHPL_TEST_PERF_TRIALS: Default number of trials for perf tests
# CHPL_ONETEST: Name of the one test in this directory to run
# CHPL_TEST_SINGLES: If false, test the entire directory
# CHPL_SYSTEM_PREEXEC: If set, run comma-separated scripts on test output prior to execution
# CHPL_SYSTEM_PREDIFF: If set, run comma-separated scripts on each test output
# CHPL_COMM: Chapel communication layer
# CHPL_COMPONLY: Only build the test (same as -noexec flag)
# CHPL_TEST_NUM_LOCALES_AVAILABLE: same as CHPL_TEST_MAX_LOCALES (for backwards compatibility)
# CHPL_TEST_MAX_LOCALES: Maximum number of locales to use (overrides above)
# CHPL_TEST_MULTILOCALE_ONLY: Only run tests that use numlocales > 1
# CHPL_NO_STDIN_REDIRECT: do not redirect stdin when running tests
# also, skip tests with .stdin files
# CHPL_LAUNCHER_TIMEOUT: if defined, pass an option/options to the executable
# for it to enforce timeout instead of using timedexec;
# the value of the variable determines the option format.
# CHPL_TEST_TIMEOUT: The default global timeout to use.
# CHPL_TEST_UNIQUIFY_EXE: Uniquify the name of the test executable in the test
# system. CAUTION: This wont necessarily work for all
# tests, but can allow for running multiple start_tests
# over a directory in parallel.
# CHPL_TEST_ROOT_DIR: Absolute path to the test/ dir. Useful when test dir is
# not under $CHPL_HOME. Should not be set when test/ is
# under $CHPL_HOME. When it is set and the path prefixes a
# test in the logs, it will be removed (from the logs).
#
#
# DIRECTORY-WIDE FILES: These settings are for the entire directory and
# in many cases can be overridden or augmented with test-specific settings.
#
# NOEXEC: Do not execute tests in this directory
# NOVGRBIN: Do not execute valgrind
# COMPSTDIN: Get stdin from this file (default /dev/null)
# COMPOPTS: Compiler flags
# LASTCOMPOPTS: Compiler flags to be put at the end of the command line
# CHPLDOCOPTS: chpldoc flags
# EXECENV: Environment variables to be applied to the entire directory
# EXECOPTS: Test program flags to be applied to the entire directory
# LASTEXECOPTS: Test program flags to be put at the end of the command line
# NUMLOCALES: Number of locales to use
# CATFILES: List of files whose contents are added to end of test output
# PREDIFF: Script to execute before diff'ing output (arguments: <test
# executable>, <log>, <compiler executable>)
# PREEXEC: Script to execute before executing test program (arguments: <test
# executable>, <log>, <compiler executable>)
# PRECOMP: Script to execute before running the compiler (arguments: <test
# executable>, <log>, <compiler executable>).
# PERFNUMTRIALS: Number of trials to run for performance testing
#
#
# TEST-SPECIFIC FILES: These setting override or augment the directory-wide
# settings. Unless otherwise specified, these files are named
# <test executable>.suffix (where suffix is one of the following).
#
# .good: "Golden" output file (can have different basenames)
# .compenv: Additional environment variables for the compile
# .compopts: Additional compiler options
# .perfcompenv: Additional environment variables for performance compiling
# .perfcompopts: Additional compiler options for performance testing
# .lastcompopts: Additional compiler options to be added at the end of the
# command line
# .chpldocopts: Additional chpldoc options.
# .execenv: Additional environment variables for the test
# .execopts: Additional test options
# .perfexecenv: Additional environment variables for performance testing
# .perfexecopts: Additional test options for performance testing
# .perfnumtrials: Number of trials to run for performance testing
# .notest: Do not run this test
# .numlocales: Number of locales to use (overrides NUMLOCALES)
# .future: Future test
# .ifuture: Future test
# .noexec: Do not execute this test
# .skipif: Skip this test if certain environment conditions hold true
# .suppressif: Suppress this test if certain environment conditions hold true
# .timeout: Test timeout (overrides TIMEOUT)
# .perftimeout: Performance test timeout
# .killtimeout: Kill timeout (overrides KILLTIMEOUT)
# .catfiles: Additional list of files whose contents are added to end of
# test output
# .precomp: Additional script to execute before compiling the test
# .prediff: Additional script to execute before diff'ing output
# .preexec: Additional script to execute before executing test program
# .perfkeys: Existence indicates a performance test. Contents specifies
# performance "keys"
#
# In general, the performance label from CHPL_TEST_PERF_LABEL is used
# instead of "perf" in the above suffixes, and its all-caps version is used
# in the all-caps file names instead "PERF".
from __future__ import with_statement
import execution_limiter
import py3_compat
import sys, os, subprocess, string, signal
import operator
import select, fcntl
import fnmatch, time
import re
import shlex
import datetime
import errno
# update path to allow 'import fixpath' below
util_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'util')
config_dir = os.path.join(util_dir, 'config')
sys.path.insert(0, os.path.abspath(config_dir))
# update PATH to remove CHPL_HOME paths if any
# This essentially deactivates the venv that sub_test is run in,
# because the test venv is built inside of CHPL_HOME.
# We do this so tests/prediffs can use the system python instead of the venv
import fixpath
fixpath.update_path_env()
localdir = ''
sub_test_start_time = time.time()
def elapsed_sub_test_time():
"""Print elapsed time for sub_test call to console."""
global sub_test_start_time, localdir
elapsed_sec = time.time() - sub_test_start_time
test_name = localdir
if 'CHPL_ONETEST' in os.environ:
chpl_name = os.environ.get('CHPL_ONETEST')
base_name = os.path.splitext(chpl_name)[0]
test_name = os.path.join(test_name, base_name)
print('[Finished subtest "{0}" - {1:.3f} seconds]\n'.format(test_name, elapsed_sec))
import atexit
atexit.register(elapsed_sub_test_time)
#
# Time out class: Read from a stream until time out
# A little ugly but sending SIGALRM (or any other signal) to Python
# can be unreliable (will not respond if holding certain locks).
#
class ReadTimeoutException(Exception): pass
def SetNonBlock(stream):
flags = fcntl.fcntl(stream.fileno(), fcntl.F_GETFL)
flags |= os.O_NONBLOCK
fcntl.fcntl(stream.fileno(), fcntl.F_SETFL, flags)
def SuckOutputWithTimeout(stream, timeout):
SetNonBlock(stream)
buffer = b''
end_time = time.time() + timeout
while True:
now = time.time()
if end_time <= now:
# Maybe return partial result instead?
raise ReadTimeoutException('Teh tiem iz out!');
ready_set = select.select([stream], [], [], end_time - now)[0]
if stream in ready_set:
bytes = stream.read()
if len(bytes) == 0:
break # EOF
buffer += bytes # Inefficient way to accumulate bytes.
# len(ready_set) == 0 is also an indication of timeout. However,
# if we relied on that, we would require no data ready in order
# to timeout which doesn't seem quite right either.
return buffer
def LauncherTimeoutArgs(seconds):
if useLauncherTimeout == 'pbs' or useLauncherTimeout == 'slurm':
# --walltime=hh:mm:ss
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
fmttime = '--walltime={0:02d}:{1:02d}:{2:02d}'.format(h, m, s)
return [fmttime]
else:
Fatal('LauncherTimeoutArgs encountered an unknown format spec: ' + \
useLauncherTimeout)
#
# Auxiliary functions
#
# Escape all special characters
def ShellEscape(arg):
return re.sub(r'([\\!@#$%^&*()?\'"|<>[\]{} ])', r'\\\1', arg)
# Escape all special characters but leave spaces alone
def ShellEscapeCommand(arg):
return re.sub(r'([\\!@#$%^&*()?\'"|<>[\]{}])', r'\\\1', arg)
# Grabs the start and end of the output and replaces non-printable chars with ~
def trim_output(output):
max_size = 256*1024 # ~1/4 MB
if len(output) > max_size:
new_output = output[:max_size//2]
new_output += output[-max_size//2:]
output = new_output
return ''.join(s if s in string.printable else "~" for s in output)
# return True if f has .chpl, .test.c or .ml-test.c extension
def hasTestableExtension(f):
if f.endswith(('.chpl',
'.test.c', '.test.cpp',
'.ml-test.c', '.ml-test.cpp')):
return True
else:
return False
perflabel = '' # declare it for the following functions
# file suffix: 'keys' -> '.perfkeys' etc.
def PerfSfx(s):
return '.' + perflabel + s
# directory-wide file: 'COMPOPTS' or 'compopts' -> './PERFCOMPOPTS' etc.
def PerfDirFile(s):
return './' + perflabel.upper() + s.upper()
# test-specific file: (foo,keys) -> foo.perfkeys etc.
def PerfTFile(test_filename, sfx):
return test_filename + '.' + perflabel + sfx
def get_chplenv():
env_cmd = [os.path.join(utildir, 'printchplenv'), '--all', '--simple', '--no-tidy', '--internal']
chpl_env = py3_compat.Popen(env_cmd, stdout=subprocess.PIPE).communicate()[0]
chpl_env = dict(map(lambda l: l.split('=', 1), chpl_env.splitlines()))
return chpl_env
# Similar to os.path.expandvars but stuff chplenv into it too
def expandvars_chpl(path):
expand_env = os.environ.copy()
expand_env.update(get_chplenv())
return string.Template(path).safe_substitute(expand_env)
# Read a file or if the file is executable read its output. If the file is
# executable, the current chplenv is copied into the env before executing.
# Expands shell and chplenv variables and strip out comments/whitespace.
# Returns a list of string, one per line in the file.
def ReadFileWithComments(f, ignoreLeadingSpace=True):
mylines = ""
# if the file is executable, run it and grab the output. If we get an
# OSError while trying to run, report it and try to keep going
if os.access(f, os.X_OK):
try:
# grab the chplenv so it can be stuffed into the subprocess env
chpl_env = get_chplenv()
file_env = os.environ.copy()
file_env.update(chpl_env)
# execute the file and grab its output
cmd = py3_compat.Popen([os.path.abspath(f)], stdout=subprocess.PIPE, env=file_env)
mylines = cmd.communicate()[0].splitlines()
except OSError as e:
global localdir
f_name = os.path.join(localdir, f)
sys.stdout.write("[Error trying to execute '{0}': {1}]\n".format(f_name, str(e)))
# otherwise, just read the file
else:
with open(f, 'r') as myfile:
mylines = myfile.readlines()
mylist=list()
for line in mylines:
line = line.rstrip()
# ignore blank lines
if not line.strip(): continue
# ignore comments
if ignoreLeadingSpace:
if line.lstrip()[0] == '#': continue
else:
if line[0] == '#': continue
# expand shell variables
line = expandvars_chpl(line)
mylist.append(line)
return mylist
# diff 2 files
def DiffFiles(f1, f2):
sys.stdout.write('[Executing diff %s %s]\n'%(f1, f2))
p = py3_compat.Popen(['diff',f1,f2],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
myoutput = p.communicate()[0] # grab stdout to avoid potential deadlock
if p.returncode != 0:
sys.stdout.write(trim_output(myoutput))
return p.returncode
def DiffBinaryFiles(f1, f2):
sys.stdout.write('[Executing binary diff %s %s]\n'%(f1, f2))
p = py3_compat.Popen(['diff', '-a', f1,f2],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
myoutput = p.communicate()[0] # grab stdout to avoid potential deadlock
if p.returncode != 0:
sys.stdout.write('Binary files differed\n')
return p.returncode
# diff output vs. .bad file, filtering line numbers out of error messages that arise
# in module files.
def DiffBadFiles(f1, f2):
sys.stdout.write('[Executing diff-ignoring-module-line-numbers %s %s]\n'%(f1, f2))
p = py3_compat.Popen([utildir+'/test/diff-ignoring-module-line-numbers', f1, f2],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
myoutput = p.communicate()[0] # grab stdout to avoid potential deadlock
if p.returncode != 0:
sys.stdout.write(myoutput)
return p.returncode
# kill process
def KillProc(p, timeout):
k = py3_compat.Popen(['kill',str(p.pid)])
k.wait()
now = time.time()
end_time = now + timeout # give it a little time
while end_time > now:
if p.poll():
return
now = time.time()
# use the big hammer (and don't bother waiting)
py3_compat.Popen(['kill','-9', str(p.pid)])
return
# clean up after the test has been built
def cleanup(execname):
try:
if execname is not None:
if os.path.isfile(execname):
os.unlink(execname)
if os.path.isfile(execname+'_real'):
os.unlink(execname+'_real')
except (IOError, OSError) as ex:
# If the error is "Device or resource busy", call lsof on the file (or
# handle for windows) to see what is holding the file handle, to help
# debug the issue.
if isinstance(ex, OSError) and ex.errno == 16:
handle = which('handle')
lsof = which('lsof')
if handle is not None:
sys.stdout.write('[Inspecting open file handles with: {0}\n'.format(handle))
py3_compat.Popen([handle]).communicate()
elif lsof is not None:
cmd = [lsof, execname]
sys.stdout.write('[Inspecting open file handles with: {0}\n'.format(' '.join(cmd)))
py3_compat.Popen(cmd).communicate()
# Do not print the warning for cygwin32 when errno is 16 (Device or resource busy).
if not (getattr(ex, 'errno', 0) == 16 and platform == 'cygwin32'):
sys.stdout.write('[Warning: could not remove {0}: {1}]\n'.format(execname, ex))
def which(program):
"""Returns absolute path to program, if it exists in $PATH. If not found,
returns None.
From: http://stackoverflow.com/a/377028
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ.get('PATH', '').split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
# print (compopts: XX, execopts: XX) for later decoding of failed tests
def printTestVariation(compoptsnum, compoptslist,
execoptsnum=0, execoptslist=[] ):
printCompOpts = True
printExecOpts = True
if compoptsnum==0 or len(compoptslist) <= 1:
printCompOpts = False
if execoptsnum==0 or len(execoptslist) <= 1:
printExecOpts = False
if (not printCompOpts) and (not printExecOpts):
return;
sys.stdout.write(' (')
if printCompOpts:
sys.stdout.write('compopts: %d'%(compoptsnum))
if printExecOpts:
if printCompOpts:
sys.stdout.write(', ')
sys.stdout.write('execopts: %d'%(execoptsnum))
sys.stdout.write(')')
return
# print '[Elapsed time to compile and execute all versions of ...'
# in the format expected by convert_start_test_log_to_junit_xml.py.
def printEndOfTestMsg(test_name, elapsedTime):
sys.stdout.flush()
print('[Elapsed time to compile and execute all versions of "{0}" - '
'{1:.3f} seconds]'.format(test_name, elapsedTime))
# return true if string is an integer
def IsInteger(str):
try:
int(str)
return True
except ValueError:
return False
# read integer value from a file
def ReadIntegerValue(f, localdir):
to = ReadFileWithComments(f)
if to:
for l in to:
if l[0] == '#':
continue
if IsInteger(l):
return int(l)
else:
break
Fatal('Invalid integer value in '+f+' ('+localdir+')')
# report an error message and exit
def Fatal(message):
sys.stdout.write('[Error (sub_test): '+message+']\n')
magic_exit_code = reduce(operator.add, map(ord, 'CHAPEL')) % 256
sys.exit(magic_exit_code)
# Attempts to find an appropriate timer to use. The timer must be in
# util/test/timers/. Expects to be passed a file containing only the name of
# the timer script. If the file is improperly formatted the default timer is
# used, and if the timer is not executable or can't be found 'time -p' is used
def GetTimer(f):
timersdir = os.path.join(utildir, 'test', 'timers')
defaultTimer = os.path.join(timersdir, 'defaultTimer')
lines = ReadFileWithComments(f)
if len(lines) != 1:
sys.stdout.write('[Error "%s" must contain exactly one non-comment line '
'with the name of the timer located in %s to use. Using default '
'timer %s.]\n' %(f, timersdir, defaultTimer))
timer = defaultTimer
else:
timer = os.path.join(timersdir, lines[0])
if not os.access(timer,os.R_OK|os.X_OK):
sys.stdout.write('[Error cannot execute timer "%s", using "time -p"]\n' %(timer))
return 'time -p'
return timer
# attempts to find an appropriate .good file. Good files are expected to be of
# the form basename.<configuration>.<commExecNums>.good. Where configuration
# options are one of the below configuration specific parameters that are
# checked for. E.G the current comm layer. commExecNums are the optional
# compopt and execopt number to enable different .good files for different
# compopts/execopts with explicitly specifying name.
def FindGoodFile(basename, commExecNums=['']):
goodfile = ''
for commExecNum in commExecNums:
# Try the machine specific .good
if not os.path.isfile(goodfile):
goodfile = basename+'.'+machine+commExecNum+'.good'
# Else if --no-local try the no-local .good file.
if not os.path.isfile(goodfile):
if '--no-local' in envCompopts:
goodfile=basename+'.no-local'+commExecNum+'.good'
# Else try comm-, networkAtomics-, and localeModel-specific .good
# files. All 3, any 2, or just 1 of these may be used, but if more
# then 1 they must be in the above order.
if not os.path.isfile(goodfile):
for specstr in [ chplcommstr+chplnastr+chpllmstr,
chplcommstr+chplnastr,
chplcommstr+chpllmstr,
chplnastr+chpllmstr,
chplcommstr,
chplnastr,
chpllmstr ]:
goodfile=basename+specstr+commExecNum+'.good'
if os.path.isfile(goodfile):
break
# Else try the platform-specific .good file.
if not os.path.isfile(goodfile):
goodfile=basename+'.'+platform+commExecNum+'.good'
# Else use the execopts-specific .good file.
if not os.path.isfile(goodfile):
goodfile=basename+commExecNum+'.good'
return goodfile
def get_exec_log_name(execname, comp_opts_count=None, exec_opts_count=None):
"""Returns the execution output log name based on number of comp and exec opts."""
suffix = '.exec.out.tmp'
if comp_opts_count is None and exec_opts_count is None:
return '{0}{1}'.format(execname, suffix)
else:
return '{0}.{1}-{2}{3}'.format(execname, comp_opts_count, exec_opts_count, suffix)
# Use testEnv to process skipif files, it works for executable and
# non-executable versions
def runSkipIf(skipifName):
p = py3_compat.Popen([utildir+'/test/testEnv', './'+skipifName], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
status = p.returncode
stderr = stderr.strip()
errmsg = ""
if stderr:
errmsg = stderr
if status:
if stderr:
errmsg += '\n'
errmsg += 'exit status %d' % (status)
if stderr or status:
raise RuntimeError(errmsg)
return stdout
# Translate some known failures into more easily understood forms
def translateOutput(output_in):
xlates = (('slurmstepd: Munge decode failed: Expired credential',
'Jira 18 -- Expired slurm credential for'),
('output file from job .* does not exist',
'private issue #906 -- Missing output file for'),
('aprun: Unexpected close of the apsys control connection',
'Jira 193 -- Unexpected close of apsys for'),
('qsub: cannot connect to server sdb',
'Jira 283 -- Sporadic: qstat failed to connect to server sdb'),
('Failed to recv data from background qsub',
'Jira 260 -- Failed to recv data from background qsub for'),
(r'\d+ Killed /var/spool/PBS/mom_priv/jobs',
'Jira 324 -- PBS job killed for'),
('Fatal MPP reservation error on confirm',
'Jira 329 -- Fatal MPP reservation error for'),
('Fatal MPP reservation error on create',
'Jira 329 -- Fatal MPP reservation error for'),
('Text file busy',
'private issue #474 -- Text file busy for'),
('Socket timed out on send/recv operation',
'private issue #579 -- Slurm socket timed out on send/recv'))
known_error = ''
was_timeout = False
output = output_in
if isinstance(output, bytes):
output = str(output, encoding='utf-8', errors='surrogateescape')
for x in xlates:
if re.search(x[0], output, re.IGNORECASE) != None:
known_error = x[1]
break
else:
if (re.search('PBS: job killed: walltime', output, re.IGNORECASE) != None or
re.search('slurm.* CANCELLED .* DUE TO TIME LIMIT', output, re.IGNORECASE) != None):
known_error = 'Timed out executing program'
was_timeout = True
return known_error, was_timeout
# Remove innocuous warnings about clock skew from when we `make` the generated code
def remove_clock_skew_warning(output):
output = re.sub(r'g?make.*: Warning: File .* has modification time .* s in the future *\n', '', output)
output = re.sub(r'g?make.*: warning: Clock skew detected\. Your build may be incomplete\. *\n', '', output)
return output
def filter_compiler_errors(compiler_output):
"""Identify common errors that occur in compilation.
Return message to emit when error found."""
error_msg = ''
err_strings = ['could not checkout FLEXlm license']
for s in err_strings:
if re.search(s, compiler_output, re.IGNORECASE) != None:
error_msg = '(private issue #398) '
break
return error_msg
def filter_errors(output_in, pre_exec_output, execgoodfile, execlog):
"""Identify common errors that occur in runtime or compiler warnings.
Return message to emit when error found."""
# If the output contains messages consistent with JIRA 154, add a
# hint to the error summary and force a text base diff since
# sometimes the output contains a null character
extra_msg = ''
err_strings = ['got exn while reading exit code: connection closed',
'slave got an unknown command on coord socket:',
'Slave got an xSocket: connection closed on recv',
'recursive failure in AMUDP_SPMDShutdown',
'AM_ERR_RESOURCE \(Problem with requested resource\)']
output = output_in
if isinstance(output, bytes):
output = str(output, encoding='utf-8', errors='surrogateescape')
for s in err_strings:
if re.search(s, output, re.IGNORECASE) != None:
extra_msg = '(possible JIRA 154) '
DiffBinaryFiles(execgoodfile, execlog)
break
err_strings = ['Master got an xSocket: error in sendAll']
for s in err_strings:
if re.search(s, output, re.IGNORECASE) != None:
extra_msg = '(possible JIRA 274) '
break
err_strings = ['Clock skew detected']
for s in err_strings:
# NOTE: checking pre_exec (compiler) output
if re.search(s, pre_exec_output, re.IGNORECASE) != None:
extra_msg = '(private issue #482) '
break
err_strings = ['could not checkout FLEXlm license']
for s in err_strings:
if (re.search(s, output, re.IGNORECASE) != None or
re.search(s, pre_exec_output, re.IGNORECASE) != None):
extra_msg = '(private issue #398) '
break
err_strings = ['=* Memory Leaks =*']
for s in err_strings:
if (re.search(s, output, re.IGNORECASE) != None):
extra_msg = '(memory leak) '
break
# detect cases of 'GASNet timer calibration on %s detected non-linear
# timer behavior:' messages which we can't do much about
err_strings = ['GASNet timer calibration on']
for s in err_strings:
if (re.search(s, output, re.IGNORECASE) != None):
extra_msg = '(private issue #480) '
break
return extra_msg
# Start of sub_test proper
#
if len(sys.argv)!=2:
print('usage: sub_test COMPILER')
sys.exit(0)
# Find the base installation
compiler=sys.argv[1]
if not os.access(compiler,os.R_OK|os.X_OK):
Fatal('Cannot execute compiler \''+compiler+'\'')
is_chpldoc = compiler.endswith('chpldoc')
path_to_compiler=os.path.abspath(os.path.dirname(compiler))
# Assume chpl binary is 2 directory levels down in the base installation
(chpl_base, tmp) = os.path.split(path_to_compiler)
(chpl_base, tmp) = os.path.split(chpl_base)
chpl_base=os.path.normpath(chpl_base)
# sys.stdout.write('CHPL_BASE='+chpl_base+'\n')
# If $CHPL_HOME is not set, use the base installation of the compiler
chpl_home=os.getenv('CHPL_HOME', chpl_base);
chpl_home=os.path.normpath(chpl_home)
# sys.stdout.write('CHPL_HOME='+chpl_home+'\n');
# Find the test util directory -- set this in start_test to permit
# a version of start_test other than the one in CHPL_HOME to be used
utildir=os.getenv('CHPL_TEST_UTIL_DIR');
if utildir is None or not os.path.isdir(utildir):
Fatal('Cannot find test util directory {0}'.format(utildir))
# Needed for MacOS mount points
utildir = os.path.realpath(utildir)
# sys.stdout.write('utildir='+utildir+'\n');
# Find the c compiler
# We open the compileline inside of CHPL_HOME rather than CHPL_TEST_UTIL_DIR on
# purpose. compileline will not work correctly in some configurations when run
# outside of its directory tree.
compileline = os.path.join(chpl_home, 'util', 'config', 'compileline')
p = py3_compat.Popen([compileline, '--compile'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
c_compiler = p.communicate()[0].rstrip()
if p.returncode != 0:
Fatal('Cannot find c compiler')
p = py3_compat.Popen([compileline, '--compile-c++'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
cpp_compiler = p.communicate()[0].rstrip()
if p.returncode != 0:
Fatal('Cannot find c++ compiler')
p = py3_compat.Popen([compileline, '--host-c-compiler'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
host_c_compiler = p.communicate()[0].rstrip()
if p.returncode != 0:
Fatal('Cannot find host c compiler')
p = py3_compat.Popen([compileline, '--host-cxx-compiler'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
host_cpp_compiler = p.communicate()[0].rstrip()
if p.returncode != 0:
Fatal('Cannot find host c++ compiler')
# Get runtime includes and defines
p = py3_compat.Popen([compileline, '--includes-and-defines'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
runtime_includes_and_defines= p.communicate()[0].rstrip()
if p.returncode != 0:
Fatal('Cannot find runtime includes and defines')
# Find the test directory
testdir=chpl_home+'/test'
if os.path.isdir(testdir)==0:
testdir=chpl_home+'/examples'
if os.path.isdir(testdir)==0:
Fatal('Cannot find test directory '+chpl_home+'/test or '+testdir)
# Needed for MacOS mount points
testdir = os.path.realpath(testdir)
# sys.stdout.write('testdir='+testdir+'\n');
# If user specified a different test directory (e.g. with --test-root flag on
# start_test), use it instead.
test_root_dir = os.environ.get('CHPL_TEST_ROOT_DIR')
if test_root_dir is not None:
testdir = test_root_dir
# Use timedexec
# As much as I hate calling out to another script for the time out stuff,
# subprocess doesn't quite cut it for this kind of stuff
useTimedExec=True
if useTimedExec:
timedexec=utildir+'/test/timedexec'
if not os.access(timedexec,os.R_OK|os.X_OK):
Fatal('Cannot execute timedexec script \''+timedexec+'\'')
# sys.stdout.write('timedexec='+timedexec+'\n');
# HW platform
platform=py3_compat.Popen([utildir+'/chplenv/chpl_platform.py', '--target'], stdout=subprocess.PIPE).communicate()[0]
platform = platform.strip()
# sys.stdout.write('platform='+platform+'\n')
# Machine name we are running on
machine=os.uname()[1].split('.', 1)[0]
# sys.stdout.write('machine='+machine+'\n')
# Get the system-wide preexec(s)
systemPreexecs = os.getenv('CHPL_SYSTEM_PREEXEC')
if systemPreexecs:
systemPreexecs = systemPreexecs.strip().split(',')
for spreexec in systemPreexecs:
if not os.access(spreexec, os.R_OK|os.X_OK):
Fatal('Cannot execute system-wide preexec \''+spreexec+'\'')
# Get the system-wide prediff(s)
systemPrediffs = os.getenv('CHPL_SYSTEM_PREDIFF')
if systemPrediffs:
systemPrediffs = systemPrediffs.strip().split(',')
for sprediff in systemPrediffs:
if not os.access(sprediff,os.R_OK|os.X_OK):
Fatal('Cannot execute system-wide prediff \''+sprediff+'\'')
# Use the launcher walltime option for timeout
useLauncherTimeout = os.getenv('CHPL_LAUNCHER_TIMEOUT')
uniquifyTests = False
if os.getenv('CHPL_TEST_UNIQUIFY_EXE') != None:
uniquifyTests = True
# Get the current directory (normalize for MacOS case-sort-of-sensitivity)
localdir = os.path.normpath(os.getcwd()).replace(testdir, '.')
# sys.stdout.write('localdir=%s\n'%(localdir))
if localdir.find('./') == 0:
# strip off the leading './'
localdir = localdir.lstrip('.')
localdir = localdir.lstrip('/')
# sys.stdout.write('localdir=%s\n'%(localdir))
# CHPL_COMM
chplcomm=os.getenv('CHPL_COMM','none').strip()
chplcommstr='.comm-'+chplcomm
# sys.stdout.write('chplcomm=%s\n'%(chplcomm))
# CHPL_NETWORK_ATOMICS
chplna=os.getenv('CHPL_NETWORK_ATOMICS','none').strip()
chplnastr='.na-'+chplna
#sys.stdout.write('chplna=%s\n'%(chplna))
# CHPL_LAUNCHER
chpllauncher=os.getenv('CHPL_LAUNCHER','none').strip()
# CHPL_LOCALE_MODEL
chpllm=os.getenv('CHPL_LOCALE_MODEL','flat').strip()
chpllmstr='.lm-'+chpllm
#sys.stdout.write('lm=%s\n'%(chpllm))
#
# Test options for all tests in this directory
#
if os.getenv('CHPL_TEST_PERF')!=None:
perftest=True
perflabel=os.getenv('CHPL_TEST_PERF_LABEL')
perfdir=os.getenv('CHPL_TEST_PERF_DIR')
perfdescription = os.getenv('CHPL_TEST_PERF_DESCRIPTION')
if perfdescription != None:
sys.stdout.write('Setting perfdir to %s from %s because of additional perf description\n' %(os.path.join(perfdir, perfdescription), perfdir))
perfdir = os.path.join(perfdir, perfdescription)
else:
perfdescription= ''
if perflabel==None or perfdir==None:
Fatal('$CHPL_TEST_PERF_DIR and $CHPL_TEST_PERF_LABEL must be set for performance testing')
else:
perftest=False
perflabel=''
compoptssuffix = PerfSfx('compopts') # .compopts or .perfcompopts or ...
# If compiler is chpldoc, use .chpldocopts for options.
chpldocsuffix = '.chpldocopts'
compenvsuffix = PerfSfx('compenv') # compenv or .perfcompenv or ...
execenvsuffix = PerfSfx('execenv') # .execenv or .perfexecenv or ...
execoptssuffix = PerfSfx('execopts') # .execopts or .perfexecopts or ...
timeoutsuffix = PerfSfx('timeout') # .timeout or .perftimeout or ...
# sys.stdout.write('perftest=%d perflabel=%s\n'%(perftest,perflabel))
# Get global timeout
if os.getenv('CHPL_TEST_VGRND_COMP')=='on' or os.getenv('CHPL_TEST_VGRND_EXE')=='on':
defaultTimeout=1000
else:
defaultTimeout=300
globalTimeout = int(os.getenv('CHPL_TEST_TIMEOUT', defaultTimeout))
# get a threshold for which to report long running tests
if os.getenv("CHPL_TEST_EXEC_TIME_WARN_LIMIT"):
execTimeWarnLimit = int(os.getenv('CHPL_TEST_EXEC_TIME_WARN_LIMIT', '0'))
else:
execTimeWarnLimit = 0
# get a threshold for which to skip any remaining trials
if os.getenv("CHPL_TEST_EXEC_TIME_LIMIT_NUM_TRIALS"):
execTimeSkipTrials = int(os.getenv('CHPL_TEST_EXEC_TIME_LIMIT_NUM_TRIALS', '0'))
else:
execTimeSkipTrials = 0
# directory level timeout
directoryTimeout = globalTimeout
if os.access('./TIMEOUT',os.R_OK):
fileTimeout = ReadIntegerValue('./TIMEOUT', localdir)
if fileTimeout < defaultTimeout or fileTimeout > globalTimeout:
directoryTimeout = fileTimeout
# sys.stdout.write('globalTimeout=%d\n'%(globalTimeout))
# Check for global PERFTIMEEXEC option
timerFile = PerfDirFile('TIMEEXEC') # e.g. ./PERFTIMEEXEC
if os.access(timerFile, os.R_OK):
globalTimer = GetTimer(timerFile)
else:
globalTimer = None
# Get global timeout for kill
if os.access('./KILLTIMEOUT',os.R_OK):
globalKillTimeout = ReadIntegerValue('./KILLTIMEOUT', localdir)
else:
globalKillTimeout=10
# sys.stdout.write('globalKillTimeout=%d\n'%(globalKillTimeout))
if os.access('./NOEXEC',os.R_OK):
execute=False
else:
execute=True
# sys.stdout.write('execute=%d\n'%(execute))
if os.access('./NOVGRBIN',os.R_OK):
vgrbin=False
else:
vgrbin=True
# sys.stdout.write('vgrbin=%d\n'%(vgrbin))
if os.access('./COMPSTDIN',os.R_OK):
compstdin='./COMPSTDIN'
else:
compstdin='/dev/null'
# sys.stdout.write('compstdin=%s\n'%(compstdin))
globalLastcompopts=list();
if os.access('./LASTCOMPOPTS',os.R_OK):
globalLastcompopts+=py3_compat.Popen(['cat', './LASTCOMPOPTS'], stdout=subprocess.PIPE).communicate()[0].strip().split()
# sys.stdout.write('globalLastcompopts=%s\n'%(globalLastcompopts))
globalLastexecopts=list();
if os.access('./LASTEXECOPTS',os.R_OK):
globalLastexecopts+=py3_compat.Popen(['cat', './LASTEXECOPTS'], stdout=subprocess.PIPE).communicate()[0].strip().split()
# sys.stdout.write('globalLastexecopts=%s\n'%(globalLastexecopts))
if os.access(PerfDirFile('NUMLOCALES'),os.R_OK):
globalNumlocales=ReadIntegerValue(PerfDirFile('NUMLOCALES'), localdir)
# globalNumlocales.strip(globalNumlocales)
else:
# start_test sets this, so we'll assume it's right :)
globalNumlocales=int(os.getenv('NUMLOCALES', '0'))
# sys.stdout.write('globalNumlocales=%s\n'%(globalNumlocales))
maxLocalesAvailable = os.getenv('CHPL_TEST_MAX_LOCALES')
if maxLocalesAvailable == None:
maxLocalesAvailable = os.getenv('CHPL_TEST_NUM_LOCALES_AVAILABLE')
if maxLocalesAvailable is not None:
maxLocalesAvailable = int(maxLocalesAvailable)
if os.access('./CATFILES',os.R_OK):
globalCatfiles=py3_compat.Popen(['cat', './CATFILES'], stdout=subprocess.PIPE).communicate()[0]
globalCatfiles.strip(globalCatfiles)
else:
globalCatfiles=None
# sys.stdout.write('globalCatfiles=%s\n'%(globalCatfiles))
#
# valgrind stuff
#
chpl_valgrind_opts=os.getenv('CHPL_VALGRIND_OPTS', '--tool=memcheck')
# sys.stdout.write('chpl_valgrind_opts=%s\n'%(chpl_valgrind_opts))
if os.getenv('CHPL_TEST_VGRND_COMP')=='on':
valgrindcomp = 'valgrind'
valgrindcompopts=chpl_valgrind_opts.split()
valgrindcompopts+=['--gen-suppressions=all']
valgrindcompopts+=['--suppressions=%s/compiler/etc/valgrind.suppressions'%(chpl_home)]
valgrindcompopts+=['-q']
else:
valgrindcomp = None
valgrindcompopts = None
# sys.stdout.write('valgrindcomp=%s %s\n'%(valgrindcomp, valgrindcompopts))
if (os.getenv('CHPL_TEST_VGRND_EXE')=='on' and vgrbin):
valgrindbin = 'valgrind'
valgrindbinopts = chpl_valgrind_opts.split()+['-q']
if (chplcomm!='none'):
valgrindbinopts+=['--trace-children=yes']
if (chplcomm=='gasnet'):
valgrindbinopts+=['--suppressions=%s/third-party/gasnet/gasnet-src/other/valgrind/gasnet.supp'%(chpl_home)]
else:
valgrindbin = None
valgrindbinopts = None
# sys.stdout.write('valgrindbin=%s %s\n'%(valgrindbin, valgrindbinopts))
#
# Misc set up
#
testfutures=int(os.getenv('CHPL_TEST_FUTURES','0'))