Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines with new year.
[simgrid.git] / tools / tesh / tesh.py
1 #! @PYTHON_EXECUTABLE@
2 # -*- coding: utf-8 -*-
3 """
4
5 tesh -- testing shell
6 ========================
7
8 Copyright (c) 2012-2019. The SimGrid Team. All rights reserved.
9
10 This program is free software; you can redistribute it and/or modify it
11 under the terms of the license (GNU LGPL) which comes with this package.
12
13
14 #TODO: child of child of child that printfs. Does it work?
15 #TODO: a child dies after its parent. What happen?
16
17 #TODO: regular expression in output
18 #ex: >> Time taken: [0-9]+s
19 #TODO: linked regular expression in output
20 #ex:
21 # >> Bytes sent: ([0-9]+)
22 # >> Bytes recv: \1
23 # then, even better:
24 # ! expect (\1 > 500)
25
26 """
27
28
29 import sys, os
30 import shlex
31 import re
32 import difflib
33 import signal
34 import argparse
35
36 if sys.version_info[0] == 3:
37     import subprocess
38     import _thread
39 else:
40     raise "This program is expected to run with Python3 only"
41
42 ##############
43 #
44 # Utilities
45 #
46 #
47
48 def isWindows():
49     return sys.platform.startswith('win')
50
51 # Singleton metaclass that works in Python 2 & 3
52 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
53 class _Singleton(type):
54     """ A metaclass that creates a Singleton base class when called. """
55     _instances = {}
56     def __call__(cls, *args, **kwargs):
57         if cls not in cls._instances:
58             cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
59         return cls._instances[cls]
60 class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
61
62 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
63     for n in dir(signal) if n.startswith('SIG') and '_' not in n )
64
65
66
67 #exit correctly
68 def tesh_exit(errcode):
69     #If you do not flush some prints are skipped
70     sys.stdout.flush()
71     #os._exit exit even when executed within a thread
72     os._exit(errcode)
73
74
75 def fatal_error(msg):
76     print("[Tesh/CRITICAL] "+str(msg))
77     tesh_exit(1)
78
79
80 #Set an environment variable.
81 # arg must be a string with the format "variable=value"
82 def setenv(arg):
83     print("[Tesh/INFO] setenv "+arg)
84     t = arg.split("=")
85     os.environ[t[0]] = t[1]
86     #os.putenv(t[0], t[1]) does not work
87     #see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
88
89
90 #http://stackoverflow.com/questions/30734967/how-to-expand-environment-variables-in-python-as-bash-does
91 def expandvars2(path):
92     return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
93
94 # https://github.com/Cadair/jupyter_environment_kernels/issues/10
95 try:
96     FileNotFoundError
97 except NameError:
98     #py2
99     FileNotFoundError = OSError
100
101 ##############
102 #
103 # Cleanup on signal
104 #
105 #
106
107 # Global variable. Stores which process group should be killed (or None otherwise)
108 pgtokill = None
109
110 def kill_process_group(pgid):
111     if pgid is None: # Nobody to kill. We don't know who to kill on windows, or we don't have anyone to kill on signal handler
112         return
113
114     # print("Kill process group {}".format(pgid))
115     try:
116         os.killpg(pgid, signal.SIGTERM)
117     except OSError:
118         # os.killpg failed. OK. Some subprocesses may still be running.
119         pass
120
121 def signal_handler(signal, frame):
122     print("Caught signal {}".format(SIGNALS_TO_NAMES_DICT[signal]))
123     if pgtokill is not None:
124         kill_process_group(pgtokill)
125     tesh_exit(5)
126
127
128
129 ##############
130 #
131 # Classes
132 #
133 #
134
135
136
137 # read file line per line (and concat line that ends with "\")
138 class FileReader(Singleton):
139     def __init__(self, filename=None):
140         if filename is None:
141             self.filename = "(stdin)"
142             self.f = sys.stdin
143         else:
144             self.filename_raw = filename
145             self.filename = os.path.basename(filename)
146             self.abspath = os.path.abspath(filename)
147             self.f = open(self.filename_raw)
148
149         self.linenumber = 0
150
151     def __repr__(self):
152         return self.filename+":"+str(self.linenumber)
153
154     def readfullline(self):
155         try:
156             line = next(self.f)
157             self.linenumber += 1
158         except StopIteration:
159             return None
160         if line[-1] == "\n":
161             txt = line[0:-1]
162         else:
163             txt = line
164         while len(line) > 1 and line[-2] == "\\":
165             txt = txt[0:-1]
166             line = next(self.f)
167             self.linenumber += 1
168             txt += line[0:-1]
169         return txt
170
171
172 #keep the state of tesh (mostly configuration values)
173 class TeshState(Singleton):
174     def __init__(self):
175         self.threads = []
176         self.args_suffix = ""
177         self.ignore_regexps_common = []
178         self.jenkins = False # not a Jenkins run by default
179         self.timeout = 10 # default value: 10 sec
180         self.wrapper = None
181         self.keep = False
182
183     def add_thread(self, thread):
184         self.threads.append(thread)
185
186     def join_all_threads(self):
187         for t in self.threads:
188             t.acquire()
189             t.release()
190
191 # Command line object
192 class Cmd(object):
193     def __init__(self):
194         self.input_pipe = []
195         self.output_pipe_stdout = []
196         self.output_pipe_stderr = []
197         self.timeout = TeshState().timeout
198         self.args = None
199         self.linenumber = -1
200
201         self.background = False
202         # Python threads loose the cwd
203         self.cwd = os.getcwd()
204
205         self.ignore_output = False
206         self.expect_return = 0
207
208         self.output_display = False
209
210         self.sort = -1
211
212         self.ignore_regexps = TeshState().ignore_regexps_common
213
214     def add_input_pipe(self, l):
215         self.input_pipe.append(l)
216
217     def add_output_pipe_stdout(self, l):
218         self.output_pipe_stdout.append(l)
219
220     def add_output_pipe_stderr(self, l):
221         self.output_pipe_stderr.append(l)
222
223     def set_cmd(self, args, linenumber):
224         self.args = args
225         self.linenumber = linenumber
226
227     def add_ignore(self, txt):
228         self.ignore_regexps.append(re.compile(txt))
229
230     def remove_ignored_lines(self, lines):
231         for ign in self.ignore_regexps:
232                 lines = [l for l in lines if not ign.match(l)]
233         return lines
234
235
236     def _cmd_mkfile(self, argline):
237         filename = argline[len("mkfile "):]
238         file = open(filename, "w")
239         if file is None:
240             fatal_error("Unable to create file "+filename)
241         file.write("\n".join(self.input_pipe))
242         file.write("\n")
243         file.close()
244
245     def _cmd_cd(self, argline):
246         args = shlex.split(argline)
247         if len(args) != 2:
248             fatal_error("Too many arguments to cd")
249         try:
250             os.chdir(args[1])
251             print("[Tesh/INFO] change directory to "+args[1])
252         except FileNotFoundError:
253             print("Chdir to "+args[1]+" failed: No such file or directory")
254             print("Test suite `"+FileReader().filename+"': NOK (system error)")
255             tesh_exit(4)
256
257
258     #Run the Cmd if possible.
259     # Return False if nothing has been ran.
260     def run_if_possible(self):
261         if self.can_run():
262             if self.background:
263                 lock = _thread.allocate_lock()
264                 lock.acquire()
265                 TeshState().add_thread(lock)
266                 _thread.start_new_thread( Cmd._run, (self, lock) )
267             else:
268                 self._run()
269             return True
270         else:
271             return False
272
273
274     def _run(self, lock=None):
275         # Python threads loose the cwd
276         os.chdir(self.cwd)
277
278         #retrocompatibility: support ${aaa:=.} variable format
279         def replace_perl_variables(m):
280             vname = m.group(1)
281             vdefault = m.group(2)
282             if vname in os.environ:
283                 return "$"+vname
284             else:
285                 return vdefault
286         self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
287
288         #replace bash environment variables ($THINGS) to their values
289         self.args = expandvars2(self.args)
290
291         if re.match("^mkfile ", self.args) is not None:
292             self._cmd_mkfile(self.args)
293             if lock is not None: lock.release()
294             return
295
296         if re.match("^cd ", self.args) is not None:
297             self._cmd_cd(self.args)
298             if lock is not None: lock.release()
299             return
300
301         if TeshState().wrapper is not None:
302             self.timeout *= 20
303             self.args = TeshState().wrapper + self.args
304         elif re.match(".*smpirun.*", self.args) is not None:
305             self.args = "sh " + self.args
306         if TeshState().jenkins and self.timeout != None:
307             self.timeout *= 10
308
309         self.args += TeshState().args_suffix
310
311         print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
312
313         args = shlex.split(self.args)
314         #print (args)
315
316         global pgtokill
317
318         try:
319             proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, start_new_session=True)
320             try:
321                 if not isWindows():
322                     pgtokill = os.getpgid(proc.pid)
323             except OSError:
324                 # os.getpgid failed. OK. No cleanup.
325                 pass
326         except PermissionError:
327             print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': The binary is not executable.")
328             print("["+FileReader().filename+":"+str(self.linenumber)+"] Current dir: "+os.getcwd())
329             tesh_exit(3)            
330         except NotADirectoryError:
331             print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': The path to binary does not exist.")
332             print("["+FileReader().filename+":"+str(self.linenumber)+"] Current dir: "+os.getcwd())
333             tesh_exit(3)
334         except FileNotFoundError:
335             print("["+FileReader().filename+":"+str(self.linenumber)+"] Cannot start '"+args[0]+"': File not found")
336             tesh_exit(3)
337         except OSError as osE:
338             if osE.errno == 8:
339                 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
340             raise osE
341
342         cmdName = FileReader().filename+":"+str(self.linenumber)
343         try:
344             (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
345             pgtokill = None
346         except subprocess.TimeoutExpired:
347             print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> timeout after "+str(self.timeout)+" sec)")
348             kill_process_group(pgtokill)
349             tesh_exit(3)
350
351         if self.output_display:
352             print(stdout_data)
353
354         #remove text colors
355         ansi_escape = re.compile(r'\x1b[^m]*m')
356         stdout_data = ansi_escape.sub('', stdout_data)
357
358         #print ((stdout_data, stderr_data))
359
360         if self.ignore_output:
361             print("(ignoring the output of <"+cmdName+"> as requested)")
362         else:
363             stdouta = stdout_data.split("\n")
364             while len(stdouta) > 0 and stdouta[-1] == "":
365                 del stdouta[-1]
366             stdouta = self.remove_ignored_lines(stdouta)
367             stdcpy = stdouta[:]
368
369             # Mimic the "sort" bash command, which is case unsensitive.
370             if self.sort == 0:
371                 stdouta.sort(key=lambda x: x.lower())
372                 self.output_pipe_stdout.sort(key=lambda x: x.lower())
373             elif self.sort > 0:
374                 stdouta.sort(key=lambda x: x[:self.sort].lower())
375                 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
376
377             diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
378             if len(diff) > 0:
379                 print("Output of <"+cmdName+"> mismatch:")
380                 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
381                     difflen = 0;
382                     for line in diff:
383                         if difflen<50:
384                             print(line)
385                         difflen += 1
386                     if difflen > 50:
387                         print("(diff truncated after 50 lines)")
388                     print("Unsorted observed output:\n")
389                     for line in stdcpy:
390                         print(line)
391                 else: # If not sorted, just display the diff
392                     for line in diff:
393                         print(line)
394
395                 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)")
396                 if lock is not None: lock.release()
397                 if TeshState().keep:
398                     f = open('obtained','w')
399                     obtained = stdout_data.split("\n")
400                     while len(obtained) > 0 and obtained[-1] == "":
401                         del obtained[-1]
402                     obtained = self.remove_ignored_lines(obtained)
403                     for line in obtained:
404                         f.write("> "+line+"\n")
405                     f.close()
406                     print("Obtained output kept as requested: "+os.path.abspath("obtained"))
407                 tesh_exit(2)
408
409         #print ((proc.returncode, self.expect_return))
410
411         if proc.returncode != self.expect_return:
412             if proc.returncode >= 0:
413                 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")")
414                 if lock is not None: lock.release()
415                 tesh_exit(2)
416             else:
417                 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
418                 if lock is not None: lock.release()
419                 tesh_exit(-proc.returncode)
420
421         if lock is not None: lock.release()
422
423
424
425     def can_run(self):
426         return self.args is not None
427
428
429
430
431 ##############
432 #
433 # Main
434 #
435 #
436
437
438
439 if __name__ == '__main__':
440     signal.signal(signal.SIGINT, signal_handler)
441     signal.signal(signal.SIGTERM, signal_handler)
442
443     parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
444     group1 = parser.add_argument_group('Options')
445     group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
446     group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
447     group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
448     group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
449     group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
450     group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
451     group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
452     group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one')
453
454     try:
455         options = parser.parse_args()
456     except SystemExit:
457         tesh_exit(1)
458
459     if options.cd is not None:
460         print("[Tesh/INFO] change directory to " + options.cd)
461         os.chdir(options.cd)
462
463     if options.ignore_jenkins:
464         print("Ignore all cruft seen on SimGrid's continous integration servers")
465         # Note: regexps should match at the beginning of lines
466         TeshState().ignore_regexps_common = [
467            re.compile(r"profiling:"),
468            re.compile(r"Unable to clean temporary file C:"),
469            re.compile(r".*Configuration change: Set 'contexts/"),
470            re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
471            re.compile(r"Picked up _JAVA_OPTIONS: "),
472            re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
473            re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
474            re.compile(r"False positive error reports may follow"),
475            re.compile(r"For details see http://code.google.com/p/address-sanitizer/issues/detail\?id=189"),
476            re.compile(r"For details see https://github.com/google/sanitizers/issues/189"),
477            re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
478            re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"), # Seen on CircleCI
479            re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too. Switching to dlopen\+raw contexts\."),
480            re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
481            ]
482         TeshState().jenkins = True # This is a Jenkins build
483
484     if options.teshfile is None:
485         f = FileReader(None)
486         print("Test suite from stdin")
487     else:
488         if not os.path.isfile(options.teshfile):
489             print("Cannot open teshfile '"+options.teshfile+"': File not found")
490             tesh_exit(3)
491         f = FileReader(options.teshfile)
492         print("Test suite '"+f.abspath+"'")
493
494     if options.setenv is not None:
495         for e in options.setenv:
496             setenv(e)
497
498     if options.cfg is not None:
499         for c in options.cfg:
500             TeshState().args_suffix += " --cfg=" + c
501     if options.log is not None:
502         for l in options.log:
503             TeshState().args_suffix += " --log=" + l
504
505     if options.wrapper is not None:
506         TeshState().wrapper = options.wrapper
507
508     if options.keep:
509         TeshState().keep = True
510
511     #cmd holds the current command line
512     # tech commands will add some parameters to it
513     # when ready, we execute it.
514     cmd = Cmd()
515
516     line = f.readfullline()
517     while line is not None:
518         #print(">>============="+line+"==<<")
519         if len(line) == 0:
520             #print ("END CMD block")
521             if cmd.run_if_possible():
522                 cmd = Cmd()
523
524         elif line[0] == "#":
525             pass
526
527         elif line[0:2] == "p ":
528             print("["+str(FileReader())+"] "+line[2:])
529
530         elif line[0:2] == "< ":
531             cmd.add_input_pipe(line[2:])
532         elif line[0:1] == "<":
533             cmd.add_input_pipe(line[1:])
534
535         elif line[0:2] == "> ":
536             cmd.add_output_pipe_stdout(line[2:])
537         elif line[0:1] == ">":
538             cmd.add_output_pipe_stdout(line[1:])
539
540         elif line[0:2] == "$ ":
541             if cmd.run_if_possible():
542                 cmd = Cmd()
543             cmd.set_cmd(line[2:], f.linenumber)
544
545         elif line[0:2] == "& ":
546             if cmd.run_if_possible():
547                 cmd = Cmd()
548             cmd.set_cmd(line[2:], f.linenumber)
549             cmd.background = True
550
551         elif line[0:15] == "! output ignore":
552             cmd.ignore_output = True
553             #print("cmd.ignore_output = True")
554         elif line[0:16] == "! output display":
555             cmd.output_display = True
556             cmd.ignore_output = True
557         elif line[0:15] == "! expect return":
558             cmd.expect_return = int(line[16:])
559             #print("expect return "+str(int(line[16:])))
560         elif line[0:15] == "! expect signal":
561             sig = line[16:]
562             #get the signal integer value from the signal module
563             if sig not in signal.__dict__:
564                 fatal_error("unrecognized signal '"+sig+"'")
565             sig = int(signal.__dict__[sig])
566             #popen return -signal when a process ends with a signal
567             cmd.expect_return = -sig
568         elif line[0:len("! timeout ")] == "! timeout ":
569             if "no" in line[len("! timeout "):]:
570                 cmd.timeout = None
571             else:
572                 cmd.timeout = int(line[len("! timeout "):])
573
574         elif line[0:len("! output sort")] == "! output sort":
575             if len(line) >= len("! output sort "):
576                 sort = int(line[len("! output sort "):])
577             else:
578                 sort = 0
579             cmd.sort = sort
580         elif line[0:len("! setenv ")] == "! setenv ":
581             setenv(line[len("! setenv "):])
582
583         elif line[0:len("! ignore ")] == "! ignore ":
584             cmd.add_ignore(line[len("! ignore "):])
585
586         else:
587             fatal_error("UNRECOGNIZED OPTION")
588
589
590         line = f.readfullline()
591
592     cmd.run_if_possible()
593
594     TeshState().join_all_threads()
595
596     if f.filename == "(stdin)":
597         print("Test suite from stdin OK")
598     else:
599         print("Test suite `"+f.filename+"' OK")