profiles_service_cleanup.py 4.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Profile delete/rename: remove the OLD name's supervisor registrations that live outside
  2. the user systemd / launchd arms in ``profiles._cleanup_gateway_service``.
  3. Every registration is keyed on the profile name and starts ``--profile <old>`` with
  4. ``HERMES_HOME`` pinned to a directory that the delete removed or the rename moved, so a
  5. survivor crash-loops (KeepAlive / Restart= / Task Scheduler retry) at the next boot or login.
  6. Callers bind the profile's home (``set_hermes_home_override``) before calling so the
  7. name-deriving helpers resolve THAT profile, never the ambient one.
  8. """
  9. from __future__ import annotations
  10. import os
  11. import subprocess
  12. from pathlib import Path
  13. def owned_by_profile(definition: Path, profile_dir: Path) -> bool:
  14. """False (one-line notice) when *definition* pins another HERMES_HOME. Unit names derive from the
  15. profile name, and a scratch ``HOME``'s ``profiles/<name>`` resolves the ACCOUNT's real
  16. ``hermes-gateway-<name>`` unit (the unit dir is account-anchored): delete/rename then disabled,
  17. stopped and unlinked a live gateway of another install. Same owner rule as
  18. ``gateway_service_owner.definition_belongs_to_home``."""
  19. from hermes_cli.gateway_service_owner import _resolve, pinned_home
  20. raw = pinned_home(definition)
  21. if raw is None or _resolve(raw) == _resolve(profile_dir):
  22. return True
  23. print(f"↷ {definition} runs HERMES_HOME={raw}, not {profile_dir}: another install's service, left alone")
  24. return False
  25. def remove_system_systemd_unit(profile_dir: Path) -> bool:
  26. """Remove ``/etc/systemd/system/hermes-gateway-<profile>.service`` when root; otherwise
  27. name the leftover and the exact command, because the profile dir the ``gateway uninstall
  28. --system`` verb would need to resolve the name from is about to vanish."""
  29. from hermes_cli import gateway
  30. svc_name = gateway.get_service_name()
  31. unit = gateway._SYSTEM_UNIT_DIR / f"{svc_name}.service"
  32. if not unit.exists() or not owned_by_profile(unit, profile_dir):
  33. return False
  34. if os.geteuid() != 0: # windows-footgun: ok — called only from the Linux arm of profiles._cleanup_gateway_service
  35. print(f"⚠ System service {svc_name} remains at {unit}; it will restart the removed profile at boot.")
  36. print(f" Remove it with: sudo systemctl disable --now {svc_name} && sudo rm {unit} && sudo systemctl daemon-reload")
  37. return False
  38. subprocess.run(["systemctl", "disable", svc_name], capture_output=True, check=False, timeout=30)
  39. stopped = subprocess.run(["systemctl", "stop", svc_name], capture_output=True, check=False, timeout=30)
  40. unit.unlink(missing_ok=True)
  41. subprocess.run(["systemctl", "daemon-reload"], capture_output=True, check=False, timeout=30)
  42. if getattr(stopped, "returncode", 0) != 0:
  43. # The unit file is gone (it must not resurrect the removed profile at boot), but the
  44. # gateway it supervised may still be running under the old name.
  45. print(f"⚠ System service {svc_name} unit removed, but `systemctl stop` exited {stopped.returncode}; "
  46. f"its gateway may still be running. Stop it with: sudo systemctl stop {svc_name}")
  47. return True
  48. print(f"✓ System service {svc_name} removed")
  49. return True
  50. def remove_windows_task() -> bool:
  51. """Delete the profile's Scheduled Task and Startup-folder login item. Direct ``schtasks
  52. /Delete`` rather than ``gateway_windows.uninstall()``: that verb may open a UAC prompt,
  53. which a dashboard DELETE or a scripted rename must never block on."""
  54. from hermes_cli import gateway_windows as gw
  55. task_name = gw.get_task_name()
  56. removed = False
  57. if gw.is_task_registered():
  58. code, _out, err = gw._exec_schtasks(["/Delete", "/F", "/TN", task_name])
  59. if code == 0:
  60. removed = True
  61. print(f"✓ Removed Scheduled Task {task_name!r}")
  62. else:
  63. print(f"⚠ Scheduled Task {task_name!r} remains (schtasks code {code}): {err.strip()}")
  64. for path in (gw.get_startup_entry_path(), gw._legacy_startup_entry_path()):
  65. try:
  66. path.unlink()
  67. except FileNotFoundError:
  68. continue
  69. removed = True
  70. print(f"✓ Removed Windows login item: {path}")
  71. return removed