exec_wrapper.py 5.2 KB

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