This commit is contained in:
tyuXX 2026-11-07 15:22:48 +03:00
parent d37503c863
commit 1509789cde
19 changed files with 1534 additions and 112 deletions

5
.gitignore vendored
View file

@ -26,3 +26,8 @@ go.work.sum
# env file
.env
# History logs and stats database
/logs/
/stats.db*
/data/

View file

@ -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 `<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`. |
@ -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=<monitor-id>` (also reachable as `/monitor/<monitor-id>`), 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.
---

View file

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

View file

@ -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:
```bash
# Minimal HTML Status Page
curl http://localhost:8080/
Then open `http://localhost:8080/` (HTML) or `http://localhost:8080/?format=json` (JSON).
# 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:
### Docker Compose
```bash
docker compose up -d --build
docker compose up -d --build # exposes port 8080, persists ./data
```
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:
### 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`.
---
## Configuration Documentation
## Configuration
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**.

View file

@ -9,6 +9,7 @@ services:
- "8080"
volumes:
- ./rud.json:/app/rud.json:ro
- ./data:/app/data
cap_add:
- NET_RAW
networks:

View file

@ -9,5 +9,6 @@ services:
- "${RUD_PORT:-8080}:8080"
volumes:
- ./rud.json:/app/rud.json:ro
- ./data:/app/data
cap_add:
- NET_RAW

19
go.mod
View file

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

52
go.sum Normal file
View file

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

View file

@ -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"`
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.
@ -365,6 +369,9 @@ func DefaultConfig() Config {
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)

View file

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

229
internal/history/logger.go Normal file
View file

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

285
internal/history/stats.go Normal file
View file

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

260
internal/server/charts.go Normal file
View file

@ -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(`<svg viewBox="0 0 ` + strconv.Itoa(w) + ` ` + strconv.Itoa(h) + `" style="width:100%;height:auto;display:block" role="img">`)
// horizontal gridlines at 0/50/100%
for _, pct := range []float64{0, 50, 100} {
y := padT + plotH*(1-pct/100)
b.WriteString(fmt.Sprintf(`<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="var(--border,#333)" stroke-width="0.5"/>`, padL, y, float64(w)-padR, y))
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="end">%d%%</text>`, 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(`<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="%s" rx="1"><title>%s</title></rect>`,
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(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="middle">%s</text>`,
x, float64(h)-5, template.HTMLEscapeString(buckets[i].Label)))
}
b.WriteString(`</svg>`)
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(`<svg viewBox="0 0 ` + strconv.Itoa(w) + ` ` + strconv.Itoa(h) + `" style="width:100%;height:auto;display:block" role="img">`)
// 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(`<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="var(--border,#333)" stroke-width="0.5"/>`, padL, yy, float64(w)-padR, yy))
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="end">%.0fms</text>`, padL-4, yy+3, v))
}
color := safeColor(lineColor)
// area fill
b.WriteString(`<path d="`)
b.WriteString(fmt.Sprintf(`M %.1f %.1f `, x(0), padT+plotH))
for i, v := range values {
b.WriteString(fmt.Sprintf(`L %.1f %.1f `, x(i), y(v)))
}
b.WriteString(fmt.Sprintf(`L %.1f %.1f Z" fill="%s" fill-opacity="0.15" stroke="none"/>`, x(n-1), padT+plotH, color))
// line
b.WriteString(`<polyline fill="none" stroke="` + color + `" stroke-width="1.5" points="`)
for i, v := range values {
b.WriteString(fmt.Sprintf(`%.1f,%.1f `, x(i), y(v)))
}
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(`<circle cx="%.1f" cy="%.1f" r="2.5" fill="%s"><title>%s</title></circle>`, 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(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="middle">%s</text>`, x(i), float64(h)-5, template.HTMLEscapeString(lbl)))
}
b.WriteString(`</svg>`)
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)
}

169
internal/server/monitor.go Normal file
View file

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

View file

@ -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 = "/"
@ -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(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
<style>
}).Parse(`{{define "pagecss"}}<style>
:root {
--bg: {{.Theme.BgColor}};
--card: {{.Theme.CardBgColor}};
@ -597,7 +615,13 @@ a:hover { color: var(--accent); }
color: var(--muted);
}
{{.CustomCSS}}
</style>
</style>{{end}}{{define "page"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
{{template "pagecss" .}}
</head>
<body>
<div class="container">
@ -652,11 +676,8 @@ a:hover { color: var(--accent); }
<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}}
<a class="mon-name" href="/monitor?id={{.Monitor.ID}}">{{.Monitor.Name}}</a>
{{- if .Monitor.Link}}<a class="mon-ext" href="{{.Monitor.Link}}" target="_blank" rel="noopener" title="External link">&#8599;</a>{{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>
@ -699,7 +720,7 @@ a:hover { color: var(--accent); }
{{- end}}
<footer class="footer">
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a>
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a> {{Version}}
</footer>
</div>
{{- if gt .RefreshMs 0}}
@ -789,5 +810,96 @@ a:hover { color: var(--accent); }
</script>
{{- end}}
</body>
</html>
</html>{{end}}
{{define "monitor"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
{{template "pagecss" .}}
</head>
<body>
<div class="container">
<header class="header header-left">
<div>
{{- if .Monitor}}<h1>{{.Monitor.Name}}</h1>
<div class="subtitle">{{upper .Monitor.Method}}{{if .Monitor.Target}} — {{.Monitor.Target}}{{end}}</div>
{{- else if .Index}}<h1>Monitors</h1>
<div class="subtitle">Select a monitor to view its history</div>
{{- else}}<h1>{{.MonitorID}}</h1>
<div class="subtitle">Monitor not found</div>{{end}}
</div>
<div class="header-meta"><a href="{{.BackLink}}">&larr; status page</a></div>
</header>
{{- if .Index}}
<section class="group">
<div class="monitors-list">
{{- range .Monitors}}
<div class="mon">
<div class="mon-top">
<div class="mon-left">
<a class="mon-name" href="/monitor?id={{.ID}}">{{.Name}}</a>
<span class="mon-method">{{upper .Method}}</span>
{{- if .Target}}<span class="mon-target">{{.Target}}</span>{{end}}
</div>
<div class="mon-right">
<span class="badge" data-state="{{.State}}">{{.State}}</span>
</div>
</div>
</div>
{{- end}}
</div>
</section>
{{- else if .Monitor}}
<section class="banner" data-state="{{.Monitor.State}}">
<div class="banner-title">{{upper .Monitor.State}}</div>
<div class="banner-meta">
<span>last checked {{fmtTime .Monitor.LastCheckedAt}}</span>
<span>{{printf "%.1fms" .Monitor.LatencyMs}} latency</span>
<span>{{printf "%.2f%%" .Monitor.UptimePct}} uptime</span>
{{- if .Monitor.LastMessage}}<span>{{.Monitor.LastMessage}}</span>{{end}}
</div>
</section>
<section>
<div class="cards">
<div class="card"><div class="card-label">CHECKS ({{.Days}}D)</div><div class="card-val">{{.RangeChecks}}</div></div>
<div class="card"><div class="card-label">UPTIME ({{.Days}}D)</div><div class="card-val">{{printf "%.2f%%" .RangeUptime}}</div></div>
<div class="card"><div class="card-label">AVG LATENCY</div><div class="card-val">{{printf "%.1fms" .RangeAvgLat}}</div></div>
<div class="card"><div class="card-label">FAILURES ({{.Days}}D)</div><div class="card-val" style="color:var(--down)">{{.RangeDown}}</div></div>
</div>
</section>
{{- if .HasStats}}
<section class="group">
<div class="group-hdr"><div class="group-title">Daily uptime — last {{.Days}} days</div></div>
{{.UptimeChart}}
</section>
<section class="group">
<div class="group-hdr"><div class="group-title">Avg response time — last {{.Days}} days</div></div>
{{.LatencyChart}}
</section>
<section class="group">
<div class="group-hdr"><div class="group-title">Hourly uptime — {{.HourlyLabel}}</div></div>
{{.HourlyChart}}
</section>
{{- else}}
<section class="custom-block" data-style="info"><div>No historical stats recorded yet for this monitor.</div></section>
{{- end}}
{{- if .Monitor.Description}}<section class="custom-block" data-style="neutral"><div>{{.Monitor.Description}}</div></section>{{end}}
{{- else}}
<section class="custom-block" data-style="warning"><div>Unknown monitor <code>{{.MonitorID}}</code>.</div></section>
{{- end}}
<footer class="footer">
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a> {{Version}}
</footer>
</div>
</body>
</html>{{end}}
`))

View file

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

63
main.go
View file

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

View file

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