exec_wrapper.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2023 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. scripts/exec_wrapper.py: wrapper to launch MMGen scripts in a testing environment
  12. """
  13. # Import as few modules and define as few names as possible at module level before exec'ing the
  14. # file, as all names will be seen by the exec'ed code. To prevent name collisions, all names
  15. # defined or imported here at module level should begin with 'exec_wrapper_'
  16. def exec_wrapper_get_colors():
  17. from collections import namedtuple
  18. return namedtuple('colors',['red','green','yellow','blue','purple'])(*[
  19. (lambda s:s) if exec_wrapper_os.getenv('MMGEN_DISABLE_COLOR') else
  20. (lambda s,n=n:f'\033[{n};1m{s}\033[0m' )
  21. for n in (31,32,33,34,35) ])
  22. def exec_wrapper_init():
  23. if exec_wrapper_os.path.dirname(exec_wrapper_sys.argv[1]) == 'test':
  24. # support running of test scripts under wrapper
  25. exec_wrapper_sys.path[0] = exec_wrapper_os.getcwd() # assume we’re in repo root
  26. else:
  27. exec_wrapper_sys.path.pop(0)
  28. exec_wrapper_os.environ['MMGEN_EXEC_WRAPPER'] = '1'
  29. def exec_wrapper_write_traceback(e,exit_val):
  30. import sys,os
  31. exc_line = (
  32. repr(e) if type(e).__name__ in ('MMGenError','MMGenSystemExit') else
  33. f'{type(e).__name__}: {e}')
  34. c = exec_wrapper_get_colors()
  35. if os.getenv('EXEC_WRAPPER_TRACEBACK'):
  36. import traceback
  37. cwd = os.getcwd()
  38. sys.path.insert(0,cwd)
  39. from test.overlay import get_overlay_tree_dir
  40. overlay_path_pfx = os.path.relpath(get_overlay_tree_dir(cwd)) + '/'
  41. def fixup_fn(fn_in):
  42. from mmgen.util2 import removeprefix,removesuffix
  43. fn = removeprefix(removeprefix(fn_in,cwd+'/'),overlay_path_pfx)
  44. return removesuffix(fn,'_orig.py') + '.py' if fn.endswith('_orig.py') else fn
  45. # Python 3.9:
  46. # fn = fn_in.removeprefix(cwd+'/').removeprefix('test/overlay/tree/')
  47. # return fn.removesuffix('_orig.py') + '.py' if fn.endswith('_orig.py') else fn
  48. def gen_output():
  49. yield 'Traceback (most recent call last):'
  50. for e in traceback.extract_tb(sys.exc_info()[2]):
  51. yield ' File "{f}", line {l}, in {n}\n {L}'.format(
  52. f = exec_wrapper_execed_file if e.filename == '<string>' else fixup_fn(e.filename),
  53. l = '(scrubbed)' if os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') else e.lineno,
  54. n = e.name,
  55. L = e.line or 'N/A' )
  56. tb_lines = list( gen_output() )
  57. if 'SystemExit' in exc_line:
  58. tb_lines.pop()
  59. sys.stdout.write('{}\n{}\n'.format( c.yellow( '\n'.join(tb_lines) ), c.red(exc_line) ))
  60. with open('test.err','w') as fp:
  61. fp.write('\n'.join(tb_lines + [exc_line]))
  62. print(c.blue('{} script exited with error').format(
  63. 'Test' if os.path.dirname(sys.argv[0]) == 'test' else 'Spawned' ))
  64. else:
  65. sys.stdout.write( c.purple((f'NONZERO_EXIT[{exit_val}]: ' if exit_val else '') + exc_line) + '\n' )
  66. def exec_wrapper_end_msg():
  67. if (
  68. exec_wrapper_os.getenv('EXEC_WRAPPER_SPAWN')
  69. and not exec_wrapper_os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') ):
  70. c = exec_wrapper_get_colors()
  71. # write to stdout to ensure script output gets to terminal first
  72. exec_wrapper_sys.stdout.write(c.blue('Runtime: {:0.5f} secs\n'.format(
  73. exec_wrapper_time.time() - exec_wrapper_tstart )))
  74. def exec_wrapper_tracemalloc_setup():
  75. exec_wrapper_os.environ['PYTHONTRACEMALLOC'] = '1'
  76. import tracemalloc
  77. tracemalloc.start()
  78. exec_wrapper_sys.stderr.write("INFO → Appending memory allocation stats to 'tracemalloc.log'\n")
  79. def exec_wrapper_tracemalloc_log():
  80. import tracemalloc,re
  81. snapshot = tracemalloc.take_snapshot()
  82. stats = snapshot.statistics('lineno')
  83. depth = 100
  84. col1w = 100
  85. with open('tracemalloc.log','a') as fp:
  86. fp.write('##### TOP {} {} #####\n'.format(depth,' '.join(exec_wrapper_sys.argv)))
  87. for stat in stats[:depth]:
  88. frame = stat.traceback[0]
  89. fn = re.sub(r'.*\/site-packages\/|.*\/mmgen\/test\/overlay\/tree\/','',frame.filename)
  90. fn = re.sub(r'.*\/mmgen\/test\/','test/',fn)
  91. fp.write('{f:{w}} {s:>8.2f} KiB\n'.format(
  92. f = f'{fn}:{frame.lineno}:',
  93. s = stat.size/1024,
  94. w = col1w ))
  95. fp.write('{f:{w}} {s:8.2f} KiB\n\n'.format(
  96. f = 'TOTAL {}:'.format(' '.join(exec_wrapper_sys.argv))[:col1w],
  97. s = sum(stat.size for stat in stats) / 1024,
  98. w = col1w ))
  99. import sys as exec_wrapper_sys
  100. import os as exec_wrapper_os
  101. import time as exec_wrapper_time
  102. exec_wrapper_init() # sets sys.path[0] to overlay root
  103. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  104. exec_wrapper_tracemalloc_setup()
  105. # import mmgen mods only after sys.path[0] is set to overlay root!
  106. if exec_wrapper_os.getenv('MMGEN_DEVTOOLS'):
  107. from mmgen.devinit import init_dev as exec_wrapper_init_dev
  108. exec_wrapper_init_dev()
  109. exec_wrapper_tstart = exec_wrapper_time.time()
  110. try:
  111. exec_wrapper_sys.argv.pop(0)
  112. exec_wrapper_execed_file = exec_wrapper_sys.argv[0]
  113. with open(exec_wrapper_execed_file) as fp:
  114. exec(fp.read())
  115. except SystemExit as e:
  116. if e.code != 0:
  117. exec_wrapper_write_traceback(e,e.code)
  118. else:
  119. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  120. exec_wrapper_tracemalloc_log()
  121. exec_wrapper_end_msg()
  122. exec_wrapper_sys.exit(e.code)
  123. except Exception as e:
  124. exit_val = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  125. exec_wrapper_write_traceback(e,exit_val)
  126. exec_wrapper_sys.exit(exit_val)
  127. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  128. exec_wrapper_tracemalloc_log()
  129. exec_wrapper_end_msg()