uuid.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import os
  2. import sys
  3. import subprocess
  4. import logging
  5. from typing import Optional
  6. logger = logging.getLogger(__name__)
  7. legacy_uuid_filename = "worker_uuid"
  8. worker_name_filename = "worker_name"
  9. def get_legacy_uuid(data_dir: str) -> Optional[str]:
  10. legacy_uuid_path = os.path.join(data_dir, legacy_uuid_filename)
  11. if os.path.exists(legacy_uuid_path):
  12. with open(legacy_uuid_path, "r") as file:
  13. return file.read().strip()
  14. return None
  15. def set_legacy_uuid(data_dir: str, legacy_uuid: str):
  16. legacy_uuid_path = os.path.join(data_dir, legacy_uuid_filename)
  17. with open(legacy_uuid_path, "w") as file:
  18. file.write(legacy_uuid)
  19. def get_system_uuid() -> str:
  20. system = sys.platform
  21. linux_uuid_path = '/sys/class/dmi/id/product_uuid'
  22. try:
  23. if system == 'linux' and os.path.exists(linux_uuid_path):
  24. with open(linux_uuid_path, 'r') as f:
  25. return f.read().strip()
  26. elif system == 'darwin': # MacOS
  27. output = subprocess.check_output(
  28. ['ioreg', '-rd1', '-c', 'IOPlatformExpertDevice']
  29. )
  30. for line in output.decode().split('\n'):
  31. if 'IOPlatformUUID' in line:
  32. return line.split('=')[-1].strip().strip('"')
  33. elif sys.platform == 'win32':
  34. # Try PowerShell first (works on Win11 24H2+ where wmic is removed)
  35. try:
  36. output = subprocess.check_output(
  37. ['powershell', '-NoProfile', '-NonInteractive',
  38. '-Command', '(Get-CimInstance Win32_ComputerSystemProduct).UUID'],
  39. stderr=subprocess.DEVNULL,
  40. text=True,
  41. )
  42. result = output.strip()
  43. if result:
  44. return result
  45. except (subprocess.CalledProcessError, FileNotFoundError):
  46. pass
  47. # Fallback to wmic for older Windows versions
  48. output = subprocess.check_output(
  49. ['wmic', 'csproduct', 'get', 'uuid'], stderr=subprocess.DEVNULL
  50. )
  51. lines = output.decode().split('\n')
  52. if len(lines) > 1:
  53. return lines[1].strip()
  54. raise RuntimeError("Unable to retrieve Windows UUID")
  55. else:
  56. raise RuntimeError(f"Not supported OS or unable to retrieve {system} UUID")
  57. except Exception as e:
  58. logger.warning(f"{e}")
  59. raise e
  60. def get_worker_name(data_dir: str) -> Optional[str]:
  61. worker_name_path = os.path.join(data_dir, worker_name_filename)
  62. if os.path.exists(worker_name_path):
  63. with open(worker_name_path, "r") as file:
  64. return file.read().strip()
  65. return None
  66. def set_worker_name(data_dir: str, worker_name: str):
  67. worker_name_path = os.path.join(data_dir, worker_name_filename)
  68. current_worker_name = get_worker_name(data_dir)
  69. if current_worker_name is None or current_worker_name != worker_name:
  70. logger.warning(
  71. f"Worker name is being updated from {current_worker_name or '<empty>'} to {worker_name}"
  72. )
  73. with open(worker_name_path, "w") as file:
  74. file.write(worker_name)