policy.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """Install identity for gateway monitoring.
  2. A stable, resettable pseudonymous id attached to exported health signals so an
  3. operator can tell instances apart. Carries no account identity; rotate by
  4. clearing ``monitoring.install_id`` in config.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import uuid
  9. from typing import Any, Dict
  10. logger = logging.getLogger(__name__)
  11. def ensure_install_id(config: dict[str, Any]) -> str:
  12. """Return a stable install id, minting and persisting one when empty.
  13. The id becomes ``service.instance.id`` and must survive restarts, so a fresh
  14. UUID is written to config.yaml immediately. Fail-open: if persisting fails
  15. (read-only home, managed scope) the ephemeral id is still returned.
  16. """
  17. mon = config.get("monitoring") if isinstance(config, dict) else None
  18. existing = (mon or {}).get("install_id") if isinstance(mon, dict) else None
  19. if isinstance(existing, str) and existing.strip():
  20. return existing
  21. minted = str(uuid.uuid4())
  22. try:
  23. from hermes_cli.config import load_config, save_config
  24. fresh = load_config()
  25. if isinstance(fresh, dict):
  26. slot = fresh.setdefault("monitoring", {})
  27. if isinstance(slot, dict) and not str(slot.get("install_id") or "").strip():
  28. slot["install_id"] = minted
  29. save_config(fresh)
  30. except Exception:
  31. logger.debug("install_id persist failed; using ephemeral id", exc_info=True)
  32. # Keep the in-memory config consistent for this process either way.
  33. if isinstance(config, dict):
  34. config.setdefault("monitoring", {})
  35. if isinstance(config["monitoring"], dict):
  36. config["monitoring"]["install_id"] = minted
  37. return minted
  38. __all__ = ["ensure_install_id"]