exec_wrapper.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2024 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. exec_wrapper_sys.path.insert(0,exec_wrapper_os.path.join('test', 'overlay', 'tree'))
  27. else:
  28. exec_wrapper_sys.path.pop(0)
  29. exec_wrapper_os.environ['MMGEN_EXEC_WRAPPER'] = '1'
  30. def exec_wrapper_write_traceback(e,exit_val):
  31. import sys,os
  32. exc_line = (
  33. f'{type(e).__name__}({e.mmcode}) {e}' if type(e).__name__ in ('MMGenError','MMGenSystemExit') else
  34. f'{type(e).__name__}: {e}')
  35. c = exec_wrapper_get_colors()
  36. if os.getenv('EXEC_WRAPPER_TRACEBACK'):
  37. import traceback
  38. cwd = os.getcwd()
  39. sys.path.insert(0,cwd)
  40. from test.overlay import get_overlay_tree_dir
  41. overlay_path_pfx = os.path.relpath(get_overlay_tree_dir(cwd)) + '/'
  42. def fixup_fn(fn_in):
  43. fn = fn_in.removeprefix(cwd+'/').removeprefix(overlay_path_pfx)
  44. return fn.removesuffix('_orig.py') + '.py' if fn.endswith('_orig.py') else fn
  45. def gen_output():
  46. yield 'Traceback (most recent call last):'
  47. for e in traceback.extract_tb(sys.exc_info()[2]):
  48. yield ' File "{f}", line {l}, in {n}\n {L}'.format(
  49. f = exec_wrapper_execed_file if e.filename == '<string>' else fixup_fn(e.filename),
  50. l = '(scrubbed)' if os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') else e.lineno,
  51. n = e.name,
  52. L = e.line or 'N/A' )
  53. tb_lines = list( gen_output() )
  54. if 'SystemExit' in exc_line:
  55. tb_lines.pop()
  56. if os.getenv('EXEC_WRAPPER_EXIT_VAL') == str(exit_val):
  57. sys.stdout.write(c.yellow(exc_line) + '\n')
  58. else:
  59. sys.stdout.write('{}\n{}\n'.format(
  60. c.yellow('\n'.join(tb_lines)),
  61. c.red(exc_line)))
  62. print(c.blue('{} script exited with error').format(
  63. 'Test' if os.path.dirname(sys.argv[0]) == 'test' else 'Spawned' ))
  64. with open('test.err','w') as fp:
  65. fp.write('\n'.join(tb_lines + [exc_line]))
  66. else:
  67. sys.stdout.write( c.purple((f'NONZERO_EXIT[{exit_val}]: ' if exit_val else '') + exc_line) + '\n' )
  68. def exec_wrapper_end_msg():
  69. if (
  70. exec_wrapper_os.getenv('EXEC_WRAPPER_DO_RUNTIME_MSG')
  71. and not exec_wrapper_os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC') ):
  72. c = exec_wrapper_get_colors()
  73. # write to stdout to ensure script output gets to terminal first
  74. exec_wrapper_sys.stdout.write(c.blue('Runtime: {:0.5f} secs\n'.format(
  75. exec_wrapper_time.time() - exec_wrapper_tstart )))
  76. def exec_wrapper_tracemalloc_setup():
  77. exec_wrapper_os.environ['PYTHONTRACEMALLOC'] = '1'
  78. import tracemalloc
  79. tracemalloc.start()
  80. exec_wrapper_sys.stderr.write("INFO → Appending memory allocation stats to 'tracemalloc.log'\n")
  81. def exec_wrapper_tracemalloc_log():
  82. import tracemalloc,re
  83. snapshot = tracemalloc.take_snapshot()
  84. stats = snapshot.statistics('lineno')
  85. depth = 100
  86. col1w = 100
  87. with open('tracemalloc.log','a') as fp:
  88. fp.write('##### TOP {} {} #####\n'.format(depth,' '.join(exec_wrapper_sys.argv)))
  89. for stat in stats[:depth]:
  90. frame = stat.traceback[0]
  91. fn = re.sub(r'.*\/site-packages\/|.*\/mmgen\/test\/overlay\/tree\/','',frame.filename)
  92. fn = re.sub(r'.*\/mmgen\/test\/','test/',fn)
  93. fp.write('{f:{w}} {s:>8.2f} KiB\n'.format(
  94. f = f'{fn}:{frame.lineno}:',
  95. s = stat.size/1024,
  96. w = col1w ))
  97. fp.write('{f:{w}} {s:8.2f} KiB\n\n'.format(
  98. f = 'TOTAL {}:'.format(' '.join(exec_wrapper_sys.argv))[:col1w],
  99. s = sum(stat.size for stat in stats) / 1024,
  100. w = col1w ))
  101. import sys as exec_wrapper_sys
  102. import os as exec_wrapper_os
  103. import time as exec_wrapper_time
  104. exec_wrapper_init() # sets sys.path[0] to overlay root
  105. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  106. exec_wrapper_tracemalloc_setup()
  107. # import mmgen mods only after sys.path[0] is set to overlay root!
  108. if exec_wrapper_os.getenv('MMGEN_DEVTOOLS'):
  109. from mmgen.devinit import init_dev as exec_wrapper_init_dev
  110. exec_wrapper_init_dev()
  111. exec_wrapper_tstart = exec_wrapper_time.time()
  112. try:
  113. exec_wrapper_sys.argv.pop(0)
  114. exec_wrapper_execed_file = exec_wrapper_sys.argv[0]
  115. with open(exec_wrapper_execed_file) as fp:
  116. exec(fp.read())
  117. except SystemExit as e:
  118. if e.code != 0:
  119. exec_wrapper_write_traceback(e,e.code)
  120. else:
  121. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  122. exec_wrapper_tracemalloc_log()
  123. exec_wrapper_end_msg()
  124. exec_wrapper_sys.exit(e.code)
  125. except Exception as e:
  126. exit_val = e.mmcode if hasattr(e,'mmcode') else e.code if hasattr(e,'code') else 1
  127. exec_wrapper_write_traceback(e,exit_val)
  128. exec_wrapper_sys.exit(exit_val)
  129. if exec_wrapper_os.getenv('MMGEN_TRACEMALLOC'):
  130. exec_wrapper_tracemalloc_log()
  131. exec_wrapper_end_msg()