main_container.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """NixOS container mode: route a ``hermes`` invocation into the managed container (``main()``)."""
  2. from __future__ import annotations
  3. import os
  4. import shutil
  5. import subprocess
  6. import sys
  7. def _probe_container(cmd: list, backend: str, via_sudo: bool = False):
  8. """Run a container inspect probe, returning the CompletedProcess.
  9. Catches TimeoutExpired specifically for a human-readable message;
  10. all other exceptions propagate naturally.
  11. """
  12. try:
  13. return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, check=False)
  14. except subprocess.TimeoutExpired:
  15. label = f"sudo {backend}" if via_sudo else backend
  16. print(
  17. f"Error: timed out waiting for {label} to respond.\n"
  18. f"The {backend} daemon may be unresponsive or starting up.",
  19. file=sys.stderr,
  20. )
  21. sys.exit(1)
  22. def exec_in_container(container_info: dict, cli_args: list):
  23. """Replace the current process with a command inside the managed container.
  24. Probes whether sudo is needed (rootful containers), then os.execvp
  25. into the container. On success the Python process is replaced entirely
  26. and the container's exit code becomes the process exit code (OS semantics).
  27. On failure, OSError propagates naturally.
  28. Args:
  29. container_info: dict with backend, container_name, exec_user, hermes_bin
  30. cli_args: the original CLI arguments (everything after 'hermes')
  31. """
  32. backend = container_info["backend"]
  33. container_name = container_info["container_name"]
  34. exec_user = container_info["exec_user"]
  35. hermes_bin = container_info["hermes_bin"]
  36. runtime = shutil.which(backend)
  37. if not runtime:
  38. print(
  39. f"Error: {backend} not found on PATH. Cannot route to container.",
  40. file=sys.stderr,
  41. )
  42. sys.exit(1)
  43. # Rootful containers (NixOS systemd service) are invisible to unprivileged
  44. # users — Podman uses per-user namespaces, Docker needs group access.
  45. # Probe whether the runtime can see the container; if not, try via sudo.
  46. inspect_cmd = [runtime, "inspect", "--format", "ok", container_name]
  47. cmd_prefix = [runtime]
  48. if _probe_container(inspect_cmd, backend).returncode != 0:
  49. sudo_path = shutil.which("sudo")
  50. if not sudo_path:
  51. print(
  52. f"Error: container '{container_name}' not found via {backend}.\n"
  53. f"The container may be running under root. Try: sudo hermes {' '.join(cli_args)}",
  54. file=sys.stderr,
  55. )
  56. sys.exit(1)
  57. cmd_prefix = [sudo_path, "-n", runtime]
  58. if _probe_container(cmd_prefix[:2] + inspect_cmd, backend, via_sudo=True).returncode != 0:
  59. print(
  60. f"Error: container '{container_name}' not found via {backend}.\n"
  61. f"\n"
  62. f"The container is likely running as root. Your user cannot see it\n"
  63. f"because {backend} uses per-user namespaces. Grant passwordless\n"
  64. f"sudo for {backend} — the -n (non-interactive) flag is required\n"
  65. f"because a password prompt would hang or break piped commands.\n"
  66. f"\n"
  67. f"On NixOS:\n"
  68. f"\n"
  69. f" security.sudo.extraRules = [{{\n"
  70. f' users = [ "{os.getenv("USER", "your-user")}" ];\n'
  71. f' commands = [{{ command = "{runtime}"; options = [ "NOPASSWD" ]; }}];\n'
  72. f" }}];\n"
  73. f"\n"
  74. f"Or run: sudo hermes {' '.join(cli_args)}",
  75. file=sys.stderr,
  76. )
  77. sys.exit(1)
  78. env_flags = []
  79. for var in ("TERM", "COLORTERM", "LANG", "LC_ALL"):
  80. val = os.environ.get(var)
  81. if val:
  82. env_flags.extend(["-e", f"{var}={val}"])
  83. exec_cmd = (
  84. cmd_prefix
  85. + ["exec", "-it" if sys.stdin.isatty() else "-i", "-u", exec_user]
  86. + env_flags
  87. + [container_name, hermes_bin]
  88. + cli_args
  89. )
  90. os.execvp(exec_cmd[0], exec_cmd)