6 from inspect import stack
9 # This module is commonly used by others in here and should avoid
10 # taking any unnecessary dependencies back on them.
12 from argparse_utils import ActionNoYes
16 logger = logging.getLogger(__name__)
18 args = config.add_commandline_args(
19 f'Bootstrap ({__file__})',
20 'Args related to python program bootstrapper and Swiss army knife',
23 '--debug_unhandled_exceptions',
26 help='Break into pdb on top level unhandled exceptions.',
32 help='Should we display (and log.debug) the global random seed?',
40 help='Override the global random seed with a particular number.',
46 help='Should we dump the Python import tree before main?',
49 '--audit_import_events',
52 help='Should we audit all import events?',
58 help='Should we run cProfile on this code?',
64 help='Should we record/report on memory utilization?',
67 original_hook = sys.excepthook
70 def handle_uncaught_exception(exc_type, exc_value, exc_tb):
72 Top-level exception handler for exceptions that make it past any exception
73 handlers in the python code being run. Logs the error and stacktrace then
74 maybe attaches a debugger.
78 msg = f'Unhandled top level exception {exc_type}'
80 print(msg, file=sys.stderr)
81 if issubclass(exc_type, KeyboardInterrupt):
82 sys.__excepthook__(exc_type, exc_value, exc_tb)
85 if not sys.stderr.isatty() or not sys.stdin.isatty():
86 # stdin or stderr is redirected, just do the normal thing
87 original_hook(exc_type, exc_value, exc_tb)
89 # a terminal is attached and stderr is not redirected, maybe debug.
92 traceback.print_exception(exc_type, exc_value, exc_tb)
93 if config.config['debug_unhandled_exceptions']:
96 logger.info("Invoking the debugger...")
99 original_hook(exc_type, exc_value, exc_tb)
102 class ImportInterceptor(object):
106 self.module_by_filename_cache = {}
107 self.repopulate_modules_by_filename()
108 self.tree = collect.trie.Trie()
109 self.tree_node_by_module = {}
111 def repopulate_modules_by_filename(self):
112 self.module_by_filename_cache.clear()
113 for mod in sys.modules:
114 if hasattr(sys.modules[mod], '__file__'):
115 fname = getattr(sys.modules[mod], '__file__')
118 self.module_by_filename_cache[fname] = mod
120 def should_ignore_filename(self, filename: str) -> bool:
121 return 'importlib' in filename or 'six.py' in filename
123 def find_spec(self, loaded_module, path=None, target=None):
125 for x in range(3, len(s)):
126 filename = s[x].filename
127 if self.should_ignore_filename(filename):
130 loading_function = s[x].function
131 if filename in self.module_by_filename_cache:
132 loading_module = self.module_by_filename_cache[filename]
134 self.repopulate_modules_by_filename()
135 loading_module = self.module_by_filename_cache.get(filename, 'unknown')
137 path = self.tree_node_by_module.get(loading_module, [])
138 path.extend([loaded_module])
139 self.tree.insert(path)
140 self.tree_node_by_module[loading_module] = path
142 msg = f'*** Import {loaded_module} from {filename}:{s[x].lineno} in {loading_module}::{loading_function}'
146 msg = f'*** Import {loaded_module} from ?????'
150 def find_importer(self, module: str):
151 if module in self.tree_node_by_module:
152 node = self.tree_node_by_module[module]
157 # Audit import events? Note: this runs early in the lifetime of the
158 # process (assuming that import bootstrap happens early); config has
159 # (probably) not yet been loaded or parsed the commandline. Also,
160 # some things have probably already been imported while we weren't
161 # watching so this information may be incomplete.
163 # Also note: move bootstrap up in the global import list to catch
164 # more import events and have a more complete record.
165 import_interceptor = None
167 if arg == '--audit_import_events':
168 import_interceptor = ImportInterceptor()
169 sys.meta_path = [import_interceptor] + sys.meta_path
172 def dump_all_objects() -> None:
173 global import_interceptor
175 all_modules = sys.modules
176 for obj in object.__subclasses__():
177 if not hasattr(obj, '__name__'):
180 if not hasattr(obj, '__module__'):
182 class_mod_name = obj.__module__
183 if class_mod_name in all_modules:
184 mod = all_modules[class_mod_name]
185 if not hasattr(mod, '__name__'):
186 mod_name = class_mod_name
188 mod_name = mod.__name__
189 if hasattr(mod, '__file__'):
190 mod_file = mod.__file__
193 if import_interceptor is not None:
194 import_path = import_interceptor.find_importer(mod_name)
196 import_path = 'unknown'
197 msg = f'{class_mod_name}::{klass} ({mod_file})'
198 if import_path != 'unknown' and len(import_path) > 0:
199 msg += f' imported by {import_path}'
200 messages[f'{class_mod_name}::{klass}'] = msg
201 for x in sorted(messages.keys()):
202 logger.debug(messages[x])
206 def initialize(entry_point):
208 Remember to initialize config, initialize logging, set/log a random
209 seed, etc... before running main.
213 @functools.wraps(entry_point)
214 def initialize_wrapper(*args, **kwargs):
215 # Hook top level unhandled exceptions, maybe invoke debugger.
216 if sys.excepthook == sys.__excepthook__:
217 sys.excepthook = handle_uncaught_exception
219 # Try to figure out the name of the program entry point. Then
220 # parse configuration (based on cmdline flags, environment vars
223 '__globals__' in entry_point.__dict__
224 and '__file__' in entry_point.__globals__
226 config.parse(entry_point.__globals__['__file__'])
230 if config.config['trace_memory']:
235 # Initialize logging... and log some remembered messages from
237 logging_utils.initialize_logging(logging.getLogger())
238 config.late_logging()
240 # Maybe log some info about the python interpreter itself.
242 f'Platform: {sys.platform}, maxint=0x{sys.maxsize:x}, byteorder={sys.byteorder}'
244 logger.debug(f'Python interpreter version: {sys.version}')
245 logger.debug(f'Python implementation: {sys.implementation}')
246 logger.debug(f'Python C API version: {sys.api_version}')
247 logger.debug(f'Python path: {sys.path}')
249 # Allow programs that don't bother to override the random seed
250 # to be replayed via the commandline.
253 random_seed = config.config['set_random_seed']
254 if random_seed is not None:
255 random_seed = random_seed[0]
257 random_seed = int.from_bytes(os.urandom(4), 'little')
259 if config.config['show_random_seed']:
260 msg = f'Global random seed is: {random_seed}'
263 random.seed(random_seed)
265 # Do it, invoke the user's code. Pay attention to how long it takes.
266 logger.debug(f'Starting {entry_point.__name__} (program entry point)')
270 if config.config['run_profiler']:
272 from pstats import SortKey
274 with stopwatch.Timer() as t:
276 "ret = entry_point(*args, **kwargs)",
283 with stopwatch.Timer() as t:
284 ret = entry_point(*args, **kwargs)
286 logger.debug(f'{entry_point.__name__} (program entry point) returned {ret}.')
288 if config.config['trace_memory']:
289 snapshot = tracemalloc.take_snapshot()
290 top_stats = snapshot.statistics('lineno')
292 print("--trace_memory's top 10 memory using files:")
293 for stat in top_stats[:10]:
296 if config.config['dump_all_objects']:
299 if config.config['audit_import_events']:
300 global import_interceptor
301 if import_interceptor is not None:
302 print(import_interceptor.tree)
305 (utime, stime, cutime, cstime, elapsed_time) = os.times()
309 f'system: {stime}s\n'
310 f'child user: {cutime}s\n'
311 f'child system: {cstime}s\n'
312 f'machine uptime: {elapsed_time}s\n'
313 f'walltime: {walltime}s'
316 # If it doesn't return cleanly, call attention to the return value.
317 if ret is not None and ret != 0:
318 logger.error(f'Exit {ret}')
320 logger.debug(f'Exit {ret}')
323 return initialize_wrapper