Logo AND Algorithmique Numérique Distribuée

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