Logo AND Algorithmique Numérique Distribuée

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