exec_wrapper.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #!/usr/bin/env python3
  2. # Import as few modules and define as few names as possible at global level before exec'ing the
  3. # file, as all names will be seen by the exec'ed code. To prevent name collisions, all names
  4. # defined here should begin with 'exec_wrapper_'
  5. import sys,os,time
  6. def exec_wrapper_get_colors():
  7. from collections import namedtuple
  8. return namedtuple('colors',['red','green','yellow','blue'])(*[
  9. (lambda s:s) if os.getenv('MMGEN_DISABLE_COLOR') else
  10. (lambda s,n=n:f'\033[{n};1m{s}\033[0m' )
  11. for n in (31,32,33,34) ])
  12. def exec_wrapper_init(): # don't change: name is used to test if script is running under exec_wrapper
  13. if os.path.dirname(sys.argv[1]) == 'test': # scripts in ./test do overlay setup themselves
  14. sys.path[0] = 'test'
  15. else:
  16. from test.overlay import overlay_setup
  17. sys.path[0] = overlay_setup(repo_root=os.getcwd()) # assume we're in the repo root
  18. os.environ['MMGEN_EXEC_WRAPPER'] = '1'
  19. os.environ['PYTHONPATH'] = '.'
  20. if 'TMUX' in os.environ:
  21. del os.environ['TMUX']
  22. if not os.getenv('EXEC_WRAPPER_NO_TRACEBACK'):
  23. try:
  24. os.unlink('test.py.err')
  25. except:
  26. pass
  27. def exec_wrapper_write_traceback(e):
  28. import traceback,re
  29. lines = traceback.format_exception(*sys.exc_info()) # returns a list
  30. pat = re.compile('File "<string>"')
  31. repl = f'File "{exec_wrapper_execed_file}"'
  32. lines = [pat.sub(repl,line,count=1) for line in lines]
  33. exc = lines.pop()
  34. if exc.startswith('SystemExit:'):
  35. lines.pop()
  36. if os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC'):
  37. pat = re.compile(", line [0-9]+,")
  38. lines = [pat.sub(", line (scrubbed),",line) for line in lines]
  39. c = exec_wrapper_get_colors()
  40. message = ( repr(e) if type(e).__name__ in ('MMGenError','MMGenSystemExit') else exc )
  41. sys.stdout.write('{}{}'.format(
  42. c.yellow( ''.join(lines) ),
  43. c.red(message) )
  44. + '\n' )
  45. if not os.getenv('EXEC_WRAPPER_NO_TRACEBACK'):
  46. with open('test.py.err','w') as fp:
  47. fp.write(''.join(lines+[exc]))
  48. def exec_wrapper_end_msg():
  49. if os.getenv('EXEC_WRAPPER_SPAWN') and not os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC'):
  50. c = exec_wrapper_get_colors()
  51. # write to stdout to ensure script output gets to terminal first
  52. sys.stdout.write(c.blue('Runtime: {:0.5f} secs\n'.format(time.time() - exec_wrapper_tstart)))
  53. def exec_wrapper_tracemalloc_setup():
  54. if os.getenv('MMGEN_TRACEMALLOC'):
  55. os.environ['PYTHONTRACEMALLOC'] = '1'
  56. import tracemalloc
  57. tracemalloc.start()
  58. sys.stderr.write("INFO → Appending memory allocation stats to 'tracemalloc.log'\n")
  59. def exec_wrapper_tracemalloc_log():
  60. if os.getenv('MMGEN_TRACEMALLOC'):
  61. import tracemalloc,re
  62. snapshot = tracemalloc.take_snapshot()
  63. stats = snapshot.statistics('lineno')
  64. depth = 100
  65. col1w = 100
  66. with open('tracemalloc.log','a') as fp:
  67. fp.write('##### TOP {} {} #####\n'.format(depth,' '.join(sys.argv)))
  68. for stat in stats[:depth]:
  69. frame = stat.traceback[0]
  70. fn = re.sub(r'.*\/site-packages\/|.*\/mmgen\/test\/overlay\/tree\/','',frame.filename)
  71. fn = re.sub(r'.*\/mmgen\/test\/','test/',fn)
  72. fp.write('{f:{w}} {s:>8.2f} KiB\n'.format(
  73. f = f'{fn}:{frame.lineno}:',
  74. s = stat.size/1024,
  75. w = col1w ))
  76. fp.write('{f:{w}} {s:8.2f} KiB\n\n'.format(
  77. f = 'TOTAL {}:'.format(' '.join(sys.argv))[:col1w],
  78. s = sum(stat.size for stat in stats) / 1024,
  79. w = col1w ))
  80. exec_wrapper_init() # sets sys.path[0]
  81. exec_wrapper_tstart = time.time()
  82. exec_wrapper_tracemalloc_setup()
  83. try:
  84. sys.argv.pop(0)
  85. exec_wrapper_execed_file = sys.argv[0]
  86. with open(exec_wrapper_execed_file) as fp:
  87. exec(fp.read())
  88. except SystemExit as e:
  89. if e.code != 0 and not os.getenv('EXEC_WRAPPER_NO_TRACEBACK'):
  90. exec_wrapper_write_traceback(e)
  91. else:
  92. exec_wrapper_tracemalloc_log()
  93. exec_wrapper_end_msg()
  94. sys.exit(e.code)
  95. except Exception as e:
  96. if not os.getenv('EXEC_WRAPPER_NO_TRACEBACK'):
  97. exec_wrapper_write_traceback(e)
  98. retval = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  99. sys.exit(retval)
  100. exec_wrapper_tracemalloc_log()
  101. exec_wrapper_end_msg()