Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 144 additions & 63 deletions scripts/managed-gateway-control.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@
import subprocess
import sys
import time
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass


Expand All @@ -78,23 +80,51 @@
RECOVERY_TIMEOUT_SECONDS = 150.0
RECOVER_EXISTING_GRACE_SECONDS = 10.0
POLL_SECONDS = 0.2
SUPERVISOR_DISCOVERY_ATTEMPTS = 3
SUPERVISOR_DISCOVERY_RETRY_SECONDS = 0.02
PROCESS_PROOF_GRACE_SECONDS = 1.0
PROCESS_PROOF_RETRY_SECONDS = 0.05
NEMOCLAW_RUNTIME_DIR = "/run/nemoclaw"
NEMOCLAW_RUNTIME_DIR_MODE = 0o711
EXPECTED_EXIT_MARKER_NAME = "managed-gateway-expected-exit"
EXPECTED_EXIT_LOCK_NAME = "managed-gateway-expected-exit.lock"
NONCE_RE = re.compile(r"[0-9a-f]{64}\Z")
ENV_KEY_RE = re.compile(rb"[A-Za-z_][A-Za-z0-9_]*\Z")
SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")
CONTROL_STAGES = frozenset(
{
"detect-agent",
"discover-supervisor",
"initial-gateway-proof",
"preflight",
"await-existing-gateway",
"publish-expected-exit",
"terminate-gateway",
"await-replacement",
"cleanup-expected-exit",
}
)


class ControlError(RuntimeError):
"""A failure whose code is part of the existing host marker contract."""

def __init__(self, code: str):
def __init__(self, code: str, *, stage: str | None = None):
super().__init__(code)
self.code = code
self.stage = stage


@contextmanager
def _control_stage(stage: str) -> Iterator[None]:
"""Attach one fixed, non-sensitive lifecycle stage to generic failures."""

if stage not in CONTROL_STAGES:
raise AssertionError(f"unknown managed-control stage: {stage}")
try:
yield
except ControlError as error:
if error.code == "SUPERVISOR_UNAVAILABLE" and error.stage is None:
raise ControlError(error.code, stage=stage) from error
raise


@dataclass(frozen=True)
Expand Down Expand Up @@ -732,6 +762,39 @@ def read_stable_file(
os.close(pid_fd)


def _recapture_exact_identity(
reader: ProcReader,
expected: ProcessIdentity,
*,
deadline: float | None = None,
) -> ProcessIdentity:
"""Retry only an internally inconsistent read of one already-pinned process."""

proof_deadline = (
time.monotonic() + PROCESS_PROOF_GRACE_SECONDS
if deadline is None
else deadline
)
while True:
try:
current = reader.capture(expected.pid)
except (FileNotFoundError, ProcessLookupError, PermissionError) as exc:
# A missing or unreadable pinned process is a conclusive loss of the
# proof. Only ProcReader's double-read inconsistency is retryable.
raise ControlError("SUPERVISOR_UNAVAILABLE") from exc
except ControlError as error:
if error.code != "SUPERVISOR_UNAVAILABLE":
raise
remaining = proof_deadline - time.monotonic()
if remaining <= 0:
raise
time.sleep(min(PROCESS_PROOF_RETRY_SECONDS, remaining))
continue
if current.stable_key() != expected.stable_key():
raise ControlError("SUPERVISOR_UNAVAILABLE")
return current


def _basename(value: bytes) -> bytes:
return value.rsplit(b"/", 1)[-1]

Expand Down Expand Up @@ -813,17 +876,16 @@ def _discover_supervisor(reader: ProcReader) -> ProcessIdentity:
if len(matches) != 1:
raise ControlError("SUPERVISOR_UNAVAILABLE")
expected = matches[0].stable_key()
for _attempt in range(1, SUPERVISOR_DISCOVERY_ATTEMPTS):
time.sleep(SUPERVISOR_DISCOVERY_RETRY_SECONDS)
if reader.capture(1).stable_key() != pid1.stable_key():
deadline = time.monotonic() + PROCESS_PROOF_GRACE_SECONDS
while inconclusive:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise ControlError("SUPERVISOR_UNAVAILABLE")
time.sleep(min(PROCESS_PROOF_RETRY_SECONDS, remaining))
_recapture_exact_identity(reader, pid1, deadline=deadline)
matches, inconclusive = _supervisor_candidates(reader, pid1, sandbox_uid)
if len(matches) != 1 or matches[0].stable_key() != expected:
raise ControlError("SUPERVISOR_UNAVAILABLE")
if not inconclusive:
break
if inconclusive:
raise ControlError("SUPERVISOR_UNAVAILABLE")
if len(matches) == 0:
# A zero-match scan is the only absence signal that may authorize the
# host to recreate a legacy Docker container with its managed startup
Expand All @@ -846,14 +908,9 @@ def _discover_supervisor(reader: ProcReader) -> ProcessIdentity:
raise ControlError("SUPERVISOR_UNAVAILABLE")
if len(matches) != 1:
raise ControlError("SUPERVISOR_UNAVAILABLE")
current_pid1 = reader.capture(1)
current_supervisor = reader.capture(matches[0].pid)
if (
current_pid1.stable_key() != pid1.stable_key()
or current_supervisor.stable_key() != matches[0].stable_key()
):
raise ControlError("SUPERVISOR_UNAVAILABLE")
return current_supervisor
deadline = time.monotonic() + PROCESS_PROOF_GRACE_SECONDS
_recapture_exact_identity(reader, pid1, deadline=deadline)
return _recapture_exact_identity(reader, matches[0], deadline=deadline)


def _is_hermes_gateway(identity: ProcessIdentity) -> bool:
Expand Down Expand Up @@ -970,9 +1027,7 @@ def _gateway_candidates(
matches.append(identity)
if len(matches) > 1:
break
current_supervisor = reader.capture(supervisor.pid)
if current_supervisor.stable_key() != supervisor.stable_key():
raise ControlError("SUPERVISOR_UNAVAILABLE")
_recapture_exact_identity(reader, supervisor)
if len(matches) > 1:
raise ControlError("SUPERVISOR_UNAVAILABLE")
return matches
Expand Down Expand Up @@ -1294,14 +1349,16 @@ def _preflight(
_openclaw_preflight()


def _pidfd_open(pid: int) -> int:
def _pidfd_open(pid: int) -> int | None:
opener = getattr(os, "pidfd_open", None)
sender = getattr(signal, "pidfd_send_signal", None)
if opener is None or sender is None:
raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE")
try:
return opener(pid, 0)
except OSError as exc:
if exc.errno == errno.ESRCH:
return None
raise ControlError("SUPERVISOR_UNAVAILABLE") from exc


Expand All @@ -1311,29 +1368,41 @@ def _pidfd_exited(pidfd: int, timeout_seconds: float) -> bool:
return bool(poller.poll(max(0, int(timeout_seconds * 1000))))


def _send_pidfd(pidfd: int, signum: signal.Signals) -> None:
def _send_pidfd(pidfd: int, signum: signal.Signals) -> bool:
sender = getattr(signal, "pidfd_send_signal", None)
if sender is None:
raise ControlError("PRIVILEGED_CONTROL_UNAVAILABLE")
try:
sender(pidfd, signum, None, 0)
except OSError as exc:
if exc.errno == errno.ESRCH:
return False
raise ControlError("GATEWAY_FAILED") from exc
return True


def _terminate_gateway(reader: ProcReader, identity: ProcessIdentity) -> None:
pidfd = _pidfd_open(identity.pid)
if pidfd is None:
return
try:
current = reader.capture(identity.pid)
if current.stable_key() != identity.stable_key():
raise ControlError("SUPERVISOR_UNAVAILABLE")
_send_pidfd(pidfd, signal.SIGTERM)
try:
_recapture_exact_identity(reader, identity)
except ControlError:
# The pidfd is readable only when the exact process opened above has
# exited. Accept that race without ever falling back to a PID signal.
if _pidfd_exited(pidfd, 0):
return
raise
if not _send_pidfd(pidfd, signal.SIGTERM):
return
if _pidfd_exited(pidfd, STOP_GRACE_SECONDS):
return
current = reader.capture(identity.pid)
if current.stable_key() != identity.stable_key():
raise ControlError("SUPERVISOR_UNAVAILABLE")
_send_pidfd(pidfd, signal.SIGKILL)
# The pidfd already pins the proven gateway across exit and PID reuse.
# Re-reading /proc here races with the normal live-to-zombie transition
# and adds no signal-target safety.
if not _send_pidfd(pidfd, signal.SIGKILL):
return
if not _pidfd_exited(pidfd, KILL_GRACE_SECONDS):
raise ControlError("GATEWAY_FAILED")
finally:
Expand Down Expand Up @@ -1410,14 +1479,18 @@ def _wait_for_recovery_candidate(


def _control(action: str, nonce: str) -> tuple[str, int, int]:
agent = _detect_agent()
with _control_stage("detect-agent"):
agent = _detect_agent()
with ProcReader() as reader:
supervisor = _discover_supervisor(reader)
spec = _agent_spec(agent, reader, supervisor)
candidates = _gateway_candidates(reader, supervisor, spec)
old_identity = candidates[0] if candidates else None
with _control_stage("discover-supervisor"):
supervisor = _discover_supervisor(reader)
with _control_stage("initial-gateway-proof"):
spec = _agent_spec(agent, reader, supervisor)
candidates = _gateway_candidates(reader, supervisor, spec)
old_identity = candidates[0] if candidates else None

_preflight(spec, reader, supervisor)
with _control_stage("preflight"):
_preflight(spec, reader, supervisor)

if action == "probe":
if old_identity is None:
Expand All @@ -1439,21 +1512,23 @@ def _control(action: str, nonce: str) -> tuple[str, int, int]:
# grace, give the one successor its own bounded grace before any
# signal so recovery cannot churn a newly launched replacement.
original_identity = old_identity
existing, old_identity = _wait_for_recovery_candidate(
reader,
supervisor,
spec,
original_identity,
)
if existing is not None:
completed = _wait_for_healthy_gateway(
with _control_stage("await-existing-gateway"):
existing, old_identity = _wait_for_recovery_candidate(
reader,
supervisor,
spec,
None,
RECOVERY_TIMEOUT_SECONDS,
True,
original_identity,
)
if existing is not None:
with _control_stage("await-existing-gateway"):
completed = _wait_for_healthy_gateway(
reader,
supervisor,
spec,
None,
RECOVERY_TIMEOUT_SECONDS,
True,
)
return "already-running", original_identity.pid, completed.pid

expected_exit_lease = None
Expand All @@ -1464,26 +1539,30 @@ def _control(action: str, nonce: str) -> tuple[str, int, int]:
# signal. The marker names this live root controller so a
# delayed reap remains authorized without trusting wall time,
# while an orphaned marker fails closed as an ordinary crash.
controller_identity = _controller_process_identity(reader)
expected_exit_lease = _publish_expected_exit_lease(
old_identity,
controller_identity,
)
with _control_stage("publish-expected-exit"):
controller_identity = _controller_process_identity(reader)
expected_exit_lease = _publish_expected_exit_lease(
old_identity,
controller_identity,
)
if old_identity is not None:
_terminate_gateway(reader, old_identity)
with _control_stage("terminate-gateway"):
_terminate_gateway(reader, old_identity)

replacement = _wait_for_healthy_gateway(
reader,
supervisor,
spec,
old_identity,
RECOVERY_TIMEOUT_SECONDS,
True,
)
with _control_stage("await-replacement"):
replacement = _wait_for_healthy_gateway(
reader,
supervisor,
spec,
old_identity,
RECOVERY_TIMEOUT_SECONDS,
True,
)
return "ok", old_identity.pid if old_identity else 0, replacement.pid
finally:
if expected_exit_lease is not None:
_clear_expected_exit_lease(expected_exit_lease)
with _control_stage("cleanup-expected-exit"):
_clear_expected_exit_lease(expected_exit_lease)


def _validate_request(argv: list[str]) -> tuple[str, str]:
Expand All @@ -1508,6 +1587,8 @@ def main(argv: list[str]) -> int:
return 0
except ControlError as error:
print(error.code, file=sys.stderr)
if error.code == "SUPERVISOR_UNAVAILABLE" and error.stage is not None:
print(f"NEMOCLAW_CONTROL_STAGE={error.stage}", file=sys.stderr)
return 1
except (OSError, subprocess.SubprocessError):
print("GATEWAY_FAILED", file=sys.stderr)
Expand Down
4 changes: 4 additions & 0 deletions src/lib/actions/sandbox/gateway-restart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ describe("gateway restart failure markers", () => {
> = [
["PRIVILEGED_CONTROL_UNAVAILABLE", "privileged control unavailable"],
["SUPERVISOR_UNAVAILABLE", "privileged control unavailable"],
[
"SUPERVISOR_UNAVAILABLE\nNEMOCLAW_CONTROL_STAGE=await-replacement",
"privileged control unavailable",
],
["SUPERVISOR_NOT_RUNNING", "supervisor not running"],
["SUPERVISOR_REBUILD_REQUIRED", "privileged control unavailable"],
["SUPERVISOR_BUSY", "privileged control unavailable"],
Expand Down
Loading
Loading