exec_wrapper.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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('my.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. c = exec_wrapper_get_colors()
  37. message = ( repr(e) if type(e).__name__ in ('MMGenError','MMGenSystemExit') else exc )
  38. sys.stdout.write('{}{}'.format(
  39. c.yellow( ''.join(lines) ),
  40. c.red(message) )
  41. + '\n' )
  42. with open('my.err','w') as fp:
  43. fp.write(''.join(lines+[exc]))
  44. def exec_wrapper_end_msg():
  45. if os.getenv('EXEC_WRAPPER_SPAWN') and not os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC'):
  46. c = exec_wrapper_get_colors()
  47. # write to stdout to ensure script output gets to terminal first
  48. sys.stdout.write(c.blue('Runtime: {:0.5f} secs\n'.format(time.time() - exec_wrapper_tstart)))
  49. def exec_wrapper_tracemalloc_setup():
  50. if os.getenv('MMGEN_TRACEMALLOC'):
  51. os.environ['PYTHONTRACEMALLOC'] = '1'
  52. import tracemalloc
  53. tracemalloc.start()
  54. sys.stderr.write("INFO → Appending memory allocation stats to 'tracemalloc.log'\n")
  55. def exec_wrapper_tracemalloc_log():
  56. if os.getenv('MMGEN_TRACEMALLOC'):
  57. import tracemalloc,re
  58. snapshot = tracemalloc.take_snapshot()
  59. stats = snapshot.statistics('lineno')
  60. depth = 100
  61. col1w = 100
  62. with open('tracemalloc.log','a') as fp:
  63. fp.write('##### TOP {} {} #####\n'.format(depth,' '.join(sys.argv)))
  64. for stat in stats[:depth]:
  65. frame = stat.traceback[0]
  66. fn = re.sub(r'.*\/site-packages\/|.*\/mmgen\/test\/overlay\/tree\/','',frame.filename)
  67. fn = re.sub(r'.*\/mmgen\/test\/','test/',fn)
  68. fp.write('{f:{w}} {s:>8.2f} KiB\n'.format(
  69. f = f'{fn}:{frame.lineno}:',
  70. s = stat.size/1024,
  71. w = col1w ))
  72. fp.write('{f:{w}} {s:8.2f} KiB\n\n'.format(
  73. f = 'TOTAL {}:'.format(' '.join(sys.argv))[:col1w],
  74. s = sum(stat.size for stat in stats) / 1024,
  75. w = col1w ))
  76. exec_wrapper_init() # sets sys.path[0]
  77. exec_wrapper_tstart = time.time()
  78. exec_wrapper_tracemalloc_setup()
  79. try:
  80. sys.argv.pop(0)
  81. exec_wrapper_execed_file = sys.argv[0]
  82. with open(exec_wrapper_execed_file) as fp:
  83. exec(fp.read())
  84. except SystemExit as e:
  85. if e.code != 0 and not os.getenv('EXEC_WRAPPER_NO_TRACEBACK'):
  86. exec_wrapper_write_traceback(e)
  87. else:
  88. exec_wrapper_tracemalloc_log()
  89. exec_wrapper_end_msg()
  90. sys.exit(e.code)
  91. except Exception as e:
  92. exec_wrapper_write_traceback(e)
  93. retval = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  94. sys.exit(retval)
  95. exec_wrapper_tracemalloc_log()
  96. exec_wrapper_end_msg()