Logo AND Algorithmique Numérique Distribuée

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