8 from inspect import stack
9 from typing import List
13 from argparse_utils import ActionNoYes
15 # This module is commonly used by others in here and should avoid
16 # taking any unnecessary dependencies back on them.
19 logger = logging.getLogger(__name__)
21 args = config.add_commandline_args(
22 f'Bootstrap ({__file__})',
23 'Args related to python program bootstrapper and Swiss army knife',
26 '--debug_unhandled_exceptions',
29 help='Break into pdb on top level unhandled exceptions.',
35 help='Should we display (and log.debug) the global random seed?',
43 help='Override the global random seed with a particular number.',
49 help='Should we dump the Python import tree before main?',
52 '--audit_import_events',
55 help='Should we audit all import events?',
61 help='Should we run cProfile on this code?',
67 help='Should we record/report on memory utilization?',
70 original_hook = sys.excepthook
73 def handle_uncaught_exception(exc_type, exc_value, exc_tb):
75 Top-level exception handler for exceptions that make it past any exception
76 handlers in the python code being run. Logs the error and stacktrace then
77 maybe attaches a debugger.
81 msg = f'Unhandled top level exception {exc_type}'
83 print(msg, file=sys.stderr)
84 if issubclass(exc_type, KeyboardInterrupt):
85 sys.__excepthook__(exc_type, exc_value, exc_tb)
88 if not sys.stderr.isatty() or not sys.stdin.isatty():
89 # stdin or stderr is redirected, just do the normal thing
90 original_hook(exc_type, exc_value, exc_tb)
92 # a terminal is attached and stderr is not redirected, maybe debug.
95 traceback.print_exception(exc_type, exc_value, exc_tb)
96 if config.config['debug_unhandled_exceptions']:
99 logger.info("Invoking the debugger...")
102 original_hook(exc_type, exc_value, exc_tb)
105 class ImportInterceptor(importlib.abc.MetaPathFinder):
109 self.module_by_filename_cache = {}
110 self.repopulate_modules_by_filename()
111 self.tree = collect.trie.Trie()
112 self.tree_node_by_module = {}
114 def repopulate_modules_by_filename(self):
115 self.module_by_filename_cache.clear()
116 for mod in sys.modules:
117 if hasattr(sys.modules[mod], '__file__'):
118 fname = getattr(sys.modules[mod], '__file__')
121 self.module_by_filename_cache[fname] = mod
123 def should_ignore_filename(self, filename: str) -> bool:
124 return 'importlib' in filename or 'six.py' in filename
126 def find_module(self, fullname, path):
128 "This method has been deprecated since Python 3.4, please upgrade."
131 def find_spec(self, loaded_module, path=None, target=None):
133 for x in range(3, len(s)):
134 filename = s[x].filename
135 if self.should_ignore_filename(filename):
138 loading_function = s[x].function
139 if filename in self.module_by_filename_cache:
140 loading_module = self.module_by_filename_cache[filename]
142 self.repopulate_modules_by_filename()
143 loading_module = self.module_by_filename_cache.get(filename, 'unknown')
145 path = self.tree_node_by_module.get(loading_module, [])
146 path.extend([loaded_module])
147 self.tree.insert(path)
148 self.tree_node_by_module[loading_module] = path
150 msg = f'*** Import {loaded_module} from {filename}:{s[x].lineno} in {loading_module}::{loading_function}'
154 msg = f'*** Import {loaded_module} from ?????'
158 def invalidate_caches(self):
161 def find_importer(self, module: str):
162 if module in self.tree_node_by_module:
163 node = self.tree_node_by_module[module]
168 # Audit import events? Note: this runs early in the lifetime of the
169 # process (assuming that import bootstrap happens early); config has
170 # (probably) not yet been loaded or parsed the commandline. Also,
171 # some things have probably already been imported while we weren't
172 # watching so this information may be incomplete.
174 # Also note: move bootstrap up in the global import list to catch
175 # more import events and have a more complete record.
176 import_interceptor = None
178 if arg == '--audit_import_events':
179 import_interceptor = ImportInterceptor()
180 sys.meta_path.insert(0, import_interceptor)
183 def dump_all_objects() -> None:
184 global import_interceptor
186 all_modules = sys.modules
187 for obj in object.__subclasses__():
188 if not hasattr(obj, '__name__'):
191 if not hasattr(obj, '__module__'):
193 class_mod_name = obj.__module__
194 if class_mod_name in all_modules:
195 mod = all_modules[class_mod_name]
196 if not hasattr(mod, '__name__'):
197 mod_name = class_mod_name
199 mod_name = mod.__name__
200 if hasattr(mod, '__file__'):
201 mod_file = mod.__file__
204 if import_interceptor is not None:
205 import_path = import_interceptor.find_importer(mod_name)
207 import_path = 'unknown'
208 msg = f'{class_mod_name}::{klass} ({mod_file})'
209 if import_path != 'unknown' and len(import_path) > 0:
210 msg += f' imported by {import_path}'
211 messages[f'{class_mod_name}::{klass}'] = msg
212 for x in sorted(messages.keys()):
213 logger.debug(messages[x])
217 def initialize(entry_point):
219 Remember to initialize config, initialize logging, set/log a random
220 seed, etc... before running main.
224 @functools.wraps(entry_point)
225 def initialize_wrapper(*args, **kwargs):
226 # Hook top level unhandled exceptions, maybe invoke debugger.
227 if sys.excepthook == sys.__excepthook__:
228 sys.excepthook = handle_uncaught_exception
230 # Try to figure out the name of the program entry point. Then
231 # parse configuration (based on cmdline flags, environment vars
234 '__globals__' in entry_point.__dict__
235 and '__file__' in entry_point.__globals__
237 config.parse(entry_point.__globals__['__file__'])
241 if config.config['trace_memory']:
246 # Initialize logging... and log some remembered messages from
248 logging_utils.initialize_logging(logging.getLogger())
249 config.late_logging()
251 # Maybe log some info about the python interpreter itself.
253 f'Platform: {sys.platform}, maxint=0x{sys.maxsize:x}, byteorder={sys.byteorder}'
255 logger.debug(f'Python interpreter version: {sys.version}')
256 logger.debug(f'Python implementation: {sys.implementation}')
257 logger.debug(f'Python C API version: {sys.api_version}')
258 logger.debug(f'Python path: {sys.path}')
260 # Allow programs that don't bother to override the random seed
261 # to be replayed via the commandline.
264 random_seed = config.config['set_random_seed']
265 if random_seed is not None:
266 random_seed = random_seed[0]
268 random_seed = int.from_bytes(os.urandom(4), 'little')
270 if config.config['show_random_seed']:
271 msg = f'Global random seed is: {random_seed}'
274 random.seed(random_seed)
276 # Do it, invoke the user's code. Pay attention to how long it takes.
277 logger.debug(f'Starting {entry_point.__name__} (program entry point)')
281 if config.config['run_profiler']:
283 from pstats import SortKey
285 with stopwatch.Timer() as t:
287 "ret = entry_point(*args, **kwargs)",
294 with stopwatch.Timer() as t:
295 ret = entry_point(*args, **kwargs)
297 logger.debug(f'{entry_point.__name__} (program entry point) returned {ret}.')
299 if config.config['trace_memory']:
300 snapshot = tracemalloc.take_snapshot()
301 top_stats = snapshot.statistics('lineno')
303 print("--trace_memory's top 10 memory using files:")
304 for stat in top_stats[:10]:
307 if config.config['dump_all_objects']:
310 if config.config['audit_import_events']:
311 global import_interceptor
312 if import_interceptor is not None:
313 print(import_interceptor.tree)
316 (utime, stime, cutime, cstime, elapsed_time) = os.times()
320 f'system: {stime}s\n'
321 f'child user: {cutime}s\n'
322 f'child system: {cstime}s\n'
323 f'machine uptime: {elapsed_time}s\n'
324 f'walltime: {walltime}s'
327 # If it doesn't return cleanly, call attention to the return value.
328 if ret is not None and ret != 0:
329 logger.error(f'Exit {ret}')
331 logger.debug(f'Exit {ret}')
334 return initialize_wrapper