Logo AND Algorithmique Numérique Distribuée

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