From d37503c86376e2c30be1cf04f505938a2ee953f9 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 1 Nov 2026 13:11:54 +0000 Subject: [PATCH] Init --- .env.example | 6 + .gitignore | 1 + CONFIGURATION.md | 432 +++++++++++++++++ Dockerfile | 25 + README.md | 101 +++- docker-compose.cloudflared.yml | 31 ++ docker-compose.yml | 13 + go.mod | 3 + internal/checker/checker.go | 661 ++++++++++++++++++++++++++ internal/checker/checker_test.go | 120 +++++ internal/config/config.go | 790 ++++++++++++++++++++++++++++++ internal/config/config_test.go | 75 +++ internal/events/engine.go | 438 +++++++++++++++++ internal/events/engine_test.go | 152 ++++++ internal/server/server.go | 793 +++++++++++++++++++++++++++++++ internal/server/server_test.go | 70 +++ internal/store/store.go | 334 +++++++++++++ internal/store/store_test.go | 58 +++ main.go | 135 ++++++ rud.json | 198 ++++++++ 20 files changed, 4433 insertions(+), 3 deletions(-) create mode 100644 .env.example create mode 100644 CONFIGURATION.md create mode 100644 Dockerfile create mode 100644 docker-compose.cloudflared.yml create mode 100644 docker-compose.yml create mode 100644 go.mod create mode 100644 internal/checker/checker.go create mode 100644 internal/checker/checker_test.go create mode 100644 internal/config/config.go create mode 100644 internal/config/config_test.go create mode 100644 internal/events/engine.go create mode 100644 internal/events/engine_test.go create mode 100644 internal/server/server.go create mode 100644 internal/server/server_test.go create mode 100644 internal/store/store.go create mode 100644 internal/store/store_test.go create mode 100644 main.go create mode 100644 rud.json diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..528482a --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +# Port exposed on the host when using the main docker-compose.yml +RUD_PORT=8080 + +# Cloudflare Tunnel token when using docker-compose.cloudflared.yml +# In the Cloudflare Zero Trust dashboard, point your tunnel's public hostname to: http://rud:8080 +TUNNEL_TOKEN=your_cloudflare_tunnel_token_here diff --git a/.gitignore b/.gitignore index 5b90e79..19cef92 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore # # Binaries for programs and plugins +/rud *.exe *.exe~ *.dll diff --git a/CONFIGURATION.md b/CONFIGURATION.md new file mode 100644 index 0000000..5966351 --- /dev/null +++ b/CONFIGURATION.md @@ -0,0 +1,432 @@ +# `rud.json` Configuration Guide + +**R u ded? (`rud`)** is configured entirely through a single JSON file (`rud.json` by default). The configuration is loaded once at startup and controls: + +1. **`server`** — The single HTTP endpoint binding, auto-refresh interval, and HTTP status codes. +2. **`storage`** — In-memory ring-buffer size and optional disk persistence. +3. **`defaults`** — Global fallback intervals, timeouts, retries, and degraded latency thresholds. +4. **`monitors`** — Health and uptime checks (`http`/`https`, `tcp`, `ping`, `dns`, `cmd`). +5. **`events`** — Declarative alert triggers (combining monitor boolean conditions, sustained durations, and metrics) and actions (`webhook`, `command`). +6. **`page`** — Minimalist styling (`theme`) and the explicit list of UI `elements` rendered on the web status page. + +> **Note:** On the web status page, **only** the elements explicitly listed in `page.elements` are rendered (plus the `'Powered by R u ded?'` attribution footer). If `rud.json` does not exist when `rud` starts (or when you run `rud -init`), a sensible default `rud.json` is generated automatically. + +--- + +## Duration Format + +All duration fields in `rud.json` accept human-readable Go duration strings: +- `"500ms"` (500 milliseconds) +- `"10s"` (10 seconds) +- `"5m"` (5 minutes) +- `"5h"` (5 hours) +- `"1h30m"` (1 hour 30 minutes) + +--- + +## 1. `server` Section + +Controls the single HTTP endpoint served by `rud`. + +```json +"server": { + "listen": ":8080", + "endpoint": "/", + "refresh_interval": "10s", + "status_codes": { + "html": { + "up": 200, + "degraded": 200, + "down": 200, + "pending": 200 + }, + "json": { + "up": 200, + "degraded": 200, + "down": 503, + "pending": 200 + } + } +} +``` + +| Field | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `listen` | `string` | `":8080"` | TCP address and port to bind (`"127.0.0.1:8080"`, `":8080"`). | +| `endpoint` | `string` | `"/"` | The single HTTP path served. All other paths return `404 Not Found`. | +| `refresh_interval` | `Duration` | `"10s"` | Browser live-update polling interval (fetches `?format=json`). Set to `"0s"` to disable client-side polling. | +| `status_codes.html` | `object` | `200` for all | HTTP status codes returned for HTML requests per global state (`up`, `degraded`, `down`, `pending`). Keeping HTML at `200` prevents Cloudflare Tunnel from replacing your status page with a Cloudflare 5xx error page. | +| `status_codes.json` | `object` | `200` (`503` on `down`) | HTTP status codes returned when JSON is requested via `Accept: application/json` or `?format=json`. | + +--- + +## 2. `storage` Section + +Controls the in-memory check history ring buffer and optional state persistence across restarts. + +```json +"storage": { + "history_size": 60, + "persistence_file": "./data/rud_state.json", + "save_interval": "1m" +} +``` + +| Field | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `history_size` | `int` | `60` | Maximum number of recent check results retained in memory per monitor. | +| `persistence_file` | `string` | `""` (disabled) | Optional file path to save and restore monitor state and history across restarts. Leave empty (`""`) for pure in-memory operation. | +| `save_interval` | `Duration` | `"1m"` | How often state is written to `persistence_file` (also saved automatically on graceful shutdown). | + +--- + +## 3. `defaults` Section + +Provides fallback check settings when a monitor omits them. + +```json +"defaults": { + "interval": "15s", + "timeout": "5s", + "retries": 1, + "degraded_latency": "750ms" +} +``` + +| Field | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `interval` | `Duration` | `"30s"` | How often each monitor check runs. | +| `timeout` | `Duration` | `"5s"` | Per-attempt timeout for a check. | +| `retries` | `int` | `1` | Number of immediate retry attempts before marking a monitor as `"down"`. | +| `degraded_latency` | `Duration` | `"1000ms"` | If a check succeeds but takes longer than this threshold, its state becomes `"degraded"`. | + +--- + +## 4. `monitors` Section + +An array of health checks. Every monitor shares these base fields: + +| Field | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| `id` | `string` | **Yes** | Unique identifier for the monitor (referenced in `page.elements` and `events`). | +| `name` | `string` | No | Friendly display name (defaults to `id`). | +| `description` | `string` | No | Short description shown when `show_description` is enabled. | +| `link` | `string` | No | Optional URL to link the monitor's name to on the status page. | +| `method` | `string` | **Yes** | Check method: `"http"`, `"https"`, `"tcp"`, `"ping"`, `"dns"`, or `"cmd"`. | +| `interval` | `Duration` | No | Overrides `defaults.interval`. | +| `timeout` | `Duration` | No | Overrides `defaults.timeout`. | +| `retries` | `int` | No | Overrides `defaults.retries`. | +| `degraded_latency` | `Duration` | No | Overrides `defaults.degraded_latency`. | + +### Method 1: HTTP / HTTPS (`"method": "http"` or `"https"`) + +```json +{ + "id": "main-api", + "name": "Core API", + "method": "https", + "url": "https://api.gsdistance.org/health", + "http_method": "GET", + "expected_status": [200, 204], + "headers": { + "Authorization": "Bearer secret-token", + "X-Custom-Header": "rud" + }, + "body": "", + "body_regex": "\"ok\":\\s*true", + "insecure_skip_verify": false +} +``` + +- `url` (**required**): Full HTTP/HTTPS endpoint URL. +- `http_method`: HTTP verb (`"GET"`, `"POST"`, `"HEAD"`, etc.; default `"GET"`). +- `expected_status`: List of accepted HTTP status codes (defaults to any `200..299` if omitted). +- `headers`: Key-value map of custom request headers. +- `body`: Optional request payload body string. +- `body_regex`: Optional regular expression that must match the response body. +- `insecure_skip_verify`: Set `true` to ignore self-signed/expired TLS certificates. + +### Method 2: TCP Port (`"method": "tcp"`) + +```json +{ + "id": "postgres-db", + "name": "PostgreSQL Primary", + "method": "tcp", + "target": "10.0.0.12:5432" +} +``` + +- `target` (**required**): `host:port` to verify TCP 3-way handshake connectivity and latency. + +### Method 3: Direct ICMP Ping (`"method": "ping"`) + +```json +{ + "id": "edge-router", + "name": "Edge Gateway", + "method": "ping", + "host": "1.1.1.1", + "count": 1, + "privileged": false +} +``` + +- `host` (**required**): IP address or hostname to ping. +- `count`: Number of echo packets (default `1`). +- `privileged`: Uses native ICMP echo sockets with automatic fallback to the system `ping` command. + +### Method 4: DNS Record Check (`"method": "dns"`) + +```json +{ + "id": "domain-dns", + "name": "GsDistance DNS", + "method": "dns", + "host": "gsdistance.org", + "record_type": "A", + "resolver": "1.1.1.1:53", + "expected_regex": "^(104|172)\\." +} +``` + +- `host` (**required**): Domain name to resolve. +- `record_type`: `"A"`, `"AAAA"`, `"CNAME"`, `"MX"`, `"TXT"`, or `"NS"` (default `"A"`). +- `resolver`: Optional custom DNS server (`ip:port` or `ip`). Uses system resolver if omitted. +- `expected_regex`: Optional regular expression verified against returned DNS records. + +### Method 5: Custom Command / Script (`"method": "cmd"`) + +```json +{ + "id": "disk-space", + "name": "Root Disk Free Space", + "method": "cmd", + "command": "df -h / | awk 'NR==2 {print $5}'", + "shell": true, + "expected_exit_code": 0, + "output_regex": "^[0-8][0-9]%$" +} +``` + +- `command` (**required**): Executable or shell command line. +- `args`: Optional array of arguments when `shell` is `false`. +- `shell`: When `true`, executes via `/bin/sh -c`. +- `working_dir`: Optional working directory path. +- `env`: Optional map of environment variables (`{"KEY": "VALUE"}`). +- `expected_exit_code`: Expected process exit status (default `0`). +- `output_regex`: Optional regular expression matched against combined `stdout`/`stderr`. + +--- + +## 5. `events` Section (Declarative Triggers & Actions) + +Events allow you to declaratively combine **monitor boolean state triggers**, **sustained duration requirements (`for`)**, and **metric triggers** using `"and"` / `"or"` logic to execute outbound webhooks or custom shell commands. + +```json +"events": [ + { + "id": "cluster-critical", + "name": "Cluster Down or Sustained High Latency", + "cooldown": "30m", + "trigger_on_recovery": true, + "condition": { + "operator": "or", + "conditions": [ + { + "type": "state", + "monitors": ["1", "2", "3"], + "match": "all", + "state": "down" + }, + { + "type": "state", + "monitors": ["*"], + "match": "any", + "state": "down", + "for": "5h" + }, + { + "type": "metric", + "monitors": ["main-api"], + "match": "any", + "metric": "uptime_pct", + "comparator": "<", + "value": 99.0, + "for": "15m" + } + ] + }, + "actions": [ + { + "type": "webhook", + "url": "https://hooks.example.com/rud", + "http_method": "POST", + "headers": { + "Authorization": "Bearer webhook-secret" + }, + "body_template": "{\"event\":\"{{.EventName}}\",\"status\":\"{{.Status}}\",\"monitors\":\"{{.TriggeredMonitors}}\",\"timestamp\":\"{{.Timestamp}}\"}" + }, + { + "type": "command", + "command": "/usr/local/bin/notify-oncall.sh \"{{.EventName}}\" \"{{.Status}}\" \"{{.TriggeredMonitors}}\"", + "shell": true, + "timeout": "10s" + } + ] + } +] +``` + +### Condition Fields + +- **Boolean Combinators**: + - `operator`: `"and"` or `"or"` + - `conditions`: Array of nested condition objects (can be nested to any depth). +- **Monitor State Conditions (`"type": "state"`)**: + - `monitors`: Array of monitor IDs (e.g., `["1", "2", "3"]`) or `["*"]` for all monitors. + - `match`: `"all"` (every listed monitor must match) or `"any"` (at least one listed monitor must match). + - `state`: `"down"`, `"degraded"`, or `"up"`. + - `for`: Optional sustained duration (e.g., `"5h"` — monitor must remain in `state` continuously for at least 5 hours). +- **Metric Conditions (`"type": "metric"`)**: + - `monitors`: Array of monitor IDs or `["*"]`. + - `match`: `"all"` or `"any"`. + - `metric`: `"uptime_pct"`, `"latency_ms"`, or `"consecutive_failures"`. + - `comparator`: `"<"`, `"<="`, `">"`, `">="`, `"=="`, or `"!="`. + - `value`: Numeric threshold (e.g., `99.5` for 99.5% uptime, `500` for 500ms latency). + - `for`: Optional sustained duration that the metric inequality must hold continuously. + +### Action Template Variables + +Both `webhook` (`body_template`) and `command` (`command`, `args`) support Go `text/template` placeholders: +- `{{.EventID}}` — ID of the event rule +- `{{.EventName}}` — Name of the event rule +- `{{.Status}}` — `"TRIGGERED"` or `"RESOLVED"` +- `{{.OverallState}}` — Global status (`"up"`, `"degraded"`, `"down"`) +- `{{.OverallUptimePct}}` — Aggregate uptime percentage +- `{{.TriggeredMonitors}}` — Comma-separated list of monitor IDs that matched +- `{{.MonitorsJSON}}` — Raw JSON array of matching monitor states +- `{{.Timestamp}}` — ISO-8601 UTC timestamp + +Command actions also receive environment variables: `RUD_EVENT_ID`, `RUD_EVENT_NAME`, `RUD_EVENT_STATUS`, `RUD_OVERALL_STATE`, `RUD_TRIGGERED_MONITORS`, and `RUD_TIMESTAMP`. + +--- + +## 6. `page` Section (Theme & UI Elements) + +The web status page is minimalist and strictly renders **only** the elements configured in `page.elements` in the exact order they appear, followed by the `'Powered by R u ded?'` footer. + +### `page.theme` + +```json +"theme": { + "bg_color": "#111111", + "card_bg_color": "#191919", + "text_color": "#e5e5e5", + "muted_text_color": "#888888", + "border_color": "#2e2e2e", + "accent_color": "#cccccc", + "up_color": "#2ecc71", + "degraded_color": "#f1c40f", + "down_color": "#e74c3c", + "pending_color": "#7f8c8d", + "font_family": "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace", + "max_width": "820px", + "border_radius": "2px", + "custom_css": "" +} +``` + +### `page.elements` Types + +#### 1. `header` +Renders the page heading, optional subtitle, live indicator dot, and last-updated timestamp. +```json +{ + "type": "header", + "title": "R u ded?", + "subtitle": "Minimalist system status & health monitor", + "align": "split", + "show_last_updated": true, + "show_live_indicator": true +} +``` +- `align`: `"split"` (title left, timestamp right), `"left"`, or `"center"`. + +#### 2. `status_banner` +Renders a global status bar colored by the overall state (`up`, `degraded`, `down`, `pending`). +```json +{ + "type": "status_banner", + "messages": { + "up": "No — All systems operational", + "degraded": "Kinda — Some systems are experiencing degraded performance", + "down": "Yes — One or more systems are down", + "pending": "Checking system status..." + }, + "show_overall_uptime": true, + "show_counts": true +} +``` + +#### 3. `summary_cards` +Renders a compact row of aggregate metrics. +```json +{ + "type": "summary_cards", + "title": "Overview", + "metrics": ["total", "up", "degraded", "down", "overall_uptime", "avg_latency"] +} +``` + +#### 4. `monitor_group` +Renders a list or grid of monitors with granular toggles for bars, badges, and metadata. You can include multiple `monitor_group` elements to organize services by category. +```json +{ + "type": "monitor_group", + "title": "Core Infrastructure", + "description": "Primary endpoints", + "monitors": ["rud-http", "rud-tcp"], + "layout": "list", + "display": { + "show_bar": true, + "bar_ticks": 40, + "show_uptime": true, + "show_latency": true, + "show_status_badge": true, + "show_method": true, + "show_target": false, + "show_description": true, + "show_message": false, + "show_last_checked": false, + "custom_labels": { + "up": "OK", + "degraded": "SLOW", + "down": "DED", + "pending": "WAIT" + } + } +} +``` +- `monitors`: Array of monitor IDs to include in this group, or `["*"]` for all monitors. +- `layout`: `"list"` (vertical stack) or `"grid"` (responsive multi-column grid). + +#### 5. `custom_block` +Renders a static notice, maintenance message, or text block. +```json +{ + "type": "custom_block", + "title": "Scheduled Maintenance", + "content": "Database maintenance scheduled for Sunday 02:00 UTC.", + "style": "info" +} +``` +- `style`: `"neutral"`, `"info"`, `"warning"`, or `"danger"`. + +#### 6. `divider` +Renders a clean horizontal separator line between elements. +```json +{ + "type": "divider" +} +``` diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ea8e92f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +# Stage 1: Build static Go binary +FROM golang:1.23-alpine AS builder + +WORKDIR /src +COPY go.mod ./ +COPY . . + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/rud . + +# Stage 2: Minimal Alpine runtime (supports HTTPS certs, ICMP ping, and /bin/sh custom checks) +FROM alpine:3.20 + +RUN apk add --no-cache ca-certificates tzdata iputils-ping + +WORKDIR /app +COPY --from=builder /out/rud /usr/local/bin/rud +COPY rud.json /app/rud.json + +EXPOSE 8080 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD wget -q -O /dev/null http://127.0.0.1:8080/ || exit 1 + +ENTRYPOINT ["/usr/local/bin/rud"] +CMD ["-config", "/app/rud.json"] diff --git a/README.md b/README.md index 6a78364..e5fd4db 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,99 @@ -# RUD +# R u ded? (`rud`) -R u ded? -Performant and lightweight uptime and health check monitor written in go. \ No newline at end of file +**R u ded? (`rud`)** is a performant, lightweight, self-contained uptime monitor and health checker written in Go by **tyuXX** for **GsDistance.org** ([git.gsdistance.org/tyuXX/RUD](https://git.gsdistance.org/tyuXX/RUD)). + +It compiles to a single zero-dependency binary, runs concurrent checks across multiple protocols, evaluates declarative alert rules, and serves a **single HTTP endpoint** whose minimal status page and JSON health output are configured entirely through a single human-readable [`rud.json`](file:///home/devuser/workspace/RUD/rud.json) file. + +--- + +## Features + +- **Single `rud.json` Configuration**: Intuitive, human-readable JSON file loaded at startup. Automatically generates a sensible default `rud.json` if missing. +- **Strict Config-Driven Minimalist UI**: Renders **only** the UI elements, bars, and metrics declared in `rud.json` (plus a subtle `'Powered by R u ded?'` attribution footer), with all CSS and live-refresh JS inlined into a single fast response. +- **Single HTTP Endpoint (HTML + JSON)**: + - Browser requests receive the clean, minimal status page with automatic background updates. + - Requests with `Accept: application/json` or `?format=json` receive structured JSON status and metrics. + - Configurable HTTP status codes per state (defaults HTML to `200` so Cloudflare Tunnel never intercepts your status page with a 5xx error screen). +- **Multi-Method Health Checks**: + - `http` / `https`: Status codes, custom request headers, body regex matching, latency, TLS options. + - `tcp`: Port connectivity and handshake latency. + - `ping`: Direct ICMP echo reachability and RTT latency. + - `dns`: Record resolution (`A`, `AAAA`, `CNAME`, `MX`, `TXT`, `NS`), custom resolvers, and regex validation. + - `cmd`: Custom shell commands or scripts with exit code and output regex verification. +- **Declarative Event & Alert Engine**: Combine monitor boolean triggers (`all` or `any` of monitor IDs in a state), sustained durations (e.g., `"for": "5h"`), and metric thresholds (`uptime_pct`, `latency_ms`, `consecutive_failures`) using `"and"` / `"or"` logic to trigger outbound webhooks or execute commands. +- **In-Memory Ring Buffer + Optional Persistence**: Maximum speed in-memory circular buffer by default, with optional atomic disk persistence across restarts. +- **Docker & Cloudflare Tunnel Ready**: Includes a multi-stage `Dockerfile`, a direct `docker-compose.yml`, and a zero-exposed-port `docker-compose.cloudflared.yml`. + +--- + +## Quick Start + +### 1. Run as a Standalone Binary + +```bash +# Build the self-contained binary +go build -trimpath -ldflags="-s -w" -o rud . + +# (Optional) Generate a default rud.json explicitly +./rud -init -config rud.json + +# Run R u ded? (auto-generates rud.json if not present) +./rud -config rud.json +``` + +Query the single endpoint: +```bash +# Minimal HTML Status Page +curl http://localhost:8080/ + +# Structured JSON Output (via query parameter or Accept header) +curl "http://localhost:8080/?format=json" +curl -H "Accept: application/json" http://localhost:8080/ +``` + +--- + +### 2. Run with Docker Compose (Direct Port Exposure) + +Uses [`docker-compose.yml`](./docker-compose.yml) to expose port `8080` directly on the host: + +```bash +docker compose up -d --build +``` + +Edit `./rud.json` and restart the container to apply changes: +```bash +docker compose restart rud +``` + +--- + +### 3. Run with Docker Compose + Cloudflare Tunnel (Zero Exposed Host Ports) + +Uses [`docker-compose.cloudflared.yml`](./docker-compose.cloudflared.yml) to run `rud` and `cloudflared` on an isolated internal Docker bridge network (`rud_tunnel_net`) with **no ports bound to the host**: + +1. Copy `.env.example` to `.env` and set your Cloudflare Tunnel token: + ```bash + cp .env.example .env + # Set TUNNEL_TOKEN=... in .env + ``` +2. In your Cloudflare Zero Trust dashboard, configure your tunnel's Public Hostname service URL to point to: + ```text + http://rud:8080 + ``` +3. Start the stack: + ```bash + docker compose -f docker-compose.cloudflared.yml up -d --build + ``` + +--- + +## Configuration Documentation + +See [**`CONFIGURATION.md`**](./CONFIGURATION.md) for the complete reference covering every section, check method, declarative event condition, and UI element in `rud.json`. + +--- + +## License + +MIT License — Created by **tyuXX** for **GsDistance.org** ([https://git.gsdistance.org/tyuXX/RUD](https://git.gsdistance.org/tyuXX/RUD)). diff --git a/docker-compose.cloudflared.yml b/docker-compose.cloudflared.yml new file mode 100644 index 0000000..c43abed --- /dev/null +++ b/docker-compose.cloudflared.yml @@ -0,0 +1,31 @@ +services: + rud: + build: + context: . + dockerfile: Dockerfile + container_name: rud + restart: unless-stopped + expose: + - "8080" + volumes: + - ./rud.json:/app/rud.json:ro + cap_add: + - NET_RAW + networks: + - rud_tunnel_net + + cloudflared: + image: cloudflare/cloudflared:latest + container_name: rud-cloudflared + restart: unless-stopped + depends_on: + - rud + command: tunnel --no-autoupdate run + environment: + - TUNNEL_TOKEN=${TUNNEL_TOKEN} + networks: + - rud_tunnel_net + +networks: + rud_tunnel_net: + driver: bridge diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d178461 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,13 @@ +services: + rud: + build: + context: . + dockerfile: Dockerfile + container_name: rud + restart: unless-stopped + ports: + - "${RUD_PORT:-8080}:8080" + volumes: + - ./rud.json:/app/rud.json:ro + cap_add: + - NET_RAW diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..093ac3c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.gsdistance.org/tyuXX/RUD + +go 1.23 diff --git a/internal/checker/checker.go b/internal/checker/checker.go new file mode 100644 index 0000000..a4e9ac5 --- /dev/null +++ b/internal/checker/checker.go @@ -0,0 +1,661 @@ +package checker + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "regexp" + "strings" + "sync" + "syscall" + "time" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +// Scheduler manages concurrent periodic health checks for all configured monitors. +type Scheduler struct { + cfg *config.Config + store *store.Store + onCheckComplete func(snap store.Snapshot) + wg sync.WaitGroup +} + +// NewScheduler creates a new check scheduler. +func NewScheduler(cfg *config.Config, st *store.Store, onCheckComplete func(snap store.Snapshot)) *Scheduler { + return &Scheduler{ + cfg: cfg, + store: st, + onCheckComplete: onCheckComplete, + } +} + +// Start launches background check workers for all monitors until ctx is cancelled. +func (s *Scheduler) Start(ctx context.Context) { + for _, mon := range s.cfg.Monitors { + m := mon + s.wg.Add(1) + go func() { + defer s.wg.Done() + s.runMonitorLoop(ctx, m) + }() + } +} + +// Wait blocks until all monitor workers have exited. +func (s *Scheduler) Wait() { + s.wg.Wait() +} + +func (s *Scheduler) runMonitorLoop(ctx context.Context, m config.MonitorConfig) { + interval := m.EffectiveInterval(s.cfg.Defaults) + + // Perform initial check immediately + s.executeAndRecord(ctx, m) + + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + s.executeAndRecord(ctx, m) + } + } +} + +func (s *Scheduler) executeAndRecord(ctx context.Context, m config.MonitorConfig) { + if ctx.Err() != nil { + return + } + res := RunCheckWithRetries(ctx, m, s.cfg.Defaults) + if ctx.Err() != nil { + return + } + s.store.Record(m.ID, res) + if s.onCheckComplete != nil { + s.onCheckComplete(s.store.Snapshot()) + } +} + +// RunCheckWithRetries executes a single monitor check, retrying on failure up to the configured retry limit. +func RunCheckWithRetries(ctx context.Context, m config.MonitorConfig, def config.DefaultsConfig) store.CheckResult { + retries := m.EffectiveRetries(def) + if retries < 0 { + retries = 0 + } + degradedThreshold := m.EffectiveDegradedLatency(def) + + var lastRes store.CheckResult + for attempt := 0; attempt <= retries; attempt++ { + if attempt > 0 { + select { + case <-ctx.Done(): + return lastRes + case <-time.After(150 * time.Millisecond): + } + } + + lastRes = RunSingleCheck(ctx, m, def) + if lastRes.State != store.StateDown { + if degradedThreshold > 0 && lastRes.LatencyMs >= float64(degradedThreshold.Milliseconds()) { + lastRes.State = store.StateDegraded + if lastRes.Message == "" || lastRes.Message == "OK" { + lastRes.Message = fmt.Sprintf("High latency (%.0fms >= %dms)", lastRes.LatencyMs, degradedThreshold.Milliseconds()) + } + } + return lastRes + } + } + return lastRes +} + +// RunSingleCheck executes a single attempt of a monitor's configured method. +func RunSingleCheck(ctx context.Context, m config.MonitorConfig, def config.DefaultsConfig) store.CheckResult { + timeout := m.EffectiveTimeout(def) + checkCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + switch strings.ToLower(m.Method) { + case "http", "https": + return checkHTTP(checkCtx, m, timeout) + case "tcp": + return checkTCP(checkCtx, m, timeout) + case "ping": + return checkPing(checkCtx, m, timeout) + case "dns": + return checkDNS(checkCtx, m, timeout) + case "cmd", "script", "command": + return checkCmd(checkCtx, m) + default: + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + Message: fmt.Sprintf("unsupported method: %s", m.Method), + } + } +} + +func checkHTTP(ctx context.Context, m config.MonitorConfig, timeout time.Duration) store.CheckResult { + method := strings.ToUpper(strings.TrimSpace(m.HTTPMethod)) + if method == "" { + method = http.MethodGet + } + + var bodyReader io.Reader + if m.Body != "" { + bodyReader = strings.NewReader(m.Body) + } + + req, err := http.NewRequestWithContext(ctx, method, m.URL, bodyReader) + if err != nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + Message: fmt.Sprintf("invalid request: %v", err), + } + } + + req.Header.Set("User-Agent", "RUD-Monitor/1.0 (+https://git.gsdistance.org/tyuXX/RUD)") + for k, v := range m.Headers { + req.Header.Set(k, v) + } + + tr := &http.Transport{ + DisableKeepAlives: true, + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: m.InsecureSkipVerify, + }, + } + client := &http.Client{ + Transport: tr, + Timeout: timeout, + } + + start := time.Now() + resp, err := client.Do(req) + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + if err != nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: cleanErr(err), + } + } + defer resp.Body.Close() + + bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024)) + if err != nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Code: resp.StatusCode, + Message: fmt.Sprintf("read body error: %v", err), + } + } + + statusOK := false + if len(m.ExpectedStatus) == 0 { + statusOK = resp.StatusCode >= 200 && resp.StatusCode < 300 + } else { + for _, code := range m.ExpectedStatus { + if resp.StatusCode == code { + statusOK = true + break + } + } + } + + if !statusOK { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Code: resp.StatusCode, + Message: fmt.Sprintf("unexpected HTTP %d", resp.StatusCode), + } + } + + if m.BodyRegex != "" { + re, err := regexp.Compile(m.BodyRegex) + if err != nil || !re.Match(bodyBytes) { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Code: resp.StatusCode, + Message: fmt.Sprintf("body did not match regex %q", m.BodyRegex), + } + } + } + + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateUp, + LatencyMs: latencyMs, + Code: resp.StatusCode, + Message: fmt.Sprintf("HTTP %d", resp.StatusCode), + } +} + +func checkTCP(ctx context.Context, m config.MonitorConfig, timeout time.Duration) store.CheckResult { + target := m.Target + if target == "" { + target = m.Host + } + dialer := net.Dialer{Timeout: timeout} + start := time.Now() + conn, err := dialer.DialContext(ctx, "tcp", target) + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + if err != nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: cleanErr(err), + } + } + _ = conn.Close() + + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateUp, + LatencyMs: latencyMs, + Message: "TCP connected", + } +} + +func checkPing(ctx context.Context, m config.MonitorConfig, timeout time.Duration) store.CheckResult { + host := m.Host + if host == "" { + host = m.Target + } + count := m.Count + if count <= 0 { + count = 1 + } + + // First attempt native ICMP echo (works with CAP_NET_RAW, root, or unprivileged ICMP sockets) + if latencyMs, err := nativeICMPPing(ctx, host, timeout, m.Privileged); err == nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateUp, + LatencyMs: latencyMs, + Message: "ICMP echo reply", + } + } + + // Fallback to system ping utility if available + waitSec := int(timeout.Seconds()) + if waitSec < 1 { + waitSec = 1 + } + start := time.Now() + cmd := exec.CommandContext(ctx, "ping", "-c", fmt.Sprintf("%d", count), "-W", fmt.Sprintf("%d", waitSec), host) + out, err := cmd.CombinedOutput() + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + if err == nil { + if parsed := parsePingRTT(string(out)); parsed > 0 { + latencyMs = parsed + } + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateUp, + LatencyMs: latencyMs, + Message: "ICMP ping OK", + } + } + + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: fmt.Sprintf("ping failed: %s", cleanErr(err)), + } +} + +func nativeICMPPing(ctx context.Context, host string, timeout time.Duration, privilegedOnly bool) (float64, error) { + ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host) + if err != nil || len(ips) == 0 { + return 0, fmt.Errorf("resolve %s: %w", host, err) + } + ip4 := ips[0].To4() + if ip4 == nil { + return 0, fmt.Errorf("no IPv4 address for %s", host) + } + + // Try Linux unprivileged ICMP datagram socket (SOCK_DGRAM + IPPROTO_ICMP) first unless privilegedOnly is set, + // with fallback to raw ICMP socket (SOCK_RAW + IPPROTO_ICMP). + sockTypes := []int{syscall.SOCK_DGRAM, syscall.SOCK_RAW} + if privilegedOnly { + sockTypes = []int{syscall.SOCK_RAW, syscall.SOCK_DGRAM} + } + + fd := -1 + usedType := 0 + for _, st := range sockTypes { + s, err := syscall.Socket(syscall.AF_INET, st, syscall.IPPROTO_ICMP) + if err == nil { + fd = s + usedType = st + break + } + } + if fd < 0 { + return 0, errors.New("icmp socket unavailable") + } + defer syscall.Close(fd) + + tv := syscall.NsecToTimeval(timeout.Nanoseconds()) + _ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv) + _ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &tv) + + // Construct ICMPv4 Echo Request (type 8, code 0) + pkt := make([]byte, 16) + pkt[0] = 8 // Echo Request + pkt[1] = 0 + id := uint16(os.Getpid() & 0xffff) + binary.BigEndian.PutUint16(pkt[4:6], id) + binary.BigEndian.PutUint16(pkt[6:8], 1) // Seq 1 + copy(pkt[8:], []byte("RUD-PING")) + cs := icmpChecksum(pkt) + binary.BigEndian.PutUint16(pkt[2:4], cs) + + var sa syscall.SockaddrInet4 + copy(sa.Addr[:], ip4) + + start := time.Now() + if err := syscall.Sendto(fd, pkt, 0, &sa); err != nil { + return 0, err + } + + buf := make([]byte, 1500) + n, _, err := syscall.Recvfrom(fd, buf, 0) + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + if err != nil { + return 0, err + } + if n < 8 { + return 0, errors.New("short icmp reply") + } + payload := buf[:n] + if usedType == syscall.SOCK_RAW && len(payload) >= 28 && (payload[0]>>4) == 4 { + hdrLen := int(payload[0]&0x0f) * 4 + if len(payload) >= hdrLen+8 { + payload = payload[hdrLen:] + } + } + if payload[0] != 0 { // 0 = Echo Reply + return 0, fmt.Errorf("unexpected icmp type %d", payload[0]) + } + return latencyMs, nil +} + +func icmpChecksum(b []byte) uint16 { + var sum uint32 + for i := 0; i < len(b)-1; i += 2 { + sum += uint32(binary.BigEndian.Uint16(b[i : i+2])) + } + if len(b)%2 == 1 { + sum += uint32(b[len(b)-1]) << 8 + } + for (sum >> 16) > 0 { + sum = (sum & 0xffff) + (sum >> 16) + } + return ^uint16(sum) +} + +var pingRTTRe = regexp.MustCompile(`time[=<]([0-9.]+)\s*ms`) + +func parsePingRTT(output string) float64 { + m := pingRTTRe.FindStringSubmatch(output) + if len(m) == 2 { + var v float64 + if _, err := fmt.Sscanf(m[1], "%f", &v); err == nil { + return v + } + } + return 0 +} + +func checkDNS(ctx context.Context, m config.MonitorConfig, timeout time.Duration) store.CheckResult { + host := m.Host + if host == "" { + host = m.Target + } + recType := strings.ToUpper(strings.TrimSpace(m.RecordType)) + if recType == "" { + recType = "A" + } + + resolver := net.DefaultResolver + if m.Resolver != "" { + addr := m.Resolver + if !strings.Contains(addr, ":") { + addr = addr + ":53" + } + resolver = &net.Resolver{ + PreferGo: true, + Dial: func(ctx context.Context, network, _ string) (net.Conn, error) { + d := net.Dialer{Timeout: timeout} + return d.DialContext(ctx, network, addr) + }, + } + } + + start := time.Now() + var records []string + var err error + + switch recType { + case "A": + var ips []net.IP + ips, err = resolver.LookupIP(ctx, "ip4", host) + for _, ip := range ips { + records = append(records, ip.String()) + } + case "AAAA": + var ips []net.IP + ips, err = resolver.LookupIP(ctx, "ip6", host) + for _, ip := range ips { + records = append(records, ip.String()) + } + case "CNAME": + var cname string + cname, err = resolver.LookupCNAME(ctx, host) + if cname != "" { + records = append(records, cname) + } + case "MX": + var mxs []*net.MX + mxs, err = resolver.LookupMX(ctx, host) + for _, mx := range mxs { + records = append(records, fmt.Sprintf("%s (%d)", mx.Host, mx.Pref)) + } + case "TXT": + records, err = resolver.LookupTXT(ctx, host) + case "NS": + var nss []*net.NS + nss, err = resolver.LookupNS(ctx, host) + for _, ns := range nss { + records = append(records, ns.Host) + } + default: + records, err = resolver.LookupHost(ctx, host) + } + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + + if err != nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: cleanErr(err), + } + } + if len(records) == 0 { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: fmt.Sprintf("no %s records found", recType), + } + } + + joined := strings.Join(records, ", ") + if m.ExpectedRegex != "" { + re, err := regexp.Compile(m.ExpectedRegex) + if err != nil { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: fmt.Sprintf("invalid expected_regex: %v", err), + } + } + matched := false + for _, r := range records { + if re.MatchString(r) { + matched = true + break + } + } + if !matched && !re.MatchString(joined) { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Message: fmt.Sprintf("records [%s] did not match %q", joined, m.ExpectedRegex), + } + } + } + + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateUp, + LatencyMs: latencyMs, + Message: fmt.Sprintf("%s: %s", recType, truncateStr(joined, 64)), + } +} + +func checkCmd(ctx context.Context, m config.MonitorConfig) store.CheckResult { + var cmd *exec.Cmd + if m.Shell || (len(m.Args) == 0 && strings.ContainsAny(m.Command, " \t|&;<>()$`\"'")) { + fullCmd := m.Command + if len(m.Args) > 0 { + fullCmd = fullCmd + " " + strings.Join(m.Args, " ") + } + cmd = exec.CommandContext(ctx, "/bin/sh", "-c", fullCmd) + } else { + cmd = exec.CommandContext(ctx, m.Command, m.Args...) + } + + if m.WorkingDir != "" { + cmd.Dir = m.WorkingDir + } + if len(m.Env) > 0 { + env := os.Environ() + for k, v := range m.Env { + env = append(env, fmt.Sprintf("%s=%s", k, v)) + } + cmd.Env = env + } + + var outBuf bytes.Buffer + cmd.Stdout = &outBuf + cmd.Stderr = &outBuf + + start := time.Now() + err := cmd.Run() + latencyMs := float64(time.Since(start).Microseconds()) / 1000.0 + output := strings.TrimSpace(outBuf.String()) + + exitCode := 0 + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + exitCode = exitErr.ExitCode() + } else { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Code: -1, + Message: cleanErr(err), + } + } + } + + expectedCode := 0 + if m.ExpectedExitCode != nil { + expectedCode = *m.ExpectedExitCode + } + + if exitCode != expectedCode { + msg := fmt.Sprintf("exit code %d (expected %d)", exitCode, expectedCode) + if output != "" { + msg += ": " + truncateStr(output, 64) + } + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Code: exitCode, + Message: msg, + } + } + + if m.OutputRegex != "" { + re, regErr := regexp.Compile(m.OutputRegex) + if regErr != nil || !re.MatchString(output) { + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateDown, + LatencyMs: latencyMs, + Code: exitCode, + Message: fmt.Sprintf("output did not match regex %q", m.OutputRegex), + } + } + } + + msg := "exit 0" + if output != "" { + msg = truncateStr(output, 64) + } + return store.CheckResult{ + Timestamp: time.Now().UTC(), + State: store.StateUp, + LatencyMs: latencyMs, + Code: exitCode, + Message: msg, + } +} + +func cleanErr(err error) string { + if err == nil { + return "" + } + return truncateStr(err.Error(), 96) +} + +func truncateStr(s string, max int) string { + s = strings.ReplaceAll(s, "\n", " ") + s = strings.ReplaceAll(s, "\r", "") + if len(s) <= max { + return s + } + return s[:max-3] + "..." +} diff --git a/internal/checker/checker_test.go b/internal/checker/checker_test.go new file mode 100644 index 0000000..dbb54c9 --- /dev/null +++ b/internal/checker/checker_test.go @@ -0,0 +1,120 @@ +package checker + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +func TestHTTPChecker(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-Custom") != "expected-val" { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"service":"alive","code":42}`)) + })) + defer ts.Close() + + def := config.DefaultsConfig{ + Timeout: config.NewDuration(2 * time.Second), + Retries: 0, + DegradedLatency: config.NewDuration(1 * time.Second), + } + + mon := config.MonitorConfig{ + ID: "http-1", + Method: "http", + URL: ts.URL, + ExpectedStatus: []int{201}, + Headers: map[string]string{"X-Custom": "expected-val"}, + BodyRegex: `"service":\s*"alive"`, + } + + res := RunCheckWithRetries(context.Background(), mon, def) + if res.State != store.StateUp { + t.Fatalf("expected HTTP check up, got %s (%s)", res.State, res.Message) + } + + // Regex mismatch should mark down + mon.BodyRegex = `"service":\s*"missing"` + resFail := RunCheckWithRetries(context.Background(), mon, def) + if resFail.State != store.StateDown { + t.Fatalf("expected HTTP regex mismatch to mark down, got %s", resFail.State) + } +} + +func TestTCPChecker(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen failed: %v", err) + } + defer ln.Close() + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + _ = c.Close() + } + }() + + def := config.DefaultsConfig{Timeout: config.NewDuration(1 * time.Second)} + mon := config.MonitorConfig{ + ID: "tcp-1", + Method: "tcp", + Target: ln.Addr().String(), + } + res := RunCheckWithRetries(context.Background(), mon, def) + if res.State != store.StateUp { + t.Fatalf("expected TCP check up, got %s (%s)", res.State, res.Message) + } +} + +func TestDNSAndCmdAndPingCheckers(t *testing.T) { + def := config.DefaultsConfig{Timeout: config.NewDuration(2 * time.Second)} + + dnsMon := config.MonitorConfig{ + ID: "dns-1", + Method: "dns", + Host: "localhost", + RecordType: "A", + ExpectedRegex: `^127\.`, + } + dnsRes := RunCheckWithRetries(context.Background(), dnsMon, def) + if dnsRes.State != store.StateUp { + t.Fatalf("expected DNS check up, got %s (%s)", dnsRes.State, dnsRes.Message) + } + + cmdMon := config.MonitorConfig{ + ID: "cmd-1", + Method: "cmd", + Command: "printf 'rud-ok-123'", + Shell: true, + ExpectedExitCode: config.IntPtr(0), + OutputRegex: `^rud-ok-[0-9]+$`, + } + cmdRes := RunCheckWithRetries(context.Background(), cmdMon, def) + if cmdRes.State != store.StateUp { + t.Fatalf("expected Cmd check up, got %s (%s)", cmdRes.State, cmdRes.Message) + } + + pingMon := config.MonitorConfig{ + ID: "ping-1", + Method: "ping", + Host: "127.0.0.1", + Count: 1, + } + pingRes := RunCheckWithRetries(context.Background(), pingMon, def) + if pingRes.State != store.StateUp { + t.Fatalf("expected Ping check up, got %s (%s)", pingRes.State, pingRes.Message) + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..9576f17 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,790 @@ +package config + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "regexp" + "strings" + "time" +) + +// Duration wraps time.Duration so zero values are omitted by json:",omitempty" +// while non-zero values serialize as clean human-readable strings ("15s", "5m", "5h"). +type Duration time.Duration + +func NewDuration(d time.Duration) Duration { + return Duration(d) +} + +func (d Duration) Std() time.Duration { + return time.Duration(d) +} + +func (d Duration) MarshalJSON() ([]byte, error) { + s := time.Duration(d).String() + if strings.HasSuffix(s, "m0s") { + s = strings.TrimSuffix(s, "0s") + } + if strings.HasSuffix(s, "h0m") { + s = strings.TrimSuffix(s, "0m") + } + return json.Marshal(s) +} + +func (d *Duration) UnmarshalJSON(b []byte) error { + var v any + if err := json.Unmarshal(b, &v); err != nil { + return err + } + switch val := v.(type) { + case string: + if val == "" { + *d = 0 + return nil + } + parsed, err := time.ParseDuration(val) + if err != nil { + return fmt.Errorf("invalid duration %q: %w", val, err) + } + *d = Duration(parsed) + return nil + case float64: + *d = Duration(time.Duration(val) * time.Millisecond) + return nil + default: + return fmt.Errorf("invalid duration type %T", v) + } +} + +// Config represents the top-level rud.json configuration file. +type Config struct { + Server ServerConfig `json:"server"` + Storage StorageConfig `json:"storage"` + Defaults DefaultsConfig `json:"defaults"` + Monitors []MonitorConfig `json:"monitors"` + Events []EventConfig `json:"events,omitempty"` + Page PageConfig `json:"page"` +} + +// ServerConfig configures the single HTTP endpoint server. +type ServerConfig struct { + Listen string `json:"listen"` + Endpoint string `json:"endpoint"` + RefreshInterval Duration `json:"refresh_interval"` + StatusCodes EndpointStatusCodes `json:"status_codes"` +} + +type EndpointStatusCodes struct { + HTML StatusCodesByState `json:"html"` + JSON StatusCodesByState `json:"json"` +} + +type StatusCodesByState struct { + Up int `json:"up"` + Degraded int `json:"degraded"` + Down int `json:"down"` + Pending int `json:"pending"` +} + +// StorageConfig configures the in-memory ring buffer and optional disk persistence. +type StorageConfig struct { + HistorySize int `json:"history_size"` + PersistenceFile string `json:"persistence_file,omitempty"` + SaveInterval Duration `json:"save_interval,omitempty"` +} + +// DefaultsConfig provides global fallback check intervals and thresholds. +type DefaultsConfig struct { + Interval Duration `json:"interval"` + Timeout Duration `json:"timeout"` + Retries int `json:"retries"` + DegradedLatency Duration `json:"degraded_latency"` +} + +// MonitorConfig defines an individual health/uptime check. +type MonitorConfig struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Link string `json:"link,omitempty"` + Method string `json:"method"` // "http", "https", "tcp", "ping", "dns", "cmd" + Interval Duration `json:"interval,omitempty"` + Timeout Duration `json:"timeout,omitempty"` + Retries *int `json:"retries,omitempty"` + DegradedLatency Duration `json:"degraded_latency,omitempty"` + + // HTTP / HTTPS options + URL string `json:"url,omitempty"` + HTTPMethod string `json:"http_method,omitempty"` + ExpectedStatus []int `json:"expected_status,omitempty"` + Headers map[string]string `json:"headers,omitempty"` + Body string `json:"body,omitempty"` + BodyRegex string `json:"body_regex,omitempty"` + InsecureSkipVerify bool `json:"insecure_skip_verify,omitempty"` + + // TCP options + Target string `json:"target,omitempty"` // host:port + + // Ping & DNS options + Host string `json:"host,omitempty"` + Count int `json:"count,omitempty"` // ping packet count + Privileged bool `json:"privileged,omitempty"` // raw ICMP socket toggle + RecordType string `json:"record_type,omitempty"` // A, AAAA, CNAME, MX, TXT, NS + Resolver string `json:"resolver,omitempty"` // custom DNS server ip:port + ExpectedRegex string `json:"expected_regex,omitempty"` // regex for DNS record validation + + // Command / Script options + Command string `json:"command,omitempty"` + Args []string `json:"args,omitempty"` + Shell bool `json:"shell,omitempty"` + WorkingDir string `json:"working_dir,omitempty"` + Env map[string]string `json:"env,omitempty"` + ExpectedExitCode *int `json:"expected_exit_code,omitempty"` + OutputRegex string `json:"output_regex,omitempty"` +} + +// EffectiveInterval returns the monitor's interval or the global default. +func (m MonitorConfig) EffectiveInterval(def DefaultsConfig) time.Duration { + if m.Interval > 0 { + return m.Interval.Std() + } + if def.Interval > 0 { + return def.Interval.Std() + } + return 30 * time.Second +} + +// EffectiveTimeout returns the monitor's timeout or the global default. +func (m MonitorConfig) EffectiveTimeout(def DefaultsConfig) time.Duration { + if m.Timeout > 0 { + return m.Timeout.Std() + } + if def.Timeout > 0 { + return def.Timeout.Std() + } + return 5 * time.Second +} + +// EffectiveRetries returns the monitor's retry count or the global default. +func (m MonitorConfig) EffectiveRetries(def DefaultsConfig) int { + if m.Retries != nil { + return *m.Retries + } + return def.Retries +} + +// EffectiveDegradedLatency returns the monitor's degraded latency threshold or the global default. +func (m MonitorConfig) EffectiveDegradedLatency(def DefaultsConfig) time.Duration { + if m.DegradedLatency > 0 { + return m.DegradedLatency.Std() + } + return def.DegradedLatency.Std() +} + +// DisplayTarget returns a human-readable target summary for optional display. +func (m MonitorConfig) DisplayTarget() string { + switch strings.ToLower(m.Method) { + case "http", "https": + return m.URL + case "tcp": + if m.Target != "" { + return m.Target + } + return m.Host + case "ping": + return m.Host + case "dns": + rec := m.RecordType + if rec == "" { + rec = "A" + } + return fmt.Sprintf("%s (%s)", m.Host, strings.ToUpper(rec)) + case "cmd", "script", "command": + if len(m.Args) > 0 { + return m.Command + " " + strings.Join(m.Args, " ") + } + return m.Command + default: + return m.Target + } +} + +// EventConfig defines a declarative alert/event rule and its actions. +type EventConfig struct { + ID string `json:"id"` + Name string `json:"name"` + Cooldown Duration `json:"cooldown,omitempty"` + TriggerOnRecovery bool `json:"trigger_on_recovery,omitempty"` + Condition EventCondition `json:"condition"` + Actions []EventAction `json:"actions"` + RecoveryActions []EventAction `json:"recovery_actions,omitempty"` +} + +// EventCondition supports boolean combinators ("and"/"or"), monitor state checks, and metric threshold checks. +type EventCondition struct { + // Composite condition fields + Operator string `json:"operator,omitempty"` // "and", "or" + Conditions []EventCondition `json:"conditions,omitempty"` + + // Leaf condition fields + Type string `json:"type,omitempty"` // "state" or "metric" (auto-detected if omitted) + Monitors []string `json:"monitors,omitempty"` // monitor IDs or ["*"] + Match string `json:"match,omitempty"` // "all" (default) or "any" + State string `json:"state,omitempty"` // "down", "degraded", "up" + Metric string `json:"metric,omitempty"` // "uptime_pct", "latency_ms", "consecutive_failures" + Comparator string `json:"comparator,omitempty"` // "<", "<=", ">", ">=", "==", "!=" + Value float64 `json:"value,omitempty"` // numeric threshold for metric triggers + For Duration `json:"for,omitempty"` // sustained duration requirement (e.g. "5h") +} + +// EventAction defines an outbound webhook or command execution when an event triggers. +type EventAction struct { + Type string `json:"type"` // "webhook" or "command" + Timeout Duration `json:"timeout,omitempty"` + + // Webhook fields + URL string `json:"url,omitempty"` + HTTPMethod string `json:"http_method,omitempty"` + Headers map[string]string `json:"headers,omitempty"` + BodyTemplate string `json:"body_template,omitempty"` + + // Command fields + Command string `json:"command,omitempty"` + Args []string `json:"args,omitempty"` + Shell bool `json:"shell,omitempty"` + WorkingDir string `json:"working_dir,omitempty"` + Env map[string]string `json:"env,omitempty"` +} + +// PageConfig defines the styling and explicit list of elements to render on the status page. +type PageConfig struct { + Title string `json:"title"` + Theme ThemeConfig `json:"theme"` + Elements []PageElement `json:"elements"` +} + +// ThemeConfig defines minimal, clean visual styling parameters. +type ThemeConfig struct { + BgColor string `json:"bg_color,omitempty"` + CardBgColor string `json:"card_bg_color,omitempty"` + TextColor string `json:"text_color,omitempty"` + MutedTextColor string `json:"muted_text_color,omitempty"` + BorderColor string `json:"border_color,omitempty"` + AccentColor string `json:"accent_color,omitempty"` + UpColor string `json:"up_color,omitempty"` + DegradedColor string `json:"degraded_color,omitempty"` + DownColor string `json:"down_color,omitempty"` + PendingColor string `json:"pending_color,omitempty"` + FontFamily string `json:"font_family,omitempty"` + MaxWidth string `json:"max_width,omitempty"` + BorderRadius string `json:"border_radius,omitempty"` + CustomCSS string `json:"custom_css,omitempty"` +} + +// PageElement represents a single configurable block rendered on the web status page. +type PageElement struct { + Type string `json:"type"` // "header", "status_banner", "summary_cards", "monitor_group", "custom_block", "divider" + + // Common fields + Title string `json:"title,omitempty"` + Subtitle string `json:"subtitle,omitempty"` + Description string `json:"description,omitempty"` + + // Header fields + Align string `json:"align,omitempty"` // "left", "center", "split" + ShowLastUpdated bool `json:"show_last_updated,omitempty"` + ShowLiveIndicator bool `json:"show_live_indicator,omitempty"` + + // Status banner fields + Messages map[string]string `json:"messages,omitempty"` // keys: "up", "degraded", "down", "pending" + ShowOverallUptime bool `json:"show_overall_uptime,omitempty"` + ShowCounts bool `json:"show_counts,omitempty"` + + // Summary cards fields + Metrics []string `json:"metrics,omitempty"` // "total", "up", "degraded", "down", "overall_uptime", "avg_latency" + + // Monitor group fields + Monitors []string `json:"monitors,omitempty"` // monitor IDs or ["*"] + Layout string `json:"layout,omitempty"` // "list", "grid", "compact" + Display *MonitorDisplayConfig `json:"display,omitempty"` + + // Custom block fields + Content string `json:"content,omitempty"` + Style string `json:"style,omitempty"` // "neutral", "info", "warning", "danger" +} + +// MonitorDisplayConfig controls which data points and bars are rendered for monitors in a group. +type MonitorDisplayConfig struct { + ShowBar *bool `json:"show_bar,omitempty"` + BarTicks int `json:"bar_ticks,omitempty"` + ShowUptime *bool `json:"show_uptime,omitempty"` + ShowLatency *bool `json:"show_latency,omitempty"` + ShowStatusBadge *bool `json:"show_status_badge,omitempty"` + ShowMethod *bool `json:"show_method,omitempty"` + ShowTarget *bool `json:"show_target,omitempty"` + ShowDescription *bool `json:"show_description,omitempty"` + ShowMessage *bool `json:"show_message,omitempty"` + ShowLastChecked *bool `json:"show_last_checked,omitempty"` + CustomLabels map[string]string `json:"custom_labels,omitempty"` +} + +func BoolPtr(v bool) *bool { + return &v +} + +func IntPtr(v int) *int { + return &v +} + +// DefaultConfig returns a clean, minimal, ready-to-run default configuration. +func DefaultConfig() Config { + return Config{ + Server: ServerConfig{ + Listen: ":8080", + Endpoint: "/", + RefreshInterval: NewDuration(10 * time.Second), + StatusCodes: EndpointStatusCodes{ + HTML: StatusCodesByState{ + Up: 200, + Degraded: 200, + Down: 200, + Pending: 200, + }, + JSON: StatusCodesByState{ + Up: 200, + Degraded: 200, + Down: 503, + Pending: 200, + }, + }, + }, + Storage: StorageConfig{ + HistorySize: 60, + PersistenceFile: "", + SaveInterval: NewDuration(1 * time.Minute), + }, + Defaults: DefaultsConfig{ + Interval: NewDuration(15 * time.Second), + Timeout: NewDuration(5 * time.Second), + Retries: 1, + DegradedLatency: NewDuration(750 * time.Millisecond), + }, + Monitors: []MonitorConfig{ + { + ID: "rud-http", + Name: "RUD Status Endpoint", + Description: "Local HTTP health check", + Method: "http", + URL: "http://127.0.0.1:8080/?format=json", + HTTPMethod: "GET", + ExpectedStatus: []int{200, 503}, + BodyRegex: `"status"`, + }, + { + ID: "rud-tcp", + Name: "Local TCP Listener", + Description: "TCP socket handshake on port 8080", + Method: "tcp", + Target: "127.0.0.1:8080", + }, + { + ID: "local-ping", + Name: "Loopback ICMP Ping", + Description: "Direct ping reachability check", + Method: "ping", + Host: "127.0.0.1", + Count: 1, + }, + { + ID: "local-dns", + Name: "Localhost DNS Resolution", + Description: "Verifies A record resolution for localhost", + Method: "dns", + Host: "localhost", + RecordType: "A", + ExpectedRegex: `^127\.`, + }, + { + ID: "host-cmd", + Name: "System Shell Check", + Description: "Custom command check verifying shell responsiveness", + Method: "cmd", + Command: "echo ok", + Shell: true, + ExpectedExitCode: IntPtr(0), + OutputRegex: `^ok`, + }, + }, + Events: []EventConfig{ + { + ID: "core-outage", + Name: "Core Monitors Down or Degraded Uptime", + Cooldown: NewDuration(30 * time.Minute), + TriggerOnRecovery: true, + Condition: EventCondition{ + Operator: "or", + Conditions: []EventCondition{ + { + Type: "state", + Monitors: []string{"rud-http", "rud-tcp"}, + Match: "all", + State: "down", + }, + { + Type: "metric", + Monitors: []string{"*"}, + Match: "any", + Metric: "uptime_pct", + Comparator: "<", + Value: 50.0, + For: NewDuration(5 * time.Minute), + }, + }, + }, + Actions: []EventAction{ + { + Type: "command", + Command: "echo \"[RUD ALERT] {{.EventName}}: status={{.Status}} monitors={{.TriggeredMonitors}}\"", + Shell: true, + Timeout: NewDuration(5 * time.Second), + }, + }, + }, + }, + Page: PageConfig{ + Title: "R u ded?", + Theme: ThemeConfig{ + BgColor: "#111111", + CardBgColor: "#191919", + TextColor: "#e5e5e5", + MutedTextColor: "#888888", + BorderColor: "#2e2e2e", + AccentColor: "#cccccc", + UpColor: "#2ecc71", + DegradedColor: "#f1c40f", + DownColor: "#e74c3c", + PendingColor: "#7f8c8d", + FontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace", + MaxWidth: "820px", + BorderRadius: "2px", + }, + Elements: []PageElement{ + { + Type: "header", + Title: "R u ded?", + Subtitle: "Minimalist system status & health monitor", + Align: "split", + ShowLastUpdated: true, + ShowLiveIndicator: true, + }, + { + Type: "status_banner", + Messages: map[string]string{ + "up": "No — All systems operational", + "degraded": "Kinda — Some systems are experiencing degraded performance", + "down": "Yes — One or more systems are down", + "pending": "Checking system status...", + }, + ShowOverallUptime: true, + ShowCounts: true, + }, + { + Type: "summary_cards", + Metrics: []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"}, + }, + { + Type: "monitor_group", + Title: "Monitored Services", + Description: "Live health checks", + Monitors: []string{"*"}, + Layout: "list", + Display: &MonitorDisplayConfig{ + ShowBar: BoolPtr(true), + BarTicks: 40, + ShowUptime: BoolPtr(true), + ShowLatency: BoolPtr(true), + ShowStatusBadge: BoolPtr(true), + ShowMethod: BoolPtr(true), + ShowTarget: BoolPtr(false), + ShowDescription: BoolPtr(true), + ShowMessage: BoolPtr(false), + ShowLastChecked: BoolPtr(false), + CustomLabels: map[string]string{ + "up": "OK", + "degraded": "SLOW", + "down": "DED", + "pending": "WAIT", + }, + }, + }, + }, + }, + } +} + +// LoadOrInit loads rud.json from path. If the file does not exist and createIfMissing is true, +// it writes DefaultConfig() to path and returns it. +func LoadOrInit(path string, createIfMissing bool) (*Config, bool, error) { + data, err := os.ReadFile(path) + created := false + if err != nil { + if errors.Is(err, os.ErrNotExist) && createIfMissing { + cfg := DefaultConfig() + if err := SaveConfig(path, &cfg); err != nil { + return nil, false, fmt.Errorf("failed to write default config to %s: %w", path, err) + } + cfg.ApplyFallbacks() + if err := cfg.Validate(); err != nil { + return nil, true, err + } + return &cfg, true, nil + } + return nil, false, fmt.Errorf("failed to read config %s: %w", path, err) + } + + var cfg Config + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, created, fmt.Errorf("failed to parse %s: %w", path, err) + } + cfg.ApplyFallbacks() + if err := cfg.Validate(); err != nil { + return nil, created, fmt.Errorf("invalid config in %s: %w", path, err) + } + return &cfg, created, nil +} + +// SaveConfig writes the Config struct as indented, human-readable JSON without HTML-escaping characters like '<' or '&'. +func SaveConfig(path string, cfg *Config) error { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + if err := enc.Encode(cfg); err != nil { + return err + } + return os.WriteFile(path, buf.Bytes(), 0644) +} + +// ApplyFallbacks populates missing structural defaults (like listen address, endpoint, status codes, theme colors) +// while strictly preserving the user's explicit page.elements and monitors list. +func (c *Config) ApplyFallbacks() { + if c.Server.Listen == "" { + c.Server.Listen = ":8080" + } + if c.Server.Endpoint == "" { + c.Server.Endpoint = "/" + } + if !strings.HasPrefix(c.Server.Endpoint, "/") { + c.Server.Endpoint = "/" + c.Server.Endpoint + } + if c.Server.StatusCodes.HTML.Up == 0 { + c.Server.StatusCodes.HTML.Up = 200 + } + if c.Server.StatusCodes.HTML.Degraded == 0 { + c.Server.StatusCodes.HTML.Degraded = 200 + } + if c.Server.StatusCodes.HTML.Down == 0 { + c.Server.StatusCodes.HTML.Down = 200 + } + if c.Server.StatusCodes.HTML.Pending == 0 { + c.Server.StatusCodes.HTML.Pending = 200 + } + if c.Server.StatusCodes.JSON.Up == 0 { + c.Server.StatusCodes.JSON.Up = 200 + } + if c.Server.StatusCodes.JSON.Degraded == 0 { + c.Server.StatusCodes.JSON.Degraded = 200 + } + if c.Server.StatusCodes.JSON.Down == 0 { + c.Server.StatusCodes.JSON.Down = 503 + } + if c.Server.StatusCodes.JSON.Pending == 0 { + c.Server.StatusCodes.JSON.Pending = 200 + } + + if c.Storage.HistorySize <= 0 { + c.Storage.HistorySize = 60 + } + if c.Storage.SaveInterval <= 0 { + c.Storage.SaveInterval = NewDuration(1 * time.Minute) + } + + if c.Defaults.Interval <= 0 { + c.Defaults.Interval = NewDuration(30 * time.Second) + } + if c.Defaults.Timeout <= 0 { + c.Defaults.Timeout = NewDuration(5 * time.Second) + } + if c.Defaults.DegradedLatency <= 0 { + c.Defaults.DegradedLatency = NewDuration(1000 * time.Millisecond) + } + + // Theme color fallbacks if omitted + defTheme := DefaultConfig().Page.Theme + if c.Page.Theme.BgColor == "" { + c.Page.Theme.BgColor = defTheme.BgColor + } + if c.Page.Theme.CardBgColor == "" { + c.Page.Theme.CardBgColor = defTheme.CardBgColor + } + if c.Page.Theme.TextColor == "" { + c.Page.Theme.TextColor = defTheme.TextColor + } + if c.Page.Theme.MutedTextColor == "" { + c.Page.Theme.MutedTextColor = defTheme.MutedTextColor + } + if c.Page.Theme.BorderColor == "" { + c.Page.Theme.BorderColor = defTheme.BorderColor + } + if c.Page.Theme.AccentColor == "" { + c.Page.Theme.AccentColor = defTheme.AccentColor + } + if c.Page.Theme.UpColor == "" { + c.Page.Theme.UpColor = defTheme.UpColor + } + if c.Page.Theme.DegradedColor == "" { + c.Page.Theme.DegradedColor = defTheme.DegradedColor + } + if c.Page.Theme.DownColor == "" { + c.Page.Theme.DownColor = defTheme.DownColor + } + if c.Page.Theme.PendingColor == "" { + c.Page.Theme.PendingColor = defTheme.PendingColor + } + if c.Page.Theme.FontFamily == "" { + c.Page.Theme.FontFamily = defTheme.FontFamily + } + if c.Page.Theme.MaxWidth == "" { + c.Page.Theme.MaxWidth = defTheme.MaxWidth + } + if c.Page.Theme.BorderRadius == "" { + c.Page.Theme.BorderRadius = defTheme.BorderRadius + } +} + +// Validate checks the configuration for duplicate IDs, invalid methods, or invalid regexes. +func (c *Config) Validate() error { + seen := make(map[string]bool) + for i := range c.Monitors { + m := &c.Monitors[i] + if strings.TrimSpace(m.ID) == "" { + return fmt.Errorf("monitor at index %d is missing an 'id'", i) + } + if seen[m.ID] { + return fmt.Errorf("duplicate monitor id %q", m.ID) + } + seen[m.ID] = true + if m.Name == "" { + m.Name = m.ID + } + + method := strings.ToLower(strings.TrimSpace(m.Method)) + m.Method = method + switch method { + case "http", "https": + if m.URL == "" { + return fmt.Errorf("monitor %q (method %s) requires 'url'", m.ID, method) + } + if m.BodyRegex != "" { + if _, err := regexp.Compile(m.BodyRegex); err != nil { + return fmt.Errorf("monitor %q has invalid body_regex %q: %w", m.ID, m.BodyRegex, err) + } + } + case "tcp": + if m.Target == "" && m.Host == "" { + return fmt.Errorf("monitor %q (method tcp) requires 'target' (host:port)", m.ID) + } + if m.Target == "" { + m.Target = m.Host + } + case "ping": + if m.Host == "" && m.Target == "" { + return fmt.Errorf("monitor %q (method ping) requires 'host'", m.ID) + } + if m.Host == "" { + m.Host = m.Target + } + case "dns": + if m.Host == "" && m.Target == "" { + return fmt.Errorf("monitor %q (method dns) requires 'host'", m.ID) + } + if m.Host == "" { + m.Host = m.Target + } + if m.ExpectedRegex != "" { + if _, err := regexp.Compile(m.ExpectedRegex); err != nil { + return fmt.Errorf("monitor %q has invalid expected_regex %q: %w", m.ID, m.ExpectedRegex, err) + } + } + case "cmd", "script", "command": + if m.Command == "" { + return fmt.Errorf("monitor %q (method %s) requires 'command'", m.ID, method) + } + if m.OutputRegex != "" { + if _, err := regexp.Compile(m.OutputRegex); err != nil { + return fmt.Errorf("monitor %q has invalid output_regex %q: %w", m.ID, m.OutputRegex, err) + } + } + default: + return fmt.Errorf("monitor %q has unsupported method %q (supported: http, https, tcp, ping, dns, cmd)", m.ID, m.Method) + } + } + + for i, ev := range c.Events { + if ev.ID == "" { + return fmt.Errorf("event at index %d is missing an 'id'", i) + } + if err := validateCondition(ev.Condition); err != nil { + return fmt.Errorf("event %q has invalid condition: %w", ev.ID, err) + } + } + + return nil +} + +func validateCondition(cond EventCondition) error { + if len(cond.Conditions) > 0 { + op := strings.ToLower(cond.Operator) + if op != "" && op != "and" && op != "or" { + return fmt.Errorf("unsupported boolean operator %q (expected 'and' or 'or')", cond.Operator) + } + for _, sub := range cond.Conditions { + if err := validateCondition(sub); err != nil { + return err + } + } + return nil + } + + t := strings.ToLower(cond.Type) + if t == "" { + if cond.Metric != "" { + t = "metric" + } else if cond.State != "" { + t = "state" + } + } + switch t { + case "state": + s := strings.ToLower(cond.State) + if s != "up" && s != "degraded" && s != "down" && s != "pending" { + return fmt.Errorf("invalid state %q in state condition", cond.State) + } + case "metric": + m := strings.ToLower(cond.Metric) + if m != "uptime_pct" && m != "uptime" && m != "latency_ms" && m != "latency" && m != "consecutive_failures" { + return fmt.Errorf("invalid metric %q (expected uptime_pct, latency_ms, or consecutive_failures)", cond.Metric) + } + switch cond.Comparator { + case "<", "<=", ">", ">=", "==", "!=": + default: + return fmt.Errorf("invalid comparator %q in metric condition", cond.Comparator) + } + default: + return fmt.Errorf("condition must specify either 'conditions' (and/or), 'state', or 'metric'") + } + return nil +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..a86b913 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,75 @@ +package config + +import ( + "path/filepath" + "testing" + "time" +) + +func TestLoadOrInitGeneratesDefault(t *testing.T) { + tmpDir := t.TempDir() + cfgPath := filepath.Join(tmpDir, "rud.json") + + cfg, created, err := LoadOrInit(cfgPath, true) + if err != nil { + t.Fatalf("LoadOrInit failed: %v", err) + } + if !created { + t.Fatalf("expected created=true when file did not exist") + } + if len(cfg.Monitors) == 0 { + t.Fatalf("expected default monitors to be populated") + } + if len(cfg.Page.Elements) == 0 { + t.Fatalf("expected default page elements to be populated") + } + + // Reload existing file + cfg2, created2, err := LoadOrInit(cfgPath, true) + if err != nil { + t.Fatalf("second LoadOrInit failed: %v", err) + } + if created2 { + t.Fatalf("expected created=false when file already exists") + } + if len(cfg2.Monitors) != len(cfg.Monitors) { + t.Fatalf("expected %d monitors, got %d", len(cfg.Monitors), len(cfg2.Monitors)) + } +} + +func TestDurationMarshalUnmarshal(t *testing.T) { + d := NewDuration(5 * time.Hour) + b, err := d.MarshalJSON() + if err != nil { + t.Fatalf("MarshalJSON failed: %v", err) + } + if string(b) != `"5h"` { + t.Fatalf("expected \"5h\", got %s", string(b)) + } + + var parsed Duration + if err := parsed.UnmarshalJSON([]byte(`"15m"`)); err != nil { + t.Fatalf("UnmarshalJSON failed: %v", err) + } + if parsed.Std() != 15*time.Minute { + t.Fatalf("expected 15m, got %v", parsed.Std()) + } +} + +func TestConfigValidation(t *testing.T) { + cfg := DefaultConfig() + cfg.Monitors = []MonitorConfig{ + {ID: "dup", Method: "tcp", Target: "127.0.0.1:80"}, + {ID: "dup", Method: "tcp", Target: "127.0.0.1:81"}, + } + if err := cfg.Validate(); err == nil { + t.Fatalf("expected duplicate monitor id error") + } + + cfg.Monitors = []MonitorConfig{ + {ID: "bad-regex", Method: "http", URL: "http://example.com", BodyRegex: "["}, + } + if err := cfg.Validate(); err == nil { + t.Fatalf("expected invalid body_regex error") + } +} diff --git a/internal/events/engine.go b/internal/events/engine.go new file mode 100644 index 0000000..7a60cf9 --- /dev/null +++ b/internal/events/engine.go @@ -0,0 +1,438 @@ +package events + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "os/exec" + "sort" + "strings" + "sync" + "text/template" + "time" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +type ruleState struct { + Active bool + ActiveSince time.Time + LastFiredAt time.Time +} + +// EventPayload is passed to webhook body templates and command templates when an event triggers or resolves. +type EventPayload struct { + EventID string `json:"event_id"` + EventName string `json:"event_name"` + Status string `json:"status"` // "TRIGGERED" or "RESOLVED" + OverallState string `json:"overall_state"` + OverallUptimePct float64 `json:"overall_uptime_pct"` + TriggeredMonitors string `json:"triggered_monitors"` + Monitors []store.MonitorState `json:"monitors"` + MonitorsJSON string `json:"-"` + Timestamp string `json:"timestamp"` +} + +// Engine evaluates declarative event rules against Store snapshots and dispatches actions. +type Engine struct { + mu sync.Mutex + events []config.EventConfig + states map[string]*ruleState + metricMatchedSince map[string]time.Time + actionWg sync.WaitGroup + ActionHook func(eventID, status, actionType string, payload EventPayload) // optional test hook +} + +// NewEngine creates a new declarative Event Engine. +func NewEngine(events []config.EventConfig) *Engine { + states := make(map[string]*ruleState, len(events)) + for _, ev := range events { + states[ev.ID] = &ruleState{} + } + return &Engine{ + events: events, + states: states, + metricMatchedSince: make(map[string]time.Time), + } +} + +// Evaluate checks all configured event rules against the given store snapshot. +func (e *Engine) Evaluate(ctx context.Context, snap store.Snapshot) { + if len(e.events) == 0 { + return + } + now := snap.UpdatedAt + if now.IsZero() { + now = time.Now().UTC() + } + + e.mu.Lock() + defer e.mu.Unlock() + + for _, ev := range e.events { + st := e.states[ev.ID] + if st == nil { + st = &ruleState{} + e.states[ev.ID] = st + } + + matched, matchedIDs := e.evalCondition(ev.ID, "root", ev.Condition, snap, now) + if matched { + cooldown := ev.Cooldown.Std() + canFire := !st.Active && (st.LastFiredAt.IsZero() || cooldown <= 0 || now.Sub(st.LastFiredAt) >= cooldown) + if !st.Active { + st.Active = true + st.ActiveSince = now + } + if canFire { + st.LastFiredAt = now + payload := buildPayload(ev, "TRIGGERED", matchedIDs, snap, now) + e.dispatchActions(ctx, ev.ID, payload, ev.Actions) + } + } else { + if st.Active { + st.Active = false + if ev.TriggerOnRecovery { + actions := ev.RecoveryActions + if len(actions) == 0 { + actions = ev.Actions + } + payload := buildPayload(ev, "RESOLVED", matchedIDs, snap, now) + e.dispatchActions(ctx, ev.ID, payload, actions) + } + } + } + } +} + +// Wait blocks until any in-flight asynchronous actions complete. +func (e *Engine) Wait() { + e.actionWg.Wait() +} + +func (e *Engine) evalCondition(eventID, path string, cond config.EventCondition, snap store.Snapshot, now time.Time) (bool, []string) { + if len(cond.Conditions) > 0 { + op := strings.ToLower(strings.TrimSpace(cond.Operator)) + if op == "" { + op = "and" + } + var collected []string + seen := make(map[string]bool) + + if op == "or" { + anyMatched := false + for i, sub := range cond.Conditions { + subPath := fmt.Sprintf("%s.%d", path, i) + ok, ids := e.evalCondition(eventID, subPath, sub, snap, now) + if ok { + anyMatched = true + for _, id := range ids { + if !seen[id] { + seen[id] = true + collected = append(collected, id) + } + } + } + } + return anyMatched, collected + } + + // Default: "and" + if len(cond.Conditions) == 0 { + return false, nil + } + for i, sub := range cond.Conditions { + subPath := fmt.Sprintf("%s.%d", path, i) + ok, ids := e.evalCondition(eventID, subPath, sub, snap, now) + if !ok { + return false, nil + } + for _, id := range ids { + if !seen[id] { + seen[id] = true + collected = append(collected, id) + } + } + } + return true, collected + } + + targets := selectMonitors(cond.Monitors, snap) + if len(targets) == 0 { + return false, nil + } + + matchMode := strings.ToLower(strings.TrimSpace(cond.Match)) + if matchMode == "" { + matchMode = "all" + } + + condType := strings.ToLower(strings.TrimSpace(cond.Type)) + if condType == "" { + if cond.Metric != "" { + condType = "metric" + } else { + condType = "state" + } + } + + var matchedIDs []string + for _, m := range targets { + // Do not evaluate pending monitors unless state explicitly checks "pending" + if m.State == store.StatePending && strings.ToLower(cond.State) != store.StatePending { + continue + } + + var monMatch bool + switch condType { + case "state": + targetState := strings.ToLower(strings.TrimSpace(cond.State)) + if strings.ToLower(m.State) == targetState { + if cond.For.Std() <= 0 || (!m.StateChangedAt.IsZero() && now.Sub(m.StateChangedAt) >= cond.For.Std()) { + monMatch = true + } + } + case "metric": + rawMatch := compareMetric(m, cond.Metric, cond.Comparator, cond.Value) + key := fmt.Sprintf("%s:%s:%s", eventID, path, m.ID) + if rawMatch { + since, exists := e.metricMatchedSince[key] + if !exists { + since = now + e.metricMatchedSince[key] = since + } + if cond.For.Std() <= 0 || now.Sub(since) >= cond.For.Std() { + monMatch = true + } + } else { + delete(e.metricMatchedSince, key) + } + } + + if monMatch { + matchedIDs = append(matchedIDs, m.ID) + } + } + + if matchMode == "any" { + return len(matchedIDs) > 0, matchedIDs + } + // "all" mode requires every targeted monitor to match + return len(matchedIDs) == len(targets) && len(targets) > 0, matchedIDs +} + +func selectMonitors(ids []string, snap store.Snapshot) []store.MonitorState { + if len(ids) == 0 { + return snap.Monitors + } + for _, id := range ids { + if id == "*" { + return snap.Monitors + } + } + res := make([]store.MonitorState, 0, len(ids)) + for _, id := range ids { + if m, ok := snap.MonitorsByID[id]; ok { + res = append(res, m) + } + } + return res +} + +func compareMetric(m store.MonitorState, metric, comparator string, threshold float64) bool { + var val float64 + switch strings.ToLower(strings.TrimSpace(metric)) { + case "uptime_pct", "uptime": + val = m.UptimePct + case "latency_ms", "latency": + val = m.LatencyMs + case "consecutive_failures": + val = float64(m.ConsecutiveFailures) + default: + return false + } + + switch strings.TrimSpace(comparator) { + case "<": + return val < threshold + case "<=": + return val <= threshold + case ">": + return val > threshold + case ">=": + return val >= threshold + case "==": + return val == threshold + case "!=": + return val != threshold + default: + return false + } +} + +func buildPayload(ev config.EventConfig, status string, matchedIDs []string, snap store.Snapshot, now time.Time) EventPayload { + sort.Strings(matchedIDs) + monitors := make([]store.MonitorState, 0, len(matchedIDs)) + for _, id := range matchedIDs { + if m, ok := snap.MonitorsByID[id]; ok { + monitors = append(monitors, m) + } + } + monBytes, _ := json.Marshal(monitors) + return EventPayload{ + EventID: ev.ID, + EventName: ev.Name, + Status: status, + OverallState: snap.OverallState, + OverallUptimePct: snap.OverallUptimePct, + TriggeredMonitors: strings.Join(matchedIDs, ","), + Monitors: monitors, + MonitorsJSON: string(monBytes), + Timestamp: now.Format(time.RFC3339), + } +} + +func (e *Engine) dispatchActions(ctx context.Context, eventID string, payload EventPayload, actions []config.EventAction) { + for _, act := range actions { + action := act + if e.ActionHook != nil { + e.ActionHook(eventID, payload.Status, action.Type, payload) + } + e.actionWg.Add(1) + go func() { + defer e.actionWg.Done() + timeout := action.Timeout.Std() + if timeout <= 0 { + timeout = 10 * time.Second + } + actCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + switch strings.ToLower(strings.TrimSpace(action.Type)) { + case "webhook": + if err := executeWebhook(actCtx, action, payload, timeout); err != nil { + log.Printf("[event:%s] webhook action error: %v", eventID, err) + } + case "command", "cmd", "script": + if err := executeCommand(actCtx, action, payload); err != nil { + log.Printf("[event:%s] command action error: %v", eventID, err) + } + } + }() + } +} + +func executeWebhook(ctx context.Context, act config.EventAction, payload EventPayload, timeout time.Duration) error { + if act.URL == "" { + return fmt.Errorf("webhook URL is empty") + } + method := strings.ToUpper(strings.TrimSpace(act.HTTPMethod)) + if method == "" { + method = http.MethodPost + } + + var bodyBytes []byte + if act.BodyTemplate != "" { + rendered, err := renderTemplate(act.BodyTemplate, payload) + if err != nil { + return fmt.Errorf("render webhook body_template: %w", err) + } + bodyBytes = []byte(rendered) + } else { + var err error + bodyBytes, err = json.Marshal(payload) + if err != nil { + return err + } + } + + req, err := http.NewRequestWithContext(ctx, method, act.URL, bytes.NewReader(bodyBytes)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "RUD-Alert/1.0 (+https://git.gsdistance.org/tyuXX/RUD)") + for k, v := range act.Headers { + req.Header.Set(k, v) + } + + client := &http.Client{Timeout: timeout} + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + if resp.StatusCode >= 400 { + return fmt.Errorf("webhook returned HTTP %d", resp.StatusCode) + } + return nil +} + +func executeCommand(ctx context.Context, act config.EventAction, payload EventPayload) error { + cmdStr, err := renderTemplate(act.Command, payload) + if err != nil { + return fmt.Errorf("render command template: %w", err) + } + args := make([]string, len(act.Args)) + for i, a := range act.Args { + rendered, err := renderTemplate(a, payload) + if err != nil { + return fmt.Errorf("render arg template: %w", err) + } + args[i] = rendered + } + + var cmd *exec.Cmd + if act.Shell || (len(args) == 0 && strings.ContainsAny(cmdStr, " \t|&;<>()$`\"'")) { + full := cmdStr + if len(args) > 0 { + full += " " + strings.Join(args, " ") + } + cmd = exec.CommandContext(ctx, "/bin/sh", "-c", full) + } else { + cmd = exec.CommandContext(ctx, cmdStr, args...) + } + + if act.WorkingDir != "" { + cmd.Dir = act.WorkingDir + } + + env := os.Environ() + env = append(env, + "RUD_EVENT_ID="+payload.EventID, + "RUD_EVENT_NAME="+payload.EventName, + "RUD_EVENT_STATUS="+payload.Status, + "RUD_OVERALL_STATE="+payload.OverallState, + "RUD_TRIGGERED_MONITORS="+payload.TriggeredMonitors, + "RUD_TIMESTAMP="+payload.Timestamp, + ) + for k, v := range act.Env { + env = append(env, fmt.Sprintf("%s=%s", k, v)) + } + cmd.Env = env + + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out))) + } + return nil +} + +func renderTemplate(tmplStr string, data EventPayload) (string, error) { + t, err := template.New("action").Parse(tmplStr) + if err != nil { + return "", err + } + var buf bytes.Buffer + if err := t.Execute(&buf, data); err != nil { + return "", err + } + return buf.String(), nil +} diff --git a/internal/events/engine_test.go b/internal/events/engine_test.go new file mode 100644 index 0000000..1dcfe46 --- /dev/null +++ b/internal/events/engine_test.go @@ -0,0 +1,152 @@ +package events + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) { + var webhookMu sync.Mutex + var webhookBodies []string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + webhookMu.Lock() + webhookBodies = append(webhookBodies, string(b)) + webhookMu.Unlock() + w.WriteHeader(http.StatusOK) + })) + defer ts.Close() + + tmpFile := filepath.Join(t.TempDir(), "cmd_alert.txt") + + evCfg := []config.EventConfig{ + { + ID: "multi-or-sustained", + Name: "Multi Monitor Down or 5h Outage", + Cooldown: config.NewDuration(10 * time.Minute), + TriggerOnRecovery: true, + Condition: config.EventCondition{ + Operator: "or", + Conditions: [ ]config.EventCondition{ + // Monitors 1, 2, 3 are all down + { + Type: "state", + Monitors: []string{"1", "2", "3"}, + Match: "all", + State: "down", + }, + // Any monitor down for >= 5 hours AND uptime_pct < 90 + { + Operator: "and", + Conditions: []config.EventCondition{ + { + Type: "state", + Monitors: []string{"*"}, + Match: "any", + State: "down", + For: config.NewDuration(5 * time.Hour), + }, + { + Type: "metric", + Monitors: []string{"*"}, + Match: "any", + Metric: "uptime_pct", + Comparator: "<", + Value: 90.0, + }, + }, + }, + }, + }, + Actions: []config.EventAction{ + { + Type: "webhook", + URL: ts.URL, + BodyTemplate: `{"event":"{{.EventID}}","status":"{{.Status}}","monitors":"{{.TriggeredMonitors}}"}`, + }, + { + Type: "command", + Command: "printf '%s:%s' '{{.Status}}' '{{.TriggeredMonitors}}' > " + tmpFile, + Shell: true, + }, + }, + }, + } + + eng := NewEngine(evCfg) + now := time.Now().UTC() + + // Case 1: Only monitor 1 and 2 are down for 1 minute (should NOT trigger) + snap1 := store.Snapshot{ + OverallState: store.StateDown, + UpdatedAt: now, + Monitors: []store.MonitorState{ + {ID: "1", State: store.StateDown, StateChangedAt: now.Add(-time.Minute), UptimePct: 95}, + {ID: "2", State: store.StateDown, StateChangedAt: now.Add(-time.Minute), UptimePct: 95}, + {ID: "3", State: store.StateUp, StateChangedAt: now.Add(-time.Hour), UptimePct: 100}, + }, + } + snap1.MonitorsByID = map[string]store.MonitorState{ + "1": snap1.Monitors[0], + "2": snap1.Monitors[1], + "3": snap1.Monitors[2], + } + eng.Evaluate(context.Background(), snap1) + eng.Wait() + + webhookMu.Lock() + if len(webhookBodies) != 0 { + t.Fatalf("expected 0 webhook calls, got %d", len(webhookBodies)) + } + webhookMu.Unlock() + + // Case 2: Monitor 1 has been down for 5h10m and uptime_pct is 80% (SHOULD trigger!) + snap2 := snap1 + snap2.Monitors[0].StateChangedAt = now.Add(-5*time.Hour - 10*time.Minute) + snap2.Monitors[0].UptimePct = 80.0 + snap2.MonitorsByID["1"] = snap2.Monitors[0] + + eng.Evaluate(context.Background(), snap2) + eng.Wait() + + webhookMu.Lock() + if len(webhookBodies) != 1 { + t.Fatalf("expected 1 webhook call on sustained 5h + metric trigger, got %d", len(webhookBodies)) + } + if !strings.Contains(webhookBodies[0], `"status":"TRIGGERED"`) { + t.Fatalf("unexpected webhook body: %s", webhookBodies[0]) + } + webhookMu.Unlock() + + cmdData, err := os.ReadFile(tmpFile) + if err != nil || !strings.HasPrefix(string(cmdData), "TRIGGERED:") { + t.Fatalf("expected command action output TRIGGERED:..., got %q (err=%v)", string(cmdData), err) + } + + // Case 3: All monitors recover -> should fire RESOLVED + snap3 := snap1 + for i := range snap3.Monitors { + snap3.Monitors[i].State = store.StateUp + snap3.Monitors[i].UptimePct = 99.9 + snap3.MonitorsByID[snap3.Monitors[i].ID] = snap3.Monitors[i] + } + eng.Evaluate(context.Background(), snap3) + eng.Wait() + + webhookMu.Lock() + if len(webhookBodies) != 2 || !strings.Contains(webhookBodies[1], `"status":"RESOLVED"`) { + t.Fatalf("expected recovery webhook call, got %v", webhookBodies) + } + webhookMu.Unlock() +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..48f4b54 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,793 @@ +package server + +import ( + "bytes" + "encoding/json" + "fmt" + "html/template" + "net/http" + "strings" + "time" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +// Server serves the single configured HTTP status and health check endpoint. +type Server struct { + cfg *config.Config + store *store.Store +} + +// New creates a new single-endpoint HTTP server. +func New(cfg *config.Config, st *store.Store) *Server { + return &Server{ + cfg: cfg, + store: st, + } +} + +// ServeHTTP handles incoming HTTP requests strictly on the configured single endpoint. +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + endpoint := s.cfg.Server.Endpoint + if endpoint == "" { + endpoint = "/" + } + if r.URL.Path != endpoint { + http.NotFound(w, r) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + snap := s.store.Snapshot() + w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") + + if wantsJSON(r) { + code := statusCodeForState(s.cfg.Server.StatusCodes.JSON, snap.OverallState) + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(code) + if r.Method == http.MethodHead { + return + } + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + _ = enc.Encode(snap) + return + } + + code := statusCodeForState(s.cfg.Server.StatusCodes.HTML, snap.OverallState) + rendered, err := s.renderHTML(snap) + if err != nil { + http.Error(w, "template error", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(code) + if r.Method == http.MethodHead { + return + } + _, _ = w.Write(rendered) +} + +func wantsJSON(r *http.Request) bool { + q := r.URL.Query() + if strings.EqualFold(q.Get("format"), "json") || q.Get("json") == "1" || strings.EqualFold(q.Get("json"), "true") { + return true + } + accept := strings.ToLower(r.Header.Get("Accept")) + if strings.Contains(accept, "application/json") && !strings.Contains(accept, "text/html") { + return true + } + return false +} + +func statusCodeForState(codes config.StatusCodesByState, state string) int { + switch state { + case store.StateUp: + if codes.Up > 0 { + return codes.Up + } + case store.StateDegraded: + if codes.Degraded > 0 { + return codes.Degraded + } + case store.StateDown: + if codes.Down > 0 { + return codes.Down + } + default: + if codes.Pending > 0 { + return codes.Pending + } + } + return http.StatusOK +} + +type viewData struct { + Title string + Theme config.ThemeConfig + CustomCSS template.CSS + RefreshMs int64 + Snapshot store.Snapshot + RenderedElements []renderedElement +} + +type renderedElement struct { + Type string + Title string + Subtitle string + Description string + Align string + ShowLastUpdated bool + ShowLiveIndicator bool + + // Banner + BannerMessage string + BannerMessagesJSON template.JS + ShowOverallUptime bool + ShowCounts bool + + // Summary cards + Cards []summaryCardView + + // Monitor group + Layout string + Monitors []monitorView + Display monitorDisplayFlags + + // Custom block + Content string + Style string +} + +type summaryCardView struct { + Key string + Label string + Value string +} + +type monitorDisplayFlags struct { + ShowBar bool + BarTicks int + ShowUptime bool + ShowLatency bool + ShowStatusBadge bool + ShowMethod bool + ShowTarget bool + ShowDescription bool + ShowMessage bool + ShowLastChecked bool + LabelsJSON template.JS +} + +type monitorView struct { + Monitor store.MonitorState + BadgeLabel string + Ticks []barTickView + LastChecked string +} + +type barTickView struct { + State string + Tooltip string +} + +func (s *Server) renderHTML(snap store.Snapshot) ([]byte, error) { + title := s.cfg.Page.Title + if title == "" { + title = "R u ded?" + } + + elements := make([]renderedElement, 0, len(s.cfg.Page.Elements)) + for _, el := range s.cfg.Page.Elements { + elType := strings.ToLower(strings.TrimSpace(el.Type)) + switch elType { + case "header": + align := strings.ToLower(el.Align) + if align == "" { + align = "split" + } + elements = append(elements, renderedElement{ + Type: "header", + Title: el.Title, + Subtitle: el.Subtitle, + Align: align, + ShowLastUpdated: el.ShowLastUpdated, + ShowLiveIndicator: el.ShowLiveIndicator, + }) + + case "status_banner": + msgs := map[string]string{ + store.StateUp: "All systems operational", + store.StateDegraded: "Some systems are degraded", + store.StateDown: "Systems are down", + store.StatePending: "Checking systems...", + } + for k, v := range el.Messages { + msgs[strings.ToLower(k)] = v + } + msgBytes, _ := json.Marshal(msgs) + elements = append(elements, renderedElement{ + Type: "status_banner", + BannerMessage: msgs[snap.OverallState], + BannerMessagesJSON: template.JS(msgBytes), + ShowOverallUptime: el.ShowOverallUptime, + ShowCounts: el.ShowCounts, + }) + + case "summary_cards", "summary": + cards := buildSummaryCards(el.Metrics, snap) + elements = append(elements, renderedElement{ + Type: "summary_cards", + Title: el.Title, + Cards: cards, + }) + + case "monitor_group", "monitors": + var dispCfg config.MonitorDisplayConfig + if el.Display != nil { + dispCfg = *el.Display + } + flags := resolveDisplayFlags(dispCfg, s.cfg.Storage.HistorySize) + mons := selectGroupMonitors(el.Monitors, snap, flags) + layout := strings.ToLower(el.Layout) + if layout == "" { + layout = "list" + } + elements = append(elements, renderedElement{ + Type: "monitor_group", + Title: el.Title, + Description: el.Description, + Layout: layout, + Monitors: mons, + Display: flags, + }) + + case "custom_block", "text": + style := strings.ToLower(el.Style) + if style == "" { + style = "neutral" + } + elements = append(elements, renderedElement{ + Type: "custom_block", + Title: el.Title, + Content: el.Content, + Style: style, + }) + + case "divider": + elements = append(elements, renderedElement{ + Type: "divider", + }) + } + } + + vd := viewData{ + Title: title, + Theme: s.cfg.Page.Theme, + CustomCSS: template.CSS(s.cfg.Page.Theme.CustomCSS), + RefreshMs: s.cfg.Server.RefreshInterval.Std().Milliseconds(), + Snapshot: snap, + RenderedElements: elements, + } + + var buf bytes.Buffer + if err := pageTemplate.Execute(&buf, vd); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func buildSummaryCards(metrics []string, snap store.Snapshot) []summaryCardView { + if len(metrics) == 0 { + metrics = []string{"total", "up", "degraded", "down", "overall_uptime", "avg_latency"} + } + cards := make([]summaryCardView, 0, len(metrics)) + for _, m := range metrics { + key := strings.ToLower(strings.TrimSpace(m)) + switch key { + case "total": + cards = append(cards, summaryCardView{Key: "total", Label: "TOTAL", Value: fmt.Sprintf("%d", snap.Counts.Total)}) + case "up": + cards = append(cards, summaryCardView{Key: "up", Label: "UP", Value: fmt.Sprintf("%d", snap.Counts.Up)}) + case "degraded": + cards = append(cards, summaryCardView{Key: "degraded", Label: "DEGRADED", Value: fmt.Sprintf("%d", snap.Counts.Degraded)}) + case "down": + cards = append(cards, summaryCardView{Key: "down", Label: "DOWN", Value: fmt.Sprintf("%d", snap.Counts.Down)}) + case "overall_uptime", "uptime": + cards = append(cards, summaryCardView{Key: "overall_uptime", Label: "UPTIME", Value: fmt.Sprintf("%.2f%%", snap.OverallUptimePct)}) + case "avg_latency", "latency": + cards = append(cards, summaryCardView{Key: "avg_latency", Label: "AVG LATENCY", Value: fmt.Sprintf("%.1fms", snap.AvgLatencyMs)}) + } + } + return cards +} + +func resolveDisplayFlags(d config.MonitorDisplayConfig, defaultTicks int) monitorDisplayFlags { + boolVal := func(p *bool, def bool) bool { + if p == nil { + return def + } + return *p + } + ticks := d.BarTicks + if ticks <= 0 { + ticks = 40 + if defaultTicks > 0 && defaultTicks < ticks { + ticks = defaultTicks + } + } + labels := map[string]string{ + store.StateUp: "UP", + store.StateDegraded: "DEGRADED", + store.StateDown: "DOWN", + store.StatePending: "PENDING", + } + for k, v := range d.CustomLabels { + labels[strings.ToLower(k)] = v + } + labelsBytes, _ := json.Marshal(labels) + + return monitorDisplayFlags{ + ShowBar: boolVal(d.ShowBar, true), + BarTicks: ticks, + ShowUptime: boolVal(d.ShowUptime, true), + ShowLatency: boolVal(d.ShowLatency, true), + ShowStatusBadge: boolVal(d.ShowStatusBadge, true), + ShowMethod: boolVal(d.ShowMethod, true), + ShowTarget: boolVal(d.ShowTarget, false), + ShowDescription: boolVal(d.ShowDescription, true), + ShowMessage: boolVal(d.ShowMessage, false), + ShowLastChecked: boolVal(d.ShowLastChecked, false), + LabelsJSON: template.JS(labelsBytes), + } +} + +func selectGroupMonitors(ids []string, snap store.Snapshot, flags monitorDisplayFlags) []monitorView { + var raw []store.MonitorState + if len(ids) == 0 { + raw = snap.Monitors + } else { + all := false + for _, id := range ids { + if id == "*" { + all = true + break + } + } + if all { + raw = snap.Monitors + } else { + for _, id := range ids { + if m, ok := snap.MonitorsByID[id]; ok { + raw = append(raw, m) + } + } + } + } + + var labels map[string]string + _ = json.Unmarshal([]byte(flags.LabelsJSON), &labels) + + views := make([]monitorView, 0, len(raw)) + for _, m := range raw { + lbl := labels[m.State] + if lbl == "" { + lbl = strings.ToUpper(m.State) + } + + ticks := make([]barTickView, flags.BarTicks) + hist := m.History + if len(hist) > flags.BarTicks { + hist = hist[len(hist)-flags.BarTicks:] + } + padCount := flags.BarTicks - len(hist) + for i := 0; i < padCount; i++ { + ticks[i] = barTickView{State: store.StatePending, Tooltip: "No data"} + } + for i, h := range hist { + tip := fmt.Sprintf("%s | %s | %.1fms", h.Timestamp.Format("15:04:05 UTC"), strings.ToUpper(h.State), h.LatencyMs) + if h.Message != "" { + tip += " | " + h.Message + } + ticks[padCount+i] = barTickView{ + State: h.State, + Tooltip: tip, + } + } + + lastChecked := "never" + if !m.LastCheckedAt.IsZero() { + lastChecked = m.LastCheckedAt.Format("15:04:05 UTC") + } + + views = append(views, monitorView{ + Monitor: m, + BadgeLabel: lbl, + Ticks: ticks, + LastChecked: lastChecked, + }) + } + return views +} + +var pageTemplate = template.Must(template.New("status").Funcs(template.FuncMap{ + "upper": strings.ToUpper, + "fmtTime": func(t time.Time) string { + if t.IsZero() { + return "-" + } + return t.UTC().Format("2006-01-02 15:04:05 UTC") + }, +}).Parse(` + + + + +{{.Title}} + + + +
+{{- range .RenderedElements}} + {{- if eq .Type "header"}} +
+
+ {{- if .Title}}

{{.Title}}

{{end}} + {{- if .Subtitle}}
{{.Subtitle}}
{{end}} +
+ {{- if or .ShowLastUpdated .ShowLiveIndicator}} +
+ {{- if .ShowLiveIndicator}}{{end}} + {{- if .ShowLastUpdated}}{{fmtTime $.Snapshot.UpdatedAt}}{{end}} +
+ {{- end}} +
+ + {{- else if eq .Type "status_banner"}} + + + {{- else if eq .Type "summary_cards"}} +
+ {{- if .Title}}
{{.Title}}
{{end}} +
+ {{- range .Cards}} +
+
{{.Label}}
+
{{.Value}}
+
+ {{- end}} +
+
+ + {{- else if eq .Type "monitor_group"}} +
+ {{- if or .Title .Description}} +
+ {{- if .Title}}
{{.Title}}
{{end}} + {{- if .Description}}
{{.Description}}
{{end}} +
+ {{- end}} +
+ {{- $disp := .Display}} + {{- range .Monitors}} +
+
+
+ {{- if .Monitor.Link}} + {{.Monitor.Name}} + {{- else}} + {{.Monitor.Name}} + {{- end}} + {{- if $disp.ShowMethod}}{{upper .Monitor.Method}}{{end}} + {{- if and $disp.ShowTarget .Monitor.Target}}{{.Monitor.Target}}{{end}} +
+
+ {{- if $disp.ShowLatency}}{{printf "%.1fms" .Monitor.LatencyMs}}{{end}} + {{- if $disp.ShowUptime}}{{printf "%.2f%%" .Monitor.UptimePct}}{{end}} + {{- if $disp.ShowStatusBadge}}{{.BadgeLabel}}{{end}} +
+
+ {{- if $disp.ShowBar}} +
+ {{- range .Ticks}} +
+ {{- end}} +
+ {{- end}} + {{- if or $disp.ShowDescription $disp.ShowMessage $disp.ShowLastChecked}} +
+ + {{- if and $disp.ShowDescription .Monitor.Description}}{{.Monitor.Description}}{{end}} + {{- if and $disp.ShowMessage .Monitor.LastMessage}} ({{.Monitor.LastMessage}}){{end}} + + {{- if $disp.ShowLastChecked}}{{.LastChecked}}{{end}} +
+ {{- end}} +
+ {{- end}} +
+
+ + {{- else if eq .Type "custom_block"}} +
+ {{- if .Title}}
{{.Title}}
{{end}} +
{{.Content}}
+
+ + {{- else if eq .Type "divider"}} +
+ {{- end}} +{{- end}} + + +
+{{- if gt .RefreshMs 0}} + +{{- end}} + + +`)) diff --git a/internal/server/server_test.go b/internal/server/server_test.go new file mode 100644 index 0000000..12c954d --- /dev/null +++ b/internal/server/server_test.go @@ -0,0 +1,70 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +func TestSingleEndpointHTMLAndJSON(t *testing.T) { + cfg := config.DefaultConfig() + // Configure only a single header element to verify strict element rendering + cfg.Page.Elements = []config.PageElement{ + { + Type: "header", + Title: "Custom Minimal Title", + }, + } + + st := store.New(&cfg) + st.Record("rud-http", store.CheckResult{State: store.StateDown, LatencyMs: 12.3, Message: "connection refused"}) + + srv := New(&cfg, st) + + // 1. Non-configured path must return 404 + req404 := httptest.NewRequest(http.MethodGet, "/other-path", nil) + w404 := httptest.NewRecorder() + srv.ServeHTTP(w404, req404) + if w404.Code != http.StatusNotFound { + t.Fatalf("expected 404 on non-endpoint path, got %d", w404.Code) + } + + // 2. HTML request returns 200 (default for Cloudflared compatibility), renders only the header + 'Powered by R u ded?' + reqHTML := httptest.NewRequest(http.MethodGet, "/", nil) + wHTML := httptest.NewRecorder() + srv.ServeHTTP(wHTML, reqHTML) + if wHTML.Code != http.StatusOK { + t.Fatalf("expected HTML status 200, got %d", wHTML.Code) + } + htmlBody := wHTML.Body.String() + if !strings.Contains(htmlBody, "Custom Minimal Title") { + t.Fatalf("expected configured header title in HTML") + } + if !strings.Contains(htmlBody, "Powered by") || !strings.Contains(htmlBody, "R u ded?") { + t.Fatalf("expected 'Powered by R u ded?' attribution in HTML") + } + if strings.Contains(htmlBody, `