diff --git a/.gitignore b/.gitignore index 19cef92..140e73a 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,8 @@ go.work.sum # env file .env +# History logs and stats database +/logs/ +/stats.db* +/data/ + diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 5966351..8637939 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -3,7 +3,7 @@ **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. +2. **`storage`** — In-memory ring-buffer size, daily JSONL history logs (zstd-compressed), the SQLite stats database, and optional state 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`). @@ -53,7 +53,7 @@ Controls the single HTTP endpoint served by `rud`. | 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`. | +| `endpoint` | `string` | `"/"` | The single HTTP path served for the status page. All other paths return `404 Not Found`, except `/monitor` which serves the per-monitor history pages. | | `refresh_interval` | `Duration` | `"10s"` | Browser live-update polling interval (fetches `?format=json`). Set to `"0s"` to disable client-side polling. | | `status_codes.html` | `object` | `200` for all | HTTP status codes returned for HTML requests per global state (`up`, `degraded`, `down`, `pending`). Keeping HTML at `200` prevents Cloudflare Tunnel from replacing your status page with a Cloudflare 5xx error page. | | `status_codes.json` | `object` | `200` (`503` on `down`) | HTTP status codes returned when JSON is requested via `Accept: application/json` or `?format=json`. | @@ -62,21 +62,41 @@ Controls the single HTTP endpoint served by `rud`. ## 2. `storage` Section -Controls the in-memory check history ring buffer and optional state persistence across restarts. +Controls the in-memory check history ring buffer, long-term history logging, the stats database, and optional state persistence across restarts. ```json "storage": { "history_size": 60, "persistence_file": "./data/rud_state.json", - "save_interval": "1m" + "save_interval": "1m", + "logs_dir": "logs", + "stats_db": "stats.db", + "stats_retention_days": 90 } ``` | Field | Type | Default | Description | | :--- | :--- | :--- | :--- | -| `history_size` | `int` | `60` | Maximum number of recent check results retained in memory per monitor. | +| `history_size` | `int` | `60` | Maximum number of recent check results retained in memory per monitor (powers the live tick-bars on the status page). | | `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). | +| `logs_dir` | `string` | `"logs"` | Directory for the **full-history daily logs**. Every check result is appended as one JSON object per line to `DD-MM-YYYY.json`. When the day rolls over (or on startup for stale files), the previous day's file is zstd-compressed to `DD-MM-YYYY.json.zst` and the original removed — full history is retained indefinitely for external viewers. Set to `"off"` or `"none"` to disable. | +| `stats_db` | `string` | `"stats.db"` | Path to the **SQLite stats database** (pure-Go driver, no cgo). Stores per-hour aggregates (checks, up/degraded/down counts, latency sum/min/max) per monitor, powering the `/monitor` history page. Set to `"off"` or `"none"` to disable. | +| `stats_retention_days` | `int` | `90` | How many days of hourly stats are kept in `stats_db`; older rows are pruned automatically. Also caps the `?days=` window on the `/monitor` page. | + +### Daily log format + +Each line of `DD-MM-YYYY.json` is a self-contained JSON object, e.g.: + +```json +{"monitor_id":"rud-http","name":"RUD Status Endpoint","method":"http","target":"http://127.0.0.1:8080/?format=json","timestamp":"2026-11-07T12:08:05Z","state":"up","latency_ms":0.84,"code":200,"message":"HTTP 200"} +``` + +Files are named in `DD-MM-YYYY` format using the server's local time zone. Once compressed they can be decompressed with any zstd tool (`zstd -d`, `unzstd`, etc.). + +### Monitor history page + +Every monitor name on the status page links to `/monitor?id=` (also reachable as `/monitor/`), which renders the monitor's current state plus server-side SVG charts of the retained stats: daily uptime and average latency over the last `stats_retention_days` days (or `?days=N`, capped at the retention window), and hourly uptime for the most recent period. `/monitor` without an ID lists all monitors. --- diff --git a/Dockerfile b/Dockerfile index ea8e92f..83bd67a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Stage 1: Build static Go binary -FROM golang:1.23-alpine AS builder +FROM golang:1.26-alpine AS builder WORKDIR /src COPY go.mod ./ diff --git a/README.md b/README.md index e5fd4db..a9a923c 100644 --- a/README.md +++ b/README.md @@ -1,99 +1,47 @@ # R u ded? (`rud`) -**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)). +Lightweight uptime monitor and health checker written in Go by [tyuXX] ([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. +Mainly created for use in GsDistance.org. ---- - -## 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`. +Compiles to a single static binary, checks `http`/`https`, `tcp`, `ping`, `dns`, and `cmd` targets, sends declarative alerts (webhooks/commands), and serves a minimal status page plus JSON health output — all configured through one `rud.json` file. Full check history is kept in daily JSONL logs (zstd-compressed) and a SQLite stats database, viewable per-monitor at `/monitor`. --- ## Quick Start -### 1. Run as a Standalone Binary +### 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 +./rud -config rud.json # auto-generates rud.json if missing ``` -Query the single endpoint: +Then open `http://localhost:8080/` (HTML) or `http://localhost:8080/?format=json` (JSON). + +### Docker Compose + ```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/ +docker compose up -d --build # exposes port 8080, persists ./data ``` +### Docker Compose + Cloudflare Tunnel (no exposed ports) + +```bash +cp .env.example .env # set TUNNEL_TOKEN=... +docker compose -f docker-compose.cloudflared.yml up -d --build +``` + +Point your tunnel's public hostname at `http://rud:8080`. + --- -### 2. Run with Docker Compose (Direct Port Exposure) +## Configuration -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`. +See [**`CONFIGURATION.md`**](./CONFIGURATION.md) for the full `rud.json` reference — monitors, check methods, alert events, page elements, and storage/history options. --- ## License -MIT License — Created by **tyuXX** for **GsDistance.org** ([https://git.gsdistance.org/tyuXX/RUD](https://git.gsdistance.org/tyuXX/RUD)). +MIT — Created by **tyuXX** for **GsDistance.org**. diff --git a/docker-compose.cloudflared.yml b/docker-compose.cloudflared.yml index c43abed..b9ddeed 100644 --- a/docker-compose.cloudflared.yml +++ b/docker-compose.cloudflared.yml @@ -9,6 +9,7 @@ services: - "8080" volumes: - ./rud.json:/app/rud.json:ro + - ./data:/app/data cap_add: - NET_RAW networks: diff --git a/docker-compose.yml b/docker-compose.yml index d178461..50a5537 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,5 +9,6 @@ services: - "${RUD_PORT:-8080}:8080" volumes: - ./rud.json:/app/rud.json:ro + - ./data:/app/data cap_add: - NET_RAW diff --git a/go.mod b/go.mod index 093ac3c..2f2ec0c 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,20 @@ module git.gsdistance.org/tyuXX/RUD -go 1.23 +go 1.26.0 + +require ( + github.com/klauspost/compress v1.20.3 + modernc.org/sqlite v1.62.0 +) + +require ( + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.49.0 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8d6ded3 --- /dev/null +++ b/go.sum @@ -0,0 +1,52 @@ +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= +github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g= +modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/config/config.go b/internal/config/config.go index 9576f17..67c55e3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -89,11 +89,15 @@ type StatusCodesByState struct { Pending int `json:"pending"` } -// StorageConfig configures the in-memory ring buffer and optional disk persistence. +// StorageConfig configures the in-memory ring buffer, long-term history +// logging, the stats database, and optional state persistence. type StorageConfig struct { - HistorySize int `json:"history_size"` - PersistenceFile string `json:"persistence_file,omitempty"` - SaveInterval Duration `json:"save_interval,omitempty"` + HistorySize int `json:"history_size"` + PersistenceFile string `json:"persistence_file,omitempty"` + SaveInterval Duration `json:"save_interval,omitempty"` + LogsDir string `json:"logs_dir,omitempty"` + StatsDB string `json:"stats_db,omitempty"` + StatsRetentionDays int `json:"stats_retention_days,omitempty"` } // DefaultsConfig provides global fallback check intervals and thresholds. @@ -362,9 +366,12 @@ func DefaultConfig() Config { }, }, Storage: StorageConfig{ - HistorySize: 60, - PersistenceFile: "", - SaveInterval: NewDuration(1 * time.Minute), + HistorySize: 60, + PersistenceFile: "", + SaveInterval: NewDuration(1 * time.Minute), + LogsDir: "logs", + StatsDB: "stats.db", + StatsRetentionDays: 90, }, Defaults: DefaultsConfig{ Interval: NewDuration(15 * time.Second), @@ -611,6 +618,15 @@ func (c *Config) ApplyFallbacks() { if c.Storage.SaveInterval <= 0 { c.Storage.SaveInterval = NewDuration(1 * time.Minute) } + if c.Storage.LogsDir == "" { + c.Storage.LogsDir = "logs" + } + if c.Storage.StatsDB == "" { + c.Storage.StatsDB = "stats.db" + } + if c.Storage.StatsRetentionDays <= 0 { + c.Storage.StatsRetentionDays = 90 + } if c.Defaults.Interval <= 0 { c.Defaults.Interval = NewDuration(30 * time.Second) diff --git a/internal/events/engine_test.go b/internal/events/engine_test.go index 1dcfe46..a6699ff 100644 --- a/internal/events/engine_test.go +++ b/internal/events/engine_test.go @@ -38,7 +38,7 @@ func TestEventEngineBooleanAndSustainedDurationAndMetricTriggers(t *testing.T) { TriggerOnRecovery: true, Condition: config.EventCondition{ Operator: "or", - Conditions: [ ]config.EventCondition{ + Conditions: []config.EventCondition{ // Monitors 1, 2, 3 are all down { Type: "state", diff --git a/internal/history/history_test.go b/internal/history/history_test.go new file mode 100644 index 0000000..cd2038f --- /dev/null +++ b/internal/history/history_test.go @@ -0,0 +1,224 @@ +package history + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/klauspost/compress/zstd" + + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +func TestDailyLoggerRolloverAndCompress(t *testing.T) { + dir := t.TempDir() + day1 := time.Date(2026, 1, 1, 10, 0, 0, 0, time.Local) + day2 := time.Date(2026, 1, 2, 0, 30, 0, 0, time.Local) + + l, err := NewDailyLogger(dir, func(id string) MonitorMeta { + return MonitorMeta{Name: "Test " + id, Method: "http"} + }) + if err != nil { + t.Fatalf("NewDailyLogger: %v", err) + } + l.now = func() time.Time { return day1 } + + res := store.CheckResult{Timestamp: day1, State: store.StateUp, LatencyMs: 12.5, Code: 200, Message: "ok"} + if err := l.Record("m1", res); err != nil { + t.Fatalf("Record day1: %v", err) + } + if err := l.Record("m1", store.CheckResult{Timestamp: day1, State: store.StateDown, LatencyMs: 0, Message: "boom"}); err != nil { + t.Fatalf("Record day1b: %v", err) + } + + // Same day: still one uncompressed file, no .zst yet. + day1File := filepath.Join(dir, "01-01-2026.json") + if _, err := os.Stat(day1File); err != nil { + t.Fatalf("expected day1 json file: %v", err) + } + if _, err := os.Stat(day1File + ".zst"); !os.IsNotExist(err) { + t.Fatal("day1 file should not be compressed while still current") + } + + // Roll into day 2. + l.now = func() time.Time { return day2 } + if err := l.Record("m1", store.CheckResult{Timestamp: day2, State: store.StateUp, LatencyMs: 9.9}); err != nil { + t.Fatalf("Record day2: %v", err) + } + + // Day 1 must now be compressed and removed. + if _, err := os.Stat(day1File); !os.IsNotExist(err) { + t.Fatal("day1 json should be removed after compression") + } + zstPath := day1File + ".zst" + zdata, err := os.ReadFile(zstPath) + if err != nil { + t.Fatalf("expected compressed day1 file: %v", err) + } + zr, err := zstd.NewReader(nil) + if err != nil { + t.Fatalf("zstd reader: %v", err) + } + defer zr.Close() + dec, err := zr.DecodeAll(zdata, nil) + if err != nil { + t.Fatalf("decompress: %v", err) + } + lines := strings.Split(strings.TrimSpace(string(dec)), "\n") + if len(lines) != 2 { + t.Fatalf("expected 2 log lines, got %d: %q", len(lines), dec) + } + var e Entry + if err := json.Unmarshal([]byte(lines[0]), &e); err != nil { + t.Fatalf("unmarshal entry: %v", err) + } + if e.MonitorID != "m1" || e.Name != "Test m1" || e.State != store.StateUp || e.Code != 200 { + t.Fatalf("unexpected entry: %+v", e) + } + + // Day 2 file is the active uncompressed log. + day2File := filepath.Join(dir, "02-01-2026.json") + data, err := os.ReadFile(day2File) + if err != nil { + t.Fatalf("expected day2 json file: %v", err) + } + if !strings.Contains(string(data), `"monitor_id":"m1"`) { + t.Fatalf("day2 file missing entry: %s", data) + } + + if err := l.Close(); err != nil { + t.Fatalf("Close: %v", err) + } +} + +func TestDailyLoggerCompressStaleOnStartup(t *testing.T) { + dir := t.TempDir() + // Simulate a leftover uncompressed file from a previous day. + stale := `{"monitor_id":"m1","state":"up"}` + "\n" + if err := os.WriteFile(filepath.Join(dir, "31-12-2025.json"), []byte(stale), 0644); err != nil { + t.Fatal(err) + } + // A non-daily file must be left alone. + if err := os.WriteFile(filepath.Join(dir, "notes.json"), []byte("hello"), 0644); err != nil { + t.Fatal(err) + } + + l, err := NewDailyLogger(dir, nil) + if err != nil { + t.Fatalf("NewDailyLogger: %v", err) + } + defer l.Close() + + if _, err := os.Stat(filepath.Join(dir, "31-12-2025.json")); !os.IsNotExist(err) { + t.Fatal("stale daily file should have been compressed") + } + if _, err := os.Stat(filepath.Join(dir, "31-12-2025.json.zst")); err != nil { + t.Fatalf("expected stale .zst: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "notes.json")); err != nil { + t.Fatal("non-daily json file should be untouched") + } +} + +func TestStatsDBRecordAndQueries(t *testing.T) { + path := filepath.Join(t.TempDir(), "stats.db") + db, err := NewStatsDB(path, 90) + if err != nil { + t.Fatalf("NewStatsDB: %v", err) + } + defer db.Close() + + now := time.Now().UTC() + hour := now.Truncate(time.Hour) + day := hour.Format("2006-01-02") + + recs := []store.CheckResult{ + {Timestamp: hour, State: store.StateUp, LatencyMs: 10}, + {Timestamp: hour.Add(time.Minute), State: store.StateUp, LatencyMs: 20}, + {Timestamp: hour.Add(2 * time.Minute), State: store.StateDegraded, LatencyMs: 900}, + {Timestamp: hour.Add(3 * time.Minute), State: store.StateDown, LatencyMs: 0}, + } + for _, r := range recs { + if err := db.Record("m1", r); err != nil { + t.Fatalf("Record: %v", err) + } + } + // Different monitor must be isolated. + if err := db.Record("m2", store.CheckResult{Timestamp: hour, State: store.StateUp, LatencyMs: 5}); err != nil { + t.Fatalf("Record m2: %v", err) + } + + hourly, err := db.HourlyStats("m1", 48) + if err != nil { + t.Fatalf("HourlyStats: %v", err) + } + if len(hourly) != 1 { + t.Fatalf("expected 1 hourly bucket, got %d", len(hourly)) + } + h := hourly[0] + if h.Checks != 4 || h.Up != 2 || h.Degraded != 1 || h.Down != 1 { + t.Fatalf("bad hourly counts: %+v", h) + } + if h.MinLatencyMs != 0 || h.MaxLatencyMs != 900 { + t.Fatalf("bad latency min/max: %+v", h) + } + if h.AvgLatencyMs <= 0 { + t.Fatalf("expected positive avg latency: %+v", h) + } + + daily, err := db.DailyStats("m1", 30) + if err != nil { + t.Fatalf("DailyStats: %v", err) + } + if len(daily) != 1 { + t.Fatalf("expected 1 daily bucket, got %d", len(daily)) + } + d := daily[0] + if d.Date != day { + t.Fatalf("expected date %s, got %s", day, d.Date) + } + if d.Checks != 4 || d.Up != 2 || d.Degraded != 1 || d.Down != 1 { + t.Fatalf("bad daily counts: %+v", d) + } + wantUptime := float64(3) / 4 * 100 + if d.UptimePct < wantUptime-0.01 || d.UptimePct > wantUptime+0.01 { + t.Fatalf("bad uptime %%: got %v want %v", d.UptimePct, wantUptime) + } + + // Retention prune: rows older than the window are deleted. + old := now.Add(-100 * 24 * time.Hour) + if err := db.Record("m1", store.CheckResult{Timestamp: old, State: store.StateUp, LatencyMs: 1}); err != nil { + t.Fatalf("Record old: %v", err) + } + if err := db.prune(now); err != nil { + t.Fatalf("prune: %v", err) + } + var cnt int + if err := db.db.QueryRow(`SELECT COUNT(*) FROM hourly_stats WHERE hour < ?`, now.Add(-90*24*time.Hour).Format(hourLayout)).Scan(&cnt); err != nil { + t.Fatalf("count old rows: %v", err) + } + if cnt != 0 { + t.Fatalf("expected old rows pruned, %d remain", cnt) + } +} + +func TestStatsDBRetentionCapsQueryWindow(t *testing.T) { + path := filepath.Join(t.TempDir(), "stats.db") + db, err := NewStatsDB(path, 7) + if err != nil { + t.Fatalf("NewStatsDB: %v", err) + } + defer db.Close() + + // Asking for 30 days with 7-day retention must be capped to 7. + daily, err := db.DailyStats("m1", 30) + if err != nil { + t.Fatalf("DailyStats: %v", err) + } + if daily == nil { + t.Fatal("expected non-nil slice") + } +} diff --git a/internal/history/logger.go b/internal/history/logger.go new file mode 100644 index 0000000..f99b2e0 --- /dev/null +++ b/internal/history/logger.go @@ -0,0 +1,229 @@ +// Package history provides long-term storage for check results: an append-only +// daily JSONL log that is zstd-compressed when the day rolls over, and a SQLite +// database of hourly aggregate statistics with configurable retention. +package history + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "log" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/klauspost/compress/zstd" + + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +// dayFileLayout is the DD-MM-YYYY filename layout used for daily log files. +const dayFileLayout = "02-01-2006" + +// MonitorMeta carries optional display metadata written alongside each log entry. +type MonitorMeta struct { + Name string `json:"name,omitempty"` + Method string `json:"method,omitempty"` + Target string `json:"target,omitempty"` +} + +// Entry is a single check result as written to the daily JSONL log. The +// CheckResult fields are flattened into the top-level object. +type Entry struct { + MonitorID string `json:"monitor_id"` + MonitorMeta + store.CheckResult +} + +// DailyLogger appends every check result to a per-day JSON Lines file named +// DD-MM-YYYY.json inside Dir. When the calendar day changes the previous file +// is flushed, compressed to DD-MM-YYYY.json.zst and removed. Stale uncompressed +// files left behind by a crash are compressed on startup. +type DailyLogger struct { + dir string + metaFor func(id string) MonitorMeta + now func() time.Time + + mu sync.Mutex + file *os.File + w *bufio.Writer + curDay string + encoder *json.Encoder +} + +// NewDailyLogger creates the log directory, compresses any stale uncompressed +// daily files from previous days, and opens (or creates) today's log file. +// metaFor may be nil, in which case entries contain only monitor_id and the +// check result fields. +func NewDailyLogger(dir string, metaFor func(id string) MonitorMeta) (*DailyLogger, error) { + if dir == "" { + return nil, fmt.Errorf("history log directory is empty") + } + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, fmt.Errorf("create history log dir %s: %w", dir, err) + } + l := &DailyLogger{ + dir: dir, + metaFor: metaFor, + now: time.Now, + } + if err := l.compressStale(); err != nil { + return nil, err + } + if err := l.openToday(); err != nil { + return nil, err + } + return l, nil +} + +// Record appends one check result to the current day's log, rotating to a new +// file (and compressing the old one) when the day has changed. +func (l *DailyLogger) Record(monitorID string, res store.CheckResult) error { + l.mu.Lock() + defer l.mu.Unlock() + + day := l.now().Format(dayFileLayout) + if day != l.curDay { + if err := l.rotateLocked(); err != nil { + return err + } + } + + entry := Entry{MonitorID: monitorID, CheckResult: res} + if l.metaFor != nil { + entry.MonitorMeta = l.metaFor(monitorID) + } + if err := l.encoder.Encode(entry); err != nil { + return fmt.Errorf("encode history entry: %w", err) + } + return l.w.Flush() +} + +// Close flushes and closes the current log file without compressing it. The +// file is compressed on the next startup by compressStale. +func (l *DailyLogger) Close() error { + l.mu.Lock() + defer l.mu.Unlock() + return l.closeLocked() +} + +func (l *DailyLogger) openToday() error { + day := l.now().Format(dayFileLayout) + path := filepath.Join(l.dir, day+".json") + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + return fmt.Errorf("open history log %s: %w", path, err) + } + l.file = f + l.w = bufio.NewWriter(f) + l.encoder = json.NewEncoder(l.w) + l.curDay = day + return nil +} + +func (l *DailyLogger) closeLocked() error { + if l.file == nil { + return nil + } + err := l.w.Flush() + if cerr := l.file.Close(); err == nil { + err = cerr + } + l.file = nil + l.w = nil + l.encoder = nil + return err +} + +// rotateLocked compresses the current day's file and opens the new day's file. +// Caller must hold l.mu. +func (l *DailyLogger) rotateLocked() error { + day := l.curDay + if err := l.closeLocked(); err != nil { + return err + } + if day != "" { + if err := compressFile(filepath.Join(l.dir, day+".json")); err != nil { + return err + } + } + return l.openToday() +} + +// compressStale compresses every DD-MM-YYYY.json file whose date is not today. +func (l *DailyLogger) compressStale() error { + today := l.now().Format(dayFileLayout) + entries, err := os.ReadDir(l.dir) + if err != nil { + return fmt.Errorf("read history log dir %s: %w", l.dir, err) + } + // Compress oldest first for deterministic behaviour. + names := make([]string, 0, len(entries)) + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".json") { + names = append(names, e.Name()) + } + } + sort.Strings(names) + for _, name := range names { + day := strings.TrimSuffix(name, ".json") + if _, err := time.Parse(dayFileLayout, day); err != nil { + continue // not a daily log file; leave it alone + } + if day == today { + continue + } + if err := compressFile(filepath.Join(l.dir, name)); err != nil { + log.Printf("history: failed to compress stale log %s: %v", name, err) + } + } + return nil +} + +// compressFile zstd-compresses path to path+".zst" and removes the original. +// Files that fail to compress are left in place. +func compressFile(path string) error { + in, err := os.Open(path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + defer in.Close() + + tmp := path + ".zst.tmp" + out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + if err != nil { + return err + } + enc, err := zstd.NewWriter(out) + if err != nil { + out.Close() + return err + } + if _, err := io.Copy(enc, in); err != nil { + enc.Close() + out.Close() + os.Remove(tmp) + return err + } + if err := enc.Close(); err != nil { + out.Close() + os.Remove(tmp) + return err + } + if err := out.Close(); err != nil { + os.Remove(tmp) + return err + } + if err := os.Rename(tmp, path+".zst"); err != nil { + os.Remove(tmp) + return err + } + return os.Remove(path) +} diff --git a/internal/history/stats.go b/internal/history/stats.go new file mode 100644 index 0000000..f4c9abc --- /dev/null +++ b/internal/history/stats.go @@ -0,0 +1,285 @@ +package history + +import ( + "context" + "database/sql" + "fmt" + "sync" + "time" + + _ "modernc.org/sqlite" + + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +// hourLayout is the UTC hour-bucket key format used in hourly_stats. +const hourLayout = "2006-01-02T15:04:05Z" + +const statsSchema = ` +CREATE TABLE IF NOT EXISTS hourly_stats ( + monitor_id TEXT NOT NULL, + hour TEXT NOT NULL, + checks INTEGER NOT NULL DEFAULT 0, + up INTEGER NOT NULL DEFAULT 0, + degraded INTEGER NOT NULL DEFAULT 0, + down INTEGER NOT NULL DEFAULT 0, + sum_latency_ms REAL NOT NULL DEFAULT 0, + min_latency_ms REAL, + max_latency_ms REAL, + PRIMARY KEY (monitor_id, hour) +); +CREATE INDEX IF NOT EXISTS idx_hourly_stats_hour ON hourly_stats(hour); +` + +// HourlyStat is an aggregate bucket of check results for one monitor and hour. +type HourlyStat struct { + Hour time.Time `json:"hour"` + Checks int `json:"checks"` + Up int `json:"up"` + Degraded int `json:"degraded"` + Down int `json:"down"` + AvgLatencyMs float64 `json:"avg_latency_ms"` + MinLatencyMs float64 `json:"min_latency_ms"` + MaxLatencyMs float64 `json:"max_latency_ms"` +} + +// DailyStat is a per-day rollup of HourlyStat rows for one monitor. +type DailyStat struct { + Date string `json:"date"` // YYYY-MM-DD (UTC) + Checks int `json:"checks"` + Up int `json:"up"` + Degraded int `json:"degraded"` + Down int `json:"down"` + UptimePct float64 `json:"uptime_pct"` + AvgLatencyMs float64 `json:"avg_latency_ms"` +} + +// StatsDB stores aggregated per-hour check statistics in SQLite and prunes +// rows older than the configured retention window. +type StatsDB struct { + db *sql.DB + retention time.Duration + mu sync.Mutex + lastPrune time.Time +} + +// NewStatsDB opens (creating if needed) the SQLite database at path and +// applies the schema. retentionDays <= 0 disables pruning. +func NewStatsDB(path string, retentionDays int) (*StatsDB, error) { + if path == "" { + return nil, fmt.Errorf("stats db path is empty") + } + db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)") + if err != nil { + return nil, fmt.Errorf("open stats db %s: %w", path, err) + } + if _, err := db.Exec(statsSchema); err != nil { + db.Close() + return nil, fmt.Errorf("init stats db schema: %w", err) + } + s := &StatsDB{db: db} + if retentionDays > 0 { + s.retention = time.Duration(retentionDays) * 24 * time.Hour + } + if err := s.prune(time.Now()); err != nil { + db.Close() + return nil, err + } + return s, nil +} + +// Close closes the underlying database handle. +func (s *StatsDB) Close() error { + return s.db.Close() +} + +// Record aggregates one check result into its UTC hour bucket. +func (s *StatsDB) Record(monitorID string, res store.CheckResult) error { + ts := res.Timestamp + if ts.IsZero() { + ts = time.Now().UTC() + } + ts = ts.UTC() + hour := ts.Truncate(time.Hour).Format(hourLayout) + + stateCol := "down" + switch res.State { + case store.StateUp: + stateCol = "up" + case store.StateDegraded: + stateCol = "degraded" + } + + // Sum latency only for non-negative measurements; min/max likewise. + lat := res.LatencyMs + hasLat := lat >= 0 + sumLat := 0.0 + if hasLat { + sumLat = lat + } + + s.mu.Lock() + defer s.mu.Unlock() + + // Opportunistic prune at most once per hour. + if s.retention > 0 && time.Since(s.lastPrune) >= time.Hour { + _ = s.pruneLocked(time.Now()) + } + + _, err := s.db.Exec(` + INSERT INTO hourly_stats (monitor_id, hour, checks, up, degraded, down, sum_latency_ms, min_latency_ms, max_latency_ms) + VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?) + ON CONFLICT(monitor_id, hour) DO UPDATE SET + checks = checks + 1, + up = up + excluded.up, + degraded = degraded + excluded.degraded, + down = down + excluded.down, + sum_latency_ms = sum_latency_ms + excluded.sum_latency_ms, + min_latency_ms = MIN(COALESCE(min_latency_ms, excluded.min_latency_ms), COALESCE(excluded.min_latency_ms, min_latency_ms)), + max_latency_ms = MAX(COALESCE(max_latency_ms, excluded.max_latency_ms), COALESCE(excluded.max_latency_ms, max_latency_ms))`, + monitorID, hour, + boolInt(stateCol == "up"), boolInt(stateCol == "degraded"), boolInt(stateCol == "down"), + sumLat, nullIf(!hasLat, lat), nullIf(!hasLat, lat), + ) + return err +} + +func (s *StatsDB) prune(now time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + return s.pruneLocked(now) +} + +func (s *StatsDB) pruneLocked(now time.Time) error { + if s.retention <= 0 { + s.lastPrune = now + return nil + } + cutoff := now.UTC().Add(-s.retention).Format(hourLayout) + if _, err := s.db.Exec(`DELETE FROM hourly_stats WHERE hour < ?`, cutoff); err != nil { + return fmt.Errorf("prune stats db: %w", err) + } + s.lastPrune = now + return nil +} + +// HourlyStats returns aggregate buckets for monitorID covering the last hours +// hours, oldest first. +func (s *StatsDB) HourlyStats(monitorID string, hours int) ([]HourlyStat, error) { + if hours <= 0 { + hours = 24 + } + if hours > 24*366 { + hours = 24 * 366 + } + cutoff := time.Now().UTC().Add(-time.Duration(hours) * time.Hour).Format(hourLayout) + rows, err := s.db.Query(` + SELECT hour, checks, up, degraded, down, sum_latency_ms, min_latency_ms, max_latency_ms + FROM hourly_stats + WHERE monitor_id = ? AND hour >= ? + ORDER BY hour`, monitorID, cutoff) + if err != nil { + return nil, err + } + defer rows.Close() + + out := make([]HourlyStat, 0) + for rows.Next() { + var st HourlyStat + var hourStr string + var sumLat float64 + var minLat, maxLat sql.NullFloat64 + if err := rows.Scan(&hourStr, &st.Checks, &st.Up, &st.Degraded, &st.Down, + &sumLat, &minLat, &maxLat); err != nil { + return nil, err + } + if t, err := time.Parse(hourLayout, hourStr); err == nil { + st.Hour = t + } + if st.Checks > 0 { + st.AvgLatencyMs = sumLat / float64(st.Checks) + } + if minLat.Valid { + st.MinLatencyMs = minLat.Float64 + } + if maxLat.Valid { + st.MaxLatencyMs = maxLat.Float64 + } + out = append(out, st) + } + return out, rows.Err() +} + +// DailyStats returns per-day rollups (UTC dates) for monitorID covering the +// last days days, oldest first. +func (s *StatsDB) DailyStats(monitorID string, days int) ([]DailyStat, error) { + if days <= 0 { + days = 30 + } + maxDays := int(s.retention.Hours() / 24) + if maxDays > 0 && days > maxDays { + days = maxDays + } + if days > 3660 { + days = 3660 + } + cutoffDay := time.Now().UTC().Add(-time.Duration(days-1) * 24 * time.Hour).Format("2006-01-02") + rows, err := s.db.Query(` + SELECT substr(hour, 1, 10) AS day, + SUM(checks), SUM(up), SUM(degraded), SUM(down), SUM(sum_latency_ms) + FROM hourly_stats + WHERE monitor_id = ? AND hour >= ? + GROUP BY day + ORDER BY day`, monitorID, cutoffDay+"T00:00:00Z") + if err != nil { + return nil, err + } + defer rows.Close() + + out := make([]DailyStat, 0) + for rows.Next() { + var d DailyStat + var sumLat float64 + if err := rows.Scan(&d.Date, &d.Checks, &d.Up, &d.Degraded, &d.Down, &sumLat); err != nil { + return nil, err + } + if d.Checks > 0 { + d.UptimePct = float64(d.Up+d.Degraded) / float64(d.Checks) * 100.0 + d.AvgLatencyMs = sumLat / float64(d.Checks) + } + out = append(out, d) + } + return out, rows.Err() +} + +// MonitorIDs returns distinct monitor IDs that have recorded stats. +func (s *StatsDB) MonitorIDs(ctx context.Context) ([]string, error) { + rows, err := s.db.QueryContext(ctx, `SELECT DISTINCT monitor_id FROM hourly_stats ORDER BY monitor_id`) + if err != nil { + return nil, err + } + defer rows.Close() + ids := make([]string, 0) + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +func boolInt(b bool) int { + if b { + return 1 + } + return 0 +} + +func nullIf(null bool, v float64) interface{} { + if null { + return nil + } + return v +} diff --git a/internal/server/charts.go b/internal/server/charts.go new file mode 100644 index 0000000..c7eef23 --- /dev/null +++ b/internal/server/charts.go @@ -0,0 +1,260 @@ +package server + +import ( + "fmt" + "html/template" + "strconv" + "strings" + "time" + + "git.gsdistance.org/tyuXX/RUD/internal/history" +) + +// safeColor strips a color string down to characters safe to embed in an SVG +// presentation attribute. +func safeColor(c string) string { + var b strings.Builder + for _, r := range c { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', + r == '#', r == '(', r == ')', r == ',', r == '.', r == '%', r == ' ', r == '-': + b.WriteRune(r) + } + } + return b.String() +} + +func f2(v float64) string { + return strconv.FormatFloat(v, 'f', -1, 64) +} + +// uptimeColorFor picks a state color for a bucket based on its uptime percent. +func uptimeColorFor(uptime float64, up, degraded, down string) string { + switch { + case uptime >= 99.5: + return up + case uptime >= 90: + return degraded + default: + return down + } +} + +// uptimeBarChart renders one vertical bar per bucket (daily or hourly) whose +// height is the bucket's uptime percentage, colored by uptime thresholds. +type barBucket struct { + Label string + UptimePct float64 + Checks int + Up int + Degraded int + Down int + AvgLatency float64 +} + +func uptimeBarChart(buckets []barBucket, w, h int, upColor, degColor, downColor string) template.HTML { + if len(buckets) == 0 || w <= 0 || h <= 0 { + return "" + } + padL, padR, padT, padB := 34.0, 8.0, 10.0, 18.0 + plotW := float64(w) - padL - padR + plotH := float64(h) - padT - padB + if plotW <= 0 || plotH <= 0 { + return "" + } + slot := plotW / float64(len(buckets)) + barW := slot * 0.72 + if barW < 1 { + barW = 1 + } + + var b strings.Builder + b.WriteString(``) + + // horizontal gridlines at 0/50/100% + for _, pct := range []float64{0, 50, 100} { + y := padT + plotH*(1-pct/100) + b.WriteString(fmt.Sprintf(``, padL, y, float64(w)-padR, y)) + b.WriteString(fmt.Sprintf(`%d%%`, padL-4, y+3, int(pct))) + } + + for i, bk := range buckets { + x := padL + float64(i)*slot + (slot-barW)/2 + bh := plotH * bk.UptimePct / 100 + if bh < 0.5 { + bh = 0.5 + } + y := padT + plotH - bh + color := uptimeColorFor(bk.UptimePct, safeColor(upColor), safeColor(degColor), safeColor(downColor)) + tip := fmt.Sprintf("%s — uptime %.2f%% | checks %d (up %d, degraded %d, down %d)", + bk.Label, bk.UptimePct, bk.Checks, bk.Up, bk.Degraded, bk.Down) + if bk.AvgLatency > 0 { + tip += fmt.Sprintf(" | avg %.1fms", bk.AvgLatency) + } + b.WriteString(fmt.Sprintf(`%s`, + x, y, barW, bh, color, template.HTMLEscapeString(tip))) + } + + // x labels: first, middle, last + labelIdx := []int{0, len(buckets) / 2, len(buckets) - 1} + seen := map[int]bool{} + for _, i := range labelIdx { + if i < 0 || i >= len(buckets) || seen[i] { + continue + } + seen[i] = true + x := padL + float64(i)*slot + slot/2 + b.WriteString(fmt.Sprintf(`%s`, + x, float64(h)-5, template.HTMLEscapeString(buckets[i].Label))) + } + b.WriteString(``) + return template.HTML(b.String()) +} + +// dailyBarBuckets converts DailyStat rows into chart buckets. +func dailyBarBuckets(stats []history.DailyStat) []barBucket { + out := make([]barBucket, 0, len(stats)) + for _, d := range stats { + label := d.Date + if t, err := time.Parse("2006-01-02", d.Date); err == nil { + label = t.Format("02-01") + } + out = append(out, barBucket{ + Label: label, + UptimePct: d.UptimePct, + Checks: d.Checks, + Up: d.Up, + Degraded: d.Degraded, + Down: d.Down, + AvgLatency: d.AvgLatencyMs, + }) + } + return out +} + +// hourlyBarBuckets converts HourlyStat rows into chart buckets. +func hourlyBarBuckets(stats []history.HourlyStat) []barBucket { + out := make([]barBucket, 0, len(stats)) + for _, s := range stats { + uptime := 0.0 + if s.Checks > 0 { + uptime = float64(s.Up+s.Degraded) / float64(s.Checks) * 100 + } + out = append(out, barBucket{ + Label: s.Hour.UTC().Format("15:04"), + UptimePct: uptime, + Checks: s.Checks, + Up: s.Up, + Degraded: s.Degraded, + Down: s.Down, + AvgLatency: s.AvgLatencyMs, + }) + } + return out +} + +// latencyLineChart renders avg-latency values as an SVG area/line chart. +func latencyLineChart(values []float64, labels []string, w, h int, lineColor string) template.HTML { + n := len(values) + if n == 0 || w <= 0 || h <= 0 { + return "" + } + padL, padR, padT, padB := 44.0, 10.0, 10.0, 18.0 + plotW := float64(w) - padL - padR + plotH := float64(h) - padT - padB + if plotW <= 0 || plotH <= 0 { + return "" + } + + minV, maxV := values[0], values[0] + for _, v := range values { + if v < minV { + minV = v + } + if v > maxV { + maxV = v + } + } + if maxV == minV { + maxV = minV + 1 + } + pad := (maxV - minV) * 0.08 + minV -= pad + maxV += pad + + x := func(i int) float64 { + if n == 1 { + return padL + plotW/2 + } + return padL + plotW*float64(i)/float64(n-1) + } + y := func(v float64) float64 { + return padT + plotH*(1-(v-minV)/(maxV-minV)) + } + + var b strings.Builder + b.WriteString(``) + + // gridlines + y labels (4 ticks) + for i := 0; i <= 3; i++ { + v := minV + (maxV-minV)*float64(i)/3 + yy := y(v) + b.WriteString(fmt.Sprintf(``, padL, yy, float64(w)-padR, yy)) + b.WriteString(fmt.Sprintf(`%.0fms`, padL-4, yy+3, v)) + } + + color := safeColor(lineColor) + // area fill + b.WriteString(``, x(n-1), padT+plotH, color)) + // line + b.WriteString(``) + // dots with tooltips + for i, v := range values { + label := "" + if i < len(labels) { + label = labels[i] + } + tip := fmt.Sprintf("%s — %.1fms", label, v) + b.WriteString(fmt.Sprintf(`%s`, x(i), y(v), color, template.HTMLEscapeString(tip))) + } + + // x labels: first, middle, last + idxs := []int{0, n / 2, n - 1} + seen := map[int]bool{} + for _, i := range idxs { + if i < 0 || i >= n || seen[i] { + continue + } + seen[i] = true + lbl := "" + if i < len(labels) { + lbl = labels[i] + } + b.WriteString(fmt.Sprintf(`%s`, x(i), float64(h)-5, template.HTMLEscapeString(lbl))) + } + b.WriteString(``) + return template.HTML(b.String()) +} + +// dailyLatencyChart builds a latency line chart from daily stats. +func dailyLatencyChart(stats []history.DailyStat, w, h int, color string) template.HTML { + values := make([]float64, 0, len(stats)) + labels := make([]string, 0, len(stats)) + for _, d := range stats { + if d.Checks == 0 { + continue + } + values = append(values, d.AvgLatencyMs) + labels = append(labels, d.Date) + } + return latencyLineChart(values, labels, w, h, color) +} diff --git a/internal/server/monitor.go b/internal/server/monitor.go new file mode 100644 index 0000000..c82c02c --- /dev/null +++ b/internal/server/monitor.go @@ -0,0 +1,169 @@ +package server + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + "strconv" + "strings" + + "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/store" +) + +type monitorPageData struct { + Title string + Theme config.ThemeConfig + CustomCSS template.CSS + BackLink string + Index bool + Monitor *store.MonitorState + MonitorID string + Monitors []store.MonitorState + Days int + + HourlyLabel string + HasStats bool + + RangeChecks int + RangeUptime float64 + RangeAvgLat float64 + RangeUp int + RangeDegraded int + RangeDown int + + UptimeChart template.HTML + LatencyChart template.HTML + HourlyChart template.HTML +} + +func (s *Server) serveMonitor(w http.ResponseWriter, r *http.Request) { + 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() + backLink := s.cfg.Server.Endpoint + if backLink == "" { + backLink = "/" + } + + // Monitor ID comes from /monitor/ path or ?id= query param. + id := strings.Trim(strings.TrimPrefix(r.URL.Path, "/monitor"), "/") + if id == "" { + id = r.URL.Query().Get("id") + } + + data := monitorPageData{ + Title: "Monitors — " + s.pageTitle(), + Theme: s.cfg.Page.Theme, + CustomCSS: template.CSS(s.cfg.Page.Theme.CustomCSS), + BackLink: backLink, + MonitorID: id, + Days: s.statsDays(r), + } + + if id == "" { + data.Index = true + data.Monitors = snap.Monitors + } else if m, ok := snap.MonitorsByID[id]; ok { + mc := m + data.Monitor = &mc + data.Title = mc.Name + " — " + s.pageTitle() + s.fillStats(&data, id) + } else { + // Unknown to the store; still try stats in case it existed before. + s.fillStats(&data, id) + } + + w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + + var buf bytes.Buffer + if err := templates.ExecuteTemplate(&buf, "monitor", data); err != nil { + http.Error(w, "template error", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) + if r.Method == http.MethodHead { + return + } + _, _ = w.Write(buf.Bytes()) +} + +func (s *Server) pageTitle() string { + if s.cfg.Page.Title != "" { + return s.cfg.Page.Title + } + return "R u ded?" +} + +// statsDays resolves the requested history window, capped at the configured +// stats retention period. +func (s *Server) statsDays(r *http.Request) int { + retention := s.cfg.Storage.StatsRetentionDays + if retention <= 0 { + retention = 90 + } + days := retention + if v := r.URL.Query().Get("days"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + days = n + } + } + if days > retention { + days = retention + } + return days +} + +// fillStats queries the stats DB and renders the SVG charts for a monitor. +func (s *Server) fillStats(data *monitorPageData, monitorID string) { + if s.stats == nil { + return + } + daily, err := s.stats.DailyStats(monitorID, data.Days) + if err != nil { + return + } + hours := data.Days * 24 + if hours > 168 { + hours = 168 + } + hourly, err := s.stats.HourlyStats(monitorID, hours) + if err != nil { + hourly = nil + } + if len(daily) == 0 && len(hourly) == 0 { + return + } + data.HasStats = true + data.HourlyLabel = fmt.Sprintf("last %d hours", hours) + + var checks, up, degraded, down int + var uptimeSum, latSum float64 + for _, d := range daily { + checks += d.Checks + up += d.Up + degraded += d.Degraded + down += d.Down + uptimeSum += d.UptimePct * float64(d.Checks) + latSum += d.AvgLatencyMs * float64(d.Checks) + } + data.RangeChecks = checks + data.RangeUp = up + data.RangeDegraded = degraded + data.RangeDown = down + if checks > 0 { + data.RangeUptime = uptimeSum / float64(checks) + data.RangeAvgLat = latSum / float64(checks) + } + + th := s.cfg.Page.Theme + data.UptimeChart = uptimeBarChart(dailyBarBuckets(daily), 720, 140, th.UpColor, th.DegradedColor, th.DownColor) + data.LatencyChart = dailyLatencyChart(daily, 720, 120, th.AccentColor) + data.HourlyChart = uptimeBarChart(hourlyBarBuckets(hourly), 720, 120, th.UpColor, th.DegradedColor, th.DownColor) +} diff --git a/internal/server/server.go b/internal/server/server.go index 48f4b54..744e9da 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -10,13 +10,24 @@ import ( "time" "git.gsdistance.org/tyuXX/RUD/internal/config" + "git.gsdistance.org/tyuXX/RUD/internal/history" "git.gsdistance.org/tyuXX/RUD/internal/store" ) -// Server serves the single configured HTTP status and health check endpoint. +const Version = "v1.1" + +// StatsQuerier is the read interface for long-term aggregated check statistics. +type StatsQuerier interface { + DailyStats(monitorID string, days int) ([]history.DailyStat, error) + HourlyStats(monitorID string, hours int) ([]history.HourlyStat, error) +} + +// Server serves the single configured HTTP status and health check endpoint, +// plus the per-monitor historical stats page at /monitor. type Server struct { cfg *config.Config store *store.Store + stats StatsQuerier } // New creates a new single-endpoint HTTP server. @@ -27,8 +38,18 @@ func New(cfg *config.Config, st *store.Store) *Server { } } +// SetStats attaches a long-term stats store used by the /monitor page. +func (s *Server) SetStats(q StatsQuerier) { + s.stats = q +} + // ServeHTTP handles incoming HTTP requests strictly on the configured single endpoint. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/monitor" || strings.HasPrefix(r.URL.Path, "/monitor/") { + s.serveMonitor(w, r) + return + } + endpoint := s.cfg.Server.Endpoint if endpoint == "" { endpoint = "/" @@ -126,10 +147,10 @@ type renderedElement struct { ShowLiveIndicator bool // Banner - BannerMessage string + BannerMessage string BannerMessagesJSON template.JS - ShowOverallUptime bool - ShowCounts bool + ShowOverallUptime bool + ShowCounts bool // Summary cards Cards []summaryCardView @@ -276,7 +297,7 @@ func (s *Server) renderHTML(snap store.Snapshot) ([]byte, error) { } var buf bytes.Buffer - if err := pageTemplate.Execute(&buf, vd); err != nil { + if err := templates.ExecuteTemplate(&buf, "page", vd); err != nil { return nil, err } return buf.Bytes(), nil @@ -415,21 +436,18 @@ func selectGroupMonitors(ids []string, snap store.Snapshot, flags monitorDisplay return views } -var pageTemplate = template.Must(template.New("status").Funcs(template.FuncMap{ +var templates = template.Must(template.New("status").Funcs(template.FuncMap{ "upper": strings.ToUpper, + "Version": func() string { + return Version + }, "fmtTime": func(t time.Time) string { if t.IsZero() { return "-" } return t.UTC().Format("2006-01-02 15:04:05 UTC") }, -}).Parse(` - - - - -{{.Title}} - +{{end}}{{define "page"}} + + + + +{{.Title}} +{{template "pagecss" .}}
@@ -652,11 +676,8 @@ a:hover { color: var(--accent); }
- {{- if .Monitor.Link}} - {{.Monitor.Name}} - {{- else}} - {{.Monitor.Name}} - {{- end}} + {{.Monitor.Name}} + {{- if .Monitor.Link}}↗{{end}} {{- if $disp.ShowMethod}}{{upper .Monitor.Method}}{{end}} {{- if and $disp.ShowTarget .Monitor.Target}}{{.Monitor.Target}}{{end}}
@@ -699,7 +720,7 @@ a:hover { color: var(--accent); } {{- end}}
{{- if gt .RefreshMs 0}} @@ -789,5 +810,96 @@ a:hover { color: var(--accent); } {{- end}} - +{{end}} + +{{define "monitor"}} + + + + +{{.Title}} +{{template "pagecss" .}} + + +
+
+
+ {{- if .Monitor}}

{{.Monitor.Name}}

+
{{upper .Monitor.Method}}{{if .Monitor.Target}} — {{.Monitor.Target}}{{end}}
+ {{- else if .Index}}

Monitors

+
Select a monitor to view its history
+ {{- else}}

{{.MonitorID}}

+
Monitor not found
{{end}} +
+ +
+ + {{- if .Index}} +
+
+ {{- range .Monitors}} +
+
+
+ {{.Name}} + {{upper .Method}} + {{- if .Target}}{{.Target}}{{end}} +
+
+ {{.State}} +
+
+
+ {{- end}} +
+
+ + {{- else if .Monitor}} + + +
+
+
CHECKS ({{.Days}}D)
{{.RangeChecks}}
+
UPTIME ({{.Days}}D)
{{printf "%.2f%%" .RangeUptime}}
+
AVG LATENCY
{{printf "%.1fms" .RangeAvgLat}}
+
FAILURES ({{.Days}}D)
{{.RangeDown}}
+
+
+ + {{- if .HasStats}} +
+
Daily uptime — last {{.Days}} days
+ {{.UptimeChart}} +
+
+
Avg response time — last {{.Days}} days
+ {{.LatencyChart}} +
+
+
Hourly uptime — {{.HourlyLabel}}
+ {{.HourlyChart}} +
+ {{- else}} +
No historical stats recorded yet for this monitor.
+ {{- end}} + {{- if .Monitor.Description}}
{{.Monitor.Description}}
{{end}} + + {{- else}} +
Unknown monitor {{.MonitorID}}.
+ {{- end}} + + +
+ +{{end}} `)) diff --git a/internal/store/store.go b/internal/store/store.go index eeb44ea..c36a3b3 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -77,6 +77,16 @@ type Store struct { persistenceFile string order []string monitors map[string]*MonitorState + onRecord func(monitorID string, res CheckResult) +} + +// SetOnRecord registers a callback invoked (outside the store lock) after every +// successfully recorded check result. It is intended for long-term history +// sinks such as the daily log and stats database. +func (s *Store) SetOnRecord(fn func(monitorID string, res CheckResult)) { + s.mu.Lock() + defer s.mu.Unlock() + s.onRecord = fn } // New creates a new Store initialized with the configured monitors. @@ -113,10 +123,10 @@ func New(cfg *config.Config) *Store { // 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 { + s.mu.Unlock() return } @@ -168,6 +178,13 @@ func (s *Store) Record(monitorID string, res CheckResult) { if latCount > 0 { m.AvgLatencyMs = round2(latSum / float64(latCount)) } + + onRecord := s.onRecord + s.mu.Unlock() + + if onRecord != nil { + onRecord(monitorID, res) + } } // Snapshot returns a deep copy of current monitor states and aggregate metrics. diff --git a/main.go b/main.go index a70099f..211464c 100644 --- a/main.go +++ b/main.go @@ -16,6 +16,7 @@ import ( "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/history" "git.gsdistance.org/tyuXX/RUD/internal/server" "git.gsdistance.org/tyuXX/RUD/internal/store" ) @@ -67,11 +68,62 @@ func main() { } } + // Long-term history: daily JSONL logs (zstd-compressed on day rollover) and + // the SQLite aggregate stats database used by the /monitor page. + monitorMeta := func(id string) history.MonitorMeta { + for _, m := range cfg.Monitors { + if m.ID == id { + return history.MonitorMeta{Name: m.Name, Method: m.Method, Target: m.DisplayTarget()} + } + } + return history.MonitorMeta{} + } + + var dailyLog *history.DailyLogger + if dir := cfg.Storage.LogsDir; dir != "" && dir != "off" && dir != "none" { + l, err := history.NewDailyLogger(dir, monitorMeta) + if err != nil { + log.Printf("Warning: could not initialize daily history log in %s: %v", dir, err) + } else { + dailyLog = l + log.Printf("Daily history logging enabled (%s)", dir) + } + } + + var statsDB *history.StatsDB + if path := cfg.Storage.StatsDB; path != "" && path != "off" && path != "none" { + db, err := history.NewStatsDB(path, cfg.Storage.StatsRetentionDays) + if err != nil { + log.Printf("Warning: could not initialize stats database %s: %v", path, err) + } else { + statsDB = db + log.Printf("Stats database enabled (%s, retention %d days)", path, cfg.Storage.StatsRetentionDays) + } + } + + if dailyLog != nil || statsDB != nil { + st.SetOnRecord(func(monitorID string, res store.CheckResult) { + if dailyLog != nil { + if err := dailyLog.Record(monitorID, res); err != nil { + log.Printf("history log write error: %v", err) + } + } + if statsDB != nil { + if err := statsDB.Record(monitorID, res); err != nil { + log.Printf("stats db write error: %v", err) + } + } + }) + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() evEngine := events.NewEngine(cfg.Events) srvHandler := server.New(cfg, st) + if statsDB != nil { + srvHandler.SetStats(statsDB) + } httpServer := &http.Server{ Addr: cfg.Server.Listen, @@ -126,6 +178,17 @@ func main() { sched.Wait() evEngine.Wait() + if dailyLog != nil { + if err := dailyLog.Close(); err != nil { + log.Printf("Error closing history log: %v", err) + } + } + if statsDB != nil { + if err := statsDB.Close(); err != nil { + log.Printf("Error closing stats database: %v", err) + } + } + if cfg.Storage.PersistenceFile != "" { if err := st.SaveToDisk(); err != nil { log.Printf("Error saving final state to disk: %v", err) diff --git a/rud.json b/rud.json index dfd4f6c..425c8d1 100644 --- a/rud.json +++ b/rud.json @@ -20,7 +20,10 @@ }, "storage": { "history_size": 60, - "save_interval": "1m" + "save_interval": "1m", + "logs_dir": "logs", + "stats_db": "stats.db", + "stats_retention_days": 90 }, "defaults": { "interval": "15s",