regulator.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import collections
  2. import os
  3. _Instance = collections.namedtuple("_Instance", ("import_tracer", "converter", "filepath"))
  4. INSTANCE = None
  5. def _get_converter_instance():
  6. import library.python.import_tracing.lib.converters.raw as text_converter
  7. import library.python.import_tracing.lib.converters.chrometrace as chrome_converter
  8. converter_mapping = {"text": text_converter.RawTextTraceConverter, "evlog": chrome_converter.ChromiumTraceConverter}
  9. env_val = os.getenv("Y_PYTHON_TRACE_FORMAT")
  10. converter = converter_mapping.get(env_val, text_converter.RawTextTraceConverter)
  11. return converter()
  12. def _resolve_filepath(filemask):
  13. import socket
  14. import sys
  15. pid = os.getpid()
  16. hostname = socket.gethostname()
  17. executable_filename = os.path.basename(sys.executable)
  18. return filemask.replace("%p", str(pid)).replace("%h", hostname).replace("%e", executable_filename)
  19. def enable(filemask):
  20. import library.python.import_tracing.lib.import_tracer as import_tracer
  21. import __res
  22. global INSTANCE
  23. if INSTANCE is not None:
  24. return INSTANCE
  25. converter = _get_converter_instance()
  26. import_tracer = import_tracer.ImportTracer()
  27. def before_import_callback(modname, filename):
  28. import_tracer.start_event(modname, filename)
  29. def after_import_callback(modname, filename):
  30. import_tracer.finish_event(modname, filename)
  31. __res.importer.set_callbacks(before_import_callback, after_import_callback)
  32. filepath = _resolve_filepath(filemask)
  33. new_instance = _Instance(import_tracer, converter, filepath)
  34. INSTANCE = new_instance
  35. return new_instance
  36. def disable(close_not_finished=False):
  37. global INSTANCE
  38. if INSTANCE is None:
  39. return
  40. import_tracer = INSTANCE.import_tracer
  41. converter = INSTANCE.converter
  42. filepath = INSTANCE.filepath
  43. converter.dump(import_tracer.get_events(close_not_finished), filepath)
  44. INSTANCE = None