release: clean installer (no cron/timer/watchdog) + latest plugin files

- Removed: connector. (artifact)
- Updated: __init__.py, client.py, config.py, install.sh, plugin.yaml
- install.sh: no systemd-timer, no watchdog — continuous service with Restart=always
- Added: tests/

@implements: [F-798]
This commit is contained in:
Bernd
2026-10-24 10:25:27 +02:00
parent e76096c584
commit c1d4d0bf6e
6 changed files with 1199 additions and 243 deletions
+318 -112
View File
@@ -1,136 +1,342 @@
#!/bin/bash
#!/usr/bin/env bash
# =============================================================================
# PMDB Connector Plugin — Installer
# @implements: [F454]
#
# Kopiert das Plugin (__init__.py, client.py, config.py, plugin.yaml, tests/)
# nach ~/.hermes/profiles/<agent>/plugins/pmdb_connector/ und richtet die
# Token-Konfiguration ein:
#
# 1. mcp_tokens.json (KANONISCHE Quelle, F590) -> agenten.<agent>.token
# 2. config.yaml (Fallback, F526) -> pmdb_connector.auth_keys.<agent>
#
# Danach optionaler curl-Test gegen den get_tasks-Endpoint.
#
# Verwendung:
# ./install.sh
# ./install.sh --agent miguel --token 'mcp_miguel_...' --api-url 'https://...'
# ./install.sh --source /pfad/zum/plugin --skip-curl --yes
#
# Hinweis zur base_url (P-NEW-CONNECTOR-MCP-SUFFIX):
# Der Client haengt selbst /mcp/api/... an die base_url an. Deshalb darf die
# base_url KEIN abschliessendes /mcp enthalten. Empfohlen:
# - intern (LAN): http://192.168.180.49:8099
# - via Proxy: https://pmdb.myowntools.org (ohne /mcp!)
# =============================================================================
set -euo pipefail
echo "Checking reachability of PMDB public route..."
if curl -s --head --request GET https://pmdb.myowntools.org | grep "200 OK" > /dev/null; then
echo "Public route is reachable."
else
echo "WARNING: Public route is not reachable. Installation might fail or connector won't start."
fi
# ---------------------------------------------------------------------------
# Defaults + Konfiguration
# ---------------------------------------------------------------------------
DEFAULT_API_URL="https://pmdb.myowntools.org/mcp"
PLUGIN_FILES=("__init__.py" "client.py" "config.py" "plugin.yaml")
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
set -e
AGENT=""
TOKEN=""
API_URL=""
SOURCE_DIR="$SCRIPT_DIR"
SKIP_CURL=0
ASSUME_YES=0
PROFILE=$1
if [ -z "$PROFILE" ]; then
echo "Usage: ./install.sh <profile> [--yes-deps]"
exit 1
fi
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
info() { printf '\033[1;32m[INFO]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*"; }
error() { printf '\033[1;31m[ERROR]\033[0m %s\n' "$*" >&2; }
# B-7 Consent-Ebene: optionale Dependencies werden nur mit ausdruecklicher
# Zustimmung (--yes-deps) nachinstalliert. Ohne Flag bleibt der Venv-Check
# beobachtend (kein Install ins Gateway-venv).
YES_DEPS=0
for _arg in "$@"; do
[ "$_arg" = "--yes-deps" ] && YES_DEPS=1
usage() {
cat <<'EOF'
PMDB Connector Plugin — Installer
Optionen:
--agent <name> Agent-/Profil-Name (sonst interaktiv)
--token <token> PMDB-Bearer-Token (sonst interaktiv, verdeckte Eingabe)
--api-url <url> PMDB MCP base_url (Default: https://pmdb.myowntools.org/mcp)
--source <dir> Quellverzeichnis der Plugin-Dateien (Default: dieses Verzeichnis)
--skip-curl curl-Verbindungstest ueberspringen
--yes, -y Nicht-interaktiv (keine Rueckfragen)
--help, -h Diese Hilfe
EOF
}
# Ermittelt das aktive Profil aus HERMES_HOME (Fallback: leer -> Eingabe noetig).
detect_agent() {
if [[ -n "${HERMES_HOME:-}" ]]; then
local parent
parent="$(basename "$(dirname "$HERMES_HOME")")"
if [[ "$parent" == "profiles" ]]; then
basename "$HERMES_HOME"
return 0
fi
fi
echo ""
}
# Basis-Verzeichnis (~/.hermes bzw. HERMES_HOME-Basis) bestimmen.
hermes_base() {
if [[ -n "${HERMES_HOME:-}" ]]; then
local parent
parent="$(basename "$(dirname "$HERMES_HOME")")"
if [[ "$parent" == "profiles" ]]; then
# HERMES_HOME zeigt auf ein Profil -> Basis ist parent.parent.
dirname "$(dirname "$HERMES_HOME")"
return 0
fi
echo "$HERMES_HOME"
return 0
fi
echo "$HOME/.hermes"
}
# ---------------------------------------------------------------------------
# Argument-Parsing
# ---------------------------------------------------------------------------
while [[ $# -gt 0 ]]; do
case "$1" in
--agent) AGENT="$2"; shift 2 ;;
--token) TOKEN="$2"; shift 2 ;;
--api-url) API_URL="$2"; shift 2 ;;
--source) SOURCE_DIR="$2"; shift 2 ;;
--skip-curl) SKIP_CURL=1; shift ;;
--yes|-y) ASSUME_YES=1; shift ;;
--help|-h) usage; exit 0 ;;
*) error "Unbekannte Option: $1"; usage; exit 1 ;;
esac
done
echo "Installing PMDB SSE Connector for profile: $PROFILE"
info "PMDB Connector Plugin — Installer"
# 1. Venv
VENV_PATH="$HOME/pmdb-sse-connector/venv"
python3 -m venv $VENV_PATH
$VENV_PATH/bin/pip install --upgrade pip
# ---------------------------------------------------------------------------
# 1. Interaktive Abfragen (nur wenn nicht via Flag gesetzt)
# ---------------------------------------------------------------------------
if [[ -z "$AGENT" ]]; then
local_detected="$(detect_agent)"
if [[ -n "$local_detected" ]]; then
read -r -p "Agent-/Profil-Name [${local_detected}]: " AGENT
AGENT="${AGENT:-$local_detected}"
else
read -r -p "Agent-/Profil-Name: " AGENT
fi
fi
[[ -z "$AGENT" ]] && { error "Agent-Name darf nicht leer sein."; exit 1; }
# 2. Systemd User Unit
UNIT_FILE="$HOME/.config/systemd/user/pmdb-sse-connector@${PROFILE}.service"
mkdir -p $(dirname $UNIT_FILE)
if [[ -z "$TOKEN" ]]; then
read -r -s -p "PMDB-Bearer-Token (verdeckte Eingabe): " TOKEN
echo
fi
[[ -z "$TOKEN" ]] && { error "Token darf nicht leer sein."; exit 1; }
cat <<EOF > $UNIT_FILE
[Unit]
Description=PMDB SSE Connector for %i
After=network-online.target
if [[ -z "$API_URL" ]]; then
read -r -p "PMDB MCP base_url [${DEFAULT_API_URL}]: " API_URL
API_URL="${API_URL:-$DEFAULT_API_URL}"
fi
# base_url ohne abschliessenden Slash speichern (client.py rstrippt ohnehin).
API_URL="$(printf '%s' "$API_URL" | sed 's#/*$##')"
[Service]
Type=simple
WorkingDirectory=$HOME/pmdb-sse-connector
ExecStart=$VENV_PATH/bin/python3 connector.py --profile %i
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1
KillMode=process
Environment=PMDB_RUN_TIMEOUT_S=300
# ---------------------------------------------------------------------------
# 2. Plugin-Dateien kopieren
# ---------------------------------------------------------------------------
BASE="$(hermes_base)"
TARGET="$BASE/profiles/$AGENT/plugins/pmdb_connector"
CONFIG_PATH="$BASE/profiles/$AGENT/config.yaml"
TOKENS_PATH="$BASE/mcp_tokens.json"
Environment=PATH=$HOME/.hermes/tools/python-3.14.7+20260901-linux-x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
if [[ ! -d "$SOURCE_DIR" ]]; then
error "Quellverzeichnis nicht gefunden: $SOURCE_DIR"
exit 1
fi
for f in "${PLUGIN_FILES[@]}"; do
[[ -f "$SOURCE_DIR/$f" ]] || { error "Plugin-Datei fehlt im Quellverzeichnis: $f"; exit 1; }
done
[Install]
WantedBy=default.target
EOF
# R6-2b: Verdrahtung versionieren — Drop-in (override.conf) mit dem %i-Vertrag
# (PROFILE=NAME, PROFILE_DIR=Pfad) wird MIT erzeugt. Ohne Drop-in zerstoert ein
# kuenftiger install.sh-Lauf den produktiven Weg (Basis-Unit ohne Verdrahtung).
# Inhalt = versionierte Kopie von systemd/pmdb-sse-connector@.service.d/override.conf.
DROPIN_DIR="$HOME/.config/systemd/user/pmdb-sse-connector@.service.d"
mkdir -p "$DROPIN_DIR"
cat <<'DROPIN_EOF' > "$DROPIN_DIR/override.conf"
[Service]
Environment=PROFILE=%i
Environment=PROFILE_DIR=$HOME/pmdb-sse-connector
ExecStartPost=$HOME/pmdb-sse-connector/scripts/post_venv_check.sh
DROPIN_EOF
# 3. Watchdog (quoted heredoc: keine Shell-Expansion im Zieldatei-Inhalt)
WATCHDOG_PATH="/usr/local/bin/pmdb-connector-watchdog.sh"
sudo tee "$WATCHDOG_PATH" > /dev/null <<'WATCHDOG_EOF'
#!/bin/bash
# F-XXX (P-NEW-F-XXX-HBSHARE): Heartbeat-Datei PRO Profil (Suffix).
HB_FILE="/tmp/pmdb-sse-hb-$1"
if [ ! -f "$HB_FILE" ]; then
systemctl --user restart pmdb-sse-connector@$1
exit 0
info "Kopiere Plugin-Dateien nach $TARGET"
mkdir -p "$TARGET"
for f in "${PLUGIN_FILES[@]}"; do
cp -f "$SOURCE_DIR/$f" "$TARGET/$f"
done
if [[ -d "$SOURCE_DIR/tests" ]]; then
mkdir -p "$TARGET/tests"
cp -f "$SOURCE_DIR"/tests/*.py "$TARGET/tests/" 2>/dev/null || true
fi
LAST_HB=$(cat "$HB_FILE")
NOW=$(date +%s)
# %% = kuerzt am ERSTEN Punkt (kein Float-Rest bei konkatenierten Timestamps).
DIFF=$((NOW - ${LAST_HB%%.*}))
# P-001: stale __pycache__/ .pyc vor UND nach Deploy entfernen (sonst laedt
# Hermes alten Bytecode statt des frischen Codes).
find "$TARGET" -name __pycache__ -type d -exec rm -rf {} + 2>/dev/null || true
find "$TARGET" -name '*.pyc' -delete 2>/dev/null || true
if [ "$DIFF" -gt 300 ]; then
systemctl --user restart pmdb-sse-connector@$1
fi
WATCHDOG_EOF
sudo chmod +x "$WATCHDOG_PATH"
info "Plugin-Dateien installiert:"
for f in "${PLUGIN_FILES[@]}"; do
printf ' - %s\n' "$TARGET/$f"
done
# 4. Watchdog Timer (systemd-timer)
TIMER_FILE="$HOME/.config/systemd/user/pmdb-sse-connector@${PROFILE}.timer"
cat <<EOF > $TIMER_FILE
[Unit]
Description=Watchdog Timer for PMDB SSE Connector %i
# ---------------------------------------------------------------------------
# 3. Token-Konfiguration schreiben (config.yaml + mcp_tokens.json)
# ---------------------------------------------------------------------------
info "Schreibe Token-Konfiguration ..."
[Timer]
OnCalendar=*:0/1
Unit=pmdb-sse-connector@%i.service
python3 - "$CONFIG_PATH" "$TOKENS_PATH" "$AGENT" "$TOKEN" "$API_URL" <<'PYEOF'
import json, os, re, shutil, sys
[Install]
WantedBy=timers.target
EOF
systemctl --user enable pmdb-sse-connector@${PROFILE}.timer
def main():
config_path, tokens_path, agent, token, base_url = sys.argv[1:6]
try:
import yaml
except ImportError:
yaml = None
# Token Check (Fail-fast)
TOKEN_FILE="$HOME/.hermes/mcp_tokens.json"
if [ ! -f "$TOKEN_FILE" ]; then
echo "-----------------------------------------------------------------------"
echo "ERROR: MCP Token file not found at $TOKEN_FILE"
echo "The service will crash cyclically without a valid token."
echo "Please create the file with the following structure:"
echo "{"
echo " "agenten": {"
echo " "$PROFILE": { "token": "your-token-here" }"
echo " }"
echo "}"
echo "-----------------------------------------------------------------------"
exit 1
# ---- config.yaml: pmdb_connector-Sektion (kommentar-erhaltend) ----
if os.path.exists(config_path):
with open(config_path, encoding="utf-8") as f:
lines = f.read().splitlines()
else:
lines = []
# Spanne der Top-Level-Sektion "pmdb_connector:" ermitteln (nur Spalte 0,
# damit "plugins.entries.pmdb_connector" und "- pmdb_connector" NICHT
# getroffen werden).
start = end = None
for i, ln in enumerate(lines):
if ln and not ln[0].isspace() and ln.split(":")[0].strip() == "pmdb_connector":
start = i
end = len(lines)
for j in range(i + 1, len(lines)):
if lines[j] and not lines[j][0].isspace():
end = j
break
break
section = {}
if start is not None and yaml is not None:
# Nur den Sektions-BODY parsen (ohne die "pmdb_connector:"-Kopfzeile),
# sonst entsteht eine verschachtelte {"pmdb_connector": {...}}-Dict.
block = "\n".join(lines[start + 1:end])
try:
loaded = yaml.safe_load(block)
if isinstance(loaded, dict):
section = loaded
except Exception:
section = {}
# Merge: base_url neu, Token fuer diesen Agenten, bestehende auth_keys
# anderer Agenten bleiben erhalten (F526-Fallback bleibt multi-agent-faehig).
section["base_url"] = base_url
ak = section.get("auth_keys")
if not isinstance(ak, dict):
ak = {}
ak[agent] = token
section["auth_keys"] = ak
section.setdefault("manager_profiles", ["bernd", "andreas"])
if yaml is not None:
dumped = yaml.safe_dump(
{"pmdb_connector": section}, sort_keys=False, allow_unicode=True,
default_flow_style=False)
new_block = dumped.rstrip("\n").splitlines()
else:
# Fallback ohne PyYAML: schlichte Zeilen (andere auth_keys gehen verloren,
# aber mcp_tokens.json bleibt kanonische Quelle).
new_block = ["pmdb_connector:",
f" base_url: {base_url}",
" auth_keys:",
f" {agent}: {token}",
" manager_profiles: [bernd, andreas]"]
if start is not None:
new_lines = lines[:start] + new_block + lines[end:]
else:
new_lines = list(lines)
if new_lines and new_lines[-1].strip() != "":
new_lines.append("")
new_lines += new_block
if os.path.exists(config_path):
shutil.copy2(config_path, config_path + ".bak-install")
with open(config_path, "w", encoding="utf-8") as f:
f.write("\n".join(new_lines) + "\n")
# ---- mcp_tokens.json: agenten.<agent>.token (F590, kanonisch) ----
tokens = {}
if os.path.exists(tokens_path):
try:
with open(tokens_path, encoding="utf-8") as f:
tokens = json.load(f)
except (OSError, ValueError):
tokens = {}
if not isinstance(tokens, dict):
tokens = {}
agenten = tokens.get("agenten")
if not isinstance(agenten, dict):
agenten = {}
entry = agenten.get(agent)
if not isinstance(entry, dict):
entry = {}
entry["token"] = token
entry.setdefault("token_prefix", agent)
agenten[agent] = entry
tokens["agenten"] = agenten
tokens.setdefault(
"kommentar",
"MCP-Bootstrap-Tokens (F531). Klartext NUR in dieser Datei \u2014 nicht "
"committen, nicht in Repos, nicht in Logs. Generiert auf .49.")
if os.path.exists(tokens_path):
shutil.copy2(tokens_path, tokens_path + ".bak-install")
with open(tokens_path, "w", encoding="utf-8") as f:
json.dump(tokens, f, ensure_ascii=False, indent=2)
f.write("\n")
print("OK")
if __name__ == "__main__":
main()
PYEOF
info "Konfiguration geschrieben:"
printf ' config.yaml -> %s\n' "$CONFIG_PATH"
printf ' mcp_tokens.json -> %s\n' "$TOKENS_PATH"
# ---------------------------------------------------------------------------
# 4. curl-Verbindungstest (get_tasks-Endpoint, exakt wie client.py)
# ---------------------------------------------------------------------------
if [[ "$SKIP_CURL" -eq 1 ]]; then
warn "curl-Test uebersprungen (--skip-curl)."
exit 0
fi
# 5. Activation
systemctl --user daemon-reload
systemctl --user enable pmdb-sse-connector@${PROFILE}.service
systemctl --user enable pmdb-sse-connector@${PROFILE}.timer
systemctl --user restart pmdb-sse-connector@${PROFILE}.service
TEST_URL="$API_URL/mcp/api/tasks"
info "Teste Verbindung: GET $TEST_URL"
HTTP="$(curl -sS -o /tmp/pmdb_connector_test_body.json -w '%{http_code}' \
--max-time 10 -H "Authorization: Bearer $TOKEN" "$TEST_URL" 2>/tmp/pmdb_connector_test_err.txt || true)"
# B-8: Trigger post-install venv check (Consent-gated: YES_DEPS)
export PROFILE=${PROFILE}
export YES_DEPS=${YES_DEPS}
$HOME/pmdb-sse-connector/scripts/post_venv_check.sh
case "$HTTP" in
200)
info "Verbindung OK (HTTP 200) — Token wird akzeptiert."
;;
401)
error "HTTP 401 — Token ungueltig oder widerrufen (auth_invalid)."
warn "Pruefe den Token. Hinweis: Der Openresty-Proxy (pmdb.myowntools.org) "
warn "blockt Bearer-Tokens (P-NEW-F563-PMDB-AUTH) — intern "
warn "http://192.168.180.49:8099 verwenden."
;;
404)
error "HTTP 404 — Endpoint nicht gefunden. Vermutlich doppeltes /mcp."
warn "Der Client haengt selbst /mcp/api/... an die base_url an. Nutze die "
warn "base_url OHNE /mcp, z.B. http://192.168.180.49:8099 oder "
warn "https://pmdb.myowntools.org."
;;
"")
error "Keine Antwort — Netzwerk/Timeout. Detail:"
cat /tmp/pmdb_connector_test_err.txt 2>/dev/null || true
;;
*)
warn "HTTP $HTTP — Antwort (Auszug):"
head -c 300 /tmp/pmdb_connector_test_body.json 2>/dev/null || true
echo
;;
esac
echo "Installation complete. Service is running."
info "Installation abgeschlossen fuer Agent '$AGENT'."