exec_wrapper.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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','purple'])(*[
  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,35) ])
  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 os.getenv('EXEC_WRAPPER_TRACEBACK'):
  23. try:
  24. os.unlink('test.py.err')
  25. except:
  26. pass
  27. def exec_wrapper_write_traceback(e,exit_val):
  28. exc_line = (
  29. repr(e) if type(e).__name__ in ('MMGenError','MMGenSystemExit') else
  30. '{}: {}'.format( type(e).__name__, e ))
  31. c = exec_wrapper_get_colors()
  32. if os.getenv('EXEC_WRAPPER_TRACEBACK'):
  33. import traceback
  34. cwd = os.path.abspath('.')
  35. def fixup_fn(fn_in):
  36. fn = fn_in.removeprefix(cwd+'/').removeprefix('test/overlay/tree/')
  37. return (fn.removesuffix('_orig.py') + '.py') if fn.endswith('_orig.py') else fn
  38. def gen_output():
  39. yield 'Traceback (most recent call last):'
  40. for e in traceback.extract_tb(sys.exc_info()[2]):
  41. yield ' File "{f}", line {l}, in {n}\n {L}'.format(
  42. f = exec_wrapper_execed_file if e.filename == '<string>' else fixup_fn(e.filename),
  43. l = '(scrubbed)' if os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') else e.lineno,
  44. n = e.name,
  45. L = e.line or 'N/A' )
  46. tb_lines = list( gen_output() )
  47. if 'SystemExit' in exc_line:
  48. tb_lines.pop()
  49. sys.stdout.write('{}\n{}\n'.format( c.yellow( '\n'.join(tb_lines) ), c.red(exc_line) ))
  50. with open('test.py.err','w') as fp:
  51. fp.write('\n'.join(tb_lines + [exc_line]))
  52. else:
  53. sys.stdout.write( c.purple(('NONZERO_EXIT: ' if exit_val else '') + exc_line) + '\n' )
  54. def exec_wrapper_end_msg():
  55. if os.getenv('EXEC_WRAPPER_SPAWN') and not os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC'):
  56. c = exec_wrapper_get_colors()
  57. # write to stdout to ensure script output gets to terminal first
  58. sys.stdout.write(c.blue('Runtime: {:0.5f} secs\n'.format(time.time() - exec_wrapper_tstart)))
  59. def exec_wrapper_tracemalloc_setup():
  60. if os.getenv('MMGEN_TRACEMALLOC'):
  61. os.environ['PYTHONTRACEMALLOC'] = '1'
  62. import tracemalloc
  63. tracemalloc.start()
  64. sys.stderr.write("INFO → Appending memory allocation stats to 'tracemalloc.log'\n")
  65. def exec_wrapper_tracemalloc_log():
  66. if os.getenv('MMGEN_TRACEMALLOC'):
  67. import tracemalloc,re
  68. snapshot = tracemalloc.take_snapshot()
  69. stats = snapshot.statistics('lineno')
  70. depth = 100
  71. col1w = 100
  72. with open('tracemalloc.log','a') as fp:
  73. fp.write('##### TOP {} {} #####\n'.format(depth,' '.join(sys.argv)))
  74. for stat in stats[:depth]:
  75. frame = stat.traceback[0]
  76. fn = re.sub(r'.*\/site-packages\/|.*\/mmgen\/test\/overlay\/tree\/','',frame.filename)
  77. fn = re.sub(r'.*\/mmgen\/test\/','test/',fn)
  78. fp.write('{f:{w}} {s:>8.2f} KiB\n'.format(
  79. f = f'{fn}:{frame.lineno}:',
  80. s = stat.size/1024,
  81. w = col1w ))
  82. fp.write('{f:{w}} {s:8.2f} KiB\n\n'.format(
  83. f = 'TOTAL {}:'.format(' '.join(sys.argv))[:col1w],
  84. s = sum(stat.size for stat in stats) / 1024,
  85. w = col1w ))
  86. exec_wrapper_init() # sets sys.path[0]
  87. exec_wrapper_tstart = time.time()
  88. exec_wrapper_tracemalloc_setup()
  89. try:
  90. sys.argv.pop(0)
  91. exec_wrapper_execed_file = sys.argv[0]
  92. with open(exec_wrapper_execed_file) as fp:
  93. exec(fp.read())
  94. except SystemExit as e:
  95. if e.code != 0:
  96. exec_wrapper_write_traceback(e,e.code)
  97. else:
  98. exec_wrapper_tracemalloc_log()
  99. exec_wrapper_end_msg()
  100. sys.exit(e.code)
  101. except Exception as e:
  102. exit_val = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  103. exec_wrapper_write_traceback(e,exit_val)
  104. sys.exit(exit_val)
  105. exec_wrapper_tracemalloc_log()
  106. exec_wrapper_end_msg()