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