-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestrunner.py
executable file
·1506 lines (1220 loc) · 61 KB
/
testrunner.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 python
# testrunner.py
# loads a yaml file, runs tests defined within that file
import argparse
import collections
import copy
import datetime
import itertools
import logging
import magic
import os
import pdb
import pprint
import random
import re
import shlex
import signal
import socket
import sys
import tempfile
import threading
import time
import yaml
if os.name == 'posix' and sys.version_info[0] < 3:
import subprocess32 as subprocess
else:
import subprocess
# logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# globals
global args
global r_vars # dict of replacement vars
global loop_vars # dict of arrays of vars to loop tasks on
global debughelper # help with debugging
global tbr
def signal_handler(signal, frame):
global tbr
print('Exiting...')
tbr.stop_daemons()
sys.exit(0)
def parse_args():
global args
parser = argparse.ArgumentParser()
parser.add_argument('tasks_file',
type=argparse.FileType('r'),
help="YAML tasks input filename")
parser.add_argument('output_file',
type=argparse.FileType('w'),
help="muxed output/error filename")
parser.add_argument('-b', '--buildurl',
default=False,
help="define the build url")
parser.add_argument('-c', '--callgrind',
default=False,
help="run valgrind callgrind, specify output file")
parser.add_argument('-d', '--debug',
action="store_true",
help="print debugging info")
parser.add_argument('-i', '--immediate',
action="store_true",
help="immediately print subprocess stdout/err")
parser.add_argument('-m', '--memcheck',
const='stderr',
default=False,
nargs='?',
help="run valgrind memcheck, specify output to stderr (default), stdout, file name, or ip:socket")
parser.add_argument('-o', '--operf',
default=False,
help="run operf")
parser.add_argument('-t', '--tap_file',
help="TAP output filename")
parser.add_argument('-f', '--time_format',
default="%Y-%m-%dT%H:%M:%S.%f",
help="specify a strftime() format")
args = parser.parse_args()
# now that we have an output file path, create a debug file handler
outputfilenamepath=((("%s" % args.output_file).split(",")[0]).split()[2]).replace("'","")
handler = logging.FileHandler(outputfilenamepath + ".debug.txt","w")
formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s", datefmt="%Y-%m-%dT%H:%M:%S")
formatter.converter = time.gmtime
handler.setFormatter(formatter)
logger.addHandler(handler)
def import_env():
global r_vars
r_vars = {}
env_var_names = [
"HOSTNAME",
"CONFIG_ROOT",
"SYNDICATE_ADMIN",
"SYNDICATE_MS",
"SYNDICATE_MS_ROOT",
"SYNDICATE_MS_KEYDIR",
"SYNDICATE_PRIVKEY_PATH",
"SYNDICATE_ROOT",
"SYNDICATE_TOOL",
"SYNDICATE_RG_ROOT",
"SYNDICATE_UG_ROOT",
"SYNDICATE_AG_ROOT",
"SYNDICATE_PYTHON_ROOT",
]
logger.debug("Environmental Vars:")
for e_key in env_var_names:
if os.environ.has_key(e_key):
r_vars[e_key] = os.environ[e_key]
logger.debug(" %s=%s" % (e_key, r_vars[e_key]))
elif e_key is 'HOSTNAME': #get hostname if it is not defined
r_vars[e_key] = socket.gethostname()
else: #log if env variables are missing
logger.error("Missing environment variable: %s" % e_key)
def tmpdir(name, varname=None, mode=0700):
global r_vars
testprefix = "synd-" + name + "-"
testdir = tempfile.mkdtemp(dir="/tmp", prefix=testprefix)
os.chmod(testdir, mode)
if varname is None:
varname = name
r_vars[varname] = testdir
logger.debug("Created tmpdir '%s', with path: '%s', with mode: '%o'" % (varname, testdir, mode))
def randstring(size):
pattern = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
return "".join([random.choice(pattern) for _ in range(size)])
def randname(name, size=12, varname=None):
global r_vars
r_name = "%s-%s" % (name, randstring(size))
if varname is None:
varname = name
r_vars[varname] = r_name
logger.debug("Created randname '%s' with value '%s'" %
(varname, r_name))
def randloop(name, quantity, size=12, copy=None, prepend='', varname=None):
global loop_vars
vararray = []
if type(copy) is str:
for icopy in loop_vars[copy]:
vararray.append("%s%s" % (prepend, icopy))
else:
for i in xrange(0, quantity):
vararray.append("%s-%s" % (name, randstring(size)))
if varname is None:
varname = name
loop_vars[varname] = vararray
logger.debug("Created random loop_var '%s' with %d items" %
(varname, quantity))
def seqloop(name, quantity, start=0, step=1, varname=None):
global loop_vars
if varname is None:
varname = name
loop_vars[varname] = range(start, start + quantity * step, step)
logger.debug("Created sequential loop_var '%s' with %d items" %
(varname, quantity))
def valueloop(name, values, varname=None):
global loop_vars
if varname is None:
varname = name
loop_vars[varname] = values
logger.debug("Created values loop_var '%s' with %d items" %
(varname, len(loop_vars[varname])))
def newvar(name, value):
global r_vars
r_vars[name] = replace_vars(value)
logger.debug("Created newvar '%s' with value '%s'" % (name, r_vars[name]))
def replace_vars(string):
global r_vars
# convert subscript format to dot format, for dictionaries
string = re.sub(r"\[\'", ".", string)
string = re.sub(r"\'\]", "", string)
# remove braces within brackets, in case a user is specifying an index of an array using a variable with braces, i.e. $array[${index}] => $array[$index]
string = re.sub(r"\[\$\{", "[$", string)
string = re.sub(r"\}\]", "]", string)
# first capture on space/word boundaries with and without dictionary keys
rsv = re.compile('[\$|\@](\w+\.\w+|\w+)(?:\W|$)*?')
rsv_matches = rsv.findall(string)
for match in rsv_matches:
if ('@%s' % match) in string: #look for @ syntax, which prints the list as a string
rr = re.compile('\@%s' % match)
if match in loop_vars and loop_vars[match] is not False:
liststr = ' '.join(loop_vars[match])
string = rr.sub(' '.join(loop_vars[match]), string, count=1) #access all elements from the loop_vars variable instead of r_vars
elif ('%s[' % match) in string: #check for explicit array use
riv = re.compile('%s\[\$?(\S+)\]' % match)
idxvar = riv.findall(string)
if not idxvar:
logger.error("Improper syntax for array: '$%s' in '%s'" % (match, string))
elif idxvar[0].isdigit(): #a hard coded index was set, i.e. $a[0]
idx = int(idxvar[0])
else: #an index variable was used, i.e. $a[$i]
idx = int(r_vars[idxvar[0]])
if type(loop_vars[match][idx]) is dict:
rrm = re.compile('%s\[\$?\S+\]\}?\.(\w+)' % match) #capture the dict dot string reference
rr_match = rrm.findall(string)
rr = re.compile('\$\{?%s\[\$?\S+\]\}?\.\w+' % match) #capture the array string reference
string = rr.sub(str(loop_vars[match][idx][rr_match[0]]), string, count=1) #and replace with the dict value
else:
rr = re.compile('\$\{?%s\[\$?\S+\]\}?' % match) #capture the array string refernce
string = rr.sub(str(loop_vars[match][idx]), string, count=1) #and replace with the array's value
elif match in r_vars: #see if captured matches are defined as a replacement variable
if match in string:
rr = re.compile('\$%s' % match)
string = rr.sub(r_vars[match], string, count=1)
else:
logger.error("Unknown variable: '$%s' in '%s'" %
(match, string))
# second capture with explicit {}'s, also look for []'s within {}'s, i.e. ${a[$i]}
rcv = re.compile('\$\{(\w+\.\w+|\w+)(?:\[\S+\])?}(?:\W|$)*?')
rcv_matches = rcv.findall(string)
for match in rcv_matches:
if ('%s[' % match) in string: #check for explicit array use
riv = re.compile('%s\[\$?(\S+)\]' % match)
idxvar = riv.findall(string)
if not idxvar:
logger.error("Improper syntax for array: '$%s' in '%s'" %
(match, string))
elif idxvar[0].isdigit(): #a hard coded index was set, i.e. ${a[0]}, or the first capture replaced the index variable
idx = int(idxvar[0])
else: #an index variable was used, i.e. ${a[$i]}
idx = int(r_vars[idxvar[0]])
if type(loop_vars[match][idx]) is dict:
rrm = re.compile('%s\[\$?\S+\]\}?\.(\w+)' % match) #capture the dict dot string reference
rr_match = rrm.findall(string)
rr = re.compile('\$\{?%s\[\$?\S+\]\}?\.\w+' % match) #capture the array string reference
string = rr.sub(str(loop_vars[match][idx][rr_match[0]]), string, count=1) #and replace with the array's value
else:
rr = re.compile('\$\{?%s\[\$?\S+\]\}?' % match) #capture the array string refernce
string = rr.sub(str(loop_vars[match][idx]), string, count=1) #and replace with the array's value
elif match in r_vars:
if match in string:
rr = re.compile('\$\{%s\}' % match)
string = rr.sub(r_vars[match], string, count=1)
else:
logger.error("Unknown variable: '$%s' in '%s'" %
(match, string))
return string
class CommandRunner():
"""
Encapsulates running a subprocess and validates return code
and optionally stdout/err streams
"""
def __init__(self, task, taskb_name):
self.buildurl = None
self.task = {}
self.p = None
self.run_in_shell = False
self.out_th = {}
self.err_th = {}
self.start_t = None
self.end_t = None
self.valgrindoutfile = ''
self.defaulttimeout = 180
self.timeout = self.defaulttimeout
self.taskb_name = taskb_name
self.q = collections.deque()
self.task = task
if args.buildurl:
self.buildurl = args.buildurl
elif os.environ.has_key("BUILD_URL"):
self.buildurl = os.environ.get("BUILD_URL",'')
if "shell" in task:
self.run_in_shell = True
self.task['command'] = task['shell']
for req_key in ["name", "command", ]:
if req_key not in self.task:
logger.error("no key '%s' in command description: %s" %
(req_key, self.task))
sys.exit(1)
def __pipe_reader(self, stream, stream_name, task_desc):
global args
for line in iter(stream.readline, b''):
event = {"time": time.time(), "stream": stream_name,
"task": task_desc, "line": line}
self.q.append(event)
# print is not thread safe, but works, mostly...
if args.immediate:
print self.decorate_output(event)
stream.close()
self.end_t = time.time()
@staticmethod
def decorate_output(event):
global args
event_dt = datetime.datetime.utcfromtimestamp(event['time'])
return ('%s | %s,%s | %s' % (event_dt.strftime(args.time_format),
event['task'], event['stream'],
event['line'].rstrip()))
def run(self):
global r_vars
global debughelper
# $task_name is name of current task
r_vars['task_name'] = self.task['name']
# replace variables
command = replace_vars(self.task['command'])
self.task['repl_command'] = command
ON_POSIX = 'posix' in sys.builtin_module_names
run_params = {"stdout": subprocess.PIPE, "stderr": subprocess.PIPE,
"bufsize": 1, "close_fds": ON_POSIX, }
if "infile" in self.task:
in_fname = replace_vars(self.task['infile'])
if os.path.isfile(in_fname):
run_params["stdin"] = open(in_fname, 'r')
else:
logger.error("infile '%s' is not a file" % in_fname)
sys.exit(1)
if "timeout" in self.task:
self.timeout = self.task["timeout"]
else:
self.timeout = self.defaulttimeout
debughelper.Check(self.task)
command = debughelper.ModifyCommand(command, self.task)
self.valgrindoutfile = debughelper.valgrindoutfile
if debughelper.debugrun:
logger.debug("Running Task '%s': `%s`" % (self.task['name'], command))
self.p = subprocess.Popen(shlex.split(command))
elif self.run_in_shell:
# pass command as string if running in a shell
logger.debug("Running Task '%s': `%s` in shell" % (self.task['name'], command))
run_params['shell'] = True
if debughelper.show:
print ("Execute (sh) Task '%s': Command: `%s`" % (self.task['name'], command))
else:
self.p = subprocess.Popen(command, **run_params)
else:
# split command into array for running directly
c_array = shlex.split(command)
logger.debug("Running Task '%s': `%s`" % (self.task['name'], command))
if debughelper.show:
print ("Execute Task '%s': Command: `%s`" % (self.task['name'], command))
else:
self.p = subprocess.Popen(c_array, **run_params)
self.start_t = time.time()
if not debughelper.show and not debughelper.debugrun:
self.out_th = threading.Thread(
target=self.__pipe_reader,
args=(self.p.stdout, "o",
"%s:%s" % (self.taskb_name, self.task['name'])))
self.out_th.daemon = True # thread ends when subprocess does
self.out_th.start()
self.err_th = threading.Thread(
target=self.__pipe_reader,
args=(self.p.stderr, "e",
"%s:%s" % (self.taskb_name, self.task['name'])))
self.err_th.daemon = True
self.err_th.start()
if debughelper.delay > 0.0:
logger.debug("Valgrind sleep delay for %0.2f seconds" % debughelper.delay)
time.sleep(debughelper.delay)
# optional sleep after start of execution
if 'sleep' in self.task:
logger.debug("Sleeping for %s seconds" % self.task['sleep'])
if not debughelper.show:
time.sleep(int(self.task['sleep']))
def terminate(self):
# check to see if already exited, send terminate signal otherwise
if not debughelper.show:
retcode = self.p.poll()
if retcode is not None:
logger.debug("Task '%s' already terminated, exited %d" %
(self.task['name'], retcode))
else:
logger.debug("Terminating task '%s'" % self.task['name'])
self.p.terminate()
# exit likely negative of signal, only set if not set
if 'exit' not in self.task:
self.task['exit'] = - signal.SIGTERM
def send_signal(self, signal):
logger.debug("Sending signal '%d' to task '%s'" %
(signal, self.task['name']))
self.p.send_signal(signal)
# exit is likely negative of signal, only set if not set
if 'exit' not in self.task:
self.task['exit'] = - signal
def duration(self, multiplier=1):
# multiplier is to easily generate mili/micro-seconds
if self.end_t is not None:
return (self.end_t - self.start_t) * multiplier
else:
return None
def finish(self, tap_writer):
global debughelper
if debughelper.show:
return
failures = []
if os.name == 'posix' and sys.version_info[0] < 3 and not debughelper.debugrun:
try:
self.p.wait(self.timeout)
except subprocess.TimeoutExpired:
logger.debug("Timeout exceeded, terminating task '%s'" % self.task['name'])
self.p.terminate()
self.p.poll()
else:
self.p.wait()
if not debughelper.debugrun:
self.out_th.join()
self.err_th.join()
if not debughelper.debugrun:
logger.debug("Duration of task '%s': %.6f" %
(self.task['name'], self.duration()))
elif os.path.exists("debug.cmd"):
os.unlink("debug.cmd")
# $task_name is name of current task
r_vars['task_name'] = self.task['name']
# default is 0, check against this in any case
exit = 0
if 'exit' in self.task:
exit = self.task['exit']
retcode = self.p.poll()
if retcode == exit:
logger.debug("Task '%s' exited correctly: %s" %
(self.task['name'], self.p.returncode))
elif retcode == -15:
exit_fail = ("Task '%s' timed out (exceeds %d seconds)" %
(self.task['name'], self.timeout))
logger.error(exit_fail)
failures.append(exit_fail)
else:
exit_fail = ("Task '%s' incorrect exit: %s, expecting %s" %
(self.task['name'], retcode, exit))
logger.error(exit_fail)
failures.append(exit_fail)
outputfilenamepath=((("%s" % args.output_file).split(",")[0]).split()[2]).replace("'","")
testfilenamepath="%s.%.3d.txt" % (outputfilenamepath, tap_writer.current_test + 1)
outfile = open(testfilenamepath, 'w')
outfile.write("Task '%s': `%s`\n" % (self.task['name'], self.task['repl_command']))
outflag=False
stdout_str = ""
stderr_str = ""
for dq_item in self.q:
if dq_item['stream'] == "o":
stdout_str += dq_item['line']
debughelper.stdOut(" STDOUT: %s" % dq_item['line'].rstrip())
outfile.write(" STDOUT: %s" % dq_item['line'])
outflag=True
elif dq_item['stream'] == "e":
stderr_str += dq_item['line']
debughelper.stdErr(" STDERR: %s" % dq_item['line'].rstrip())
outfile.write(" STDERR: %s" % dq_item['line'])
outflag=True
else:
raise Exception("Unknown stream: %s" % dq_item['stream'])
outfile.close()
if not outflag and os.path.exists(testfilenamepath):
os.unlink(testfilenamepath)
# saving stdout/stderr is optional
if 'saveout' in self.task:
so_fname = replace_vars(self.task['saveout'])
parentdir = os.path.dirname(so_fname)
if not os.path.isdir(parentdir):
logger.error("Parent '%s' is not a directory for saveout file '%s'" %
(parentdir, so_fname))
sys.exit(1)
so_f = open(so_fname, 'w')
so_f.write(stdout_str)
so_f.close()
logger.debug("Saved stdout of task '%s' to '%s'" %
(self.task['name'], so_fname))
if 'saveerr' in self.task:
se_fname = replace_vars(self.task['saveerr'])
parentdir = os.path.dirname(se_fname)
if not os.path.isdir(parentdir):
logger.error("Parent '%s' is not a directory for saveerr file '%s'" %
(parentdir, se_fname))
sys.exit(1)
se_f = open(se_fname, 'w')
se_f.write(stdout_str)
se_f.close()
logger.debug("Saved stderr of task '%s' to '%s'" %
(self.task['name'], se_fname))
# checks against stdout/stderr are optional
if 'checkout' in self.task:
checkout_buffer = ''
checkout_files = ''
#for checkout_fname in replace_vars(self.task['checkout']).split():
strlist = []
if type(self.task['checkout']) is list:
strlist = self.task['checkout']
else:
strlist = replace_vars(self.task['checkout']).split()
for checkout_fname in strlist:
if not os.path.isfile(checkout_fname):
logger.error("Task '%s', nonexistant checkout file '%s'" %
(self.task['name'], checkout_fname))
sys.exit(1)
checkout_files += checkout_fname + ' '
checkout_buffer += open(checkout_fname).read()
if stdout_str == checkout_buffer:
logger.debug("Task '%s' stdout matches contents of '%s'" %
(self.task['name'], checkout_files))
else:
checkout_fail = ("Task '%s' stdout does not match contents of '%s'" %
(self.task['name'], checkout_files))
if debughelper.verbose:
logger.debug("Task '%s' stdout was: '%s'" %
(self.task['name'], stdout_str))
logger.debug("Task '%s' stdout should be: '%s'" %
(self.task['name'], checkout_buffer))
logger.error(checkout_fail)
failures.append(checkout_fail)
if 'checkerr' in self.task:
checkerr_fname = replace_vars(self.task['checkerr'])
if not os.path.isfile(checkerr_fname):
logger.error("Task '%s', nonexistant checkerr file '%s'" %
(self.task['name'], checkerr_fname))
sys.exit(1)
if stderr_str == open(checkerr_fname).read():
logger.debug("Task '%s' stderr matches contents of '%s'" %
(self.task['name'], checkerr_fname))
else:
checkerr_fail = ("Task '%s' stderr does not match contents of '%s'" %
(self.task['name'], checkerr_fname))
logger.error(checkerr_fail)
failures.append(checkerr_fail)
if 'rangecheckout' in self.task:
rangecheckout_fname,offset_str,length_str = replace_vars(self.task['rangecheckout']).split()
offset=int(offset_str)
length=int(length_str)
if not os.path.isfile(rangecheckout_fname):
logger.error("Task '%s', nonexistant rangecheckout file '%s'" %
(self.task['name'], rangecheckout_fname))
sys.exit(1)
with open(rangecheckout_fname) as fin:
fin.seek(offset)
data = fin.read(length)
debughelper.stdOut(" STDOUT: '%s'" % stdout_str)
if stdout_str == data:
logger.debug("Task '%s' stdout matches contents within '%s' between %d and %d" %
(self.task['name'], rangecheckout_fname, offset, offset + length))
else:
rangecheckout_fail = ("Task '%s' STDOUT does not match contents of '%s' between %d and %d" %
(self.task['name'], rangecheckout_fname, offset, offset + length))
if debughelper.verbose:
logger.debug("Task '%s' stdout was: '%s'" %
(self.task['name'], stdout_str))
logger.debug("Task '%s' stdout between %d and %d should be: '%s'" %
(self.task['name'], offset, offset + length, data))
logger.error(rangecheckout_fail)
failures.append(rangecheckout_fail)
# check out/err against strings, after rstrip of output
if 'compareout' in self.task:
cout_rv = replace_vars(str(self.task['compareout']))
expectthis = True
if len(cout_rv) > 0 and cout_rv[0] == '!': #if str starts with '!', fails if str == stdout
cout_rv = cout_rv[1:] #remove the '!', then compare
expectthis = False
if cout_rv == stdout_str.rstrip():
cout_log = ("Task '%s' stdout matches string of '%s'" % (self.task['name'], cout_rv))
if expectthis:
logger.debug(cout_log)
else: #error
logger.error(cout_log)
failures.append(cout_log)
else:
cout_log = ("Task '%s' stdout '%s' does not match string '%s'" % (self.task['name'], stdout_str.rstrip(), cout_rv))
if not expectthis:
logger.debug(cout_log)
else: #error
logger.error(cout_log)
failures.append(cout_log)
if 'compareerr' in self.task:
cerr_rv = replace_vars(str(self.task['compareerr']))
expectthis = True
if len(cerr_rv) > 0 and cerr_rv[0] == '!': #if str starts with '!', fails if str == stderr
cerr_rv = cerr_rv[1:] #remove the '!', then compare
expectthis = False
if cerr_rv == stderr_str.rstrip():
cerr_log = ("Task '%s' stderr matches string of '%s'" % (self.task['name'], cerr_rv))
if expectthis:
logger.debug(cerr_log)
else: #error
logger.error(cerr_log)
failures.append(cerr_log)
else:
cerr_log = ("Task '%s' stderr '%s' does not match string '%s'" % (self.task['name'], stderr_str.rstrip(), cerr_rv))
if not expectthis:
logger.debug(cerr_log)
else: #error
logger.error(cerr_log)
failures.append(cerr_log)
if 'containsout' in self.task:
strlist = []
if type(self.task['containsout']) is list:
strlist = self.task['containsout']
else:
strlist.append(str(self.task['containsout']))
for pattern in strlist:
rpattern = replace_vars(str(pattern))
expectthis = True
if rpattern[0] == '!': #if str starts with '!', fails if str in stdout
rpattern = rpattern[1:] #remove the '!', then compare
expectthis = False
if rpattern in stdout_str.rstrip():
cout_log = ("Task '%s' stdout contains string of '%s'" % (self.task['name'], rpattern))
if expectthis:
logger.debug(cout_log)
else: #error
logger.error(cout_log)
failures.append(cout_log)
else:
cout_log = ("Task '%s' stdout does not contain string of '%s'" % (self.task['name'], rpattern))
if not expectthis:
logger.debug(cout_log)
else: #error
logger.error(cout_log)
failures.append(cout_log)
if debughelper.verbose:
logger.debug("Task '%s' stdout was: '%s'" % (self.task['name'], stdout_str))
if 'containserr' in self.task:
strlist = []
if type(self.task['containserr']) is list:
strlist = self.task['containserr']
else:
strlist.append(str(self.task['containserr']))
for pattern in strlist:
rpattern = replace_vars(str(pattern))
expectthis = True
if rpattern[0] == '!': #if str starts with '!', fails if str in stderr
rpattern = rpattern[1:] #remove the '!', then compare
expectthis = False
if rpattern in stderr_str.rstrip():
cout_log = ("Task '%s' stderr contains string of '%s'" % (self.task['name'], rpattern))
if expectthis:
logger.debug(cout_log)
else: #error
logger.error(cout_log)
failures.append(cout_log)
else:
cout_log = ("Task '%s' stderr does not contain string of '%s'" % (self.task['name'], rpattern))
if not expectthis:
logger.debug(cout_log)
else: #error
logger.error(cout_log)
failures.append(cout_log)
if debughelper.verbose:
logger.debug("Task '%s' stderr was: '%s'" %
(self.task['name'], stderr_str))
#process gprof files if they are created
if os.path.exists("gmon.out"):
cstr="%.3d" % (tap_writer.current_test + 1)
p1 = subprocess.Popen(shlex.split("gprof " + debughelper.commandfilename), stdout=subprocess.PIPE)
p2 = subprocess.Popen(shlex.split("gprof2dot"), stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
subprocess.check_output(shlex.split("dot -Tpng -o gmon." + cstr + ".png"), stdin=p2.stdout)
p2.wait()
os.rename("gmon.out", "gmon.out." + cstr)
#process profile files from sprof if available
if os.environ.get('LD_PROFILE') is not None:
filename = os.environ.get('LD_PROFILE') + '.profile'
if os.path.exists(filename) and os.environ.get('LD_PROFILE_PATH') is not None:
cstr="%.3d" % (tap_writer.current_test + 1)
with open(filename + "." + cstr + ".log", "w") as outfile:
p1 = subprocess.Popen(shlex.split("sprof " + os.environ.get('LD_PROFILE_PATH') + "/" + os.environ.get('LD_PROFILE') + " -p"), stdout=outfile)
p1.wait()
os.rename(filename, filename + "." + cstr)
#process oprofile output if available
if (debughelper.operfrun or (debughelper.operfglobal and self.valgrindoutfile is not '')) and os.path.exists("oprofile_data"):
cstr="%.3d" % (tap_writer.current_test + 1)
with open(self.valgrindoutfile + "." + cstr, "w") as outfile:
p1 = subprocess.Popen(shlex.split("opreport"), stdout=outfile)
p1.wait()
if True: #set to False if you would rather keep the original oprofile_data instead of removing it
# os.unlink("oprofile_data")
shutil.rmtree("oprofile_data")
else:
os.rename("oprofile_data", "oprofile_data." + cstr) #use this if you want to keep the operf data instead of unlinking
#merge valgrind output if valgrind is enabled
if debughelper.valgrindglobal and self.valgrindoutfile is not '' and os.path.exists(self.valgrindoutfile):
vgout = open(args.memcheck,"a")
vgrin = open(self.valgrindoutfile,"r")
vgout.write('#'*80 + "\n" + "# " + self.task['name'] + "\n" + '#'*80 + "\n")
vgout.write(vgrin.read())
vgout.close()
vgrin.close()
os.unlink(self.valgrindoutfile)
#create callgrind plots if callgrind is enabled
if debughelper.callgrindglobal and self.valgrindoutfile is not '':
plotfile=self.valgrindoutfile + ".plot.png"
p = subprocess.Popen(shlex.split("gprof2dot -f callgrind " + self.valgrindoutfile), stdout=subprocess.PIPE)
subprocess.check_output(shlex.split("dot -Tpng -o " + plotfile), stdin=p.stdout)
#save filenames in a list that can be read later
plotfilelist=open("/tmp/" + tap_writer.tap_filename.split("/")[-1] + ".cglist",'a')
plotfilelist.write(plotfile + "\n")
plotfilelist.close()
p.wait()
if tap_writer:
if not debughelper.debugrun:
yaml_data = {"duration_ms": "%.6f" % self.duration(1000),
"command": self.task['repl_command']}
if outflag and self.buildurl is not None:
testfilename=testfilenamepath.split("/")[-1]
yaml_data['output']="%sartifact/output/%s" % (self.buildurl,testfilename)
#add callgraph link from previous callgrind run
if not debughelper.callgrindglobal and os.path.exists("/tmp/" + tap_writer.tap_filename.split("/")[-1] + ".cglist"):
plotfilelist=open("/tmp/" + tap_writer.tap_filename.split("/")[-1] + ".cglist",'r')
searchstring="%.3d" % (tap_writer.current_test + 1)
for line in plotfilelist:
if ".%s." % searchstring in line:
if os.path.exists(line.rstrip()):
vgoutfile=(line.split("/")[-1]).rstrip()
yaml_data['call graph']="%sartifact/output/%s" % (self.buildurl,vgoutfile)
testname = "%s : %s" % (self.taskb_name, self.task['name'])
if failures:
yaml_data["failures"] = failures
tap_writer.record_test(False, testname, yaml_data)
else:
tap_writer.record_test(True, testname, yaml_data)
return {"failures": failures, "q": self.q}
class RunParallel():
def __init__(self, taskblock, tap_writer=None):
global loop_vars
self.numtasks = 0
self.runners = []
self.run_out = []
self.taskscontainer = [] #contains lists of tasks lists
if 'tasks' not in taskblock:
logger.error("No tasks in taskblock '%s'" % taskblock['name'])
sys.exit(1)
debughelper.Check(taskblock) #check "debug:" for options, break in py-debugger if "debug: break" is in this taskblock
if 'loop_on' in taskblock:
if taskblock['loop_on'] in loop_vars:
self.taskscontainer = self.loop_tasks(taskblock['loop_on'], taskblock)
else:
logger.error("loop_on array '%s' is unknown in taskblock '%s'" %
(taskblock['loop_on'], taskblock['name']))
sys.exit(1)
else:
self.taskscontainer.append(taskblock['tasks'])
self.taskblock_name = taskblock['name']
self.tap_writer = tap_writer
def loop_tasks(self, varname, taskblock):
global loop_vars
global r_vars
taskscontainer = []
index = 0
loopidx=0
for loop_var in loop_vars[varname]:
tasks = []
for task in taskblock['tasks']:
if type(loop_var) is dict: #check if the first element in the loop_var list is a dictionary
for key in loop_var.keys(): #if dict, for each key in the dictionary
varkeystr = "%s.%s" % (varname,key) #create a r_vars key based on the loop "varname" and dict key using the dot format
r_vars[varkeystr] = str(loop_var[key]) #set the dict value and the new key in r_vars to be used in replace_vars
varkeystr = "loop_var.%s" % (key) #maintain the original "loop_var" name for backward compatibility, i.e. use "loop_var" instead of the specified loop "varname", use dot format
r_vars[varkeystr] = str(loop_var[key])
else:
varkeystr = str(varname) #if not a dict, i.e. basic list, does not use the dictionary key as part of the loop "varname" key, does not use dot format
r_vars[varkeystr] = str(loop_var)
r_vars['loop_var'] = str(loop_var) #maintain the original "loop_var" name for backward compatibility, i.e. use "loop_var" instead of the specified loop "varname"
if 'loop_on' in task: #the task also has a loop_on option, making nested loops possible
outerindex = index
prevloopidx = loopidx
index = 0
tasks = []
nested_varname = task['loop_on'] #get the varname for the individual task
for nested_loop_var in loop_vars[nested_varname]: #this is the nested loop, it operates identical to the outer loop
if type(nested_loop_var) is dict:
for key in nested_loop_var.keys():
nvarkeystr = "%s.%s" % (nested_varname,key)
r_vars[nvarkeystr] = str(nested_loop_var[key])
nvarkeystr = "nested_loop_var.%s" % (key) #instead of "loop_var.key" use "nested_loop_var.key"
r_vars[nvarkeystr] = str(nested_loop_var[key])
else:
nvarkeystr = str(nested_varname)
r_vars[nvarkeystr] = str(nested_loop_var)
r_vars['nested_loop_var'] = str(nested_loop_var) #instead of "loop_var" use "nested_loop_var"
index+=1
r_vars['loop_index'] = str(index)
modified_task = copy.deepcopy(task)
for subtask in task: #replace_vars on all lines per task
if type(task[subtask]) is list: #also per str within lists
for itemnum in range(len(task[subtask])):
if type(task[subtask][itemnum]) is str:
modified_task[subtask][itemnum] = replace_vars(task[subtask][itemnum])
elif type(task[subtask]) is str:
modified_task[subtask] = replace_vars(task[subtask])
for key in ['name', 'saveout', 'saveerr', ]:
if key in task:
modified_task[key] = "%s-%d" % (task[key], index)
modified_task['loopidx'] = loopidx
tasks.append(modified_task)
self.numtasks+=1
loopidx+=1
index = outerindex
r_vars[nvarkeystr] = loop_vars[nested_varname][0] #be sure to reset variables after the loop
loopidx = prevloopidx #reset loopidx for valgrind, this should run only the 1st task of each multi-task set
else:
index+=1
r_vars['loop_index'] = str(index)
modified_task = copy.deepcopy(task)
for subtask in task: #replace_vars on all lines per task
if type(task[subtask]) is list: #also per str within lists
for itemnum in range(len(task[subtask])):
if type(task[subtask][itemnum]) is str:
modified_task[subtask][itemnum] = replace_vars(task[subtask][itemnum])
elif type(task[subtask]) is str:
modified_task[subtask] = replace_vars(task[subtask])
for key in ['name', 'saveout', 'saveerr', ]:
if key in task:
modified_task[key] = "%s-%d" % (task[key], index)
modified_task['loopidx'] = loopidx
tasks.append(modified_task)
self.numtasks+=1
taskscontainer.append(tasks)
loopidx+=1
r_vars['loop_index'] = str(index)
r_vars[varkeystr] = loop_vars[varname][0]
return taskscontainer
def num_tests(self):
return self.numtasks
def run(self):
for tasks in self.taskscontainer:
for task in tasks:
task['type'] = 'parallel'
debughelper.Check(task) #check "debug:" for options, break in py-debugger if "debug: break" is in this taskblock
cr = CommandRunner(task, self.taskblock_name)
self.runners.append({"name": task['name'], "cr": cr})