2 # -*- coding: utf-8 -*-
6 ========================
8 Copyright (c) 2012-2023. The SimGrid Team. All rights reserved.
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.
13 #TODO: child of child of child that printfs. Does it work?
14 #TODO: a child dies after its parent. What happen?
16 #TODO: regular expression in output
17 #ex: >> Time taken: [0-9]+s
18 #TODO: linked regular expression in output
20 # >> Bytes sent: ([0-9]+)
37 if sys.version_info[0] == 3:
41 raise RuntimeError("This program is expected to run with Python3 only")
49 # Singleton metaclass that works in Python 2 & 3
50 # http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
52 class _Singleton(type):
53 """ A metaclass that creates a Singleton base class when called. """
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]
61 class Singleton(_Singleton('SingletonMeta', (object,), {})):
62 """ The Singleton base class """
65 SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n)
66 for n in dir(signal) if n.startswith('SIG') and '_' not in n)
68 def tesh_exit(errcode):
69 """ Exit correctly """
70 # If you do not flush some prints are skipped
72 # os._exit exit even when executed within a thread
73 # pylint: disable=protected-access
78 """ Exit with error """
79 print("[Tesh/CRITICAL] " + str(msg))
85 Set an environment variable.
86 arg must be a string with the format "variable=value"
88 print("[Tesh/INFO] setenv " + arg)
89 (var, val) = arg.split("=", 1)
91 # os.putenv(var, val) does not work
92 # see http://stackoverflow.com/questions/17705419/python-os-environ-os-putenv-usr-bin-env
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))
105 def process_is_dead(pid):
106 """ Tests whether the process is dead already """
109 except ProcessLookupError:
111 except OSError as err:
112 if err.errno == errno.ESRCH: # ESRCH == No such process. The process is now dead
116 def kill_process_group(pid):
117 """ This function send TERM signal + KILL signal after 0.2s to the group of the specified process """
119 # Nobody to kill. We don't have anyone to kill on signal handler
123 pgid = os.getpgid(pid)
125 # os.getpgid failed. Ok, don't cleanup.
129 os.killpg(pgid, signal.SIGTERM)
130 if process_is_dead(pid):
133 os.killpg(pgid, signal.SIGKILL)
135 # os.killpg failed. OK. Some subprocesses may still be running.
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()
155 class FileReader(Singleton):
156 """ Read file line per line (and concat line that ends with "\") """
157 def __init__(self, filename=None):
159 self.filename = "(stdin)"
160 self.fileno = sys.stdin
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)
170 return self.filename + ":" + str(self.linenumber)
172 def readfullline(self):
173 """ Read a full line """
175 line = next(self.fileno)
177 except StopIteration:
183 while len(line) > 1 and line[-2] == "\\":
185 line = next(self.fileno)
191 class TeshState(Singleton):
192 """ Keep the state of tesh (mostly configuration values) """
194 self.running_pids = list() # stores which process group should be killed (or None otherwise)
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
204 def add_thread(self, thread):
205 """ Add another thread to wait for """
206 self.threads.append(thread)
208 def join_all_threads(self):
209 """ Wait for all threads """
210 for thread in self.threads:
214 def set_return_code(self, value):
215 """ Set exit status """
216 if value > self.return_code:
217 self.return_code = value
221 """ Command line object """
224 self.output_pipe_stdout = []
225 self.output_pipe_stderr = []
226 self.timeout = TeshState().timeout
230 self.background = False
231 # Python threads loose the cwd
232 self.cwd = os.getcwd()
234 self.ignore_output = False
235 self.expect_return = [0]
237 self.output_display = False
240 self.rerun_with_valgrind = False
242 self.ignore_regexps = TeshState().ignore_regexps_common
244 def add_input_pipe(self, line):
245 """ Add a line to stdin input """
246 self.input_pipe.append(line)
248 def add_output_pipe_stdout(self, line):
249 """ Add a line to stdout output """
250 self.output_pipe_stdout.append(line)
252 def add_output_pipe_stderr(self, line):
253 """ Add a line to stderr output """
254 self.output_pipe_stderr.append(line)
256 def set_cmd(self, args, linenumber):
257 """ Set command line """
259 self.linenumber = linenumber
261 def add_ignore(self, txt):
262 """ Add regexp to ignore lines """
263 self.ignore_regexps.append(re.compile(txt))
265 def remove_ignored_lines(self, lines):
266 """ Remove ignored lines """
267 for ign in self.ignore_regexps:
268 lines = [l for l in lines if not ign.match(l)]
271 def _cmd_mkfile(self, argline):
272 filename = argline[len("mkfile "):]
273 file = open(filename, "w")
275 fatal_error("Unable to create file " + filename)
276 file.write("\n".join(self.input_pipe))
280 def _cmd_cd(self, argline): # pylint: disable=no-self-use
281 args = shlex.split(argline)
283 fatal_error("Too many arguments to cd")
286 print("[Tesh/INFO] change directory to " + args[1])
287 except FileNotFoundError:
288 print("Chdir to " + args[1] + " failed: No such file or directory")
289 print("Test suite `" + FileReader().filename + "': NOK (system error)")
292 def run_if_possible(self):
294 Run the Cmd if possible.
295 Return False if nothing has been ran.
297 if not self.can_run():
300 lock = _thread.allocate_lock()
302 TeshState().add_thread(lock)
303 _thread.start_new_thread(Cmd._run, (self, lock))
306 if self.rerun_with_valgrind:
307 print('\n\n\nXXXXXXXXX Rerunning this test with valgrind to help debugging it XXXXXXXXX')
308 print('(this will fail if valgrind is not installed, of course)\n\n\n')
310 self.args = "valgrind " + self.args
314 def _run(self, lock=None):
315 # Python threads loose the cwd
318 # retrocompatibility: support ${aaa:=.} variable format
319 def replace_perl_variables(arg):
321 vdefault = arg.group(2)
322 if vname in os.environ:
326 self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
328 # replace bash environment variables ($THINGS) to their values
329 self.args = expandvars2(self.args)
331 if re.match("^mkfile ", self.args) is not None:
332 self._cmd_mkfile(self.args)
337 if re.match("^cd ", self.args) is not None:
338 self._cmd_cd(self.args)
343 if TeshState().wrapper is not None:
345 self.args = TeshState().wrapper + self.args
346 elif re.match(".*smpirun.*", self.args) is not None:
347 self.args = "sh " + self.args
348 if TeshState().jenkins and self.timeout is not None:
351 self.args += TeshState().args_suffix
354 logs.append("[{file}:{number}] {args}".format(file=FileReader().filename,
355 number=self.linenumber, args=self.args))
357 args = shlex.split(self.args)
362 preexec_function = lambda: os.setpgid(0, 0)
363 proc = subprocess.Popen( # pylint: disable=subprocess-popen-preexec-fn
366 stdin=subprocess.PIPE,
367 stdout=subprocess.PIPE,
368 stderr=subprocess.STDOUT,
369 universal_newlines=True,
370 preexec_fn=preexec_function)
372 TeshState().running_pids.append(local_pid)
373 except PermissionError:
374 logs.append("[{file}:{number}] Cannot start '{cmd}': The binary is not executable.".format(
375 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
376 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
377 number=self.linenumber, dir=os.getcwd()))
378 TeshState().set_return_code(3)
379 print('\n'.join(logs))
381 except NotADirectoryError:
382 logs.append("[{file}:{number}] Cannot start '{cmd}': The path to binary does not exist.".format(
383 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
384 logs.append("[{file}:{number}] Current dir: {dir}".format(file=FileReader().filename,
385 number=self.linenumber, dir=os.getcwd()))
386 TeshState().set_return_code(3)
387 print('\n'.join(logs))
389 except FileNotFoundError:
390 logs.append("[{file}:{number}] Cannot start '{cmd}': File not found.".format(
391 file=FileReader().filename, number=self.linenumber, cmd=args[0]))
392 TeshState().set_return_code(3)
393 print('\n'.join(logs))
395 except OSError as err:
398 "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/usr/bin/env sh)"
401 cmd_name = FileReader().filename + ":" + str(self.linenumber)
403 (stdout_data, _stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
404 timeout_reached = False
405 except subprocess.TimeoutExpired:
406 timeout_reached = True
407 logs.append("Test suite `{file}': NOK (<{cmd}> timeout after {timeout} sec)".format(
408 file=FileReader().filename, cmd=cmd_name, timeout=self.timeout))
409 TeshState().running_pids.remove(local_pid)
410 kill_process_group(local_pid)
411 # Try to get the output of the timeout process, to help in debugging.
413 (stdout_data, _stderr_data) = proc.communicate(timeout=1)
414 except subprocess.TimeoutExpired:
415 logs.append("[{file}:{number}] Could not retrieve output. Killing the process group failed?".format(
416 file=FileReader().filename, number=self.linenumber))
417 TeshState().set_return_code(3)
418 print('\n'.join(logs))
421 if self.output_display:
422 logs.append(str(stdout_data))
425 ansi_escape = re.compile(r'\x1b[^m]*m')
426 stdout_data = ansi_escape.sub('', stdout_data)
428 if self.ignore_output:
429 logs.append("(ignoring the output of <{cmd}> as requested)".format(cmd=cmd_name))
431 stdouta = stdout_data.split("\n")
432 stdouta = self.remove_ignored_lines(stdouta)
433 while stdouta and stdouta[-1] == "":
437 # Mimic the "sort" bash command, which is case unsensitive.
439 stdouta.sort(key=lambda x: x.lower())
440 self.output_pipe_stdout.sort(key=lambda x: x.lower())
442 stdouta.sort(key=lambda x: x[:self.sort].lower())
443 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
446 difflib.unified_diff(
447 self.output_pipe_stdout,
453 logs.append("Output of <{cmd}> mismatch:".format(cmd=cmd_name))
454 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
461 logs.append("(diff truncated after 50 lines)")
462 logs.append("Unsorted observed output:\n")
465 else: # If not sorted, just display the diff
469 logs.append("Test suite `{file}': NOK (<{cmd}> output mismatch)".format(
470 file=FileReader().filename, cmd=cmd_name))
472 # Also report any failed return code and/or signal we got in case of output mismatch
473 if not proc.returncode in self.expect_return:
474 if proc.returncode >= 0:
475 logs.append("In addition, <{cmd}> returned code {code}.".format(
476 cmd=cmd_name, code=proc.returncode))
478 logs.append("In addition, <{cmd}> got signal {sig}.".format(cmd=cmd_name,
479 sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
480 if proc.returncode == -signal.SIGSEGV:
481 self.rerun_with_valgrind = True
486 file = open('obtained', 'w')
487 obtained = stdout_data.split("\n")
488 while obtained and obtained[-1] == "":
490 obtained = self.remove_ignored_lines(obtained)
491 for line in obtained:
492 file.write("> " + line + "\n")
494 logs.append("Obtained output kept as requested: {path}".format(path=os.path.abspath("obtained")))
495 TeshState().set_return_code(2)
496 print('\n'.join(logs))
500 TeshState().set_return_code(3)
501 print('\n'.join(logs))
504 if not proc.returncode in self.expect_return:
505 if proc.returncode >= 0:
506 logs.append("Test suite `{file}': NOK (<{cmd}> returned code {code})".format(
507 file=FileReader().filename, cmd=cmd_name, code=proc.returncode))
510 TeshState().set_return_code(2)
511 print('\n'.join(logs))
514 logs.append("Test suite `{file}': NOK (<{cmd}> got signal {sig})".format(
515 file=FileReader().filename, cmd=cmd_name,
516 sig=SIGNALS_TO_NAMES_DICT[-proc.returncode]))
518 if proc.returncode == -signal.SIGSEGV:
519 self.rerun_with_valgrind = True
523 TeshState().set_return_code(max(-proc.returncode, 1))
524 print('\n'.join(logs))
530 print('\n'.join(logs))
533 """ Check if ready to run """
534 return self.args is not None
543 """ main function """
544 signal.signal(signal.SIGINT, signal_handler)
545 signal.signal(signal.SIGTERM, signal_handler)
547 parser = argparse.ArgumentParser(description='tesh -- testing shell')
548 group1 = parser.add_argument_group('Options')
549 group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
552 metavar='some/directory',
553 help='ask tesh to switch the working directory before launching the tests')
554 group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
555 group1.add_argument('--cfg', metavar='arg', action='append', help='add parameter --cfg=arg to each command line')
556 group1.add_argument('--log', metavar='arg', action='append', help='add parameter --log=arg to each command line')
560 help='ignore all cruft generated on SimGrid continuous integration servers')
561 group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
565 help='Keep the obtained output when it does not match the expected one')
567 options = parser.parse_args()
569 if options.cd is not None:
570 print("[Tesh/INFO] change directory to " + options.cd)
573 if options.ignore_jenkins:
574 print("Ignore all cruft seen on SimGrid's continuous integration servers")
575 # Note: regexps should match at the beginning of lines
576 TeshState().ignore_regexps_common = [
577 re.compile(r"profiling:"),
578 re.compile(r"Unable to clean temporary file C:"),
579 re.compile(r".*Configuration change: Set 'contexts/"),
580 re.compile(r"==[0-9]+== ?WARNING: ASan doesn't fully support"),
581 re.compile(r"==[0-9]+== ?WARNING: ASan is ignoring requested __asan_handle_no_return: stack "),
582 re.compile(r"False positive error reports may follow"),
583 re.compile(r"For details see http://code\.google\.com/p/address-sanitizer/issues/detail\?id=189"),
584 re.compile(r"For details see https://github\.com/google/sanitizers/issues/189"),
585 re.compile(r"Python runtime initialized with LC_CTYPE=C .*"),
587 re.compile(r"cmake: /usr/local/lib/libcurl\.so\.4: no version information available \(required by cmake\)"),
589 r".*mmap broken on FreeBSD, but dlopen\+thread broken too\. Switching to dlopen\+raw contexts\."),
590 re.compile(r".*dlopen\+thread broken on Apple and BSD\. Switching to raw contexts\."),
592 TeshState().jenkins = True # This is a Jenkins build
594 if options.teshfile is None:
595 file = FileReader(None)
596 print("Test suite from stdin")
598 if not os.path.isfile(options.teshfile):
599 print("Cannot open teshfile '" + options.teshfile + "': File not found")
601 file = FileReader(options.teshfile)
602 print("Test suite '" + file.abspath + "'")
604 if options.setenv is not None:
605 for env in options.setenv:
608 if options.cfg is not None:
609 for cfg in options.cfg:
610 TeshState().args_suffix += " --cfg=" + cfg
611 if options.log is not None:
612 for log in options.log:
613 TeshState().args_suffix += " --log=" + log
615 if options.wrapper is not None:
616 TeshState().wrapper = options.wrapper
619 TeshState().keep = True
621 # cmd holds the current command line
622 # tech commands will add some parameters to it
623 # when ready, we execute it.
626 line = file.readfullline()
627 while line is not None:
628 # print(">>============="+line+"==<<")
630 #print ("END CMD block")
631 if cmd.run_if_possible():
637 elif line[0:2] == "p ":
638 print("[" + str(FileReader()) + "] " + line[2:])
640 elif line[0:2] == "< ":
641 cmd.add_input_pipe(line[2:])
642 elif line[0:1] == "<":
643 cmd.add_input_pipe(line[1:])
645 elif line[0:2] == "> ":
646 cmd.add_output_pipe_stdout(line[2:])
647 elif line[0:1] == ">":
648 cmd.add_output_pipe_stdout(line[1:])
650 elif line[0:2] == "$ ":
651 if cmd.run_if_possible():
653 cmd.set_cmd(line[2:], file.linenumber)
655 elif line[0:2] == "& ":
656 if cmd.run_if_possible():
658 cmd.set_cmd(line[2:], file.linenumber)
659 cmd.background = True
661 elif line[0:15] == "! output ignore":
662 cmd.ignore_output = True
663 #print("cmd.ignore_output = True")
664 elif line[0:16] == "! output display":
665 cmd.output_display = True
666 cmd.ignore_output = True
667 elif line[0:15] == "! expect return":
668 cmd.expect_return = [int(line[16:])]
669 #print("expect return "+str(int(line[16:])))
670 elif line[0:15] == "! expect signal":
671 cmd.expect_return = []
672 for sig in (line[16:]).split("|"):
673 # get the signal integer value from the signal module
674 if sig not in signal.__dict__:
675 fatal_error("unrecognized signal '" + sig + "'")
676 sig = int(signal.__dict__[sig])
677 # popen return -signal when a process ends with a signal
678 cmd.expect_return.append(-sig)
679 elif line[0:len("! timeout ")] == "! timeout ":
680 if "no" in line[len("! timeout "):]:
683 cmd.timeout = int(line[len("! timeout "):])
685 elif line[0:len("! output sort")] == "! output sort":
686 if len(line) >= len("! output sort "):
687 sort = int(line[len("! output sort "):])
691 elif line[0:len("! setenv ")] == "! setenv ":
692 setenv(line[len("! setenv "):])
694 elif line[0:len("! ignore ")] == "! ignore ":
695 cmd.add_ignore(line[len("! ignore "):])
698 fatal_error(f"UNRECOGNIZED OPTION LINE: {line}")
700 line = file.readfullline()
702 cmd.run_if_possible()
704 TeshState().join_all_threads()
706 if TeshState().return_code == 0:
707 if file.filename == "(stdin)":
708 print("Test suite from stdin OK")
710 print("Test suite `" + file.filename + "' OK")
711 tesh_exit(TeshState().return_code)
713 if __name__ == '__main__':