Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
1985a5dbb0cc90d759e672cd19f786f72441fb1c
[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.wrapper = None
166         self.keep = False
167     
168     def add_thread(self, thread):
169         self.threads.append(thread)
170     
171     def join_all_threads(self):
172         for t in self.threads:
173             t.acquire()
174             t.release()
175
176 #Command line object
177 class Cmd(object):
178     def __init__(self):
179         self.input_pipe = []
180         self.output_pipe_stdout = []
181         self.output_pipe_stderr = []
182         self.timeout = 10
183         self.args = None
184         self.linenumber = -1
185         
186         self.background = False
187         self.cwd = None
188         
189         self.ignore_output = False
190         self.expect_return = 0
191         
192         self.output_display = False
193         
194         self.sort = -1
195         
196         self.ignore_regexps = TeshState().ignore_regexps_common
197
198     def add_input_pipe(self, l):
199         self.input_pipe.append(l)
200
201     def add_output_pipe_stdout(self, l):
202         self.output_pipe_stdout.append(l)
203
204     def add_output_pipe_stderr(self, l):
205         self.output_pipe_stderr.append(l)
206
207     def set_cmd(self, args, linenumber):
208         self.args = args
209         self.linenumber = linenumber
210     
211     def add_ignore(self, txt):
212         self.ignore_regexps.append(re.compile(txt))
213     
214     def remove_ignored_lines(self, lines):
215         for ign in self.ignore_regexps:
216                 lines = [l for l in lines if not ign.match(l)]
217         return lines
218
219
220     def _cmd_mkfile(self, argline):
221         filename = argline[len("mkfile "):]
222         file = open(filename, "w")
223         if file is None:
224             fatal_error("Unable to create file "+filename)
225         file.write("\n".join(self.input_pipe))
226         file.write("\n")
227         file.close()
228
229     def _cmd_cd(self, argline):
230         args = shlex.split(argline)
231         if len(args) != 2:
232             fatal_error("Too many arguments to cd")
233         try:
234             os.chdir(args[1])
235             print("[Tesh/INFO] change directory to "+args[1])
236         except FileNotFoundError:
237             print("Chdir to "+args[1]+" failed: No such file or directory")
238             print("Test suite `"+FileReader().filename+"': NOK (system error)")
239             exit(4)
240
241
242     #Run the Cmd if possible.
243     # Return False if nothing has been ran.
244     def run_if_possible(self):
245         if self.can_run():
246             if self.background:
247                 #Python threads loose the cwd
248                 self.cwd = os.getcwd()
249                 lock = _thread.allocate_lock()
250                 lock.acquire()
251                 TeshState().add_thread(lock)
252                 _thread.start_new_thread( Cmd._run, (self, lock) )
253             else:
254                 self._run()
255             return True
256         else:
257             return False
258
259
260     def _run(self, lock=None):
261         #Python threads loose the cwd
262         if self.cwd is not None:
263             os.chdir(self.cwd)
264             self.cwd = None
265         
266         #retrocompatibility: support ${aaa:=.} variable format
267         def replace_perl_variables(m):
268             vname = m.group(1)
269             vdefault = m.group(2)
270             if vname in os.environ:
271                 return "$"+vname
272             else:
273                 return vdefault
274         self.args = re.sub(r"\${(\w+):=([^}]*)}", replace_perl_variables, self.args)
275
276         #replace bash environment variables ($THINGS) to their values
277         self.args = expandvars2(self.args)
278         
279         if re.match("^mkfile ", self.args) is not None:
280             self._cmd_mkfile(self.args)
281             if lock is not None: lock.release()
282             return
283         
284         if re.match("^cd ", self.args) is not None:
285             self._cmd_cd(self.args)
286             if lock is not None: lock.release()
287             return
288         
289         if TeshState().wrapper is not None:
290             self.timeout *= 20
291             self.args = TeshState().wrapper + self.args
292         elif re.match(".*smpirun.*", self.args) is not None:
293             self.args = "sh " + self.args 
294
295         self.args += TeshState().args_suffix
296         
297         print("["+FileReader().filename+":"+str(self.linenumber)+"] "+self.args)
298                 
299         args = shlex.split(self.args)
300         #print (args)
301         try:
302             proc = subprocess.Popen(args, bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
303         except OSError as e:
304             if e.errno == 8:
305                 e.strerror += "\nOSError: [Errno 8] Executed scripts should start with shebang line (like #!/bin/sh)"
306             raise e
307
308         cmdName = FileReader().filename+":"+str(self.linenumber)
309         try:
310             (stdout_data, stderr_data) = proc.communicate("\n".join(self.input_pipe), self.timeout)
311         except subprocess.TimeoutExpired:
312             print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> timeout after "+str(self.timeout)+" sec)")
313             exit(3)
314
315         if self.output_display:
316             print(stdout_data)
317
318         #remove text colors
319         ansi_escape = re.compile(r'\x1b[^m]*m')
320         stdout_data = ansi_escape.sub('', stdout_data)
321         
322         #print ((stdout_data, stderr_data))
323         
324         if self.ignore_output:
325             print("(ignoring the output of <"+cmdName+"> as requested)")
326         else:
327             stdouta = stdout_data.split("\n")
328             while len(stdouta) > 0 and stdouta[-1] == "":
329                 del stdouta[-1]
330             stdouta = self.remove_ignored_lines(stdouta)
331             stdcpy = stdouta[:]
332
333             # Mimic the "sort" bash command, which is case unsensitive.
334             if self.sort == 0:
335                 stdouta.sort(key=lambda x: x.lower())
336                 self.output_pipe_stdout.sort(key=lambda x: x.lower())
337             elif self.sort > 0:
338                 stdouta.sort(key=lambda x: x[:self.sort].lower())
339                 self.output_pipe_stdout.sort(key=lambda x: x[:self.sort].lower())
340             
341             diff = list(difflib.unified_diff(self.output_pipe_stdout, stdouta,lineterm="",fromfile='expected', tofile='obtained'))
342             if len(diff) > 0: 
343                 print("Output of <"+cmdName+"> mismatch:")
344                 if self.sort >= 0: # If sorted, truncate the diff output and show the unsorted version
345                     difflen = 0;
346                     for line in diff:
347                         if difflen<250:
348                             print(line)
349                         difflen += 1
350                     if difflen > 100:
351                         print("(diff truncated after 250 lines)")
352                     print("Unsorted observed output:\n")
353                     for line in stdcpy:
354                         print(line)
355                 else: # If not sorted, just display the diff
356                     for line in diff:
357                         print(line)
358                         
359                 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> output mismatch)")
360                 if lock is not None: lock.release()
361                 if TeshState().keep:
362                     f = open('obtained','w')
363                     obtained = stdout_data.split("\n")
364                     while len(obtained) > 0 and obtained[-1] == "":
365                         del obtained[-1]
366                     obtained = self.remove_ignored_lines(obtained)
367                     for line in obtained:
368                         f.write("> "+line+"\n")
369                     f.close()
370                     print("Obtained output kept as requested: "+os.path.abspath("obtained"))
371                 exit(2)
372         
373         #print ((proc.returncode, self.expect_return))
374         
375         if proc.returncode != self.expect_return:
376             if proc.returncode >= 0:
377                 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> returned code "+str(proc.returncode)+")")
378                 if lock is not None: lock.release()
379                 exit(2)
380             else:
381                 print("Test suite `"+FileReader().filename+"': NOK (<"+cmdName+"> got signal "+SIGNALS_TO_NAMES_DICT[-proc.returncode]+")")
382                 if lock is not None: lock.release()
383                 exit(-proc.returncode)
384             
385         if lock is not None: lock.release()
386     
387     
388     
389     def can_run(self):
390         return self.args is not None
391
392
393
394
395 ##############
396 #
397 # Main
398 #
399 #
400
401
402
403 if __name__ == '__main__':
404     
405     parser = argparse.ArgumentParser(description='tesh -- testing shell', add_help=True)
406     group1 = parser.add_argument_group('Options')
407     group1.add_argument('teshfile', nargs='?', help='Name of teshfile, stdin if omitted')
408     group1.add_argument('--cd', metavar='some/directory', help='ask tesh to switch the working directory before launching the tests')
409     group1.add_argument('--setenv', metavar='var=value', action='append', help='set a specific environment variable')
410     group1.add_argument('--cfg', metavar='arg', help='add parameter --cfg=arg to each command line')
411     group1.add_argument('--log', metavar='arg', help='add parameter --log=arg to each command line')
412     group1.add_argument('--ignore-jenkins', action='store_true', help='ignore all cruft generated on SimGrid continous integration servers')
413     group1.add_argument('--wrapper', metavar='arg', help='Run each command in the provided wrapper (eg valgrind)')
414     group1.add_argument('--keep', action='store_true', help='Keep the obtained output when it does not match the expected one')
415
416     try:
417         options = parser.parse_args()
418     except:
419         exit(1)
420
421     if options.cd is not None:
422         os.chdir(options.cd)
423     
424     if options.ignore_jenkins:
425         print("Ignore all cruft seen on SimGrid's continous integration servers")
426         TeshState().ignore_regexps_common = [
427            re.compile("^profiling:"),
428            re.compile(".*WARNING: ASan doesn\'t fully support"),
429            re.compile("Unable to clean temporary file C:.*"),
430            re.compile(".*Configuration change: Set \'contexts/"),
431            re.compile(".*Picked up JAVA_TOOL_OPTIONS.*")]
432     
433     if options.teshfile is None:
434         f = FileReader(None)
435         print("Test suite from stdin")
436     else:
437         f = FileReader(options.teshfile)
438         print("Test suite '"+f.abspath+"'")
439     
440     if options.setenv is not None:
441         for e in options.setenv:
442             setenv(e)
443     
444     if options.cfg is not None:
445         TeshState().args_suffix += " --cfg="+options.cfg
446     if options.log is not None:
447         TeshState().args_suffix += " --log="+options.log
448
449     if options.wrapper is not None:
450         TeshState().wrapper = options.wrapper
451         
452     if options.keep:
453         TeshState().keep = True
454     
455     #cmd holds the current command line
456     # tech commands will add some parameters to it
457     # when ready, we execute it.
458     cmd = Cmd()
459     
460     line = f.readfullline()
461     while line is not None:
462         #print(">>============="+line+"==<<")
463         if len(line) == 0:
464             #print ("END CMD block")
465             if cmd.run_if_possible():
466                 cmd = Cmd()
467         
468         elif line[0] == "#":
469             pass
470         
471         elif line[0:2] == "p ":
472             print("["+str(FileReader())+"] "+line[2:])
473         
474         elif line[0:2] == "< ":
475             cmd.add_input_pipe(line[2:])
476         elif line[0:1] == "<":
477             cmd.add_input_pipe(line[1:])
478             
479         elif line[0:2] == "> ":
480             cmd.add_output_pipe_stdout(line[2:])
481         elif line[0:1] == ">":
482             cmd.add_output_pipe_stdout(line[1:])
483             
484         elif line[0:2] == "$ ":
485             if cmd.run_if_possible():
486                 cmd = Cmd()
487             cmd.set_cmd(line[2:], f.linenumber)
488         
489         elif line[0:2] == "& ":
490             if cmd.run_if_possible():
491                 cmd = Cmd()
492             cmd.set_cmd(line[2:], f.linenumber)
493             cmd.background = True
494         
495         elif line[0:15] == "! output ignore":
496             cmd.ignore_output = True
497             #print("cmd.ignore_output = True")
498         elif line[0:16] == "! output display":
499             cmd.output_display = True
500             cmd.ignore_output = True
501         elif line[0:15] == "! expect return":
502             cmd.expect_return = int(line[16:])
503             #print("expect return "+str(int(line[16:])))
504         elif line[0:15] == "! expect signal":
505             sig = line[16:]
506             #get the signal integer value from the signal module
507             if sig not in signal.__dict__:
508                 fatal_error("unrecognized signal '"+sig+"'")
509             sig = int(signal.__dict__[sig])
510             #popen return -signal when a process ends with a signal
511             cmd.expect_return = -sig
512         elif line[0:len("! timeout ")] == "! timeout ":
513             if "no" in line[len("! timeout "):]:
514                 cmd.timeout = None
515             else:
516                 cmd.timeout = int(line[len("! timeout "):])
517             
518         elif line[0:len("! output sort")] == "! output sort":
519             if len(line) >= len("! output sort "):
520                 sort = int(line[len("! output sort "):])
521             else:
522                 sort = 0
523             cmd.sort = sort
524         elif line[0:len("! setenv ")] == "! setenv ":
525             setenv(line[len("! setenv "):])
526         
527         elif line[0:len("! ignore ")] == "! ignore ":
528             cmd.add_ignore(line[len("! ignore "):])
529         
530         else:
531             fatal_error("UNRECOGNIZED OPTION")
532             
533         
534         line = f.readfullline()
535
536     cmd.run_if_possible()
537     
538     TeshState().join_all_threads()
539     
540     if f.filename == "(stdin)":
541         print("Test suite from stdin OK")
542     else:
543         print("Test suite `"+f.filename+"' OK")