|
|
|
|
@@ -1,212 +1,243 @@
|
|
|
|
|
"""
|
|
|
|
|
SSH dispatch utilities for cron jobs.
|
|
|
|
|
"""SSH Dispatch — validated remote hermes execution for cron jobs.
|
|
|
|
|
|
|
|
|
|
Provides validated remote execution so broken hermes binary paths
|
|
|
|
|
are caught before draining the dispatch queue.
|
|
|
|
|
Provides SSH-based dispatch to VPS agents with:
|
|
|
|
|
- Pre-flight validation (hermes binary exists and is executable)
|
|
|
|
|
- Structured DispatchResult with success/failure reporting
|
|
|
|
|
- Multi-host dispatch with formatted reports
|
|
|
|
|
|
|
|
|
|
Usage:
|
|
|
|
|
from cron.ssh_dispatch import SSHEnvironment, format_dispatch_report
|
|
|
|
|
from cron.ssh_dispatch import dispatch_to_host, dispatch_to_hosts, format_dispatch_report
|
|
|
|
|
|
|
|
|
|
ssh = SSHEnvironment(host="root@ezra", agent="allegro")
|
|
|
|
|
result = ssh.dispatch("cron tick")
|
|
|
|
|
result = dispatch_to_host("ezra", "143.198.27.163", "Check the beacon repo for open issues")
|
|
|
|
|
if not result.success:
|
|
|
|
|
print(result.failure_reason)
|
|
|
|
|
print(result.error)
|
|
|
|
|
|
|
|
|
|
results = dispatch_to_hosts(["ezra", "bezalel"], "Run fleet health check")
|
|
|
|
|
print(format_dispatch_report(results))
|
|
|
|
|
|
|
|
|
|
Ref: #350, #541, #561
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
import subprocess
|
|
|
|
|
import shutil
|
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
|
from typing import List, Optional
|
|
|
|
|
from typing import Dict, List, Optional
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
# Known VPS hosts (can be overridden via env or config)
|
|
|
|
|
DEFAULT_HOSTS: Dict[str, str] = {
|
|
|
|
|
"ezra": "143.198.27.163",
|
|
|
|
|
"bezalel": "159.203.146.185",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# SSH options for non-interactive, fast-fail connections
|
|
|
|
|
_SSH_OPTS = [
|
|
|
|
|
"-o", "ConnectTimeout=10",
|
|
|
|
|
"-o", "StrictHostKeyChecking=accept-new",
|
|
|
|
|
"-o", "BatchMode=yes",
|
|
|
|
|
"-o", "LogLevel=ERROR",
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
# Paths to check for hermes binary on remote
|
|
|
|
|
_HERMES_CHECK_PATHS = [
|
|
|
|
|
"~/.local/bin/hermes",
|
|
|
|
|
"/usr/local/bin/hermes",
|
|
|
|
|
"~/.hermes/bin/hermes",
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class DispatchResult:
|
|
|
|
|
"""Structured result of a remote command dispatch."""
|
|
|
|
|
"""Result of an SSH dispatch attempt."""
|
|
|
|
|
host: str
|
|
|
|
|
command: str
|
|
|
|
|
address: str
|
|
|
|
|
success: bool
|
|
|
|
|
exit_code: Optional[int] = None
|
|
|
|
|
stdout: str = ""
|
|
|
|
|
stderr: str = ""
|
|
|
|
|
failure_reason: Optional[str] = None
|
|
|
|
|
duration_s: float = 0.0
|
|
|
|
|
output: str = ""
|
|
|
|
|
error: str = ""
|
|
|
|
|
hermes_found: bool = False
|
|
|
|
|
hermes_path: str = ""
|
|
|
|
|
exit_code: int = -1
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def summary(self) -> str:
|
|
|
|
|
if self.success:
|
|
|
|
|
return f"[OK] {self.host} ({self.address})"
|
|
|
|
|
return f"[FAIL] {self.host} ({self.address}): {self.error}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class SSHEnvironment:
|
|
|
|
|
"""Validates and dispatches commands to a remote host via SSH."""
|
|
|
|
|
def probe_hermes(host: str, address: str) -> tuple[bool, str]:
|
|
|
|
|
"""Check if hermes binary exists and is executable on remote host.
|
|
|
|
|
|
|
|
|
|
host: str # e.g. "root@ezra" or "192.168.1.10"
|
|
|
|
|
agent: str = "" # agent name for logging
|
|
|
|
|
hermes_path: Optional[str] = None # explicit path, auto-detected if None
|
|
|
|
|
timeout: int = 120 # seconds
|
|
|
|
|
_validated_path: Optional[str] = field(default=None, init=False, repr=False)
|
|
|
|
|
Returns (found, path).
|
|
|
|
|
"""
|
|
|
|
|
check_cmds = " || ".join(f"test -x {p} && echo {p}" for p in _HERMES_CHECK_PATHS)
|
|
|
|
|
remote_cmd = f"bash -c '{check_cmds} || echo NOTFOUND'"
|
|
|
|
|
|
|
|
|
|
def _ssh_base(self) -> List[str]:
|
|
|
|
|
return [
|
|
|
|
|
"ssh",
|
|
|
|
|
"-o", "ConnectTimeout=10",
|
|
|
|
|
"-o", "StrictHostKeyChecking=accept-new",
|
|
|
|
|
"-o", "BatchMode=yes",
|
|
|
|
|
self.host,
|
|
|
|
|
]
|
|
|
|
|
try:
|
|
|
|
|
result = subprocess.run(
|
|
|
|
|
["ssh", address, *_SSH_OPTS, remote_cmd],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=15,
|
|
|
|
|
)
|
|
|
|
|
output = result.stdout.strip()
|
|
|
|
|
if output and output != "NOTFOUND":
|
|
|
|
|
return True, output
|
|
|
|
|
return False, ""
|
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
|
logger.warning("SSH probe timed out for %s", host)
|
|
|
|
|
return False, ""
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.warning("SSH probe failed for %s: %s", host, e)
|
|
|
|
|
return False, ""
|
|
|
|
|
|
|
|
|
|
def _probe_remote_binary(self, candidate: str) -> bool:
|
|
|
|
|
"""Check if a hermes binary exists and is executable on the remote host."""
|
|
|
|
|
try:
|
|
|
|
|
result = subprocess.run(
|
|
|
|
|
self._ssh_base() + [f"test -x {candidate}"],
|
|
|
|
|
capture_output=True, timeout=15,
|
|
|
|
|
)
|
|
|
|
|
return result.returncode == 0
|
|
|
|
|
except (subprocess.TimeoutExpired, FileNotFoundError):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
def detect_hermes_binary(self) -> Optional[str]:
|
|
|
|
|
"""Find a working hermes binary on the remote host."""
|
|
|
|
|
if self._validated_path:
|
|
|
|
|
return self._validated_path
|
|
|
|
|
def dispatch_to_host(
|
|
|
|
|
host: str,
|
|
|
|
|
address: str,
|
|
|
|
|
prompt: str,
|
|
|
|
|
timeout: int = 300,
|
|
|
|
|
validate: bool = True,
|
|
|
|
|
) -> DispatchResult:
|
|
|
|
|
"""Dispatch a prompt to a remote hermes instance via SSH.
|
|
|
|
|
|
|
|
|
|
candidates = []
|
|
|
|
|
if self.hermes_path:
|
|
|
|
|
candidates.append(self.hermes_path)
|
|
|
|
|
|
|
|
|
|
# Common locations
|
|
|
|
|
candidates.extend([
|
|
|
|
|
"hermes", # on PATH
|
|
|
|
|
"~/.local/bin/hermes",
|
|
|
|
|
"/usr/local/bin/hermes",
|
|
|
|
|
f"~/wizards/{self.agent}/venv/bin/hermes" if self.agent else "",
|
|
|
|
|
f"/root/wizards/{self.agent}/venv/bin/hermes" if self.agent else "",
|
|
|
|
|
])
|
|
|
|
|
candidates = [c for c in candidates if c]
|
|
|
|
|
|
|
|
|
|
for candidate in candidates:
|
|
|
|
|
if self._probe_remote_binary(candidate):
|
|
|
|
|
self._validated_path = candidate
|
|
|
|
|
return candidate
|
|
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def dispatch(self, command: str, *, validate_binary: bool = True) -> DispatchResult:
|
|
|
|
|
"""Execute a command on the remote host."""
|
|
|
|
|
import time
|
|
|
|
|
start = time.monotonic()
|
|
|
|
|
|
|
|
|
|
if validate_binary:
|
|
|
|
|
binary = self.detect_hermes_binary()
|
|
|
|
|
if not binary:
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=self.host,
|
|
|
|
|
command=command,
|
|
|
|
|
success=False,
|
|
|
|
|
failure_reason=f"No working hermes binary found on {self.host}",
|
|
|
|
|
duration_s=time.monotonic() - start,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
result = subprocess.run(
|
|
|
|
|
self._ssh_base() + [command],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
timeout=self.timeout,
|
|
|
|
|
)
|
|
|
|
|
duration = time.monotonic() - start
|
|
|
|
|
stdout = result.stdout.decode("utf-8", errors="replace")
|
|
|
|
|
stderr = result.stderr.decode("utf-8", errors="replace")
|
|
|
|
|
|
|
|
|
|
failure_reason = None
|
|
|
|
|
if result.returncode != 0:
|
|
|
|
|
failure_reason = _classify_ssh_error(stderr, result.returncode)
|
|
|
|
|
Args:
|
|
|
|
|
host: Hostname (ezra, bezalel, etc.)
|
|
|
|
|
address: IP address or hostname
|
|
|
|
|
prompt: The prompt/task to dispatch
|
|
|
|
|
timeout: SSH timeout in seconds
|
|
|
|
|
validate: Whether to probe for hermes binary first
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
DispatchResult with success/failure details.
|
|
|
|
|
"""
|
|
|
|
|
# Pre-flight validation
|
|
|
|
|
if validate:
|
|
|
|
|
found, path = probe_hermes(host, address)
|
|
|
|
|
if not found:
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=self.host,
|
|
|
|
|
command=command,
|
|
|
|
|
success=result.returncode == 0,
|
|
|
|
|
exit_code=result.returncode,
|
|
|
|
|
stdout=stdout,
|
|
|
|
|
stderr=stderr,
|
|
|
|
|
failure_reason=failure_reason,
|
|
|
|
|
duration_s=duration,
|
|
|
|
|
)
|
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=self.host,
|
|
|
|
|
command=command,
|
|
|
|
|
host=host,
|
|
|
|
|
address=address,
|
|
|
|
|
success=False,
|
|
|
|
|
failure_reason=f"SSH command timed out after {self.timeout}s",
|
|
|
|
|
duration_s=time.monotonic() - start,
|
|
|
|
|
)
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=self.host,
|
|
|
|
|
command=command,
|
|
|
|
|
success=False,
|
|
|
|
|
failure_reason="ssh binary not found on local system",
|
|
|
|
|
duration_s=time.monotonic() - start,
|
|
|
|
|
error="hermes binary not found on remote host",
|
|
|
|
|
hermes_found=False,
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
found, path = True, "~/.local/bin/hermes"
|
|
|
|
|
|
|
|
|
|
# Build the dispatch command
|
|
|
|
|
# Use hermes chat in quiet mode, pipe prompt via stdin
|
|
|
|
|
escaped_prompt = prompt.replace("'", "'\\''")
|
|
|
|
|
remote_cmd = f"echo '{escaped_prompt}' | {path} chat --quiet"
|
|
|
|
|
|
|
|
|
|
def _classify_ssh_error(stderr: str, exit_code: int) -> str:
|
|
|
|
|
"""Classify an SSH error from stderr and exit code."""
|
|
|
|
|
lower = stderr.lower()
|
|
|
|
|
try:
|
|
|
|
|
result = subprocess.run(
|
|
|
|
|
["ssh", address, *_SSH_OPTS, remote_cmd],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=timeout,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if "no such file or directory" in lower:
|
|
|
|
|
return f"Remote binary or file not found (exit {exit_code})"
|
|
|
|
|
if "command not found" in lower:
|
|
|
|
|
return f"Command not found on remote host (exit {exit_code})"
|
|
|
|
|
if "permission denied" in lower:
|
|
|
|
|
return f"Permission denied (exit {exit_code})"
|
|
|
|
|
if "connection timed out" in lower or "connection refused" in lower:
|
|
|
|
|
return f"SSH connection failed (exit {exit_code})"
|
|
|
|
|
if "host key verification failed" in lower:
|
|
|
|
|
return f"Host key verification failed (exit {exit_code})"
|
|
|
|
|
if "no route to host" in lower:
|
|
|
|
|
return f"No route to host (exit {exit_code})"
|
|
|
|
|
if exit_code == 127:
|
|
|
|
|
return f"Command not found (exit 127)"
|
|
|
|
|
if exit_code == 126:
|
|
|
|
|
return f"Command not executable (exit 126)"
|
|
|
|
|
success = result.returncode == 0
|
|
|
|
|
error = ""
|
|
|
|
|
|
|
|
|
|
return f"Command failed with exit code {exit_code}: {stderr[:200]}"
|
|
|
|
|
if not success:
|
|
|
|
|
error = result.stderr.strip() if result.stderr else f"exit code {result.returncode}"
|
|
|
|
|
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=host,
|
|
|
|
|
address=address,
|
|
|
|
|
success=success,
|
|
|
|
|
output=result.stdout.strip()[:500], # Truncate long output
|
|
|
|
|
error=error,
|
|
|
|
|
hermes_found=found,
|
|
|
|
|
hermes_path=path,
|
|
|
|
|
exit_code=result.returncode,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=host,
|
|
|
|
|
address=address,
|
|
|
|
|
success=False,
|
|
|
|
|
error=f"SSH dispatch timed out after {timeout}s",
|
|
|
|
|
hermes_found=found,
|
|
|
|
|
hermes_path=path,
|
|
|
|
|
)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return DispatchResult(
|
|
|
|
|
host=host,
|
|
|
|
|
address=address,
|
|
|
|
|
success=False,
|
|
|
|
|
error=f"SSH dispatch failed: {e}",
|
|
|
|
|
hermes_found=found,
|
|
|
|
|
hermes_path=path,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def dispatch_to_hosts(
|
|
|
|
|
hosts: List[str],
|
|
|
|
|
command: str,
|
|
|
|
|
agent: str = "",
|
|
|
|
|
timeout: int = 120,
|
|
|
|
|
prompt: str,
|
|
|
|
|
host_map: Optional[Dict[str, str]] = None,
|
|
|
|
|
timeout: int = 300,
|
|
|
|
|
) -> List[DispatchResult]:
|
|
|
|
|
"""Dispatch a command to multiple hosts and return results."""
|
|
|
|
|
"""Dispatch a prompt to multiple hosts.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
hosts: List of hostnames
|
|
|
|
|
prompt: The prompt/task to dispatch
|
|
|
|
|
host_map: Optional override of hostname -> address mapping
|
|
|
|
|
timeout: SSH timeout per host
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
List of DispatchResult, one per host.
|
|
|
|
|
"""
|
|
|
|
|
addresses = host_map or DEFAULT_HOSTS
|
|
|
|
|
results = []
|
|
|
|
|
|
|
|
|
|
for host in hosts:
|
|
|
|
|
ssh = SSHEnvironment(host=host, agent=agent, timeout=timeout)
|
|
|
|
|
result = ssh.dispatch(command)
|
|
|
|
|
address = addresses.get(host)
|
|
|
|
|
if not address:
|
|
|
|
|
results.append(DispatchResult(
|
|
|
|
|
host=host,
|
|
|
|
|
address="unknown",
|
|
|
|
|
success=False,
|
|
|
|
|
error=f"Unknown host: {host}",
|
|
|
|
|
))
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
result = dispatch_to_host(host, address, prompt, timeout=timeout)
|
|
|
|
|
results.append(result)
|
|
|
|
|
logger.info(result.summary)
|
|
|
|
|
|
|
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def format_dispatch_report(results: List[DispatchResult]) -> str:
|
|
|
|
|
"""Format a human-readable report of dispatch results."""
|
|
|
|
|
lines = ["## Dispatch Report", ""]
|
|
|
|
|
"""Format a multi-host dispatch results as a readable report."""
|
|
|
|
|
if not results:
|
|
|
|
|
return "No dispatch results."
|
|
|
|
|
|
|
|
|
|
succeeded = [r for r in results if r.success]
|
|
|
|
|
failed = [r for r in results if not r.success]
|
|
|
|
|
lines = ["SSH Dispatch Report", "=" * 40, ""]
|
|
|
|
|
|
|
|
|
|
lines.append(f"**Total:** {len(results)} hosts | "
|
|
|
|
|
f"**OK:** {len(succeeded)} | **Failed:** {len(failed)}")
|
|
|
|
|
ok_count = sum(1 for r in results if r.success)
|
|
|
|
|
fail_count = len(results) - ok_count
|
|
|
|
|
|
|
|
|
|
lines.append(f"Total: {len(results)} | OK: {ok_count} | FAIL: {fail_count}")
|
|
|
|
|
lines.append("")
|
|
|
|
|
|
|
|
|
|
for r in results:
|
|
|
|
|
status = "OK" if r.success else "FAIL"
|
|
|
|
|
lines.append(f"### {r.host} [{status}]")
|
|
|
|
|
lines.append(f"- Command: `{r.command}`")
|
|
|
|
|
lines.append(f"- Duration: {r.duration_s:.1f}s")
|
|
|
|
|
if r.exit_code is not None:
|
|
|
|
|
lines.append(f"- Exit code: {r.exit_code}")
|
|
|
|
|
if r.failure_reason:
|
|
|
|
|
lines.append(f"- **Failure:** {r.failure_reason}")
|
|
|
|
|
if r.stderr and not r.success:
|
|
|
|
|
lines.append(f"- Stderr: `{r.stderr[:300]}`")
|
|
|
|
|
status = "✓" if r.success else "✗"
|
|
|
|
|
lines.append(f" {status} {r.host} ({r.address})")
|
|
|
|
|
if r.hermes_path:
|
|
|
|
|
lines.append(f" hermes: {r.hermes_path}")
|
|
|
|
|
if r.success and r.output:
|
|
|
|
|
lines.append(f" output: {r.output[:100]}...")
|
|
|
|
|
if not r.success:
|
|
|
|
|
lines.append(f" error: {r.error}")
|
|
|
|
|
lines.append("")
|
|
|
|
|
|
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|