Bind self-healing to the selected cluster and route residual cleanup directly
This commit is contained in:
parent
64eefb603c
commit
4241954fe1
|
|
@ -0,0 +1,41 @@
|
|||
# Jeannie self-heal webhook
|
||||
|
||||
Install or reconcile the webhook from the checkout used for operations:
|
||||
|
||||
```bash
|
||||
LAB_CLUSTER_PROFILE=pimox ./jeannie self-heal install-service --apply
|
||||
```
|
||||
|
||||
The installer records the selected profile, explicit kubeconfig, and current
|
||||
checkout path in the systemd unit. It restarts the webhook so new source and
|
||||
environment settings take effect. Without `--apply`, installation defaults to
|
||||
dry-run mode unless `LAB_SELF_HEAL_APPLY=true` is explicitly supplied.
|
||||
|
||||
`HomelabStaleResidualPods`, `KubePodEvicted`, and
|
||||
`KubePodContainerStatusUnknown` select the guarded stale-pod cleanup directly.
|
||||
They do not invoke the broad doctor planner or choose unrelated VM restarts.
|
||||
The cleanup only selects supported residual states on controller-owned pods;
|
||||
Completed/Succeeded and ordinary Pending pods are not cleanup targets. It does
|
||||
not delete PVCs or change worker CPU configuration. Debian automatic disk
|
||||
cleanup remains disabled.
|
||||
|
||||
Doctor stdout and stderr are stored separately under
|
||||
`~/.local/share/homelab/self-heal-events/<event>/`. The `.log` file contains
|
||||
stdout (JSON for the doctor), `.stderr.log` contains diagnostics, and
|
||||
`result.json` records the chosen command and outcome. Generic cleanup
|
||||
verification checks eligible residual records rather than requiring all
|
||||
unrelated Pending workloads to become healthy.
|
||||
|
||||
Read-only validation:
|
||||
|
||||
```bash
|
||||
systemctl is-active jeannie-eventd
|
||||
systemctl show jeannie-eventd -p Environment --value
|
||||
LAB_CLUSTER_PROFILE=pimox ./jeannie heal cleanup-stale-pods
|
||||
```
|
||||
|
||||
Alertmanager repeats matching firing alerts according to its configured route
|
||||
(currently one hour for this receiver); service installation does not itself
|
||||
trigger a cleanup. Existing failed/completed pod objects do not prove that
|
||||
their replacement workloads are unhealthy; Pending workloads need separate
|
||||
scheduling diagnosis.
|
||||
|
|
@ -8,6 +8,8 @@ Type=simple
|
|||
User=jv
|
||||
WorkingDirectory=/home/jv/my-homelab-configs
|
||||
Environment=LAB_CLUSTER_PROFILE=pimox
|
||||
Environment=KUBECONFIG=/home/jv/.kube/pimox-config
|
||||
Environment=LAB_KUBECONFIG_PATH=/home/jv/.kube/pimox-config
|
||||
Environment=LAB_SELF_HEAL_HOST=0.0.0.0
|
||||
Environment=LAB_SELF_HEAL_PORT=18081
|
||||
Environment=LAB_SELF_HEAL_APPLY=false
|
||||
|
|
|
|||
|
|
@ -3601,11 +3601,17 @@ model_observe() {
|
|||
|
||||
heal() {
|
||||
require_debian_server "heal"
|
||||
export LAB_CLUSTER_PROFILE
|
||||
export KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH}}"
|
||||
export LAB_KUBECONFIG_PATH="${KUBECONFIG}"
|
||||
"${REPO_ROOT}/scripts/heal" "${@:2}"
|
||||
}
|
||||
|
||||
self_heal() {
|
||||
require_debian_server "self-heal"
|
||||
export LAB_CLUSTER_PROFILE
|
||||
export KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH}}"
|
||||
export LAB_KUBECONFIG_PATH="${KUBECONFIG}"
|
||||
if [ "${2:-}" = "install-service" ]; then
|
||||
local apply_mode
|
||||
local service_file
|
||||
|
|
@ -3614,9 +3620,48 @@ self_heal() {
|
|||
if [ "${3:-}" = "--apply" ]; then
|
||||
apply_mode="true"
|
||||
fi
|
||||
if [[ "${apply_mode}" != true && "${apply_mode}" != false ]]; then
|
||||
echo "LAB_SELF_HEAL_APPLY must be true or false." >&2
|
||||
return 2
|
||||
fi
|
||||
if [[ ! -r "${KUBECONFIG}" ]]; then
|
||||
echo "Self-heal kubeconfig is not readable: ${KUBECONFIG}" >&2
|
||||
return 1
|
||||
fi
|
||||
service_file="$(mktemp)"
|
||||
sed "s/^Environment=LAB_SELF_HEAL_APPLY=.*/Environment=LAB_SELF_HEAL_APPLY=${apply_mode}/" \
|
||||
"${REPO_ROOT}/infra/jeannie-eventd/jeannie-eventd.service" > "${service_file}"
|
||||
if ! python3 - "${REPO_ROOT}/infra/jeannie-eventd/jeannie-eventd.service" \
|
||||
"${REPO_ROOT}" "${LAB_CLUSTER_PROFILE}" "${KUBECONFIG}" "${apply_mode}" >"${service_file}" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
template, repo, profile, kubeconfig, apply_mode = sys.argv[1:]
|
||||
|
||||
def quote_unit(value):
|
||||
if "\n" in value or "\r" in value:
|
||||
raise SystemExit("Invalid newline in self-heal service setting")
|
||||
return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + '"'
|
||||
|
||||
replacements = {
|
||||
"WorkingDirectory": quote_unit(repo),
|
||||
"ExecStart": quote_unit(repo + "/scripts/jeannie-eventd") + " serve",
|
||||
"Environment=LAB_CLUSTER_PROFILE": quote_unit("LAB_CLUSTER_PROFILE=" + profile),
|
||||
"Environment=KUBECONFIG": quote_unit("KUBECONFIG=" + kubeconfig),
|
||||
"Environment=LAB_KUBECONFIG_PATH": quote_unit("LAB_KUBECONFIG_PATH=" + kubeconfig),
|
||||
"Environment=LAB_SELF_HEAL_APPLY": quote_unit("LAB_SELF_HEAL_APPLY=" + apply_mode),
|
||||
}
|
||||
for line in Path(template).read_text().splitlines():
|
||||
for key, value in replacements.items():
|
||||
if line.startswith(key + "="):
|
||||
prefix = "Environment" if key.startswith("Environment=") else key
|
||||
line = prefix + "=" + value
|
||||
break
|
||||
print(line)
|
||||
PY
|
||||
then
|
||||
rm -f "${service_file}"
|
||||
echo "Self-heal service rendering failed; existing service preserved." >&2
|
||||
return 1
|
||||
fi
|
||||
sudo install -m 0644 "${service_file}" /etc/systemd/system/jeannie-eventd.service
|
||||
rm -f "${service_file}"
|
||||
sudo systemctl daemon-reload
|
||||
|
|
|
|||
14
scripts/heal
14
scripts/heal
|
|
@ -15,8 +15,10 @@ from pathlib import Path
|
|||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_KUBECONFIG = Path(
|
||||
os.environ.get(
|
||||
"KUBECONFIG", os.environ.get("LAB_KUBECONFIG_PATH", "/home/jv/.kube/config")
|
||||
os.environ.get("KUBECONFIG")
|
||||
or os.environ.get("LAB_KUBECONFIG_PATH")
|
||||
or Path.home() / ".kube" / (
|
||||
"pimox-config" if os.environ.get("LAB_CLUSTER_PROFILE") == "pimox" else "config"
|
||||
)
|
||||
)
|
||||
STATE_DIR = Path(
|
||||
|
|
@ -661,6 +663,14 @@ def verify_healed(target: dict[str, object]) -> bool:
|
|||
|
||||
def target_is_healed(target: dict[str, object]) -> bool:
|
||||
command = str(target.get("command") or "")
|
||||
if command == "./jeannie heal cleanup-stale-pods --yes":
|
||||
try:
|
||||
eligible, _ = stale_pods()
|
||||
except SystemExit:
|
||||
return False
|
||||
# Pending workloads are a separate scheduling issue and cannot be
|
||||
# fixed by removing terminal residual pod records.
|
||||
return not eligible
|
||||
worker_match = re.search(r"\bworkers\s+restart\s+(\d+)\b", command)
|
||||
if worker_match:
|
||||
return pimox_worker_ready(int(worker_match.group(1)))
|
||||
|
|
|
|||
|
|
@ -46,6 +46,12 @@ DISK_SELF_HEAL_ALERTS = {
|
|||
"FreeDiskSpaceFailed",
|
||||
}
|
||||
|
||||
STALE_POD_SELF_HEAL_ALERTS = {
|
||||
"HomelabStaleResidualPods",
|
||||
"KubePodContainerStatusUnknown",
|
||||
"KubePodEvicted",
|
||||
}
|
||||
|
||||
# Debian is intentionally monitored but excluded from automatic disk cleanup:
|
||||
# its constrained root/data layout has no safe generic deletion target. Keep
|
||||
# this list explicit so adding another host cannot accidentally enable cleanup.
|
||||
|
|
@ -184,11 +190,14 @@ def run_command(command: list[str], audit_dir: Path, name: str) -> subprocess.Co
|
|||
cwd=REPO_ROOT,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n")
|
||||
write_text(audit_dir / f"{name}.log", process.stdout)
|
||||
# Doctor stdout is parsed as JSON by scripts/heal. Startup diagnostics
|
||||
# (including OCI config notices) must not be merged into that document.
|
||||
write_text(audit_dir / f"{name}.stderr.log", process.stderr)
|
||||
write_text(audit_dir / f"{name}.status", f"{process.returncode}\n")
|
||||
return process
|
||||
|
||||
|
|
@ -222,7 +231,13 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]:
|
|||
|
||||
disk_command = disk_self_heal_command(payload, set(names))
|
||||
api_command = api_self_heal_command(set(names))
|
||||
direct_command = disk_command or api_command
|
||||
# An eviction cleanup alert must not select an unrelated host restart from
|
||||
# the broad doctor report. Cleanup performs its own ownership/state checks.
|
||||
pod_command = (
|
||||
["./jeannie", "heal", "cleanup-stale-pods", "--yes"]
|
||||
if set(names) & STALE_POD_SELF_HEAL_ALERTS else None
|
||||
)
|
||||
direct_command = disk_command or api_command or pod_command
|
||||
# Disk alerts are deliberately target-specific. Do not fall through to
|
||||
# the generic doctor/heal planner when the alert does not identify a
|
||||
# Pimox node that Jeannie can clean safely. A generic heal action could
|
||||
|
|
@ -249,7 +264,7 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]:
|
|||
apply_result = run_command(
|
||||
direct_command,
|
||||
audit_dir,
|
||||
"disk-heal" if disk_command else "api-heal",
|
||||
"disk-heal" if disk_command else "api-heal" if api_command else "pod-heal",
|
||||
)
|
||||
result["status"] = "applied" if apply_result.returncode == 0 else "apply_failed"
|
||||
result["mode"] = "apply"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,103 @@
|
|||
"""Self-heal cluster selection and webhook routing regressions (Debian runner)."""
|
||||
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def load_script(filename, name):
|
||||
loader = importlib.machinery.SourceFileLoader(name, str(REPO / "scripts" / filename))
|
||||
spec = importlib.util.spec_from_loader(name, loader)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class SelfHealContextTests(unittest.TestCase):
|
||||
def heal(self, **env):
|
||||
defaults = {"LAB_CLUSTER_PROFILE": "pimox", "KUBECONFIG": "", "LAB_KUBECONFIG_PATH": ""}
|
||||
defaults.update(env)
|
||||
with patch.dict(os.environ, defaults):
|
||||
return load_script("heal", "self_heal_context_test")
|
||||
|
||||
def test_existing_pimox_service_without_kubeconfig_uses_pimox_fallback(self):
|
||||
module = self.heal()
|
||||
self.assertEqual(module.DEFAULT_KUBECONFIG, Path.home() / ".kube/pimox-config")
|
||||
|
||||
def test_explicit_kubeconfig_takes_precedence(self):
|
||||
module = self.heal(KUBECONFIG="/tmp/explicit-config", LAB_KUBECONFIG_PATH="/tmp/lab-config")
|
||||
self.assertEqual(module.DEFAULT_KUBECONFIG, Path("/tmp/explicit-config"))
|
||||
|
||||
def test_lab_path_is_used_when_kubeconfig_is_empty(self):
|
||||
module = self.heal(LAB_KUBECONFIG_PATH="/tmp/lab-config")
|
||||
self.assertEqual(module.DEFAULT_KUBECONFIG, Path("/tmp/lab-config"))
|
||||
|
||||
def test_pending_workloads_do_not_fail_successful_residual_cleanup(self):
|
||||
module = self.heal()
|
||||
with patch.object(module, "stale_pods", return_value=([], [])), \
|
||||
patch.object(module, "load_status") as status:
|
||||
self.assertTrue(module.target_is_healed({"command": "./jeannie heal cleanup-stale-pods --yes"}))
|
||||
status.assert_not_called()
|
||||
|
||||
def test_remaining_eligible_residual_fails_cleanup_verification(self):
|
||||
module = self.heal()
|
||||
with patch.object(module, "stale_pods", return_value=([{"reason": "Evicted"}], [])):
|
||||
self.assertFalse(module.target_is_healed({"command": "./jeannie heal cleanup-stale-pods --yes"}))
|
||||
|
||||
|
||||
class WebhookRoutingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.module = load_script("jeannie-eventd", "self_heal_webhook_test")
|
||||
self.payload = {"alerts": [{"labels": {"alertname": "HomelabStaleResidualPods"}}]}
|
||||
|
||||
def test_doctor_json_and_oci_notice_are_stored_separately(self):
|
||||
completed = subprocess.CompletedProcess([], 0, stdout='{"rows": []}\n', stderr="OCI foundation config=...\n")
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
audit = Path(temporary)
|
||||
with patch.object(self.module.subprocess, "run", return_value=completed) as run:
|
||||
self.module.run_command(["./jeannie", "doctor-homelab", "--json"], audit, "doctor")
|
||||
self.assertEqual(json.loads((audit / "doctor.log").read_text()), {"rows": []})
|
||||
self.assertIn("OCI foundation config", (audit / "doctor.stderr.log").read_text())
|
||||
self.assertEqual(run.call_args.kwargs["stderr"], subprocess.PIPE)
|
||||
|
||||
def test_eviction_alert_selects_cleanup_without_broad_doctor_or_restart(self):
|
||||
completed = subprocess.CompletedProcess([], 0, stdout="cleanup complete", stderr="")
|
||||
with tempfile.TemporaryDirectory() as temporary, \
|
||||
patch.object(self.module, "EVENT_DIR", Path(temporary)), \
|
||||
patch.object(self.module, "run_command", return_value=completed) as run:
|
||||
result = self.module.handle_payload(self.payload, apply=True)
|
||||
self.assertEqual(result["status"], "applied")
|
||||
self.assertEqual(run.call_count, 1)
|
||||
self.assertEqual(run.call_args.args[0], ["./jeannie", "heal", "cleanup-stale-pods", "--yes"])
|
||||
|
||||
def test_dry_run_event_never_executes_cleanup(self):
|
||||
with tempfile.TemporaryDirectory() as temporary, \
|
||||
patch.object(self.module, "EVENT_DIR", Path(temporary)), \
|
||||
patch.object(self.module, "run_command") as run:
|
||||
result = self.module.handle_payload(self.payload, apply=False)
|
||||
self.assertEqual(result["mode"], "dry-run")
|
||||
run.assert_not_called()
|
||||
|
||||
def test_disabled_debian_disk_cleanup_does_not_fall_through_to_pod_cleanup(self):
|
||||
self.payload["alerts"].append({"labels": {"alertname": "HomelabHostFilesystemNearlyFull", "node": "debian"}})
|
||||
with tempfile.TemporaryDirectory() as temporary, \
|
||||
patch.object(self.module, "EVENT_DIR", Path(temporary)), \
|
||||
patch.object(self.module, "run_command") as run:
|
||||
result = self.module.handle_payload(self.payload, apply=True)
|
||||
self.assertEqual(result["status"], "skipped")
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue