Logo AND Algorithmique Numérique Distribuée

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