exec_wrapper.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. #!/usr/bin/env python3
  2. # Import as few modules and define as few names as possible at module 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 or imported here at module level should begin with 'exec_wrapper_'
  5. def exec_wrapper_get_colors():
  6. from collections import namedtuple
  7. return namedtuple('colors',['red','green','yellow','blue','purple'])(*[
  8. (lambda s:s) if exec_wrapper_os.getenv('MMGEN_DISABLE_COLOR') else
  9. (lambda s,n=n:f'\033[{n};1m{s}\033[0m' )
  10. for n in (31,32,33,34,35) ])
  11. def exec_wrapper_init():
  12. if exec_wrapper_os.path.dirname(exec_wrapper_sys.argv[1]) == 'test': # scripts in ./test do overlay setup themselves
  13. exec_wrapper_sys.path[0] = 'test'
  14. else:
  15. exec_wrapper_sys.path.pop(0)
  16. if 'TMUX' in exec_wrapper_os.environ:
  17. del exec_wrapper_os.environ['TMUX']
  18. if exec_wrapper_os.getenv('EXEC_WRAPPER_TRACEBACK'):
  19. try:
  20. exec_wrapper_os.unlink('test.py.err')
  21. except:
  22. pass
  23. exec_wrapper_os.environ['MMGEN_EXEC_WRAPPER'] = '1'
  24. def exec_wrapper_write_traceback(e,exit_val):
  25. import sys,os
  26. exc_line = (
  27. repr(e) if type(e).__name__ in ('MMGenError','MMGenSystemExit') else
  28. '{}: {}'.format( type(e).__name__, e ))
  29. c = exec_wrapper_get_colors()
  30. if os.getenv('EXEC_WRAPPER_TRACEBACK'):
  31. import traceback
  32. cwd = os.path.abspath('.')
  33. def fixup_fn(fn_in):
  34. from mmgen.util2 import removeprefix,removesuffix
  35. fn = removeprefix(removeprefix(fn_in,cwd+'/'),'test/overlay/tree/')
  36. return removesuffix(fn,'_orig.py') + '.py' if fn.endswith('_orig.py') else fn
  37. # Python 3.9:
  38. # fn = fn_in.removeprefix(cwd+'/').removeprefix('test/overlay/tree/')
  39. # return fn.removesuffix('_orig.py') + '.py' if fn.endswith('_orig.py') else fn
  40. def gen_output():
  41. yield 'Traceback (most recent call last):'
  42. for e in traceback.extract_tb(sys.exc_info()[2]):
  43. yield ' File "{f}", line {l}, in {n}\n {L}'.format(
  44. f = exec_wrapper_execed_file if e.filename == '<string>' else fixup_fn(e.filename),
  45. l = '(scrubbed)' if os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') else e.lineno,
  46. n = e.name,
  47. L = e.line or 'N/A' )
  48. tb_lines = list( gen_output() )
  49. if 'SystemExit' in exc_line:
  50. tb_lines.pop()
  51. sys.stdout.write('{}\n{}\n'.format( c.yellow( '\n'.join(tb_lines) ), c.red(exc_line) ))
  52. from test.include.common import test_py_error_fn
  53. with open(test_py_error_fn,'w') as fp:
  54. fp.write('\n'.join(tb_lines + [exc_line]))
  55. else:
  56. sys.stdout.write( c.purple((f'NONZERO_EXIT[{exit_val}]: ' if exit_val else '') + exc_line) + '\n' )
  57. def exec_wrapper_end_msg():
  58. if (
  59. exec_wrapper_os.getenv('EXEC_WRAPPER_SPAWN')
  60. and not exec_wrapper_os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') ):
  61. c = exec_wrapper_get_colors()
  62. # write to stdout to ensure script output gets to terminal first
  63. exec_wrapper_sys.stdout.write(c.blue('Runtime: {:0.5f} secs\n'.format(
  64. exec_wrapper_time.time() - exec_wrapper_tstart )))
  65. def exec_wrapper_tracemalloc_setup():
  66. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  67. exec_wrapper_os.environ['PYTHONTRACEMALLOC'] = '1'
  68. import tracemalloc
  69. tracemalloc.start()
  70. exec_wrapper_sys.stderr.write("INFO → Appending memory allocation stats to 'tracemalloc.log'\n")
  71. def exec_wrapper_tracemalloc_log():
  72. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  73. import tracemalloc,re
  74. snapshot = tracemalloc.take_snapshot()
  75. stats = snapshot.statistics('lineno')
  76. depth = 100
  77. col1w = 100
  78. with open('tracemalloc.log','a') as fp:
  79. fp.write('##### TOP {} {} #####\n'.format(depth,' '.join(exec_wrapper_sys.argv)))
  80. for stat in stats[:depth]:
  81. frame = stat.traceback[0]
  82. fn = re.sub(r'.*\/site-packages\/|.*\/mmgen\/test\/overlay\/tree\/','',frame.filename)
  83. fn = re.sub(r'.*\/mmgen\/test\/','test/',fn)
  84. fp.write('{f:{w}} {s:>8.2f} KiB\n'.format(
  85. f = f'{fn}:{frame.lineno}:',
  86. s = stat.size/1024,
  87. w = col1w ))
  88. fp.write('{f:{w}} {s:8.2f} KiB\n\n'.format(
  89. f = 'TOTAL {}:'.format(' '.join(exec_wrapper_sys.argv))[:col1w],
  90. s = sum(stat.size for stat in stats) / 1024,
  91. w = col1w ))
  92. import sys as exec_wrapper_sys
  93. import os as exec_wrapper_os
  94. import time as exec_wrapper_time
  95. exec_wrapper_init() # sets sys.path[0], runs overlay_setup()
  96. exec_wrapper_tracemalloc_setup()
  97. # import mmgen mods only after overlay setup!
  98. from mmgen.devinit import init_dev as exec_wrapper_init_dev
  99. exec_wrapper_init_dev()
  100. exec_wrapper_tstart = exec_wrapper_time.time()
  101. try:
  102. exec_wrapper_sys.argv.pop(0)
  103. exec_wrapper_execed_file = exec_wrapper_sys.argv[0]
  104. with open(exec_wrapper_execed_file) as fp:
  105. exec(fp.read())
  106. except SystemExit as e:
  107. if e.code != 0:
  108. exec_wrapper_write_traceback(e,e.code)
  109. else:
  110. exec_wrapper_tracemalloc_log()
  111. exec_wrapper_end_msg()
  112. exec_wrapper_sys.exit(e.code)
  113. except Exception as e:
  114. exit_val = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  115. exec_wrapper_write_traceback(e,exit_val)
  116. exec_wrapper_sys.exit(exit_val)
  117. exec_wrapper_tracemalloc_log()
  118. exec_wrapper_end_msg()