exec_wrapper.py 5.4 KB

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