Logo AND Algorithmique Numérique Distribuée

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