prefix.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. import shutil
  3. import uuid
  4. from openpilot.common.params import Params
  5. from openpilot.system.hardware import PC
  6. from openpilot.system.hardware.hw import Paths
  7. from openpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT
  8. class OpenpilotPrefix:
  9. def __init__(self, prefix: str = None, clean_dirs_on_exit: bool = True, shared_download_cache: bool = False):
  10. self.prefix = prefix if prefix else str(uuid.uuid4().hex[0:15])
  11. self.msgq_path = os.path.join('/dev/shm', self.prefix)
  12. self.clean_dirs_on_exit = clean_dirs_on_exit
  13. self.shared_download_cache = shared_download_cache
  14. def __enter__(self):
  15. self.original_prefix = os.environ.get('OPENPILOT_PREFIX', None)
  16. os.environ['OPENPILOT_PREFIX'] = self.prefix
  17. try:
  18. os.mkdir(self.msgq_path)
  19. except FileExistsError:
  20. pass
  21. os.makedirs(Paths.log_root(), exist_ok=True)
  22. if self.shared_download_cache:
  23. os.environ["COMMA_CACHE"] = DEFAULT_DOWNLOAD_CACHE_ROOT
  24. return self
  25. def __exit__(self, exc_type, exc_obj, exc_tb):
  26. if self.clean_dirs_on_exit:
  27. self.clean_dirs()
  28. try:
  29. del os.environ['OPENPILOT_PREFIX']
  30. if self.original_prefix is not None:
  31. os.environ['OPENPILOT_PREFIX'] = self.original_prefix
  32. except KeyError:
  33. pass
  34. return False
  35. def clean_dirs(self):
  36. symlink_path = Params().get_param_path()
  37. if os.path.exists(symlink_path):
  38. shutil.rmtree(os.path.realpath(symlink_path), ignore_errors=True)
  39. os.remove(symlink_path)
  40. shutil.rmtree(self.msgq_path, ignore_errors=True)
  41. if PC:
  42. shutil.rmtree(Paths.log_root(), ignore_errors=True)
  43. if not os.environ.get("COMMA_CACHE", False):
  44. shutil.rmtree(Paths.download_cache_root(), ignore_errors=True)
  45. shutil.rmtree(Paths.comma_home(), ignore_errors=True)