Logo AND Algorithmique Numérique Distribuée

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