Add push monitor script deployment via SSH
All checks were successful
Build and Push Container / build (push) Successful in 33s

- Add push_scripts.py with bash templates for heartbeat, disk, memory, cpu, and updates monitoring
- Modify kuma_client.py to return push token from created monitors
- Add deploy_push_script() to monitors.py for SSH-based script deployment
- Add heartbeat push_metric type to Claude agent suggestions
- Add /api/monitors/<id>/deploy-script and /api/monitors/deploy-all-scripts endpoints
- Update frontend to show push monitors with deployment status and retry buttons

Scripts are deployed to /usr/local/bin/kuma-push-{metric}-{id}.sh with cron entries.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Debian
2026-01-05 08:36:48 +00:00
parent 908d147235
commit ae814c1aea
7 changed files with 577 additions and 21 deletions

View File

@@ -1,8 +1,13 @@
from dataclasses import dataclass
from typing import Optional
import logging
from services.kuma_client import get_kuma_client, Monitor
from services.claude_agent import MonitorSuggestion
from services.ssh_manager import get_ssh_manager
from services import push_scripts
logger = logging.getLogger(__name__)
@dataclass
@@ -176,16 +181,42 @@ class MonitorService:
elif suggestion.type == "docker":
monitor.docker_container = suggestion.target
monitor.docker_host = hostname
elif suggestion.type == "push":
# Push monitors need the push_metric field
pass
try:
result = kuma.create_monitor(monitor)
return {
response = {
"monitor": monitor.name,
"type": monitor.type,
"status": "created",
"result": result,
"reason": suggestion.reason,
"push_metric": suggestion.push_metric,
}
# For push monitors, deploy the script to the remote host
if suggestion.type == "push" and suggestion.push_metric:
push_token = result.get("pushToken")
monitor_id = result.get("monitorID")
if push_token and monitor_id:
deploy_result = self.deploy_push_script(
hostname=hostname,
push_metric=suggestion.push_metric,
push_token=push_token,
monitor_id=monitor_id,
interval_minutes=max(1, suggestion.interval // 60),
)
response["deployment"] = deploy_result
else:
response["deployment"] = {
"status": "failed",
"error": "No push token returned from Uptime Kuma",
}
return response
except Exception as e:
return {
"monitor": monitor.name,
@@ -195,6 +226,107 @@ class MonitorService:
"reason": suggestion.reason,
}
def deploy_push_script(
self,
hostname: str,
push_metric: str,
push_token: str,
monitor_id: int,
interval_minutes: int = 5,
username: str = "root",
port: int = 22,
) -> dict:
"""
Deploy a push monitoring script to a remote host via SSH.
Args:
hostname: The remote host to deploy to
push_metric: The metric type (heartbeat, disk, memory, cpu, updates)
push_token: The Uptime Kuma push token
monitor_id: The Uptime Kuma monitor ID
interval_minutes: Cronjob interval in minutes
username: SSH username
port: SSH port
Returns:
Dict with status and any error messages
"""
kuma = get_kuma_client()
ssh = get_ssh_manager()
# Build the push URL and script
push_url = kuma.get_push_url(push_token)
script_content = push_scripts.generate_script(push_metric, push_url)
if not script_content:
return {
"status": "failed",
"error": f"Unknown push metric type: {push_metric}",
}
script_path = push_scripts.get_script_path(push_metric, monitor_id)
script_filename = push_scripts.get_script_filename(push_metric, monitor_id)
cronjob_entry = push_scripts.get_cronjob_entry(push_metric, monitor_id, interval_minutes)
try:
# Ensure SSH connection
if not ssh.is_connected(hostname, username, port):
connected = ssh.connect(hostname, username, port)
if not connected:
return {
"status": "failed",
"error": f"Could not connect to {hostname}",
}
# Write the script to the remote host using heredoc
# Escape any single quotes in the script content
escaped_content = script_content.replace("'", "'\"'\"'")
write_cmd = f"cat > {script_path} << 'KUMA_SCRIPT_EOF'\n{script_content}KUMA_SCRIPT_EOF"
result = ssh.execute(hostname, write_cmd, username, port)
if not result.success:
return {
"status": "failed",
"error": f"Failed to write script: {result.stderr}",
}
# Make the script executable
chmod_result = ssh.execute(hostname, f"chmod +x {script_path}", username, port)
if not chmod_result.success:
return {
"status": "failed",
"error": f"Failed to make script executable: {chmod_result.stderr}",
}
# Add cronjob entry (remove existing entry first to avoid duplicates)
cron_cmd = f"(crontab -l 2>/dev/null | grep -v '{script_filename}'; echo '{cronjob_entry}') | crontab -"
cron_result = ssh.execute(hostname, cron_cmd, username, port)
if not cron_result.success:
return {
"status": "failed",
"error": f"Failed to add cronjob: {cron_result.stderr}",
}
# Run the script once immediately to verify it works
run_result = ssh.execute(hostname, script_path, username, port, timeout=30)
return {
"status": "deployed",
"script_path": script_path,
"cronjob": cronjob_entry,
"initial_run": {
"success": run_result.success,
"stdout": run_result.stdout,
"stderr": run_result.stderr,
},
}
except Exception as e:
logger.exception(f"Failed to deploy push script to {hostname}")
return {
"status": "failed",
"error": str(e),
}
def get_existing_monitors(self) -> list[dict]:
"""Get all existing monitors from Uptime Kuma."""
kuma = get_kuma_client()