"""Agentless Linux host collector over SSH (key authentication).""" from __future__ import annotations import subprocess from pathlib import Path from typing import Any, Dict from app import sdk SCRIPT = r""" set -e echo "__NPROC__" nproc echo "__MEM__" awk '/MemTotal/{t=$2} /MemAvailable/{a=$2} /MemFree/{f=$2} END{if(!a)a=f; print t, a}' /proc/meminfo echo "__DISK__" df -P -B1 / | awk 'NR==2 {print $2, $3}' echo "__UPTIME__" awk '{print $1}' /proc/uptime echo "__LOAD__" awk '{print $1}' /proc/loadavg echo "__OS__" uname -sr echo "__CPU1__" awk '/^cpu / {s=0; for(i=2;i<=NF;i++) s+=$i; print s, $5+$6}' /proc/stat sleep 1 echo "__CPU2__" awk '/^cpu / {s=0; for(i=2;i<=NF;i++) s+=$i; print s, $5+$6}' /proc/stat """ def _ssh(config: Dict[str, Any], command: str, timeout: int = 40) -> str: host = str(config.get("host", "")).strip() user = str(config.get("username", "")).strip() if not host or not user: raise sdk.ModuleError("Configure host and SSH username") key_path = str(config.get("key_path", "")).strip() if not key_path: key_path = "~/.ssh/id_ed25519" key = Path(key_path).expanduser() if not key.exists(): raise sdk.ModuleError(f"SSH private key not found: {key}") command_line = [ "ssh", "-i", str(key), "-p", str(sdk.free_port(config.get("port"), 22)), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=10", "-o", "LogLevel=ERROR", f"{user}@{host}", command, ] try: result = subprocess.run(command_line, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: raise sdk.ModuleError("SSH command timed out") except FileNotFoundError: raise sdk.ModuleError("The 'ssh' client is not available on the Headroom host") if result.returncode != 0: detail = (result.stderr or result.stdout or "").strip()[-500:] raise sdk.ModuleError(f"SSH failed (exit {result.returncode}): {detail}") return result.stdout def _parse_markers(output: str) -> Dict[str, str]: values: Dict[str, str] = {} current = None buffer = [] for line in output.splitlines(): if line.startswith("__") and line.endswith("__"): if current: values[current] = "\n".join(buffer).strip() current = line.strip("_") buffer = [] elif current: buffer.append(line) if current: values[current] = "\n".join(buffer).strip() return values def collect(ctx: Dict[str, Any]) -> Dict[str, Any]: if sdk.use_demo(ctx, ["host"]): return {"assets": sdk.demo_assets(ctx), "notes": "Demo snapshot — running without an SSH endpoint"} config = ctx["config"] output = _ssh(config, SCRIPT) data = _parse_markers(output) try: nproc = max(1, int(float(data.get("NPROC", "1")))) mem_parts = data.get("MEM", "0 0").split() mem_total_kb = float(mem_parts[0]) mem_avail_kb = float(mem_parts[1]) if len(mem_parts) > 1 else 0.0 disk_parts = data.get("DISK", "0 0").split() disk_total = float(disk_parts[0]) disk_used = float(disk_parts[1]) uptime_seconds = float(data.get("UPTIME", "0").split()[0]) load1 = float(data.get("LOAD", "0").split()[0]) cpu1 = [float(x) for x in data.get("CPU1", "0 0").split()] cpu2 = [float(x) for x in data.get("CPU2", "0 0").split()] total_delta = cpu2[0] - cpu1[0] idle_delta = cpu2[1] - cpu1[1] cpu_pct = (1 - idle_delta / total_delta) * 100 if total_delta > 0 else 0.0 mem_total_bytes = mem_total_kb * 1024 mem_used_bytes = max(0.0, mem_total_bytes - mem_avail_kb * 1024) metrics = { "cpu_pct": round(max(0.0, min(100.0, cpu_pct)), 2), "mem_pct": round(sdk.percent(mem_used_bytes, mem_total_bytes), 2), "storage_pct": round(sdk.percent(disk_used, disk_total), 2), "storage_used_gb": round(disk_used / 1024 ** 3, 1), "storage_total_gb": round(disk_total / 1024 ** 3, 1), "load_pct": round(load1 / nproc * 100, 1), "uptime_days": round(uptime_seconds / 86400, 1), } except (ValueError, IndexError) as exc: raise sdk.ModuleError(f"Could not parse Linux telemetry: {exc}") host = str(config.get("host")) asset = sdk.add_asset( external_id=host, name=host.split(".")[0], type_="server", metrics=metrics, capacity={ "cpu_cores": nproc, "mem_gb": round(mem_total_bytes / 1024 ** 3, 1), "storage_gb": round(disk_total / 1024 ** 3, 1), }, cluster=config.get("cluster_name") or "Linux", tags=["linux"], meta={"os": data.get("OS", ""), "host": host}, ) return {"assets": [asset], "notes": f"Collected Linux telemetry from {host}"} def test_connection(ctx: Dict[str, Any]) -> Dict[str, Any]: if sdk.use_demo(ctx, ["host"]): return {"ok": True, "message": "Demo mode — no SSH endpoint contacted."} output = _ssh(ctx["config"], "echo connected; uname -sr", timeout=25) return {"ok": True, "message": f"SSH connection OK — {output.strip()[:120]}"}