Logo AND Algorithmique Numérique Distribuée

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