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
8 changes: 8 additions & 0 deletions docs/hermes-implementation-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,16 @@

### Task 14: Implement runbook executor

**Objective:** Execute diagnostics and actions defined in runbooks.

**Files:**
- Create: `src/agentic_node_ops/executor.py`
- Create: `tests/test_executor.py`

[x] Complete — Implemented runbook executor:
- `executor.py`: Added `execute_command` (with timeout handling), `run_diagnostics` (TIER 1: always run), and `execute_action` (TIER 2/3: blocks privileged actions requiring explicit unlock).
- `test_executor.py`: 6 tests covering command success/failure/timeout, diagnostics execution, and privileged action blocking.
- All tests passing (157 total, 90% coverage).

---

Expand Down
157 changes: 157 additions & 0 deletions src/agentic_node_ops/executor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""Runbook executor for agentic-node-ops.

Executes diagnostics and actions defined in runbooks.
"""

from __future__ import annotations

import logging
import os
import shlex
import signal
import subprocess
from typing import Any

from .runbooks import Runbook, RunbookAction

log = logging.getLogger(__name__)


def _parse_timeout(timeout_str: str) -> int:
"""Parse a timeout string (e.g., '5s', '1m') into seconds."""
try:
timeout_str = timeout_str.strip().lower()
if timeout_str.endswith("m"):
return int(timeout_str[:-1]) * 60
if timeout_str.endswith("s"):
return int(timeout_str[:-1])
return int(timeout_str)
except (ValueError, AttributeError):
log.warning("Invalid timeout string '%s', defaulting to 30s", timeout_str)
return 30


def execute_command(
cmd: str, timeout: int = 30, shell_required: bool = False
) -> dict[str, Any]:
"""Execute a shell command and return the result.

Returns a dict with 'success', 'stdout', 'stderr', and 'returncode'.
Uses shell=False with shlex.split by default to prevent shell injection.
If shell_required is True, uses shell=True and ensures the entire process
group is killed on timeout to prevent orphaned child processes.
"""
try:
if shell_required:
proc = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
start_new_session=True,
)
else:
proc = subprocess.Popen(
shlex.split(cmd),
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
start_new_session=True,
)

try:
stdout, stderr = proc.communicate(timeout=timeout)
return {
"success": proc.returncode == 0,
"stdout": stdout.strip() if stdout else "",
"stderr": stderr.strip() if stderr else "",
"returncode": proc.returncode,
}
except subprocess.TimeoutExpired:
# Kill the entire process group to prevent orphaned children
try:
os.killpg(proc.pid, signal.SIGTERM)
except ProcessLookupError:
pass # Process already terminated

# Wait for graceful termination, fallback to SIGKILL if ignored
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
try:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait()
except ProcessLookupError:
pass

log.error("Command timed out after %ds: %s", timeout, cmd)
return {
"success": False,
"stdout": "",
"stderr": f"Command timed out after {timeout}s",
"returncode": -1,
}
except Exception as e:
log.error("Command execution failed: %s, error: %s", cmd, e)
return {
"success": False,
"stdout": "",
"stderr": str(e),
"returncode": -1,
}


def run_diagnostics(runbook: Runbook) -> list[dict[str, Any]]:
"""Run all diagnostics for a given runbook.

Diagnostics are TIER 1 actions: always run, no approval, no notification.
"""
results = []
for diag in runbook.diagnostics:
timeout_sec = _parse_timeout(diag.timeout)
res = execute_command(diag.cmd, timeout=timeout_sec)
results.append(
{
"id": diag.id,
"cmd": diag.cmd,
"description": diag.description,
**res,
}
)
return results


def execute_action(action: RunbookAction) -> dict[str, Any]:
"""Execute a runbook action.

TIER 2 (suggested_actions) and TIER 3 (privileged_actions) are handled here.
Privileged actions requiring explicit unlock will be blocked.
"""
if action.requires_explicit_unlock:
log.warning(
"Blocked execution of privileged action '%s': requires explicit unlock",
action.id,
)
return {
"id": action.id,
"cmd": action.cmd,
"success": False,
"stdout": "",
"stderr": "Action requires explicit unlock (privileged action blocked)",
"returncode": -1,
}

# Default execution timeout of 60 seconds for actions
timeout_sec = 60

res = execute_command(
action.cmd, timeout=timeout_sec, shell_required=action.shell_required
)
return {
"id": action.id,
"cmd": action.cmd,
"description": action.description,
**res,
}
1 change: 1 addition & 0 deletions src/agentic_node_ops/runbooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class RunbookAction:
pre_conditions: list[str] = field(default_factory=list)
requires_explicit_unlock: bool = False
phase: str | None = None
shell_required: bool = False


@dataclass
Expand Down
131 changes: 131 additions & 0 deletions tests/test_executor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Tests for runbook executor."""

import time
from agentic_node_ops.executor import (
execute_command,
run_diagnostics,
execute_action,
_parse_timeout,
)
from agentic_node_ops.runbooks import Runbook, RunbookDiagnostic, RunbookAction


def test_execute_command_success():
"""Test successful command execution."""
result = execute_command("echo 'hello'")
assert result["success"] is True
assert result["stdout"] == "hello"
assert result["stderr"] == ""
assert result["returncode"] == 0


def test_execute_command_failure():
"""Test failed command execution."""
result = execute_command("false")
assert result["success"] is False
assert result["returncode"] == 1


def test_execute_command_timeout_kills_process():
"""Test command timeout kills the entire process group."""
# Use a shell command that spawns a child (sleep)
# If process group kill works, the sleep process should not outlive the call
start = time.time()
result = execute_command("sleep 5", timeout=1)
elapsed = time.time() - start

assert result["success"] is False
assert "timed out" in result["stderr"].lower()
assert result["returncode"] == -1
# Should return quickly (around 1s), not wait for the 5s sleep to finish
assert elapsed < 2.0


def test_execute_command_shell_required():
"""Test shell_required allows shell metacharacters."""
result = execute_command("echo 'hello' && echo 'world'", shell_required=True)
assert result["success"] is True
assert "hello" in result["stdout"]
assert "world" in result["stdout"]


def test_execute_command_shell_false_blocks_metacharacters():
"""Test shell=False treats metacharacters as literal arguments."""
# This will fail because '&&' is passed as a literal argument, not as a shell operator
result2 = execute_command(
"ls /nonexistent_dir_12345 && echo 'should not run'", shell_required=False
)
assert result2["success"] is False
assert "No such file or directory" in result2["stderr"]


def test_run_diagnostics():
"""Test running diagnostics from a runbook."""
runbook = Runbook(
id="test_runbook",
diagnostics=[
RunbookDiagnostic(
id="diag1", cmd="echo 'diag1'", timeout="1s", description="Test diag"
),
RunbookDiagnostic(id="diag2", cmd="exit 1", timeout="1s"),
],
)
results = run_diagnostics(runbook)

assert len(results) == 2
assert results[0]["id"] == "diag1"
assert results[0]["success"] is True
assert results[0]["stdout"] == "diag1"

assert results[1]["id"] == "diag2"
assert results[1]["success"] is False


def test_execute_action_success():
"""Test successful action execution."""
action = RunbookAction(
id="action1",
description="Test action",
cmd="echo 'action1'",
risk="low",
reversible=True,
requires_approval=True,
)
result = execute_action(action)

assert result["success"] is True
assert result["stdout"] == "action1"
assert result["id"] == "action1"


def test_execute_action_privileged_blocked():
"""Test that privileged actions requiring unlock are blocked."""
action = RunbookAction(
id="privileged_action",
description="Dangerous action",
cmd="echo 'should not run'",
risk="high",
reversible=False,
requires_approval=True,
requires_explicit_unlock=True,
)
result = execute_action(action)

assert result["success"] is False
assert "requires explicit unlock" in result["stderr"]
assert result["returncode"] == -1


def test_parse_timeout_valid():
"""Test _parse_timeout with valid inputs."""
assert _parse_timeout("5s") == 5
assert _parse_timeout("1m") == 60
assert _parse_timeout("30") == 30
assert _parse_timeout(" 2m ") == 120


def test_parse_timeout_invalid():
"""Test _parse_timeout with invalid inputs defaults to 30s."""
assert _parse_timeout("abc") == 30
assert _parse_timeout("") == 30
assert _parse_timeout("5x") == 30
Loading