Logo AND Algorithmique Numérique Distribuée

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