Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Python 3 is required anyway.
[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 self.can_run():
282             if self.background:
283                 lock = _thread.allocate_lock()
284                 lock.acquire()
285                 TeshState().add_thread(lock)
286                 _thread.start_new_thread(Cmd._run, (self, lock))
287             else:
288                 self._run()
289             return True
290         else:
291             return False
292
293     def _run(self, lock=None):
294         # Python threads loose the cwd
295         os.chdir(self.cwd)
296
297         # retrocompatibility: support ${aaa:=.} variable format
298         def replace_perl_variables(m):
299             vname = m.group(1)
300             vdefault = m.group(2)
301             if vname in os.environ:
302                 return "$" + vname
303             return vdefault
304
305         self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
306
307         # replace bash environment variables ($THINGS) to their values
308         self.args = expandvars2(self.args)
309
310         if re.match("^mkfile ", self.args) is not None:
311             self._cmd_mkfile(self.args)
312             if lock is not None:
313                 lock.release()
314             return
315
316         if re.match("^cd ", self.args) is not None:
317             self._cmd_cd(self.args)
318             if lock is not None:
319                 lock.release()
320             return
321
322         if TeshState().wrapper is not None:
323             self.timeout *= 20
324             self.args = TeshState().wrapper + self.args
325         elif re.match(".*smpirun.*", self.args) is not None:
326             self.args = "sh " + self.args
327         if TeshState().jenkins and self.timeout is not None:
328             self.timeout *= 10
329
330         self.args += TeshState().args_suffix
331
332         logs = list()
333         logs.append("[{file}:{number}] {args}".format(file=FileReader().filename,
334             number=self.linenumber, args=self.args))
335
336         args = shlex.split(self.args)
337
338         global running_pids
339         local_pid = None
340         global return_code
341
342         try:
343             preexec_function = None
344             if not isWindows():
345                 preexec_function = lambda: os.setpgid(0, 0)
346             proc = subprocess.Popen(
347                 args,
348                 bufsize=1,
349                 stdin=subprocess.PIPE,
350                 stdout=subprocess.PIPE,
351                 stderr=subprocess.STDOUT,
352                 universal_newlines=True,
353                 preexec_fn=preexec_function)
354             if not isWindows():
355                 local_pid = proc.pid
356                 running_pids.append(local_pid)
357         except PermissionError:
358             logs.append("[{file}:{number}] Cannot start '{cmd}': The binary is not executable.".format(
359                 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
360             logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
361                 number=self.linenumber, dir=os.getcwd()))
362             return_code = max(3, return_code)
363             print('\n'.join(logs))
364             return
365         except NotADirectoryError:
366             logs.append("[{file}:{number}] Cannot start '{cmd}': The path to binary does not exist.".format(
367                 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
368             logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
369                 number=self.linenumber, dir=os.getcwd()))
370             return_code = max(3, return_code)
371             print('\n'.join(logs))
372             return
373         except FileNotFoundError:
374             logs.append("[{file}:{number}] Cannot start '{cmd}': File not found.".format(
375                 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
376             return_code = max(3, return_code)
377             print('\n'.join(logs))
378             return
379         except OSError as osE:
380             if osE.errno == 8:
381                 osE.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
382             raise osE
383
384         cmdName = FileReader().filename + ":" + str(self.linenumber)
385         try:
386             (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
387             local_pid = None
388             timeout_reached = False
389         except subprocess.TimeoutExpired:
390             timeout_reached = True
391             logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format(
392                 file=FileReader().filename, cmd=cmdName, timeout=self.timeout))
393             running_pids.remove(local_pid)
394             kill_process_group(local_pid)
395             # Try to get the output of the timeout process, to help in debugging.
396             try:
397                 (stdout_data, stderr_data) = proc.communicate(timeout=1)
398             except subprocess.TimeoutExpired:
399                 logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
400                     file=FileReader().filename, number=self.linenumber))
401                 return_code = max(3, return_code)
402                 print('\n'.join(logs))
403                 return
404
405         if self.output_display:
406             logs.append(str(stdout_data))
407
408         # remove text colors
409         ansi_escape = re.compile(r'\x1b[^m]*m')
410         stdout_data = ansi_escape.sub('', stdout_data)
411
412         if self.ignore_output:
413             logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmdName))
414         else:
415             stdouta = stdout_data.split("\n")
416             while stdouta and stdouta[-1] == "":
417                 del stdouta[-1]
418             stdouta = self.remove_ignored_lines(stdouta)
419             stdcpy = stdouta[:]
420
421             # Mimic the "sort" bash command, which is case unsensitive.
422             if self.sort == 0:
423                 stdouta.sort(key=lambda x: x.lower())
424                 self.output_pipe_stdout.sort(key=lambda x: x.lower())
425             elif self.sort > 0:
426                 stdouta.sort(key=lambda x: x[:self.sort].lower())
427                 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
428
429             diff = list(
430                 difflib.unified_diff(
431                     self.output_pipe_stdout,
432                     stdouta,
433                     lineterm="",
434                     fromfile='expected',
435                     tofile='obtained'))
436             if diff:
437                 logs.append("Output of <{cmd}> mismatch:".format(cmd=cmdName))
438                 if self.sort >= 0:  # If sorted, truncate the diff output and show the unsorted version
439                     difflen = 0
440                     for line in diff:
441                         if difflen < 50:
442                             print(line)
443                         difflen += 1
444                     if difflen > 50:
445                         logs.append("(diff truncated after 50 lines)")
446                     logs.append("Unsorted observed output:\n")
447                     for line in stdcpy:
448                         logs.append(line)
449                 else:  # If not sorted, just display the diff
450                     for line in diff:
451                         logs.append(line)
452
453                 logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format(
454                     file=FileReader().filename, cmd=cmdName))
455                 if lock is not None:
456                     lock.release()
457                 if TeshState().keep:
458                     f = open('obtained', 'w')
459                     obtained = stdout_data.split("\n")
460                     while obtained and obtained[-1] == "":
461                         del obtained[-1]
462                     obtained = self.remove_ignored_lines(obtained)
463                     for line in obtained:
464                         f.write("> " + line + "\n")
465                     f.close()
466                     logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained")))
467                 return_code = max(2, return_code)
468                 print('\n'.join(logs))
469                 return
470
471         if timeout_reached:
472             return_code = max(3, return_code)
473             print('\n'.join(logs))
474             return
475
476         if not proc.returncode in self.expect_return:
477             if proc.returncode >= 0:
478                 logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format(
479                     file=FileReader().filename, cmd=cmdName, code=proc.returncode))
480                 if lock is not None:
481                     lock.release()
482                 return_code = max(2, return_code)
483                 print('\n'.join(logs))
484                 return
485             else:
486                 logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format(
487                     file=FileReader().filename, cmd=cmdName,
488                     sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
489                 if lock is not None:
490                     lock.release()
491                 return_code = max(max(-proc.returncode, 1), return_code)
492                 print('\n'.join(logs))
493                 return
494
495         if lock is not None:
496             lock.release()
497
498         print('\n'.join(logs))
499
500     def can_run(self):
501         return self.args is not None
502
503 ##############
504 #
505 # Main
506 #
507 #
508
509 if __name__ == '__main__':
510     signal.signal(signal.SIGINT, signal_handler)
511     signal.signal(signal.SIGTERM, signal_handler)
512
513     parser = argparse.ArgumentParser(description='tesh -- testing shell')
514     group1 = parser.add_argument_group('Options')
515     group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
516     group1.add_argument(
517         '--cd',
518         metavar='some/directory',
519         help='ask tesh to switch the working directory before launching the tests')
520     group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
521     group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
522     group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
523     group1.add_argument(
524         '--ignore-jenkins',
525         action='store_true',
526         help='ignore all cruft generated on SimGrid continuous integration servers')
527     group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
528     group1.add_argument(
529         '--keep',
530         action='store_true',
531         help='Keep the obtained output when it does not match the expected one')
532
533     options = parser.parse_args()
534
535     if options.cd is not None:
536         print("[Tesh/INFO] change directory to " + options.cd)
537         os.chdir(options.cd)
538
539     if options.ignore_jenkins:
540         print("Ignore all cruft seen on SimGrid's continuous integration servers")
541         # Note: regexps should match at the beginning of lines
542         TeshState().ignore_regexps_common = [
543             re.compile(r"profiling:"),
544             re.compile(r"Unable to clean temporary file C:"),
545             re.compile(r".*Configuration change: Set 'contexts/"),
546             re.compile(r"Picked up JAVA_TOOL_OPTIONS: "),
547             re.compile(r"Picked up _JAVA_OPTIONS: "),
548             re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
549             re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack top:"),
550             re.compile(r"False positive error reports may follow"),
551             re.compile(r"For details see http://code\.google\.com/p/address-sanitizer/issues/detail\?id=189"),
552             re.compile(r"For details see https://github\.com/google/sanitizers/issues/189"),
553             re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
554             # Seen on CircleCI
555             re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
556             re.compile(r".*mmap broken on FreeBSD, but dlopen\+thread broken too\. Switching to dlopen\+raw contexts\."),
557             re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
558         ]
559         TeshState().jenkins = True  # This is a Jenkins build
560
561     if options.teshfile is None:
562         f = FileReader(None)
563         print("Test suite from stdin")
564     else:
565         if not os.path.isfile(options.teshfile):
566             print("Cannot open teshfile '" + options.teshfile + "': File not found")
567             tesh_exit(3)
568         f = FileReader(options.teshfile)
569         print("Test suite '" + f.abspath + "'")
570
571     if options.setenv is not None:
572         for e in options.setenv:
573             setenv(e)
574
575     if options.cfg is not None:
576         for c in options.cfg:
577             TeshState().args_suffix += " --cfg=" + c
578     if options.log is not None:
579         for l in options.log:
580             TeshState().args_suffix += " --log=" + l
581
582     if options.wrapper is not None:
583         TeshState().wrapper = options.wrapper
584
585     if options.keep:
586         TeshState().keep = True
587
588     # cmd holds the current command line
589     # tech commands will add some parameters to it
590     # when ready, we execute it.
591     cmd = Cmd()
592
593     line = f.readfullline()
594     while line is not None:
595         # print(">>============="+line+"==<<")
596         if not line:
597             #print ("END CMD block")
598             if cmd.run_if_possible():
599                 cmd = Cmd()
600
601         elif line[0] == "#":
602             pass
603
604         elif line[0:2] == "p ":
605             print("[" + str(FileReader()) + "] " + line[2:])
606
607         elif line[0:2] == "< ":
608             cmd.add_input_pipe(line[2:])
609         elif line[0:1] == "<":
610             cmd.add_input_pipe(line[1:])
611
612         elif line[0:2] == "> ":
613             cmd.add_output_pipe_stdout(line[2:])
614         elif line[0:1] == ">":
615             cmd.add_output_pipe_stdout(line[1:])
616
617         elif line[0:2] == "$ ":
618             if cmd.run_if_possible():
619                 cmd = Cmd()
620             cmd.set_cmd(line[2:], f.linenumber)
621
622         elif line[0:2] == "& ":
623             if cmd.run_if_possible():
624                 cmd = Cmd()
625             cmd.set_cmd(line[2:], f.linenumber)
626             cmd.background = True
627
628         elif line[0:15] == "! output ignore":
629             cmd.ignore_output = True
630             #print("cmd.ignore_output = True")
631         elif line[0:16] == "! output display":
632             cmd.output_display = True
633             cmd.ignore_output = True
634         elif line[0:15] == "! expect return":
635             cmd.expect_return = [int(line[16:])]
636             #print("expect return "+str(int(line[16:])))
637         elif line[0:15] == "! expect signal":
638             cmd.expect_return = []
639             for sig in (line[16:]).split("|"):
640                 # get the signal integer value from the signal module
641                 if sig not in signal.__dict__:
642                     fatal_error("unrecognized signal '" + sig + "'")
643                 sig = int(signal.__dict__[sig])
644                 # popen return -signal when a process ends with a signal
645                 cmd.expect_return.append(-sig)
646         elif line[0:len("! timeout ")] == "! timeout ":
647             if "no" in line[len("! timeout "):]:
648                 cmd.timeout = None
649             else:
650                 cmd.timeout = int(line[len("! timeout "):])
651
652         elif line[0:len("! output sort")] == "! output sort":
653             if len(line) >= len("! output sort "):
654                 sort = int(line[len("! output sort "):])
655             else:
656                 sort = 0
657             cmd.sort = sort
658         elif line[0:len("! setenv ")] == "! setenv ":
659             setenv(line[len("! setenv "):])
660
661         elif line[0:len("! ignore ")] == "! ignore ":
662             cmd.add_ignore(line[len("! ignore "):])
663
664         else:
665             fatal_error("UNRECOGNIZED OPTION")
666
667         line = f.readfullline()
668
669     cmd.run_if_possible()
670
671     TeshState().join_all_threads()
672
673     if return_code == 0:
674         if f.filename == "(stdin)":
675             print("Test suite from stdin OK")
676         else:
677             print("Test suite `" + f.filename + "' OK")
678     else:
679         tesh_exit(return_code)