This commit is contained in:
tyuXX 2026-11-01 13:11:54 +00:00
parent c823102a63
commit d37503c863
20 changed files with 4433 additions and 3 deletions

6
.env.example Normal file
View file

@ -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

1
.gitignore vendored
View file

@ -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

432
CONFIGURATION.md Normal file
View file

@ -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 `<endpoint>?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"
}
```

25
Dockerfile Normal file
View file

@ -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"]

101
README.md
View file

@ -1,4 +1,99 @@
# RUD
# R u ded? (`rud`)
R u ded?
Performant and lightweight uptime and health check monitor written in go.
**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)).

View file

@ -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

13
docker-compose.yml Normal file
View file

@ -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

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module git.gsdistance.org/tyuXX/RUD
go 1.23

661
internal/checker/checker.go Normal file
View file

@ -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] + "..."
}

View file

@ -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)
}
}

790
internal/config/config.go Normal file
View file

@ -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
}

View file

@ -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")
}
}

438
internal/events/engine.go Normal file
View file

@ -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
}

View file

@ -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()
}

793
internal/server/server.go Normal file
View file

@ -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(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
<style>
:root {
--bg: {{.Theme.BgColor}};
--card: {{.Theme.CardBgColor}};
--text: {{.Theme.TextColor}};
--muted: {{.Theme.MutedTextColor}};
--border: {{.Theme.BorderColor}};
--accent: {{.Theme.AccentColor}};
--up: {{.Theme.UpColor}};
--degraded: {{.Theme.DegradedColor}};
--down: {{.Theme.DownColor}};
--pending: {{.Theme.PendingColor}};
--font: {{.Theme.FontFamily}};
--maxw: {{.Theme.MaxWidth}};
--radius: {{.Theme.BorderRadius}};
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg);
color: var(--text);
font-family: var(--font);
font-size: 13px;
line-height: 1.5;
padding: 24px 16px;
}
.container {
max-width: var(--maxw);
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 14px;
}
a { color: var(--text); text-decoration: underline; }
a:hover { color: var(--accent); }
.header {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: baseline;
gap: 8px;
padding-bottom: 10px;
border-bottom: 1px solid var(--border);
}
.header-center { flex-direction: column; align-items: center; text-align: center; }
.header-left { flex-direction: column; align-items: flex-start; }
.header h1 { font-size: 18px; font-weight: 700; letter-spacing: -0.02em; }
.header .subtitle { color: var(--muted); font-size: 12px; }
.header-meta { color: var(--muted); font-size: 11px; display: flex; align-items: center; gap: 6px; }
.live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--up); display: inline-block; }
.banner {
background: var(--card);
border: 1px solid var(--border);
border-left: 4px solid var(--pending);
border-radius: var(--radius);
padding: 12px 14px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 8px;
}
.banner[data-state="up"] { border-left-color: var(--up); }
.banner[data-state="degraded"] { border-left-color: var(--degraded); }
.banner[data-state="down"] { border-left-color: var(--down); }
.banner-title { font-weight: 700; font-size: 14px; }
.banner-meta { color: var(--muted); font-size: 12px; display: flex; gap: 12px; }
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
gap: 8px;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 8px 10px;
}
.card-label { color: var(--muted); font-size: 10px; text-transform: uppercase; }
.card-val { font-size: 15px; font-weight: 700; margin-top: 2px; }
.group { display: flex; flex-direction: column; gap: 6px; }
.group-hdr { display: flex; justify-content: space-between; align-items: baseline; }
.group-title { font-size: 13px; font-weight: 700; text-transform: uppercase; color: var(--muted); }
.group-desc { font-size: 11px; color: var(--muted); }
.monitors-list { display: flex; flex-direction: column; gap: 6px; }
.monitors-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 8px; }
.mon {
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.mon-top {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 8px;
}
.mon-left { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.mon-name { font-weight: 700; font-size: 13px; text-decoration: none; }
.mon-method {
font-size: 10px;
color: var(--muted);
border: 1px solid var(--border);
padding: 0 4px;
border-radius: var(--radius);
}
.mon-target { font-size: 11px; color: var(--muted); }
.mon-right { display: flex; align-items: center; gap: 10px; font-size: 12px; }
.mon-stat { color: var(--muted); font-size: 11px; }
.badge {
font-size: 11px;
font-weight: 700;
padding: 1px 6px;
border-radius: var(--radius);
border: 1px solid var(--border);
}
.badge[data-state="up"] { color: var(--up); border-color: var(--up); }
.badge[data-state="degraded"] { color: var(--degraded); border-color: var(--degraded); }
.badge[data-state="down"] { color: var(--down); border-color: var(--down); }
.badge[data-state="pending"] { color: var(--pending); border-color: var(--pending); }
.bar {
display: grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
gap: 2px;
height: 14px;
}
.tick {
background: var(--border);
border-radius: 1px;
height: 100%;
}
.tick[data-state="up"] { background: var(--up); }
.tick[data-state="degraded"] { background: var(--degraded); }
.tick[data-state="down"] { background: var(--down); }
.tick[data-state="pending"] { background: var(--border); opacity: 0.45; }
.mon-sub {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px;
font-size: 11px;
color: var(--muted);
}
.custom-block {
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 10px 12px;
}
.custom-block[data-style="info"] { border-left: 3px solid var(--accent); }
.custom-block[data-style="warning"] { border-left: 3px solid var(--degraded); }
.custom-block[data-style="danger"] { border-left: 3px solid var(--down); }
.custom-block-title { font-weight: 700; margin-bottom: 4px; }
.divider { border: 0; border-top: 1px solid var(--border); margin: 4px 0; }
.footer {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid var(--border);
text-align: center;
font-size: 11px;
color: var(--muted);
}
{{.CustomCSS}}
</style>
</head>
<body>
<div class="container">
{{- range .RenderedElements}}
{{- if eq .Type "header"}}
<header class="header {{if eq .Align "center"}}header-center{{else if eq .Align "left"}}header-left{{end}}">
<div>
{{- if .Title}}<h1>{{.Title}}</h1>{{end}}
{{- if .Subtitle}}<div class="subtitle">{{.Subtitle}}</div>{{end}}
</div>
{{- if or .ShowLastUpdated .ShowLiveIndicator}}
<div class="header-meta">
{{- if .ShowLiveIndicator}}<span class="live-dot" title="Live"></span>{{end}}
{{- if .ShowLastUpdated}}<span data-role="updated-at">{{fmtTime $.Snapshot.UpdatedAt}}</span>{{end}}
</div>
{{- end}}
</header>
{{- else if eq .Type "status_banner"}}
<section class="banner" data-role="status-banner" data-state="{{$.Snapshot.OverallState}}" data-messages='{{.BannerMessagesJSON}}'>
<div class="banner-title" data-role="banner-msg">{{.BannerMessage}}</div>
<div class="banner-meta">
{{- if .ShowCounts}}<span data-role="banner-counts">{{$.Snapshot.Counts.Up}}/{{$.Snapshot.Counts.Total}} up</span>{{end}}
{{- if .ShowOverallUptime}}<span data-role="banner-uptime">{{printf "%.2f%%" $.Snapshot.OverallUptimePct}} uptime</span>{{end}}
</div>
</section>
{{- else if eq .Type "summary_cards"}}
<section>
{{- if .Title}}<div class="group-title" style="margin-bottom:6px">{{.Title}}</div>{{end}}
<div class="cards">
{{- range .Cards}}
<div class="card">
<div class="card-label">{{.Label}}</div>
<div class="card-val" data-summary-key="{{.Key}}">{{.Value}}</div>
</div>
{{- end}}
</div>
</section>
{{- else if eq .Type "monitor_group"}}
<section class="group" data-role="monitor-group" data-ticks="{{.Display.BarTicks}}" data-labels='{{.Display.LabelsJSON}}'>
{{- if or .Title .Description}}
<div class="group-hdr">
{{- if .Title}}<div class="group-title">{{.Title}}</div>{{end}}
{{- if .Description}}<div class="group-desc">{{.Description}}</div>{{end}}
</div>
{{- end}}
<div class="{{if eq .Layout "grid"}}monitors-grid{{else}}monitors-list{{end}}">
{{- $disp := .Display}}
{{- range .Monitors}}
<div class="mon" data-monitor-id="{{.Monitor.ID}}">
<div class="mon-top">
<div class="mon-left">
{{- if .Monitor.Link}}
<a class="mon-name" href="{{.Monitor.Link}}" target="_blank" rel="noopener">{{.Monitor.Name}}</a>
{{- else}}
<span class="mon-name">{{.Monitor.Name}}</span>
{{- end}}
{{- if $disp.ShowMethod}}<span class="mon-method">{{upper .Monitor.Method}}</span>{{end}}
{{- if and $disp.ShowTarget .Monitor.Target}}<span class="mon-target">{{.Monitor.Target}}</span>{{end}}
</div>
<div class="mon-right">
{{- if $disp.ShowLatency}}<span class="mon-stat" data-field="latency">{{printf "%.1fms" .Monitor.LatencyMs}}</span>{{end}}
{{- if $disp.ShowUptime}}<span class="mon-stat" data-field="uptime">{{printf "%.2f%%" .Monitor.UptimePct}}</span>{{end}}
{{- if $disp.ShowStatusBadge}}<span class="badge" data-field="badge" data-state="{{.Monitor.State}}">{{.BadgeLabel}}</span>{{end}}
</div>
</div>
{{- if $disp.ShowBar}}
<div class="bar" data-field="bar">
{{- range .Ticks}}
<div class="tick" data-state="{{.State}}" title="{{.Tooltip}}"></div>
{{- end}}
</div>
{{- end}}
{{- if or $disp.ShowDescription $disp.ShowMessage $disp.ShowLastChecked}}
<div class="mon-sub">
<span>
{{- if and $disp.ShowDescription .Monitor.Description}}{{.Monitor.Description}}{{end}}
{{- if and $disp.ShowMessage .Monitor.LastMessage}} <span data-field="message">({{.Monitor.LastMessage}})</span>{{end}}
</span>
{{- if $disp.ShowLastChecked}}<span data-field="last-checked">{{.LastChecked}}</span>{{end}}
</div>
{{- end}}
</div>
{{- end}}
</div>
</section>
{{- else if eq .Type "custom_block"}}
<section class="custom-block" data-style="{{.Style}}">
{{- if .Title}}<div class="custom-block-title">{{.Title}}</div>{{end}}
<div>{{.Content}}</div>
</section>
{{- else if eq .Type "divider"}}
<hr class="divider">
{{- end}}
{{- end}}
<footer class="footer">
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a>
</footer>
</div>
{{- if gt .RefreshMs 0}}
<script>
(function() {
var interval = {{.RefreshMs}};
function refresh() {
fetch(window.location.pathname + '?format=json', { headers: { 'Accept': 'application/json' }, cache: 'no-store' })
.then(function(r) { return r.json(); })
.then(function(snap) {
if (!snap || !snap.monitors) return;
var upd = document.querySelectorAll('[data-role="updated-at"]');
var ts = snap.updated_at ? new Date(snap.updated_at).toISOString().replace('T', ' ').slice(0, 19) + ' UTC' : '';
upd.forEach(function(el) { el.textContent = ts; });
document.querySelectorAll('[data-role="status-banner"]').forEach(function(b) {
b.setAttribute('data-state', snap.status);
var msgs = {};
try { msgs = JSON.parse(b.getAttribute('data-messages') || '{}'); } catch (e) {}
var msgEl = b.querySelector('[data-role="banner-msg"]');
if (msgEl && msgs[snap.status]) msgEl.textContent = msgs[snap.status];
var cntEl = b.querySelector('[data-role="banner-counts"]');
if (cntEl && snap.counts) cntEl.textContent = snap.counts.up + '/' + snap.counts.total + ' up';
var upEl = b.querySelector('[data-role="banner-uptime"]');
if (upEl && typeof snap.overall_uptime_pct === 'number') upEl.textContent = snap.overall_uptime_pct.toFixed(2) + '% uptime';
});
document.querySelectorAll('[data-summary-key]').forEach(function(c) {
var k = c.getAttribute('data-summary-key');
if (k === 'total' && snap.counts) c.textContent = snap.counts.total;
else if (k === 'up' && snap.counts) c.textContent = snap.counts.up;
else if (k === 'degraded' && snap.counts) c.textContent = snap.counts.degraded;
else if (k === 'down' && snap.counts) c.textContent = snap.counts.down;
else if (k === 'overall_uptime') c.textContent = (snap.overall_uptime_pct || 0).toFixed(2) + '%';
else if (k === 'avg_latency') c.textContent = (snap.avg_latency_ms || 0).toFixed(1) + 'ms';
});
var byId = {};
snap.monitors.forEach(function(m) { byId[m.id] = m; });
document.querySelectorAll('[data-role="monitor-group"]').forEach(function(grp) {
var ticksCount = parseInt(grp.getAttribute('data-ticks') || '40', 10);
var labels = {};
try { labels = JSON.parse(grp.getAttribute('data-labels') || '{}'); } catch (e) {}
grp.querySelectorAll('[data-monitor-id]').forEach(function(card) {
var m = byId[card.getAttribute('data-monitor-id')];
if (!m) return;
var latEl = card.querySelector('[data-field="latency"]');
if (latEl) latEl.textContent = (m.latency_ms || 0).toFixed(1) + 'ms';
var upEl = card.querySelector('[data-field="uptime"]');
if (upEl) upEl.textContent = (m.uptime_pct || 0).toFixed(2) + '%';
var bdg = card.querySelector('[data-field="badge"]');
if (bdg) {
bdg.setAttribute('data-state', m.state);
bdg.textContent = labels[m.state] || m.state.toUpperCase();
}
var msgEl = card.querySelector('[data-field="message"]');
if (msgEl) msgEl.textContent = m.last_message ? '(' + m.last_message + ')' : '';
var lcEl = card.querySelector('[data-field="last-checked"]');
if (lcEl && m.last_checked_at) {
lcEl.textContent = new Date(m.last_checked_at).toISOString().slice(11, 19) + ' UTC';
}
var bar = card.querySelector('[data-field="bar"]');
if (bar && Array.isArray(m.history)) {
var hist = m.history.slice(-ticksCount);
var pad = ticksCount - hist.length;
var html = '';
for (var i = 0; i < pad; i++) {
html += '<div class="tick" data-state="pending" title="No data"></div>';
}
for (var j = 0; j < hist.length; j++) {
var h = hist[j];
var t = h.timestamp ? new Date(h.timestamp).toISOString().slice(11, 19) + ' UTC' : '';
var tip = t + ' | ' + (h.state || '').toUpperCase() + ' | ' + (h.latency_ms || 0).toFixed(1) + 'ms' + (h.message ? ' | ' + h.message : '');
html += '<div class="tick" data-state="' + h.state + '" title="' + tip.replace(/"/g, '&quot;') + '"></div>';
}
bar.innerHTML = html;
}
});
});
})
.catch(function() {});
}
setInterval(refresh, interval);
})();
</script>
{{- end}}
</body>
</html>
`))

View file

@ -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, `<section class="banner"`) {
t.Fatalf("expected unconfigured status_banner element NOT to be rendered")
}
// 3. JSON request via Accept header returns 503 (since a monitor is down) and valid Snapshot JSON
reqJSON := httptest.NewRequest(http.MethodGet, "/", nil)
reqJSON.Header.Set("Accept", "application/json")
wJSON := httptest.NewRecorder()
srv.ServeHTTP(wJSON, reqJSON)
if wJSON.Code != http.StatusServiceUnavailable {
t.Fatalf("expected JSON status 503 when monitor is down, got %d", wJSON.Code)
}
var snap store.Snapshot
if err := json.Unmarshal(wJSON.Body.Bytes(), &snap); err != nil {
t.Fatalf("failed to unmarshal JSON response: %v", err)
}
if snap.OverallState != store.StateDown {
t.Fatalf("expected JSON status 'down', got %q", snap.OverallState)
}
}

334
internal/store/store.go Normal file
View file

@ -0,0 +1,334 @@
package store
import (
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"sync"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
)
const (
StateUp = "up"
StateDegraded = "degraded"
StateDown = "down"
StatePending = "pending"
)
// CheckResult represents a single check execution outcome stored in the ring buffer.
type CheckResult struct {
Timestamp time.Time `json:"timestamp"`
State string `json:"state"`
LatencyMs float64 `json:"latency_ms"`
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
// MonitorState holds the live and historical state for a single monitor.
type MonitorState struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Link string `json:"link,omitempty"`
Method string `json:"method"`
Target string `json:"target,omitempty"`
State string `json:"state"`
StateChangedAt time.Time `json:"state_changed_at"`
LastCheckedAt time.Time `json:"last_checked_at"`
LatencyMs float64 `json:"latency_ms"`
AvgLatencyMs float64 `json:"avg_latency_ms"`
UptimePct float64 `json:"uptime_pct"`
TotalChecks int64 `json:"total_checks"`
SuccessfulChecks int64 `json:"successful_checks"`
ConsecutiveFailures int `json:"consecutive_failures"`
ConsecutiveSuccesses int `json:"consecutive_successes"`
LastMessage string `json:"last_message,omitempty"`
History []CheckResult `json:"history"`
}
// StatusCounts summarizes how many monitors are in each state.
type StatusCounts struct {
Total int `json:"total"`
Up int `json:"up"`
Degraded int `json:"degraded"`
Down int `json:"down"`
Pending int `json:"pending"`
}
// Snapshot is an immutable point-in-time view of all monitors and aggregate metrics.
type Snapshot struct {
OverallState string `json:"status"`
OverallUptimePct float64 `json:"overall_uptime_pct"`
AvgLatencyMs float64 `json:"avg_latency_ms"`
Counts StatusCounts `json:"counts"`
UpdatedAt time.Time `json:"updated_at"`
Monitors []MonitorState `json:"monitors"`
MonitorsByID map[string]MonitorState `json:"-"`
}
// Store manages the thread-safe ring buffer and state for all configured monitors.
type Store struct {
mu sync.RWMutex
historySize int
persistenceFile string
order []string
monitors map[string]*MonitorState
}
// New creates a new Store initialized with the configured monitors.
func New(cfg *config.Config) *Store {
histSize := cfg.Storage.HistorySize
if histSize <= 0 {
histSize = 60
}
s := &Store{
historySize: histSize,
persistenceFile: cfg.Storage.PersistenceFile,
order: make([]string, 0, len(cfg.Monitors)),
monitors: make(map[string]*MonitorState, len(cfg.Monitors)),
}
now := time.Now().UTC()
for _, m := range cfg.Monitors {
s.order = append(s.order, m.ID)
s.monitors[m.ID] = &MonitorState{
ID: m.ID,
Name: m.Name,
Description: m.Description,
Link: m.Link,
Method: m.Method,
Target: m.DisplayTarget(),
State: StatePending,
StateChangedAt: now,
UptimePct: 100.0,
History: make([]CheckResult, 0, histSize),
}
}
return s
}
// Record appends a new check result for monitorID and recalculates its statistics.
func (s *Store) Record(monitorID string, res CheckResult) {
s.mu.Lock()
defer s.mu.Unlock()
m, ok := s.monitors[monitorID]
if !ok {
return
}
if res.Timestamp.IsZero() {
res.Timestamp = time.Now().UTC()
}
res.LatencyMs = round2(res.LatencyMs)
prevState := m.State
m.State = res.State
if prevState != res.State || m.StateChangedAt.IsZero() {
m.StateChangedAt = res.Timestamp
}
m.LastCheckedAt = res.Timestamp
m.LatencyMs = res.LatencyMs
m.LastMessage = res.Message
m.TotalChecks++
if res.State == StateUp || res.State == StateDegraded {
m.SuccessfulChecks++
m.ConsecutiveSuccesses++
m.ConsecutiveFailures = 0
} else if res.State == StateDown {
m.ConsecutiveFailures++
m.ConsecutiveSuccesses = 0
}
// Append to ring buffer
if len(m.History) >= s.historySize {
copy(m.History, m.History[1:])
m.History[len(m.History)-1] = res
} else {
m.History = append(m.History, res)
}
// Calculate uptime percentage and average latency across history/total checks
if m.TotalChecks > 0 {
m.UptimePct = round2((float64(m.SuccessfulChecks) / float64(m.TotalChecks)) * 100.0)
}
var latSum float64
var latCount int
for _, h := range m.History {
if h.LatencyMs >= 0 {
latSum += h.LatencyMs
latCount++
}
}
if latCount > 0 {
m.AvgLatencyMs = round2(latSum / float64(latCount))
}
}
// Snapshot returns a deep copy of current monitor states and aggregate metrics.
func (s *Store) Snapshot() Snapshot {
s.mu.RLock()
defer s.mu.RUnlock()
snap := Snapshot{
OverallState: StateUp,
OverallUptimePct: 100.0,
UpdatedAt: time.Now().UTC(),
Monitors: make([]MonitorState, 0, len(s.order)),
MonitorsByID: make(map[string]MonitorState, len(s.order)),
}
var uptimeSum float64
var uptimeCount int
var latSum float64
var latCount int
for _, id := range s.order {
m, ok := s.monitors[id]
if !ok {
continue
}
cp := *m
cp.History = make([]CheckResult, len(m.History))
copy(cp.History, m.History)
snap.Monitors = append(snap.Monitors, cp)
snap.MonitorsByID[id] = cp
snap.Counts.Total++
switch cp.State {
case StateUp:
snap.Counts.Up++
case StateDegraded:
snap.Counts.Degraded++
case StateDown:
snap.Counts.Down++
default:
snap.Counts.Pending++
}
if cp.TotalChecks > 0 {
uptimeSum += cp.UptimePct
uptimeCount++
latSum += cp.LatencyMs
latCount++
}
}
if snap.Counts.Total == 0 || snap.Counts.Pending == snap.Counts.Total {
snap.OverallState = StatePending
} else if snap.Counts.Down > 0 {
snap.OverallState = StateDown
} else if snap.Counts.Degraded > 0 {
snap.OverallState = StateDegraded
} else {
snap.OverallState = StateUp
}
if uptimeCount > 0 {
snap.OverallUptimePct = round2(uptimeSum / float64(uptimeCount))
}
if latCount > 0 {
snap.AvgLatencyMs = round2(latSum / float64(latCount))
}
return snap
}
type persistedState struct {
SavedAt time.Time `json:"saved_at"`
Monitors map[string]*MonitorState `json:"monitors"`
}
// LoadFromDisk restores monitor history and counters from the configured persistence file if it exists.
func (s *Store) LoadFromDisk() error {
if s.persistenceFile == "" {
return nil
}
data, err := os.ReadFile(s.persistenceFile)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("read persistence file %s: %w", s.persistenceFile, err)
}
var ps persistedState
if err := json.Unmarshal(data, &ps); err != nil {
return fmt.Errorf("parse persistence file %s: %w", s.persistenceFile, err)
}
s.mu.Lock()
defer s.mu.Unlock()
for id, saved := range ps.Monitors {
curr, ok := s.monitors[id]
if !ok || saved == nil {
continue
}
curr.State = saved.State
curr.StateChangedAt = saved.StateChangedAt
curr.LastCheckedAt = saved.LastCheckedAt
curr.LatencyMs = saved.LatencyMs
curr.AvgLatencyMs = saved.AvgLatencyMs
curr.UptimePct = saved.UptimePct
curr.TotalChecks = saved.TotalChecks
curr.SuccessfulChecks = saved.SuccessfulChecks
curr.ConsecutiveFailures = saved.ConsecutiveFailures
curr.ConsecutiveSuccesses = saved.ConsecutiveSuccesses
curr.LastMessage = saved.LastMessage
if len(saved.History) > s.historySize {
curr.History = append([]CheckResult(nil), saved.History[len(saved.History)-s.historySize:]...)
} else {
curr.History = append([]CheckResult(nil), saved.History...)
}
}
return nil
}
// SaveToDisk atomically writes current monitor states and history to the configured persistence file.
func (s *Store) SaveToDisk() error {
if s.persistenceFile == "" {
return nil
}
s.mu.RLock()
ps := persistedState{
SavedAt: time.Now().UTC(),
Monitors: make(map[string]*MonitorState, len(s.monitors)),
}
for id, m := range s.monitors {
cp := *m
cp.History = append([]CheckResult(nil), m.History...)
ps.Monitors[id] = &cp
}
s.mu.RUnlock()
data, err := json.MarshalIndent(ps, "", " ")
if err != nil {
return err
}
dir := filepath.Dir(s.persistenceFile)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
}
tmpFile := s.persistenceFile + ".tmp"
if err := os.WriteFile(tmpFile, data, 0644); err != nil {
return err
}
return os.Rename(tmpFile, s.persistenceFile)
}
func round2(v float64) float64 {
return math.Round(v*100) / 100
}

View file

@ -0,0 +1,58 @@
package store
import (
"path/filepath"
"testing"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
)
func TestStoreRingBufferAndPersistence(t *testing.T) {
tmpDir := t.TempDir()
persistPath := filepath.Join(tmpDir, "state.json")
cfg := config.DefaultConfig()
cfg.Storage.HistorySize = 3
cfg.Storage.PersistenceFile = persistPath
cfg.Monitors = []config.MonitorConfig{
{ID: "m1", Name: "Mon 1", Method: "http", URL: "http://localhost"},
{ID: "m2", Name: "Mon 2", Method: "tcp", Target: "localhost:80"},
}
st := New(&cfg)
t0 := time.Now().UTC().Add(-10 * time.Minute)
st.Record("m1", CheckResult{Timestamp: t0, State: StateUp, LatencyMs: 10})
st.Record("m1", CheckResult{Timestamp: t0.Add(time.Minute), State: StateUp, LatencyMs: 20})
st.Record("m1", CheckResult{Timestamp: t0.Add(2 * time.Minute), State: StateDegraded, LatencyMs: 800})
st.Record("m1", CheckResult{Timestamp: t0.Add(3 * time.Minute), State: StateDown, LatencyMs: 0, Message: "timeout"})
snap := st.Snapshot()
m1 := snap.MonitorsByID["m1"]
if len(m1.History) != 3 {
t.Fatalf("expected ring buffer length 3, got %d", len(m1.History))
}
if m1.State != StateDown {
t.Fatalf("expected m1 state down, got %s", m1.State)
}
if m1.UptimePct != 75.0 {
t.Fatalf("expected 75%% uptime (3 of 4 checks up/degraded), got %.2f%%", m1.UptimePct)
}
if snap.OverallState != StateDown {
t.Fatalf("expected overall state down, got %s", snap.OverallState)
}
if err := st.SaveToDisk(); err != nil {
t.Fatalf("SaveToDisk failed: %v", err)
}
st2 := New(&cfg)
if err := st2.LoadFromDisk(); err != nil {
t.Fatalf("LoadFromDisk failed: %v", err)
}
snap2 := st2.Snapshot()
if snap2.MonitorsByID["m1"].TotalChecks != 4 {
t.Fatalf("expected restored TotalChecks=4, got %d", snap2.MonitorsByID["m1"].TotalChecks)
}
}

135
main.go Normal file
View file

@ -0,0 +1,135 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/checker"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/events"
"git.gsdistance.org/tyuXX/RUD/internal/server"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
const Version = "1.0.0"
func main() {
defaultCfgPath := os.Getenv("RUD_CONFIG")
if defaultCfgPath == "" {
defaultCfgPath = "rud.json"
}
cfgPath := flag.String("config", defaultCfgPath, "Path to rud.json configuration file")
initOnly := flag.Bool("init", false, "Generate a sensible default rud.json at -config path and exit")
showVersion := flag.Bool("version", false, "Print version information and exit")
flag.Parse()
if *showVersion {
fmt.Printf("R u ded? (rud) v%s — by tyuXX for GsDistance.org (https://git.gsdistance.org/tyuXX/RUD)\n", Version)
return
}
if *initOnly {
cfg := config.DefaultConfig()
if err := config.SaveConfig(*cfgPath, &cfg); err != nil {
log.Fatalf("Failed to write default config to %s: %v", *cfgPath, err)
}
log.Printf("Generated default configuration at %s", *cfgPath)
return
}
cfg, created, err := config.LoadOrInit(*cfgPath, true)
if err != nil {
log.Fatalf("Configuration error: %v", err)
}
if created {
log.Printf("No config found at %s; generated sensible default configuration.", *cfgPath)
} else {
log.Printf("Loaded configuration from %s (%d monitors, %d events, %d page elements)",
*cfgPath, len(cfg.Monitors), len(cfg.Events), len(cfg.Page.Elements))
}
st := store.New(cfg)
if cfg.Storage.PersistenceFile != "" {
if err := st.LoadFromDisk(); err != nil {
log.Printf("Warning: could not restore state from %s: %v", cfg.Storage.PersistenceFile, err)
} else {
log.Printf("State persistence enabled (%s)", cfg.Storage.PersistenceFile)
}
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
evEngine := events.NewEngine(cfg.Events)
srvHandler := server.New(cfg, st)
httpServer := &http.Server{
Addr: cfg.Server.Listen,
Handler: srvHandler,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
ln, err := net.Listen("tcp", cfg.Server.Listen)
if err != nil {
log.Fatalf("Failed to bind %s: %v", cfg.Server.Listen, err)
}
log.Printf("Serving single status endpoint on http://%s%s", cfg.Server.Listen, cfg.Server.Endpoint)
go func() {
if err := httpServer.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP server error: %v", err)
}
}()
sched := checker.NewScheduler(cfg, st, func(snap store.Snapshot) {
evEngine.Evaluate(ctx, snap)
})
sched.Start(ctx)
// Optional periodic state persistence
if cfg.Storage.PersistenceFile != "" && cfg.Storage.SaveInterval.Std() > 0 {
go func() {
ticker := time.NewTicker(cfg.Storage.SaveInterval.Std())
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := st.SaveToDisk(); err != nil {
log.Printf("Error saving state to disk: %v", err)
}
}
}
}()
}
<-ctx.Done()
log.Printf("Shutting down R u ded?...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = httpServer.Shutdown(shutdownCtx)
sched.Wait()
evEngine.Wait()
if cfg.Storage.PersistenceFile != "" {
if err := st.SaveToDisk(); err != nil {
log.Printf("Error saving final state to disk: %v", err)
}
}
log.Printf("Shutdown complete.")
}

198
rud.json Normal file
View file

@ -0,0 +1,198 @@
{
"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
}
}
},
"storage": {
"history_size": 60,
"save_interval": "1m"
},
"defaults": {
"interval": "15s",
"timeout": "5s",
"retries": 1,
"degraded_latency": "750ms"
},
"monitors": [
{
"id": "rud-http",
"name": "RUD Status Endpoint",
"description": "Local HTTP health check",
"method": "http",
"url": "http://127.0.0.1:8080/?format=json",
"http_method": "GET",
"expected_status": [
200,
503
],
"body_regex": "\"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",
"record_type": "A",
"expected_regex": "^127\\."
},
{
"id": "host-cmd",
"name": "System Shell Check",
"description": "Custom command check verifying shell responsiveness",
"method": "cmd",
"command": "echo ok",
"shell": true,
"expected_exit_code": 0,
"output_regex": "^ok"
}
],
"events": [
{
"id": "core-outage",
"name": "Core Monitors Down or Degraded Uptime",
"cooldown": "30m",
"trigger_on_recovery": true,
"condition": {
"operator": "or",
"conditions": [
{
"type": "state",
"monitors": [
"rud-http",
"rud-tcp"
],
"match": "all",
"state": "down"
},
{
"type": "metric",
"monitors": [
"*"
],
"match": "any",
"metric": "uptime_pct",
"comparator": "<",
"value": 50,
"for": "5m"
}
]
},
"actions": [
{
"type": "command",
"timeout": "5s",
"command": "echo \"[RUD ALERT] {{.EventName}}: status={{.Status}} monitors={{.TriggeredMonitors}}\"",
"shell": true
}
]
}
],
"page": {
"title": "R u ded?",
"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"
},
"elements": [
{
"type": "header",
"title": "R u ded?",
"subtitle": "Minimalist system status & health monitor",
"align": "split",
"show_last_updated": true,
"show_live_indicator": true
},
{
"type": "status_banner",
"messages": {
"degraded": "Kinda — Some systems are experiencing degraded performance",
"down": "Yes — One or more systems are down",
"pending": "Checking system status...",
"up": "No — All systems operational"
},
"show_overall_uptime": true,
"show_counts": true
},
{
"type": "summary_cards",
"metrics": [
"total",
"up",
"degraded",
"down",
"overall_uptime",
"avg_latency"
]
},
{
"type": "monitor_group",
"title": "Monitored Services",
"description": "Live health checks",
"monitors": [
"*"
],
"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": {
"degraded": "SLOW",
"down": "DED",
"pending": "WAIT",
"up": "OK"
}
}
}
]
}
}