7 from inspect import stack
8 from typing import List
11 # This module is commonly used by others in here and should avoid
12 # taking any unnecessary dependencies back on them.
14 from argparse_utils import ActionNoYes
18 logger = logging.getLogger(__name__)
20 args = config.add_commandline_args(
21 f'Bootstrap ({__file__})',
22 'Args related to python program bootstrapper and Swiss army knife',
25 '--debug_unhandled_exceptions',
28 help='Break into pdb on top level unhandled exceptions.',
34 help='Should we display (and log.debug) the global random seed?',
42 help='Override the global random seed with a particular number.',
48 help='Should we dump the Python import tree before main?',
51 '--audit_import_events',
54 help='Should we audit all import events?',
60 help='Should we run cProfile on this code?',
66 help='Should we record/report on memory utilization?',
69 original_hook = sys.excepthook
72 def handle_uncaught_exception(exc_type, exc_value, exc_tb):
74 Top-level exception handler for exceptions that make it past any exception
75 handlers in the python code being run. Logs the error and stacktrace then
76 maybe attaches a debugger.
80 msg = f'Unhandled top level exception {exc_type}'
82 print(msg, file=sys.stderr)
83 if issubclass(exc_type, KeyboardInterrupt):
84 sys.__excepthook__(exc_type, exc_value, exc_tb)
87 if not sys.stderr.isatty() or not sys.stdin.isatty():
88 # stdin or stderr is redirected, just do the normal thing
89 original_hook(exc_type, exc_value, exc_tb)
91 # a terminal is attached and stderr is not redirected, maybe debug.
94 traceback.print_exception(exc_type, exc_value, exc_tb)
95 if config.config['debug_unhandled_exceptions']:
98 logger.info("Invoking the debugger...")
101 original_hook(exc_type, exc_value, exc_tb)
104 class ImportInterceptor(importlib.abc.MetaPathFinder):
108 self.module_by_filename_cache = {}
109 self.repopulate_modules_by_filename()
110 self.tree = collect.trie.Trie()
111 self.tree_node_by_module = {}
113 def repopulate_modules_by_filename(self):
114 self.module_by_filename_cache.clear()
115 for mod in sys.modules:
116 if hasattr(sys.modules[mod], '__file__'):
117 fname = getattr(sys.modules[mod], '__file__')
120 self.module_by_filename_cache[fname] = mod
122 def should_ignore_filename(self, filename: str) -> bool:
123 return 'importlib' in filename or 'six.py' in filename
125 def find_module(self, fullname, path):
127 "This method has been deprecated since Python 3.4, please upgrade."
130 def find_spec(self, loaded_module, path=None, target=None):
132 for x in range(3, len(s)):
133 filename = s[x].filename
134 if self.should_ignore_filename(filename):
137 loading_function = s[x].function
138 if filename in self.module_by_filename_cache:
139 loading_module = self.module_by_filename_cache[filename]
141 self.repopulate_modules_by_filename()
142 loading_module = self.module_by_filename_cache.get(filename, 'unknown')
144 path = self.tree_node_by_module.get(loading_module, [])
145 path.extend([loaded_module])
146 self.tree.insert(path)
147 self.tree_node_by_module[loading_module] = path
149 msg = f'*** Import {loaded_module} from {filename}:{s[x].lineno} in {loading_module}::{loading_function}'
153 msg = f'*** Import {loaded_module} from ?????'
157 def invalidate_caches(self):
160 def find_importer(self, module: str):
161 if module in self.tree_node_by_module:
162 node = self.tree_node_by_module[module]
167 # Audit import events? Note: this runs early in the lifetime of the
168 # process (assuming that import bootstrap happens early); config has
169 # (probably) not yet been loaded or parsed the commandline. Also,
170 # some things have probably already been imported while we weren't
171 # watching so this information may be incomplete.
173 # Also note: move bootstrap up in the global import list to catch
174 # more import events and have a more complete record.
175 import_interceptor = None
177 if arg == '--audit_import_events':
178 import_interceptor = ImportInterceptor()
179 sys.meta_path.insert(0, import_interceptor)
182 def dump_all_objects() -> None:
183 global import_interceptor
185 all_modules = sys.modules
186 for obj in object.__subclasses__():
187 if not hasattr(obj, '__name__'):
190 if not hasattr(obj, '__module__'):
192 class_mod_name = obj.__module__
193 if class_mod_name in all_modules:
194 mod = all_modules[class_mod_name]
195 if not hasattr(mod, '__name__'):
196 mod_name = class_mod_name
198 mod_name = mod.__name__
199 if hasattr(mod, '__file__'):
200 mod_file = mod.__file__
203 if import_interceptor is not None:
204 import_path = import_interceptor.find_importer(mod_name)
206 import_path = 'unknown'
207 msg = f'{class_mod_name}::{klass} ({mod_file})'
208 if import_path != 'unknown' and len(import_path) > 0:
209 msg += f' imported by {import_path}'
210 messages[f'{class_mod_name}::{klass}'] = msg
211 for x in sorted(messages.keys()):
212 logger.debug(messages[x])
216 def initialize(entry_point):
218 Remember to initialize config, initialize logging, set/log a random
219 seed, etc... before running main.
223 @functools.wraps(entry_point)
224 def initialize_wrapper(*args, **kwargs):
225 # Hook top level unhandled exceptions, maybe invoke debugger.
226 if sys.excepthook == sys.__excepthook__:
227 sys.excepthook = handle_uncaught_exception
229 # Try to figure out the name of the program entry point. Then
230 # parse configuration (based on cmdline flags, environment vars
233 '__globals__' in entry_point.__dict__
234 and '__file__' in entry_point.__globals__
236 config.parse(entry_point.__globals__['__file__'])
240 if config.config['trace_memory']:
245 # Initialize logging... and log some remembered messages from
247 logging_utils.initialize_logging(logging.getLogger())
248 config.late_logging()
250 # Maybe log some info about the python interpreter itself.
252 f'Platform: {sys.platform}, maxint=0x{sys.maxsize:x}, byteorder={sys.byteorder}'
254 logger.debug(f'Python interpreter version: {sys.version}')
255 logger.debug(f'Python implementation: {sys.implementation}')
256 logger.debug(f'Python C API version: {sys.api_version}')
257 logger.debug(f'Python path: {sys.path}')
259 # Allow programs that don't bother to override the random seed
260 # to be replayed via the commandline.
263 random_seed = config.config['set_random_seed']
264 if random_seed is not None:
265 random_seed = random_seed[0]
267 random_seed = int.from_bytes(os.urandom(4), 'little')
269 if config.config['show_random_seed']:
270 msg = f'Global random seed is: {random_seed}'
273 random.seed(random_seed)
275 # Do it, invoke the user's code. Pay attention to how long it takes.
276 logger.debug(f'Starting {entry_point.__name__} (program entry point)')
280 if config.config['run_profiler']:
282 from pstats import SortKey
284 with stopwatch.Timer() as t:
286 "ret = entry_point(*args, **kwargs)",
293 with stopwatch.Timer() as t:
294 ret = entry_point(*args, **kwargs)
296 logger.debug(f'{entry_point.__name__} (program entry point) returned {ret}.')
298 if config.config['trace_memory']:
299 snapshot = tracemalloc.take_snapshot()
300 top_stats = snapshot.statistics('lineno')
302 print("--trace_memory's top 10 memory using files:")
303 for stat in top_stats[:10]:
306 if config.config['dump_all_objects']:
309 if config.config['audit_import_events']:
310 global import_interceptor
311 if import_interceptor is not None:
312 print(import_interceptor.tree)
315 (utime, stime, cutime, cstime, elapsed_time) = os.times()
319 f'system: {stime}s\n'
320 f'child user: {cutime}s\n'
321 f'child system: {cstime}s\n'
322 f'machine uptime: {elapsed_time}s\n'
323 f'walltime: {walltime}s'
326 # If it doesn't return cleanly, call attention to the return value.
327 if ret is not None and ret != 0:
328 logger.error(f'Exit {ret}')
330 logger.debug(f'Exit {ret}')
333 return initialize_wrapper