diff --git a/API-GAPS.md b/API-GAPS.md index e769d3d..5e5673a 100644 --- a/API-GAPS.md +++ b/API-GAPS.md @@ -11,7 +11,7 @@ This list is based on the supplied EasyDNS Rust **0.1.4** implementation, not a | Editing transfer ACLs, upstream primaries, notify targets or TSIG of an existing zone | Not provided. Zone configuration is visible with GET; no general REST setter for these fields. | | Automatic remote token discovery/rotation | Not provided. Each remote EasyDNS auto-generates its own token. An administrator must supply that token securely to the Go panel, or use a local tunnel. | | Query log | No REST endpoint for historical DNS client queries. `GET /query` is only an immediate diagnostic lookup. | -| Native 24-hour historical graphs | `/stats` returns counters and a snapshot. The Go service samples at 15-second intervals, up to six hours in memory per enabled node. No fabricated 24-hour history. | +| Native 24-hour historical graphs | `/stats` returns counters and a snapshot. The Go service samples at 15-second intervals, up to 24 hours in memory per enabled node. No fabricated 24-hour history. | | Per-zone query rate | No per-zone QPS. The Zone Details screen does not display an invented rate chart. | | Transfer queue position / ETA / percentage progress | `/zones/{zone}/transfers` provides history, not live queue/progress. | | Generic ZoneConfig editor | No arbitrary REST configuration mutation. Create primary, replace complete zone text, delete API-created overlays, but do not edit config-only fields. | diff --git a/API-MAPPING.md b/API-MAPPING.md index 5f74ba4..635183d 100644 --- a/API-MAPPING.md +++ b/API-MAPPING.md @@ -68,3 +68,11 @@ The maximum is 15 remote servers plus the local instance. HTTP API transport is - **Native OpenAPI:** `GET /api/v1/openapi.json` exists but is not used to invent UI operations. See [MULTI-SERVER.md](MULTI-SERVER.md) and [API-GAPS.md](API-GAPS.md) for role semantics and unsupported operations. + +## EasyDNS Web 0.1.2 — time-series presentation + +The **Go Web panel** continues to poll the existing native EasyDNS `GET /api/v1/stats` endpoint every 15 s. It does **not** scrape `/metrics`, Prometheus or Grafana; it does not depend on new Rust APIs or call the Rust `/api/v1/stats/history` endpoint. Stored measurements live in Go memory for at most 24 h; restarts discard the panel's series. + +The authenticated panel-only `GET /ui/telemetry?mode=single|split|aggregate&range=15m|1h|6h|12h|24h&step=auto|15s|30s|1m|5m|15m|1h` returns `samples`, `range`, `step`, `stepSeconds`, `from`, `to`, `intervalSeconds` and retention metadata. Fleet modes include `nodes`, and Aggregate includes strict complete-coverage rate buckets. Parameters are whitelisted and bounded. Without an explicit `step`, the legacy response retains raw 15-second data. + +Downsampling averages observed per-second rates, weights cache hit ratios by actual hit/miss rates, retains the maximum observed per-sample p50/p95/p99 within a bucket (not a recalculated quantile), and preserves gaps or counter resets as `null`. Chart controls in Overview and Metrics request these reduced series. Client-side CSV export contains only currently displayed measured values, not synthetic history. Additional source-rate charts are derived from the native `sources` map (recursive, authoritative, cache and forward); host CPU/memory data are deliberately not invented. diff --git a/CHANGELOG.md b/CHANGELOG.md index e950204..8c7f9b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 0.1.2-1 — DNSSEC / server inventory patch + +- Add an optional **Hide DNSSEC records** checkbox on Zone → Records. Hides RRSIG, DNSKEY, NSEC/NSEC3, NSEC3PARAM, DS, CDS and CDNSKEY before paginating the Go panel view; native EasyDNS data remains unchanged. +- Preserve name and record-type filters when paging the filtered list. Go uses native `GET /api/v1/zones/{zone}/records` with a raw-record cursor and does not require an API schema change. +- Fix server-inventory navigation: add `/servers#server-inventory` shortcut, links to individual inventory rows, and a Server status shortcut; explain how to enable multi-server when `/servers` is unavailable instead of returning 404. +- Add API-backed integration tests for signed zones containing over 1,000 DNSSEC records, next/previous navigation, type filters, and server anchors. + + +## 0.1.2 — 2026-11-30 + +- Update EasyDNS **Web** Overview and Metrics pages to align with `design/reference` (OLED cards, tight metric grids, transparent context, improved line charts). No changes required to the Rust DNS service. +- Add global time range (15m, 1h, 6h, 12h, 24h) and downsampling controls (Auto, 15s, 30s, 1m, 5m, 15m, 1h); override both at each chart. Preserve selections locally per page/scope. +- Extend authenticated Go `/ui/telemetry` with `range` and `step`; aggregate genuine in-memory `/api/v1/stats` polls server-side, keeping missing/reset values missing. Retain up to 24 hours at 15-second polling. +- Add 15 Metrics visualizations, six Overview visualizations, sampled query sources, cache traffic/evictions, response error ratio, rate limiting and CSV export from displayed measured data. +- Preserve Single / Aggregate / Split per-node views, weighted fleet cache ratio and per-node latency percentiles. No Prometheus/Grafana, no fake metrics or browser-side DNS credentials. +- Update tests, release build version and operator documentation. + ## 0.1.1 — 2026-11-30 - Simplify the login screen and remove redundant credential and control-room copy. diff --git a/Dockerfile b/Dockerfile index 56d54d4..d47eded 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,7 @@ COPY go.mod ./ COPY cmd ./cmd COPY internal ./internal ARG BUILD_ID="" -ARG VERSION="0.1.1" +ARG VERSION="0.1.2-1" ENV CGO_ENABLED=0 GOOS=linux GOPROXY=off GOTOOLCHAIN=local RUN set -eu; \ if [ -z "$BUILD_ID" ]; then BUILD_ID="$(date -u +%Y%m%dT%H%M%S)-$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')"; fi; \ diff --git a/MULTI-SERVER.md b/MULTI-SERVER.md index d1282af..5c8ebde 100644 --- a/MULTI-SERVER.md +++ b/MULTI-SERVER.md @@ -121,3 +121,9 @@ Health checks are performed when the Servers page is visited. The Go process als This feature adds panel-owned endpoints such as `/servers`, `/servers/compare` and `/configuration/multi-server`, **not new EasyDNS API endpoints**. For preconfigured nodes in Debian TOML (`[[servers]]`) or Docker Compose `.env` (`EASYDNS_UI_SERVER_N_TOKEN`), secrets are held in the Go process memory rather than copied to the panel-owned token directory. See [CONFIGURATION.md](CONFIGURATION.md) for examples. + +## Server inventory deep links (0.1.2-1) + +- Use `/servers#server-inventory` to jump directly to the managed installations list; the Servers page contains a visible shortcut to this section. +- The **View in inventory** action on each topology card points to `/servers#server-{id}` and highlights that server's row. **Server status** also links to the inventory while multi-server is enabled. +- If multi-server is disabled, opening `/servers` redirects to Configuration and displays instructions for enabling it rather than an unexplained 404. Config-managed disabled mode must be changed in TOML/environment, not through the hidden checkbox. diff --git a/Makefile b/Makefile index cc28e87..70c805e 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ GO ?= go -VERSION ?= 0.1.1 +VERSION ?= 0.1.2-1 GOARCH ?= amd64 ARCH ?= all .PHONY: test vet build deb docker-deb clean diff --git a/README.md b/README.md index 48c45d5..0b8bcc0 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,11 @@ A standalone, self-contained Go administration panel for the EasyDNS Rust DNS se - DNS lookup, upstreams, policies, read-only views/ACL/rate limits, blocklists, cache, sampled metrics, audit, server status and configuration reload. - **Optional multi-server management**: one central panel for a local EasyDNS installation plus remote installations (for example one Primary and two Secondary DNS servers). - Server topology with per-server health, actual DNS role counts, automatic active-server selection and read-only zone serial comparison. -- **Metrics: Aggregate / Split / Single** in multi-server mode. Additive QPS rates and counters can be combined, cache ratios are weighted, and latency percentiles remain per-server. No synthetic history or new EasyDNS API endpoints. +- **Metrics: Aggregate / Split / Single** in multi-server mode, with time-range and downsampling controls globally and per chart. Additive QPS rates and counters can be combined, cache ratios are weighted, and latency percentiles remain per-server. No synthetic history or new EasyDNS API endpoints. - **Single-server mode by default**. Enable Multi-server using `config.toml` (Debian), `.env` (Compose), or the Configuration toggle only when neither source explicitly sets the mode. +- Overview and Metrics 0.1.2: 15-minute, 1-, 6-, 12- and 24-hour ranges, Auto/15s/30s/1m/5m/15m/1h server-side downsampling; chart-specific overrides, hover details and real sample CSV export. +- 15 measured chart types from existing `/api/v1/stats` fields (DNS throughput, sources, result codes, cache, latency, policy, rate limiting, errors); no Prometheus/Grafana scraping or fictitious host CPU data. +- Sampling in Go panel RAM every 15 seconds, up to 24 hours (resets on panel restart and starts empty); gaps and counter resets stay missing, including fleet aggregates. - Secure administrator login, session/CSRF protection, safe confirmations and ETag/If-Match concurrency handling for DNS record changes. The panel never invents REST endpoints or server-side capabilities. In particular, the optional “topology” is a **management view**, not a distributed cluster implementation. There is no automatic leader election, quorum, primary/secondary provisioning, DNS replication setup, or secret distribution. EasyDNS itself continues to handle native AXFR/IXFR and NOTIFY, configured on the respective DNS installations. @@ -24,13 +27,19 @@ Almost-black backgrounds, fine hairline borders, dense tables, restrained cyan/a Five approved appearance references are in `design/reference/`. The screenshots under `design/screenshots/` are rendered demo fixtures, **not live EasyDNS measurements**. UI elements are constrained by available API data and operations; the style references are not treated as a backend contract. +## Zone record readability and server inventory (0.1.2-1) + +On **Zones → [zone] → Records**, check **Hide DNSSEC records** to exclude signatures, DNSKEY and denial-of-existence records from the displayed table while preserving the original DNS data. The filter is off by default, works with name/type search, and persists across Next/Previous links. Counts in this mode refer to the unfiltered API total. No Prometheus or DNS service changes are needed. + +With optional multi-server enabled, the server overview links directly to the **Managed installations** section (`/servers#server-inventory`) and to individual server rows. When disabled, the same URL redirects to **Configuration** with a notice instead of returning 404. + ## Install with Debian packages EasyDNS itself must already be installed and running. Install the matching EasyDNS Web package: ```bash -sudo apt install ./easydns-ui_0.1.1_amd64.deb -# On ARM64, use easydns-ui_0.1.1_arm64.deb instead. +sudo apt install ./easydns-ui_0.1.2-1_amd64.deb +# On ARM64, use easydns-ui_0.1.2-1_arm64.deb instead. sudo systemctl status easydns-ui sudo cat /etc/easydns-ui/panel.password ``` @@ -76,7 +85,7 @@ sudo systemctl restart easydns-ui sudo journalctl -u easydns-ui -f ``` -**Upgrade note for Multi-server users:** 0.1.1 treats `[multiserver] enabled` in TOML as authoritative. If an older 0.1.0 installation had Multi-server enabled only via the web toggle while `config.toml` still says `enabled = false`, change the TOML value to `true` and restart after upgrading. Existing remote connections and tokens remain saved; they are not deleted. +**Upgrade note for Multi-server users:** Starting from 0.1.1, the panel treats `[multiserver] enabled` in TOML as authoritative. If an older 0.1.0 installation had Multi-server enabled only via the web toggle while `config.toml` still says `enabled = false`, change the TOML value to `true` and restart after upgrading. Existing remote connections and tokens remain saved; they are not deleted. The TOML file can configure username, password, API URL, API token (or the generated token file), bind address, session settings and up to 15 additional server connections. For an existing installation upgraded from the old `/etc/default/easydns-ui`, copy any custom values to the TOML file; the old shell environment file is no longer sourced by the systemd unit. @@ -99,8 +108,8 @@ make test make vet make build ./bin/easydns-ui -version -make deb GOARCH=amd64 VERSION=0.1.1 -make deb GOARCH=arm64 VERSION=0.1.1 +make deb GOARCH=amd64 VERSION=0.1.2-1 +make deb GOARCH=arm64 VERSION=0.1.2-1 ``` ### Reproducible Docker-based Debian packaging @@ -110,8 +119,8 @@ Only Docker is required on the build host (no local Go or `dpkg-deb`): ```bash ./scripts/build_deb.sh # amd64 + arm64 ./scripts/build_deb.sh --arch amd64 -./scripts/build_deb.sh --arch arm64 --version 0.1.1 -make docker-deb ARCH=all VERSION=0.1.1 +./scripts/build_deb.sh --arch arm64 --version 0.1.2-1 +make docker-deb ARCH=all VERSION=0.1.2-1 ``` The default build image is `golang:1.23-bookworm`, including Debian tools. The Docker build container runs with networking disabled (`--network none`), uses the existing `scripts/build-deb.sh` package definition, and compiles both Linux architectures with `CGO_ENABLED=0`. Packages are placed in `dist/`. diff --git a/UI-STRUCTURE.md b/UI-STRUCTURE.md index 2910d5b..16327b7 100644 --- a/UI-STRUCTURE.md +++ b/UI-STRUCTURE.md @@ -11,6 +11,7 @@ DNS Import full zone file /zones/import Zone details /zones/{zone} Records /zones/{zone}/records + Hide DNSSEC records ?hide_dnssec=1 (UI-only filter, before pagination) Add record /zones/{zone}/records/new Edit record /zones/{zone}/records/{id}/edit Delete record /zones/{zone}/records/{id}/delete @@ -47,6 +48,8 @@ The original navigation remains, with two additions: ```text FLEET Servers /servers + Server inventory /servers#server-inventory + Specific inventory row /servers#server-{id} Add server /servers/new Compare zone serials /servers/compare?zone=example.com. Edit display role /servers/{id}/role (POST) diff --git a/internal/server/fleet_metrics.go b/internal/server/fleet_metrics.go index 3d72951..4fb8584 100644 --- a/internal/server/fleet_metrics.go +++ b/internal/server/fleet_metrics.go @@ -124,7 +124,8 @@ func saturatingAdd(a, b uint64) uint64 { // fleetTelemetry is a panel-internal authenticated JSON endpoint. It never // calls a non-existent EasyDNS endpoint; all data comes from sampled /stats. -func (s *Server) fleetTelemetry(w http.ResponseWriter, _ *http.Request, mode string) { +func (s *Server) fleetTelemetry(w http.ResponseWriter, r *http.Request, mode string) { + window := telemetry.ParseWindow(r.URL.Query().Get("range"), r.URL.Query().Get("step"), time.Now().UTC()) all := s.nodes.All() nodes := make([]telemetry.FleetNode, 0, len(all)) for _, n := range all { @@ -144,11 +145,18 @@ func (s *Server) fleetTelemetry(w http.ResponseWriter, _ *http.Request, mode str response := map[string]any{ "mode": mode, "nodes": nodes, "total": len(all), "intervalSeconds": 15, + "range": window.Range, "step": window.Step, "stepSeconds": window.StepSeconds, + "from": window.From, "to": window.To, "retentionHours": 24, } if mode == "aggregate" { - response["samples"] = telemetry.AggregateFleet(nodes) + // Aggregate raw aligned samples first; independently downsampling each + // node would destroy time alignment and bias fleet values. + response["samples"] = telemetry.WindowFleet(telemetry.AggregateFleet(nodes), window) response["aggregation"] = "strict-complete: rates sum only when every server has a fresh sample; cache ratio weighted by cache lookups; latency per node" } + for i := range nodes { + nodes[i].Samples = telemetry.WindowSamples(nodes[i].Samples, window) + } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(response) diff --git a/internal/server/modules.go b/internal/server/modules.go index edbca48..3720e86 100644 --- a/internal/server/modules.go +++ b/internal/server/modules.go @@ -200,6 +200,9 @@ func (s *Server) metrics(w http.ResponseWriter, r *http.Request) { d.MetricTotal = len(d.MetricNodes) } sm, e, last := s.telemetry.Snapshot() + if len(sm) > 0 { + d.RecentQueryRate = sm[len(sm)-1].QueryRate + } d.SamplingCount = len(sm) d.SamplingTime = last d.SamplingError = e diff --git a/internal/server/multiserver_test.go b/internal/server/multiserver_test.go index 139462d..da47ce3 100644 --- a/internal/server/multiserver_test.go +++ b/internal/server/multiserver_test.go @@ -74,8 +74,8 @@ func TestModePreferenceAndExistingSingleServerUI(t *testing.T) { t.Fatalf("single server configuration was changed: %d, body=%s", w.Code, w.Body.String()) } w = panelRequest(t, s, "GET", "/servers", nil, nil) - if w.Code != 404 { - t.Fatalf("fleet accessible when off: %d", w.Code) + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/configuration?notice=server-inventory-disabled#multi-server-preference" { + t.Fatalf("disabled inventory should explain how to enable it: %d %s", w.Code, w.Header().Get("Location")) } w = panelRequest(t, s, "POST", "/configuration/multi-server", url.Values{"enabled": {"on"}}, nil) if w.Code != 303 || w.Header().Get("Location") != "/servers?notice=servers-enabled" { @@ -93,8 +93,8 @@ func TestModePreferenceAndExistingSingleServerUI(t *testing.T) { t.Fatal("fleet still enabled") } w = panelRequest(t, s, "GET", "/servers", nil, nil) - if w.Code != 404 { - t.Fatalf("fleet accessible after disable: %d", w.Code) + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/configuration?notice=server-inventory-disabled#multi-server-preference" { + t.Fatalf("disabled inventory must link to configuration: %d %s", w.Code, w.Header().Get("Location")) } s2 := panelWithNodes(t, backend.URL, state) if s2.nodes.Enabled() { diff --git a/internal/server/pages.go b/internal/server/pages.go index 3649b4e..df7d6eb 100644 --- a/internal/server/pages.go +++ b/internal/server/pages.go @@ -30,6 +30,15 @@ func (s *Server) overview(w http.ResponseWriter, r *http.Request) { d.Audit = audits.Items } smp, e, last := s.telemetry.Snapshot() + if len(smp) > 0 { + d.RecentQueryRate = smp[len(smp)-1].QueryRate + } + var groups struct { + Items []easydns.UpstreamGroup `json:"items"` + } + if s.get(r.Context(), "/api/v1/upstreams", &groups) == nil { + d.Upstreams = groups.Items + } d.SamplingCount = len(smp) d.SamplingTime = last d.SamplingError = e @@ -198,23 +207,71 @@ func (s *Server) zoneDetail(w http.ResponseWriter, r *http.Request, name, tab st } if tab == "records" { v := r.URL.Query() - query := url.Values{"page": {strconv.Itoa(getInt(v.Get("page"), 1, 1, 100000))}, "per_page": {"50"}} + page := getInt(v.Get("page"), 1, 1, 100000) + d.HideDNSSEC = v.Get("hide_dnssec") == "1" d.Filter = map[string]string{"name": v.Get("name"), "type": v.Get("type")} - for _, k := range []string{"name", "type"} { - if v := strings.TrimSpace(d.Filter[k]); v != "" { - query.Set(k, v) + query := url.Values{"page": {strconv.Itoa(page)}, "per_page": {"50"}} + for _, key := range []string{"name", "type"} { + if filter := strings.TrimSpace(d.Filter[key]); filter != "" { + query.Set(key, filter) } } - var p easydns.Page[easydns.Record] - if e, er := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/records?"+query.Encode(), &p); er != nil { - if d.Error == "" { - d.Error = er.Error() + d.Pagination = easydns.Pagination{Page: page, PerPage: zoneRecordPageSize} + if d.HideDNSSEC { + cursor := parseRecordCursor(v.Get("cursor")) + // A type included by the user but excluded by the checkbox + // yields no visible rows. Still fetch the API metadata so the + // total count is not misleadingly reported as zero. + if isDNSSECRecordType(v.Get("type")) { + var meta easydns.Page[easydns.Record] + q := url.Values{"per_page": {"1"}, "page": {"1"}} + if text := strings.TrimSpace(v.Get("name")); text != "" { + q.Set("name", text) + } + q.Set("type", strings.TrimSpace(v.Get("type"))) + if _, er := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/records?"+q.Encode(), &meta); er != nil { + if d.Error == "" { + d.Error = er.Error() + } + } else { + d.Pagination.Total = meta.Pagination.Total + } + } else { + listed, er := s.listVisibleZoneRecords(r.Context(), name, query, cursor, page) + if er != nil { + if d.Error == "" { + d.Error = er.Error() + } + } else { + d.Records, d.Pagination.Total = listed.records, listed.rawTotal + if listed.etag != "" { + d.ETag = listed.etag + } + if listed.hasNext { + d.RecordsNextURL = recordPageURL(name, v, page+1, listed.nextCursor, true) + } + if listed.hasPrev { + d.RecordsPrevURL = recordPageURL(name, v, page-1, listed.prevCursor, true) + } + } } } else { - d.Records = p.Items - d.Pagination = p.Pagination - if e != "" { - d.ETag = e + var p easydns.Page[easydns.Record] + if e, er := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/records?"+query.Encode(), &p); er != nil { + if d.Error == "" { + d.Error = er.Error() + } + } else { + d.Records, d.Pagination = p.Items, p.Pagination + if e != "" { + d.ETag = e + } + if page > 1 { + d.RecordsPrevURL = recordPageURL(name, v, page-1, 0, false) + } + if page*p.Pagination.PerPage < p.Pagination.Total { + d.RecordsNextURL = recordPageURL(name, v, page+1, 0, false) + } } } } diff --git a/internal/server/record_listing.go b/internal/server/record_listing.go new file mode 100644 index 0000000..18425e8 --- /dev/null +++ b/internal/server/record_listing.go @@ -0,0 +1,172 @@ +package server + +import ( + "context" + "fmt" + "net/url" + "strconv" + "strings" + + "git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns" +) + +// The EasyDNS API supports inclusion by one RR type, but no exclusion filter. +// Signed zones can contain thousands of generated signatures. The panel pages +// through the native API and applies the DNSSEC exclusion before constructing +// a visible page, so a page is never filled with hidden rows. +const ( + zoneRecordBatch = 1000 // maximum per_page accepted by native EasyDNS + zoneRecordPageSize = 50 +) + +var dnssecRecordTypes = map[string]bool{ + "RRSIG": true, "NSEC": true, "NSEC3": true, "NSEC3PARAM": true, + "DNSKEY": true, "DS": true, "CDS": true, "CDNSKEY": true, +} + +func isDNSSECRecordType(typ string) bool { return dnssecRecordTypes[strings.ToUpper(typ)] } + +type visibleRecordPage struct { + records []easydns.Record + rawTotal int + nextCursor int + prevCursor int + hasNext bool + hasPrev bool + etag string +} + +type recordPager struct { + ctx context.Context + api *easydns.Client + zone string + filters url.Values + page int + batch easydns.Page[easydns.Record] + total int + etag string + loaded bool +} + +func (p *recordPager) at(index int) (*easydns.Record, error) { + if index < 0 || p.loaded && index >= p.total { + return nil, nil + } + page := index/zoneRecordBatch + 1 + if !p.loaded || page != p.page { + q := url.Values{"per_page": {strconv.Itoa(zoneRecordBatch)}, "page": {strconv.Itoa(page)}} + for _, name := range []string{"name", "type"} { + if v := strings.TrimSpace(p.filters.Get(name)); v != "" { + q.Set(name, v) + } + } + var b easydns.Page[easydns.Record] + etag, err := p.api.Get(p.ctx, "/api/v1/zones/"+easydns.Escape(p.zone)+"/records?"+q.Encode(), &b) + if err != nil { + return nil, err + } + p.page, p.batch, p.loaded = page, b, true + p.total = b.Pagination.Total + if p.etag == "" { + p.etag = etag + } + } + if index >= p.total { + return nil, nil + } + slot := index % zoneRecordBatch + if slot >= len(p.batch.Items) { + // Treat an incomplete API page as end of data rather than looping. + return nil, nil + } + return &p.batch.Items[slot], nil +} + +// listVisibleZoneRecords filters before page construction and uses raw-record +// cursors rather than recalculating filtered counts for the whole zone. This +// avoids repeatedly scanning large signed zones when moving to the next page. +// The previous cursor is obtained by a reverse scan of just one visible page. +func (s *Server) listVisibleZoneRecords(ctx context.Context, zone string, filters url.Values, cursor, displayPage int) (visibleRecordPage, error) { + var result visibleRecordPage + pager := &recordPager{ctx: ctx, api: s.api, zone: zone, filters: filters} + if cursor < 0 { + cursor = 0 + } + if displayPage < 1 { + displayPage = 1 + } + for i := cursor; ; i++ { + rec, err := pager.at(i) + if err != nil { + return visibleRecordPage{}, err + } + if rec == nil { + break + } + if isDNSSECRecordType(rec.Type) { + continue + } + if len(result.records) == zoneRecordPageSize { + result.hasNext, result.nextCursor = true, i + break + } + result.records = append(result.records, *rec) + } + // A forged or stale cursor must not cause an unbounded reverse walk. + if cursor > pager.total { + cursor = pager.total + } + // When users browse backwards, only the previous 50 visible records are + // needed. A second page load may change the zone, so all cursors are best + // effort and no stale ETag is used for any write action. + if displayPage > 1 && cursor > 0 { + visible := 0 + for i := cursor - 1; i >= 0; i-- { + rec, err := pager.at(i) + if err != nil { + return visibleRecordPage{}, err + } + if rec == nil { + break + } + if !isDNSSECRecordType(rec.Type) { + visible++ + result.prevCursor = i + if visible == zoneRecordPageSize { + break + } + } + } + result.hasPrev = true + } + result.rawTotal, result.etag = pager.total, pager.etag + return result, nil +} + +func parseRecordCursor(raw string) int { + if raw == "" { + return 0 + } + cursor, err := strconv.Atoi(raw) + if err != nil || cursor < 0 || cursor > 100_000_000 { + return 0 + } + return cursor +} + +func recordPageURL(zone string, values url.Values, page, cursor int, hide bool) string { + q := url.Values{} + for _, key := range []string{"name", "type"} { + if v := strings.TrimSpace(values.Get(key)); v != "" { + q.Set(key, v) + } + } + q.Set("page", fmt.Sprint(page)) + if hide { + q.Set("hide_dnssec", "1") + if cursor > 0 { + q.Set("cursor", fmt.Sprint(cursor)) + } + } + return "/zones/" + easydns.Escape(zone) + "/records?" + q.Encode() +} diff --git a/internal/server/record_listing_test.go b/internal/server/record_listing_test.go new file mode 100644 index 0000000..0178462 --- /dev/null +++ b/internal/server/record_listing_test.go @@ -0,0 +1,182 @@ +package server + +import ( + "encoding/json" + "fmt" + "html" + "net/http" + "net/http/httptest" + "net/url" + "regexp" + "strconv" + "strings" + "testing" + + "git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns" +) + +func testSignedRecordPanel(t *testing.T) *Server { + t.Helper() + all := make([]easydns.Record, 0, 1155) + // More DNSSEC records than one native API page: hiding only 50 rendered + // rows would yield empty pages and make ordinary records inaccessible. + for i := 0; i < 1100; i++ { + all = append(all, easydns.Record{ID: fmt.Sprintf("sig-%d", i), Name: "example.com.", Type: "RRSIG", TTL: 300, Data: "signature-data"}) + } + for i := 0; i < 55; i++ { + all = append(all, easydns.Record{ID: fmt.Sprintf("a-%d", i), Name: fmt.Sprintf("www%02d.example.com.", i), Type: "A", TTL: 300, Data: "192.0.2.10"}) + } + return testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/api/v1/zones/example.com.": + fmt.Fprint(w, `{"name":"example.com.","kind":"primary","loaded":true,"records":1155,"dnssec":{"denial":"nsec3"}}`) + case r.URL.Path == "/api/v1/zones/example.com./records": + q := r.URL.Query() + filtered := make([]easydns.Record, 0, len(all)) + for _, rec := range all { + if q.Get("name") != "" && !strings.HasPrefix(strings.ToLower(rec.Name), strings.ToLower(q.Get("name"))) { + continue + } + if q.Get("type") != "" && !strings.EqualFold(rec.Type, q.Get("type")) { + continue + } + filtered = append(filtered, rec) + } + per, _ := strconv.Atoi(q.Get("per_page")) + if per <= 0 { + per = 100 + } + if per > 1000 { + per = 1000 + } + page, _ := strconv.Atoi(q.Get("page")) + if page < 1 { + page = 1 + } + first := (page - 1) * per + if first > len(filtered) { + first = len(filtered) + } + last := first + per + if last > len(filtered) { + last = len(filtered) + } + w.Header().Set("ETag", `"42"`) + _ = json.NewEncoder(w).Encode(easydns.Page[easydns.Record]{Items: filtered[first:last], Pagination: easydns.Pagination{Page: page, PerPage: per, Total: len(filtered)}}) + default: + http.NotFound(w, r) + } + })) +} + +func getSignedRecords(t *testing.T, s *Server, path string) string { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "http://panel.test"+path, nil) + req.AddCookie(&http.Cookie{Name: sessionCookie, Value: s.auth.makeSession()}) + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("%s: %d %s", path, w.Code, w.Body.String()) + } + return w.Body.String() +} + +func recordPaginationLink(t *testing.T, body, text string) string { + t.Helper() + re := regexp.MustCompile(`href="([^"]+)"[^>]*>` + regexp.QuoteMeta(text) + ``) + found := re.FindStringSubmatch(body) + if len(found) != 2 { + t.Fatalf("missing %s navigation link", text) + } + return html.UnescapeString(found[1]) +} + +func TestSignedZoneRecordCheckboxFiltersBeforePagination(t *testing.T) { + s := testSignedRecordPanel(t) + base := "/zones/example.com./records" + before := getSignedRecords(t, s, base) + if !strings.Contains(before, `name="hide_dnssec"`) || !strings.Contains(before, "signature-data") { + t.Fatal("default record list must show the checkbox and preserve original records") + } + first := getSignedRecords(t, s, base+"?hide_dnssec=1") + if strings.Contains(first, "signature-data") || strings.Count(first, "192.0.2.10") != 50 || !strings.Contains(first, "total before DNSSEC filtering") { + t.Fatalf("DNSSEC filter must fill page with non-DNSSEC entries: %d A rows", strings.Count(first, "192.0.2.10")) + } + next := recordPaginationLink(t, first, "Next") + if !strings.Contains(next, "hide_dnssec=1") || !strings.Contains(next, "cursor=") || !strings.Contains(next, "page=2") { + t.Fatalf("next link must retain the filter and cursor: %s", next) + } + second := getSignedRecords(t, s, next) + if strings.Count(second, "192.0.2.10") != 5 || strings.Contains(second, "signature-data") { + t.Fatalf("wrong second page: %d A rows", strings.Count(second, "192.0.2.10")) + } + previous := recordPaginationLink(t, second, "Previous") + if !strings.Contains(previous, "hide_dnssec=1") || !strings.Contains(previous, "page=1") { + t.Fatalf("previous page lost filter state: %s", previous) + } + again := getSignedRecords(t, s, previous) + if strings.Count(again, "192.0.2.10") != 50 { + t.Fatal("back navigation did not restore first visible page") + } +} + +func TestDNSSECCheckboxPreservesNameAndTypeSearch(t *testing.T) { + s := testSignedRecordPanel(t) + raw := "/zones/example.com./records?hide_dnssec=1&name=www&type=A" + first := getSignedRecords(t, s, raw) + if strings.Count(first, "192.0.2.10") != 50 || !strings.Contains(first, `value="www"`) { + t.Fatal("record search options were lost") + } + next := recordPaginationLink(t, first, "Next") + vals, err := url.Parse(next) + if err != nil || vals.Query().Get("type") != "A" || vals.Query().Get("name") != "www" || vals.Query().Get("hide_dnssec") != "1" { + t.Fatalf("record type/name filters lost in next link: %s, %v", next, err) + } + empty := getSignedRecords(t, s, "/zones/example.com./records?hide_dnssec=1&type=RRSIG") + if strings.Contains(empty, "signature-data") || !strings.Contains(empty, "1,100 total before DNSSEC filtering") { + t.Fatal("explicit DNSSEC type filter should be empty, with correct native total") + } + for _, typ := range []string{"RRSIG", "NSEC", "NSEC3", "NSEC3PARAM", "DNSKEY", "DS", "CDS", "CDNSKEY"} { + if !isDNSSECRecordType(typ) { + t.Fatalf("DNSSEC record type %s was missed", typ) + } + } + if isDNSSECRecordType("TLSA") || isDNSSECRecordType("SOA") { + t.Fatal("non-DNSSEC data records were excluded") + } +} + +func TestServersInventoryDeepLinks(t *testing.T) { + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v1/status" { + fmt.Fprint(w, `{"version":"0.1.4","roles":{"primary":1}}`) + return + } + fmt.Fprint(w, `{"status":"ok"}`) + })) + defer api.Close() + s := panelWithNodes(t, api.URL, t.TempDir()) + if err := s.nodes.SetEnabled(true); err != nil { + t.Fatal(err) + } + secondary, err := s.nodes.Add("secondary-test", "secondary", api.URL, "test-bearer") + if err != nil { + t.Fatal(err) + } + body := getSignedRecords(t, s, "/servers") + for _, expected := range []string{ + `id="server-inventory"`, `href="/servers#server-inventory"`, + `id="server-local"`, `href="/servers#server-local"`, + `id="server-` + secondary.ID + `"`, `href="/servers#server-` + secondary.ID + `"`, + } { + if !strings.Contains(body, expected) { + t.Errorf("missing working inventory anchor: %s", expected) + } + } + status := getSignedRecords(t, s, "/status") + if !strings.Contains(status, `href="/servers#server-inventory"`) { + t.Fatal("server status does not offer a reachable inventory link") + } +} diff --git a/internal/server/release_012_test.go b/internal/server/release_012_test.go new file mode 100644 index 0000000..6e5ad85 --- /dev/null +++ b/internal/server/release_012_test.go @@ -0,0 +1,94 @@ +package server + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns" +) + +func TestVersion012WebDashboardControls(t *testing.T) { + s := testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/v1/stats": + fmt.Fprint(w, `{"queries_total":100,"cache_hit_rate":0.87,"responses":{"noerror":90}}`) + case "/api/v1/status": + fmt.Fprint(w, `{"mode":"hybrid","version":"0.1.4"}`) + case "/api/v1/health": + fmt.Fprint(w, `{"status":"ok"}`) + case "/api/v1/upstreams": + fmt.Fprint(w, `{"items":[]}`) + case "/api/v1/audit": + fmt.Fprint(w, `{"items":[]}`) + default: + fmt.Fprint(w, `{}`) + } + })) + for _, path := range []string{"/", "/metrics"} { + r := httptest.NewRequest("GET", "http://panel.test"+path, nil) + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: s.auth.makeSession()}) + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + if w.Code != 200 { + t.Fatalf("%s: %d %s", path, w.Code, w.Body.String()) + } + html := w.Body.String() + for _, required := range []string{"data-global-range", "data-global-step", "data-chart-range", "data-chart-step", "Last 24 hours", "Downsample: Auto", "data-dns-chart=", "Cache traffic"} { + if !strings.Contains(html, required) { + t.Errorf("%s missing %s", path, required) + } + } + if path == "/metrics" { + if strings.Count(html, "data-dns-chart=") < 15 { + t.Error("metrics should contain at least 15 real API-derived chart visualizations") + } + if !strings.Contains(html, "data-telemetry-export") { + t.Error("CSV export unavailable") + } + } + } +} +func TestTimeWindowAppliedByAuthenticatedGoTelemetry(t *testing.T) { + s := testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{}`) })) + now := time.Now().UTC().Truncate(time.Minute).Add(-4 * time.Minute) + st := easydns.Stats{Responses: map[string]uint64{}, Sources: map[string]uint64{}} + for i := 0; i < 16; i++ { + st.QueriesTotal += 15 + s.telemetry.Record(now.Add(time.Duration(i)*15*time.Second), st) + } + get := func(path string) (int, map[string]json.RawMessage) { + r := httptest.NewRequest("GET", "http://panel.test"+path, nil) + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: s.auth.makeSession()}) + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + var body map[string]json.RawMessage + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("%s json: %v", path, err) + } + return w.Code, body + } + status, raw := get("/ui/telemetry?range=15m&step=1m") + if status != 200 || string(raw["range"]) != `"15m"` || string(raw["step"]) != `"1m"` || string(raw["stepSeconds"]) != "60" { + t.Fatalf("range/step not applied: %d %v", status, raw) + } + var reduced, legacy []map[string]any + _ = json.Unmarshal(raw["samples"], &reduced) + _, other := get("/ui/telemetry") + _ = json.Unmarshal(other["samples"], &legacy) + if len(reduced) >= len(legacy) || len(reduced) == 0 { + t.Fatalf("downsampling did not reduce real points: %d vs %d", len(reduced), len(legacy)) + } + if _, ok := reduced[0]["QueriesTotal"]; ok { + t.Fatal("raw counter leaked to chart JSON") + } + _, bad := get("/ui/telemetry?range=999years&step=bad") + if string(bad["range"]) != `"24h"` || string(bad["step"]) != `"auto"` { + t.Fatal("unsupported range and step should be bounded to safe values") + } +} diff --git a/internal/server/server.go b/internal/server/server.go index a2eaf6c..c6b5f11 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -14,6 +14,7 @@ import ( "git.linuxiarz.pl/gru/EasyDNS-Web/internal/config" "git.linuxiarz.pl/gru/EasyDNS-Web/internal/multiserver" + "git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry" ) var Version = "dev" @@ -126,8 +127,12 @@ func (s *Server) dispatch(w http.ResponseWriter, r *http.Request) { s.auth.setCookie(w, "", -1) clearNodeCookie(w, s.cfg.CookieSecure) http.Redirect(w, r, "/login", http.StatusSeeOther) - case r.URL.Path == "/servers" && r.Method == "GET" && s.nodes.Enabled(): - s.serversOverview(w, r) + case r.URL.Path == "/servers" && r.Method == "GET": + if !s.nodes.Enabled() { + redirect(w, r, "/configuration?notice=server-inventory-disabled#multi-server-preference") + } else { + s.serversOverview(w, r) + } case r.URL.Path == "/servers/new" && r.Method == "GET" && s.nodes.Enabled(): s.serverNewForm(w, r) case r.URL.Path == "/servers" && r.Method == "POST" && s.nodes.Enabled(): @@ -269,6 +274,8 @@ func notice(n string) (string, string) { return "Multi-server management is enabled. Your local EasyDNS remains the default server.", "ok" case "servers-disabled": return "Multi-server management is disabled. Saved remote connections are retained but inactive.", "ok" + case "server-inventory-disabled": + return "Server inventory requires Multi-server management. Enable it in panel settings or in your deployment configuration.", "warn" case "session-ended": return "Signed out.", "ok" default: @@ -289,9 +296,11 @@ func (s *Server) telemetryJSON(w http.ResponseWriter, r *http.Request) { return } smp, errText, last := s.telemetry.Snapshot() + window := telemetry.ParseWindow(r.URL.Query().Get("range"), r.URL.Query().Get("step"), time.Now().UTC()) + smp = telemetry.WindowSamples(smp, window) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") - _ = json.NewEncoder(w).Encode(map[string]any{"samples": smp, "error": errText, "lastPoll": last, "intervalSeconds": 15}) + _ = json.NewEncoder(w).Encode(map[string]any{"samples": smp, "error": errText, "lastPoll": last, "intervalSeconds": int(telemetry.PollInterval / time.Second), "range": window.Range, "step": window.Step, "stepSeconds": window.StepSeconds, "from": window.From, "to": window.To, "retentionHours": 24}) } func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) { if _, ok := s.auth.parseSession(r); ok { diff --git a/internal/server/static_assets.go b/internal/server/static_assets.go index e49f800..4e5ad4c 100644 --- a/internal/server/static_assets.go +++ b/internal/server/static_assets.go @@ -15,7 +15,7 @@ import ( ) // BuildID is injected by Docker/Debian build scripts. It deliberately changes -// at build time, even when the public package version stays at 0.1.1. +// at build time, even when the public package version stays at 0.1.2. // In regular `go test` / `go build` content hashes still identify every asset. var BuildID = "development" diff --git a/internal/server/web.go b/internal/server/web.go index 7b3c2a4..56cd459 100644 --- a/internal/server/web.go +++ b/internal/server/web.go @@ -20,47 +20,51 @@ import ( var assets embed.FS type PageData struct { - Status easydns.Status - Health easydns.Health - Stats easydns.Stats - Cache easydns.Cache - Zone easydns.Zone - Zones []easydns.Zone - Records []easydns.Record - Record easydns.Record - Pagination easydns.Pagination - Transfers []easydns.Transfer - Upstreams []easydns.UpstreamGroup - Policies easydns.Policies - Blocklists easydns.Blocklists - Audit []easydns.AuditItem - Query *easydns.QueryResult - Form map[string]string - Filter map[string]string - ETag string - ZoneURL string - IsPrimary bool - Error string - Success string - Action string - Tab string - FieldErrors map[string]string - SamplingCount int - SamplingTime time.Time - SamplingError string - LastRate string - ServerProbes []multiserver.Probe - Comparisons []multiserver.Comparison - ManagedNode multiserver.Node - CompareZone string - PrimarySerial string - ServerHealthy int - MetricsMode string - MetricNodes []FleetMetricsNode - MetricTotals easydns.Stats - MetricOnline int - MetricTotal int - MetricHasCache bool + Status easydns.Status + Health easydns.Health + Stats easydns.Stats + Cache easydns.Cache + Zone easydns.Zone + Zones []easydns.Zone + Records []easydns.Record + Record easydns.Record + HideDNSSEC bool + RecordsNextURL string + RecordsPrevURL string + Pagination easydns.Pagination + Transfers []easydns.Transfer + Upstreams []easydns.UpstreamGroup + Policies easydns.Policies + Blocklists easydns.Blocklists + Audit []easydns.AuditItem + Query *easydns.QueryResult + Form map[string]string + Filter map[string]string + ETag string + ZoneURL string + IsPrimary bool + Error string + Success string + Action string + Tab string + FieldErrors map[string]string + SamplingCount int + SamplingTime time.Time + SamplingError string + LastRate string + RecentQueryRate *float64 + ServerProbes []multiserver.Probe + Comparisons []multiserver.Comparison + ManagedNode multiserver.Node + CompareZone string + PrimarySerial string + ServerHealthy int + MetricsMode string + MetricNodes []FleetMetricsNode + MetricTotals easydns.Stats + MetricOnline int + MetricTotal int + MetricHasCache bool } type PageView struct { Title, Subtitle, Page, Active, Breadcrumb, User, CSRF, Message, MessageType string @@ -87,6 +91,12 @@ type Server struct { func funcs() template.FuncMap { return template.FuncMap{ "asset": assetURL, + "chart": func(id, title, description string) map[string]string { + return map[string]string{"ID": id, "Title": title, "Description": description} + }, + "filterRecordTypes": func() []string { + return []string{"A", "AAAA", "CNAME", "MX", "TXT", "NS", "SOA", "PTR", "SRV", "CAA", "DS", "DNSKEY", "RRSIG", "NSEC", "NSEC3", "NSEC3PARAM", "CDS", "CDNSKEY", "TLSA", "SSHFP", "NAPTR"} + }, "recordTypes": func() []string { return []string{"A", "AAAA", "CNAME", "MX", "TXT", "NS", "PTR", "SRV", "CAA", "DS", "DNSKEY", "TLSA", "SSHFP", "NAPTR"} }, diff --git a/internal/server/web/static/app.css b/internal/server/web/static/app.css index f727910..68c685e 100644 --- a/internal/server/web/static/app.css +++ b/internal/server/web/static/app.css @@ -124,3 +124,55 @@ .fleet-methodology{font-size:11px} @media(max-width:900px){.metrics-mode-bar{flex-direction:column;align-items:stretch}.metrics-mode-tabs{align-self:flex-start}.fleet-coverage{align-items:flex-start;flex-direction:column}.fleet-coverage-description{text-align:left}} @media(max-width:540px){.metrics-mode-tabs{width:100%}.metrics-mode-tabs a{flex:1;min-width:0;padding:9px}.fleet-coverage-main{flex-wrap:wrap;white-space:normal}} + +/* 0.1.2 — reference-aligned operational dashboards. Controls are part of the + independent EasyDNS Web panel; all chart samples come from its REST polls. */ +.page-head:has(.telemetry-toolbar){align-items:flex-end;gap:18px} +.page-head:has(.telemetry-toolbar) .page-head-right{align-self:flex-end;margin:0;max-width:100%} +.telemetry-toolbar{display:flex;align-items:center;justify-content:flex-end;gap:7px;flex-wrap:wrap} +.telemetry-toolbar .time-field{margin:0} +.telemetry-toolbar .field.compact-field{border:1px solid #536259;background:#0d1210;color:#e3ede3;min-height:34px;border-radius:3px;padding:6px 26px 6px 11px;font-size:12px;line-height:20px;cursor:pointer;width:auto;min-width:132px} +.telemetry-toolbar [data-global-step]{min-width:152px!important} +.telemetry-toolbar .tool-button{min-height:34px;padding:7px 11px} +.telemetry-toolbar .field:focus-visible,.chart-select:focus-visible{outline:2px solid var(--cyan);outline-offset:2px} +.metrics-grid.six>.metric{min-height:90px;background:#111815;border-color:#3a4840} +.metrics-grid.six>.metric strong{letter-spacing:-.25px} +.chart-grid.triple{gap:12px;margin-top:13px} +.chart-card{position:relative;min-height:268px;border-color:#3e4941;background:#0f1512} +.chart-card .panel-head.chart-head{display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;column-gap:9px;row-gap:8px;padding:13px 14px 5px;min-height:58px} +.chart-heading{min-width:135px;flex:1 1 155px;max-width:100%} +.chart-heading h2{color:#f1f6f1;font-size:14px;letter-spacing:-.15px} +.chart-heading p{color:#a7b7aa;font-size:10.5px;line-height:1.35;margin-top:3px;white-space:normal} +.chart-tools{display:flex;align-items:center;gap:5px;flex:0 0 auto;margin-left:auto} +.chart-tools label{margin:0} +.chart-select{appearance:auto;border:1px solid #3c5044;background:#101b15;color:#c5d5c7;border-radius:3px;font:10px/1.2 var(--mono);padding:4px 2px 4px 5px;min-height:25px;cursor:pointer;max-width:100px} +.chart-card canvas{height:166px;margin-top:6px;touch-action:pan-y} +.chart-foot{font-size:10px;min-height:29px;gap:6px 8px;padding-top:6px} +.chart-sampling-note{font:9.5px var(--mono);color:#89a295;margin-left:auto;white-space:nowrap} +.chart-tooltip{position:absolute;z-index:5;pointer-events:none;min-width:180px;max-width:220px;background:#0b100deF;border:1px solid #6b826e;box-shadow:0 8px 26px #000b;padding:9px 10px;border-radius:3px;font:10px/1.3 var(--mono);color:#dde7df} +.chart-tooltip[hidden]{display:none} +.chart-tooltip>strong{display:block;color:#a6d79d;padding-bottom:7px;border-bottom:1px solid #34463a;margin-bottom:5px} +.chart-tooltip>div{display:flex;align-items:center;gap:7px;margin:5px 0} +.chart-tooltip i{width:7px;height:7px;border-radius:100%;flex-shrink:0} +.chart-tooltip span{flex:1;color:#b9cbbd}.chart-tooltip b{font-weight:620;white-space:nowrap} +.metrics-footnote{font:10.5px/1.6 var(--mono);color:#8da99a;padding:13px 1px 5px} +.metrics-footnote code{font:inherit;color:#acd8ad} +.metrics-view>.chart-grid:first-of-type{margin-top:14px} +.metrics-view .fleet-coverage{background:#121c16;border-color:#45614b} +.metrics-view .metrics-grid.six{margin-top:13px} +@media (max-width:1650px){.page-head:has(.telemetry-toolbar){align-items:flex-start;flex-direction:column;gap:14px}.page-head:has(.telemetry-toolbar) .page-head-right{align-self:stretch}.telemetry-toolbar{justify-content:flex-start}.chart-select{font-size:9.5px;max-width:98px}} +@media (max-width:1050px){.chart-card .panel-head.chart-head{min-height:81px}.chart-tools{margin-left:0}.chart-heading{flex-basis:100%}.chart-card{min-height:286px}} +@media (max-width:820px){.chart-card .panel-head.chart-head{min-height:58px}.chart-heading{flex-basis:150px}.chart-tools{margin-left:auto}} +@media (max-width:620px){.telemetry-toolbar{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}.telemetry-toolbar .field.compact-field{min-width:0!important;width:100%}.telemetry-toolbar .tool-button{width:100%;white-space:nowrap}.chart-card .panel-head.chart-head{min-height:78px}.chart-heading{flex-basis:100%}.chart-tools{margin-left:0}} + +/* Signed zone record list — compact DNSSEC exclusion control. */ +.record-dnssec-toggle{display:inline-flex;align-items:center;gap:8px;white-space:nowrap;cursor:pointer;color:var(--muted);font-size:12px;padding:4px 7px;min-height:31px;border:1px solid var(--line);border-radius:3px;background:var(--panel)} +.record-dnssec-toggle:hover{color:var(--text);border-color:#62836a} +.record-dnssec-toggle input{width:15px;height:15px;accent-color:var(--green);cursor:pointer;margin:0;flex-shrink:0} +.record-dnssec-toggle:has(input:checked){color:var(--green);border-color:#557a59;background:#142018} +.record-dnssec-toggle:focus-within{outline:2px solid var(--cyan);outline-offset:2px} +/* Direct server-inventory and per-node deep links remain visible under the header. */ +#server-inventory,.server-inventory-row{scroll-margin-top:74px} +#server-inventory:target{border-color:#81a986} +.server-inventory-row:target td{background:#1b2b20;border-top:1px solid #8dbc8e;border-bottom:1px solid #8dbc8e} +@media(max-width:540px){.record-dnssec-toggle{flex:1 1 100%;width:100%;justify-content:flex-start}} diff --git a/internal/server/web/static/app.js b/internal/server/web/static/app.js index 924672c..b91b6cf 100644 --- a/internal/server/web/static/app.js +++ b/internal/server/web/static/app.js @@ -18,6 +18,15 @@ else select.form.submit(); }); }); + // DNSSEC exclusion is applied server-side, before pagination. Submit the + // current record filters without resetting name/type choices. + document.querySelectorAll('input[data-record-filter-toggle]').forEach(input => { + input.addEventListener('change', () => { + if (!input.form) return; + if (typeof input.form.requestSubmit === 'function') input.form.requestSubmit(); + else input.form.submit(); + }); + }); document.querySelectorAll('.bar-fill[data-count]').forEach(bar => { const count = Number(bar.dataset.count), total = Number(bar.dataset.total); const ratio = Number.isFinite(count) && Number.isFinite(total) && total > 0 ? 100 * count / total : 0; diff --git a/internal/server/web/static/charts.js b/internal/server/web/static/charts.js index 63a1e90..aa60b36 100644 --- a/internal/server/web/static/charts.js +++ b/internal/server/web/static/charts.js @@ -1,141 +1,302 @@ -/* EasyDNS telemetry charts. Source: authenticated Go panel samples of the - * existing EasyDNS GET /api/v1/stats endpoint. There is no synthetic history. - * Fleet aggregate QPS is server-aligned and requires complete coverage. */ +/* EasyDNS Web 0.1.2 — measured DNS traffic charts. + * Data only from authenticated /ui/telemetry, sampled from native REST + * /api/v1/stats. No Prometheus/Grafana, artificial points or backfill. */ (() => { 'use strict'; - const COLORS = {cyan:'#72cfe1', amber:'#f1b42b', red:'#ec8588',grid:'#303a34',muted:'#8d9d91',text:'#dce6df'}; - const NODE_COLORS = ['#72cfe1','#f1b42b','#a5d996','#ba9be6','#e98b87','#85a8ff','#e0bf9a','#75d3ad','#d9a6ce','#d1cc83','#b4d5e9','#b48c7e','#a5bb7f','#cc92a1','#8fb5b3','#c6bbd5']; - const chartTypes = { - queries:{series:[['queryRate','Queries / s','cyan']],unit:'/s'}, - cache:{series:[['cacheHitRate','Cache hit %','cyan']],unit:'%',range:[0,100]}, - latency:{series:[['p50ms','p50','cyan'],['p95ms','p95','amber'],['p99ms','p99','red']],unit:'ms'}, - blocked:{series:[['blocked','Blocked / s','amber']],unit:'/s'}, - responses:{series:[['noerror','NOERROR','cyan'],['nxdomain','NXDOMAIN','amber'],['servfail','SERVFAIL','red']],unit:'/s'}, - nxdomain:{series:[['nxdomain','NXDOMAIN','amber']],unit:'/s'} + const PALETTE = { + cyan:'#65d9ee',amber:'#f5b828',green:'#a4df9b',red:'#f08380',purple:'#bd9ae7', + grid:'#2c3932',muted:'#91a49a',text:'#e6eee6',background:'#111614' }; - const root = document.querySelector('[data-metrics-mode]'); - const mode = root?.dataset.metricsMode || 'single'; - let telemetry = {samples:[], nodes:[]}; + const NODE_COLORS = [PALETTE.cyan,PALETTE.amber,PALETTE.green,PALETTE.purple,PALETTE.red,'#85a8ff','#e0bf9a','#75d3ad','#d9a6ce','#d1cc83','#b4d5e9','#b48c7e','#a5bb7f','#cc92a1','#8fb5b3','#c6bbd5']; + const TYPES = { + queries:{series:[['recursiveRate','Recursive','amber'],['authoritativeRate','Authoritative','cyan']],splitKey:'queryRate',unit:'/s'}, + queryTotal:{series:[['queryRate','Total DNS traffic','cyan']],splitKey:'queryRate',unit:'/s'}, + responses:{series:[['noerror','NOERROR','cyan'],['nxdomain','NXDOMAIN','amber'],['servfail','SERVFAIL','red'],['refused','REFUSED','purple']],splitKey:'noerror',unit:'/s'}, + cache:{series:[['cacheHitRate','Cache hit','green']],splitKey:'cacheHitRate',unit:'%',range:[0,100]}, + latency:{series:[['p50ms','p50','cyan'],['p95ms','p95','amber'],['p99ms','p99','red']],splitKey:'p95ms',unit:'ms'}, + sources:{series:[['recursiveRate','Recursive','amber'],['authoritativeRate','Authoritative','cyan'],['cacheSourceRate','Cache','green'],['forwardRate','Forward','purple']],splitKey:'recursiveRate',unit:'/s'}, + cacheTraffic:{series:[['cacheHitsRate','Cache hits','amber'],['cacheMissesRate','Cache misses','cyan']],splitKey:'cacheHitsRate',unit:'/s'}, + security:{series:[['blocked','Blocked','red'],['rateLimitedRate','Rate limited','amber']],splitKey:'blocked',unit:'/s'}, + blocked:{series:[['blocked','Blocked','red']],splitKey:'blocked',unit:'/s'}, + rateLimited:{series:[['rateLimitedRate','Rate limited','amber']],splitKey:'rateLimitedRate',unit:'/s'}, + nxdomain:{series:[['nxdomain','NXDOMAIN','amber']],splitKey:'nxdomain',unit:'/s'}, + servfail:{series:[['servfail','SERVFAIL','red']],splitKey:'servfail',unit:'/s'}, + refused:{series:[['refused','REFUSED','purple']],splitKey:'refused',unit:'/s'}, + cacheEntries:{series:[['cacheEntries','Entries','green']],splitKey:'cacheEntries',unit:''}, + cacheEvictions:{series:[['cacheEvictionsRate','Evictions','amber']],splitKey:'cacheEvictionsRate',unit:'/s'}, + errorRate:{series:[['errorRate','SERVFAIL + REFUSED','red']],splitKey:'errorRate',unit:'%'} + }; + const RANGE_MS = {'15m':900000,'1h':3600000,'6h':21600000,'12h':43200000,'24h':86400000}; + const container = document.querySelector('[data-metrics-mode]'); + const mode = container?.dataset.metricsMode || 'single'; const canvases = [...document.querySelectorAll('canvas[data-dns-chart]')]; if (!canvases.length) return; + const page = location.pathname === '/metrics' ? 'metrics' : 'overview'; + const storeKey = `easydns-web-0.1.2:${page}:${mode}`; + const toolbar = document.querySelector('[data-telemetry-toolbar]'); + const globalRange = toolbar?.querySelector('[data-global-range]'); + const globalStep = toolbar?.querySelector('[data-global-step]'); + const chartData = new Map(); + const hoverTime = new WeakMap(); + let requestNo = 0; + let latestError = ''; - function asPoints(samples, key) { - return (Array.isArray(samples) ? samples : []).map(s => { - const time = Date.parse(s.time); - const value = s[key]; - return {time, value: typeof value === 'number' && Number.isFinite(value) ? value : null}; - }).filter(p => Number.isFinite(p.time)); + function loadPrefs() { + try { return JSON.parse(localStorage.getItem(storeKey) || '{}'); } catch (_) { return {}; } } - function seriesFor(typeName) { - const kind = chartTypes[typeName]; - if (!kind) return []; - const nodes = Array.isArray(telemetry.nodes) ? telemetry.nodes : []; - if (mode === 'split' || (mode === 'aggregate' && typeName === 'latency')) { - const key = mode === 'split' - ? ({queries:'queryRate',responses:'noerror',cache:'cacheHitRate',latency:'p95ms',blocked:'blocked',nxdomain:'nxdomain'}[typeName]) - : 'p95ms'; - return nodes.map((n,i) => ({label: String(n.name || n.id || 'Server'), color: NODE_COLORS[i % NODE_COLORS.length], points: asPoints(n.samples, key)})); + const preferences = loadPrefs() || {}; + if (RANGE_MS[preferences.range] && globalRange) globalRange.value = preferences.range; + if (['auto','15s','30s','1m','5m','15m','1h'].includes(preferences.step) && globalStep) globalStep.value = preferences.step; + const validRanges = new Set(['global',...Object.keys(RANGE_MS)]); + const validSteps = new Set(['global','auto','15s','30s','1m','5m','15m','1h']); + canvases.forEach(canvas => { + const card = canvas.closest('.chart-card'); + const chart = canvas.dataset.dnsChart; + if (!card || !TYPES[chart]) return; + const opts = preferences.charts?.[chart]; + const range = card.querySelector('[data-chart-range]'); + const step = card.querySelector('[data-chart-step]'); + if (validRanges.has(opts?.range) && range) range.value = opts.range; + if (validSteps.has(opts?.step) && step) step.value = opts.step; + for (const select of [range,step]) select?.addEventListener('change',()=> { savePrefs();poll(); }); + const tooltip = document.createElement('div'); + tooltip.className = 'chart-tooltip'; + tooltip.hidden = true; + card.append(tooltip); + canvas.addEventListener('pointermove',ev=>{ + const rect=canvas.getBoundingClientRect(); + const {from,to} = chartData.get(canvas) || {}; + if (!from || !to) return; + const px=ev.clientX-rect.left; + hoverTime.set(canvas,from+(Math.max(52,Math.min(rect.width-12,px))-52)/(rect.width-64)*(to-from)); + render(canvas); + }); + canvas.addEventListener('pointerleave',()=>{ + hoverTime.delete(canvas); + tooltip.hidden=true; + render(canvas); + }); + }); + function savePrefs() { + const charts = {}; + for(const canvas of canvases) { + const card=canvas.closest('.chart-card'); + charts[canvas.dataset.dnsChart] = { + range:card?.querySelector('[data-chart-range]')?.value || 'global', + step:card?.querySelector('[data-chart-step]')?.value || 'global' + }; } - return kind.series.map(([key,label,color]) => ({label, color:COLORS[color], points:asPoints(telemetry.samples, key)})); + try {localStorage.setItem(storeKey,JSON.stringify({range:globalRange?.value || '24h',step:globalStep?.value || 'auto',charts}));} catch (_) {} + } + function choices(canvas) { + const card=canvas.closest('.chart-card'); + const ownRange=card?.querySelector('[data-chart-range]')?.value || 'global'; + const ownStep=card?.querySelector('[data-chart-step]')?.value || 'global'; + return { + range: ownRange==='global' ? globalRange?.value || '24h' : ownRange, + step: ownStep==='global' ? globalStep?.value || 'auto' : ownStep + }; + } + function asPoints(samples,key) { + return (Array.isArray(samples)?samples:[]).map(s=>{ + const time=Date.parse(s.time); + const n=s[key]; + return {time,value:typeof n==='number' && Number.isFinite(n)?n:null}; + }).filter(p=>Number.isFinite(p.time)); + } + function seriesFor(canvas) { + const info=chartData.get(canvas); + const type=TYPES[canvas.dataset.dnsChart]; + if(!info || !type) return []; + const nodes=Array.isArray(info.data.nodes)?info.data.nodes:[]; + if(mode==='split' || (mode==='aggregate' && canvas.dataset.dnsChart==='latency')) { + return nodes.map((node,i)=>({label:String(node.name || node.id || 'Server'),color:NODE_COLORS[i%NODE_COLORS.length],points:asPoints(node.samples,type.splitKey)})); + } + return type.series.map(([key,label,color])=>({label,color:PALETTE[color],points:asPoints(info.data.samples,key)})); + } + function formatValue(v,unit) { + if (unit==='%') return `${v.toFixed(v<1?2:1)}%`; + if (Math.abs(v)>=10000) return `${Math.round(v).toLocaleString()}${unit}`; + if (Math.abs(v)>=100) return `${v.toFixed(0)}${unit}`; + if (Math.abs(v)>=10) return `${v.toFixed(1)}${unit}`; + return `${v.toFixed(v===0?0:2)}${unit}`; + } + function timeLabel(milliseconds,range) { + const remaining = Math.max(0,Math.round((1-range)*milliseconds/60000)); + if (remaining===0) return 'now'; + if (remaining>=60) return `−${Math.round(remaining/60)}h`; + return `−${remaining}m`; } - function render(canvas) { - const type = chartTypes[canvas.dataset.dnsChart]; if (!type) return; - const rect = canvas.getBoundingClientRect(); - if (rect.width < 30 || rect.height < 30) return; - const width = rect.width, height = rect.height, dpr = Math.min(2, window.devicePixelRatio || 1); - canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr); - const ctx = canvas.getContext('2d'); if (!ctx) return; - ctx.setTransform(dpr, 0, 0, dpr, 0, 0); - ctx.clearRect(0, 0, width, height); - const pad = {left:48,right:12,top:10,bottom:25}; - const plotW = Math.max(5,width-pad.left-pad.right), plotH = Math.max(5,height-pad.top-pad.bottom); - const series = seriesFor(canvas.dataset.dnsChart); - const observed = series.flatMap(s => s.points.filter(p => p.value !== null)); - ctx.font = '10px ui-monospace,Consolas,monospace'; ctx.textBaseline = 'middle'; - if (observed.length === 0) { - ctx.fillStyle=COLORS.muted; ctx.textAlign='center'; - ctx.fillText('Collecting live samples…',width/2,height/2-4); - ctx.fillText(mode === 'aggregate' ? 'All nodes must report fresh readings' : 'First rate after 2 successful polls',width/2,height/2+14); + const info=chartData.get(canvas); + const type=TYPES[canvas.dataset.dnsChart]; + if(!info || !type) return; + const rect=canvas.getBoundingClientRect(); + const width=rect.width,height=rect.height; + if(width<60 || height<60) return; + const dpr=Math.min(2,window.devicePixelRatio || 1); + canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr); + const ctx=canvas.getContext('2d');if(!ctx) return; + ctx.setTransform(dpr,0,0,dpr,0,0); + ctx.clearRect(0,0,width,height); + const p={left:52,right:12,top:11,bottom:29}; + const w=width-p.left-p.right,h=height-p.top-p.bottom; + const {from,to}=info; + const span=Math.max(1000,to-from); + const allSeries=seriesFor(canvas); + const observed=allSeries.flatMap(s=>s.points.filter(point=>point.value!==null && point.time>=from && point.time<=to)); + let max=type.range?type.range[1]:observed.reduce((acc,point)=>Math.max(acc,point.value),0)*1.13; + const min=type.range?type.range[0]:0; + if(!Number.isFinite(max)||max<=min) max=min+1; + const x=t=>p.left+w*(t-from)/span; + const y=v=>p.top+h*(1-(v-min)/(max-min)); + ctx.font='10px ui-monospace,Consolas,monospace';ctx.lineWidth=1; + ctx.textBaseline='middle';ctx.textAlign='right'; + for(let i=0;i<=4;i++){ + const value=min+(max-min)*i/4,py=y(value); + ctx.beginPath();ctx.setLineDash([2,4]);ctx.strokeStyle=PALETTE.grid; + ctx.moveTo(p.left,py);ctx.lineTo(width-p.right,py);ctx.stroke(); + ctx.fillStyle=PALETTE.muted; + ctx.fillText(formatValue(value,type.unit),p.left-7,py); + } + ctx.setLineDash([]);ctx.textAlign='center';ctx.textBaseline='alphabetic';ctx.fillStyle=PALETTE.muted; + for(const f of [0,.25,.5,.75,1]) ctx.fillText(timeLabel(span,f),p.left+w*f,height-8); + if(observed.length===0) { + ctx.font='11px ui-sans-serif,system-ui,sans-serif';ctx.fillStyle=PALETTE.muted; + ctx.fillText('No measured samples in this time range',width/2,height/2-5); + ctx.font='10px ui-monospace,Consolas,monospace'; + ctx.fillText('History starts when the panel begins polling',width/2,height/2+12); return; } - const times = series.flatMap(s => s.points.map(p=>p.time)); - const start = Math.min(...times), end = Math.max(...times); - const timeSpan = Math.max(1000,end-start); - const x = t => pad.left + plotW * (t-start)/timeSpan; - const min = type.range ? type.range[0] : 0; - let max = type.range ? type.range[1] : Math.max(0.001,...observed.map(p=>p.value)) * 1.16; - if (!Number.isFinite(max) || max <= min) max = min+1; - const y = val => pad.top + plotH * (1 - (val-min)/(max-min)); - ctx.textAlign = 'right'; ctx.lineWidth = 1; - for (let tick=0;tick<=4;tick++) { - const v=min+(max-min)*tick/4, py=y(v); - ctx.strokeStyle=COLORS.grid;ctx.setLineDash([2,4]);ctx.beginPath();ctx.moveTo(pad.left,py);ctx.lineTo(width-pad.right,py);ctx.stroke(); - ctx.fillStyle=COLORS.muted; - ctx.fillText((max <= 10 ? v.toFixed(1) : Math.round(v).toString()) + type.unit,pad.left-8,py); - } - ctx.setLineDash([]);ctx.textAlign='center';ctx.fillStyle=COLORS.muted; - [0,.25,.5,.75,1].forEach(f=>{ - const t=new Date(start+f*timeSpan); - ctx.fillText(t.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit'}),x(start+f*timeSpan),height-9); - }); - series.forEach(s => { - ctx.beginPath(); ctx.strokeStyle=s.color; ctx.lineWidth=1.7; ctx.lineJoin='round'; - let previous=null; - s.points.forEach(p => { - if (p.value===null) {previous=null;return;} - const px=x(p.time), py=y(p.value); - // A server outage may leave a long period without any samples. Do not - // draw a fabricated continuous line across a missing-data interval. - if (!previous || p.time-previous.time>30000) ctx.moveTo(px,py); + const maxGap=Math.max(37000,(info.data.stepSeconds||15)*2500); + for(const s of allSeries){ + ctx.strokeStyle=s.color;ctx.lineWidth=1.85;ctx.lineJoin='round';ctx.beginPath(); + let previous=null, valid=0,one=null; + for(const point of s.points){ + if(point.value===null || point.timeto){previous=null;continue;} + const px=x(point.time),py=y(point.value); + if(!previous || point.time-previous.time>maxGap)ctx.moveTo(px,py); else ctx.lineTo(px,py); - previous=p; - }); + previous=point;valid++;one=point; + } ctx.stroke(); - // A single measured rate is drawn as a point, never extended into a - // synthetic line or repeated as historical data. - const valid = s.points.filter(p=>p.value!==null); - if (valid.length === 1) { - ctx.beginPath();ctx.fillStyle=s.color; - ctx.arc(x(valid[0].time),y(valid[0].value),2.5,0,Math.PI*2);ctx.fill(); + if(valid===1 && one){ctx.fillStyle=s.color;ctx.beginPath();ctx.arc(x(one.time),y(one.value),2.7,0,Math.PI*2);ctx.fill();} + } + const hover=hoverTime.get(canvas); + const tooltip=canvas.closest('.chart-card')?.querySelector('.chart-tooltip'); + if(hover && tooltip){ + let nearest=null; + for(const s of allSeries) for(const point of s.points) { + if(point.value===null || point.timeto)continue; + if(!nearest || Math.abs(point.time-hover) { - const chartType=el.dataset.chartLegend; - const series=seriesFor(chartType); - el.replaceChildren(); - series.forEach(s => { - const marker=document.createElement('span'); - marker.className='legend-dot';marker.style.background=s.color; - const label=document.createElement('span');label.textContent=s.label; - el.append(marker,label); + if(!nearest) {tooltip.hidden=true;return;} + const nearSeries=allSeries.flatMap(s=>{ + const match=s.points.find(q=>q.time===nearest.time && q.value!==null); + return match?[{label:s.label,color:s.color,value:match.value}]:[]; }); - if (mode==='aggregate' && chartType!=='latency') { - const scope=document.createElement('span');scope.className='subtle'; - scope.textContent='Complete fleet samples only'; el.append(scope); + tooltip.replaceChildren(); + const heading=document.createElement('strong'); + heading.textContent=new Date(nearest.time).toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit'}); + tooltip.append(heading); + for(const item of nearSeries){ + const row=document.createElement('div'),chip=document.createElement('i'),label=document.createElement('span'),value=document.createElement('b'); + chip.style.background=item.color;label.textContent=item.label;value.textContent=formatValue(item.value,type.unit); + row.append(chip,label,value);tooltip.append(row); } - }); - } - - async function poll() { - try { - const path='/ui/telemetry?mode='+encodeURIComponent(mode); - const r=await fetch(path,{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}}); - if(!r.ok || !(r.headers.get('content-type')||'').includes('json'))return; - const payload=await r.json(); - if (mode !== 'single' && payload.mode !== mode) return; - telemetry={samples:Array.isArray(payload.samples)?payload.samples:[],nodes:Array.isArray(payload.nodes)?payload.nodes:[]}; - updateLegends();canvases.forEach(render); - } catch (_) { // Keep last genuine readings; do not fill gaps with zeroes. + const relX=x(nearest.time); + tooltip.style.left=`${Math.max(8,Math.min(width-205,relX-70))}px`; + tooltip.style.top='53px';tooltip.hidden=false; + ctx.strokeStyle='#97ad9a77';ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(relX,p.top);ctx.lineTo(relX,p.top+h);ctx.stroke(); } } - document.addEventListener('DOMContentLoaded',()=>{ - const observer=new ResizeObserver(()=>canvases.forEach(render)); - canvases.forEach(c=>observer.observe(c)); - poll();setInterval(poll,15000); - }); + function updateLegend(canvas) { + const foot=canvas.closest('.chart-card')?.querySelector('[data-chart-legend]'); + if(!foot)return; + const info=chartData.get(canvas); + foot.replaceChildren(); + const series=seriesFor(canvas); + for(const s of series){ + const marker=document.createElement('span');marker.className='legend-dot';marker.style.background=s.color; + const label=document.createElement('span');label.textContent=s.label; + foot.append(marker,label); + } + const note=document.createElement('small'); + note.className='chart-sampling-note'; + const num=series.length?Math.max(...series.map(s=>s.points.length)):0; + const sec=info?.data.stepSeconds || 15; + note.textContent=`${num} measured points · ${sec<60?`${sec}s`:`${sec/60}min`} buckets${info?.data.error?' · API poll failed':''}`; + foot.append(note); + } + async function poll() { + const token=++requestNo; + const combos=new Map(); + for(const canvas of canvases){ + const opts=choices(canvas); + const key=`${opts.range}|${opts.step}`; + if(!combos.has(key))combos.set(key,{...opts,canvases:[]}); + combos.get(key).canvases.push(canvas); + } + const responses=await Promise.all([...combos].map(async([key,opts])=>{ + try { + const params=new URLSearchParams({mode,range:opts.range,step:opts.step}); + const response=await fetch(`/ui/telemetry?${params}`,{cache:'no-store',credentials:'same-origin',headers:{Accept:'application/json'}}); + if(!response.ok || !(response.headers.get('content-type')||'').includes('json'))throw Error(`HTTP ${response.status}`); + const data=await response.json(); + if(mode!=='single' && data.mode!==mode)throw Error('Wrong scope'); + return [key,{data,opts}]; + }catch(err){ return [key,{error:String(err)}]; } + })); + if(token!==requestNo)return; + const results=new Map(responses); + let failures=0; + for(const [key,opts] of combos){ + const entry=results.get(key); + if(!entry || entry.error){failures++;continue;} + const data=entry.data; + const to=Date.parse(data.to); + const from=Date.parse(data.from); + for(const canvas of opts.canvases){ + chartData.set(canvas,{data,from:Number.isFinite(from)?from:Date.now()-RANGE_MS[opts.range],to:Number.isFinite(to)?to:Date.now()}); + updateLegend(canvas); + render(canvas); + } + } + latestError=failures?`${failures} chart ranges could not load` : ''; + const status=document.querySelector('[data-telemetry-status]'); + if(status)status.textContent=latestError; + } + function quoteCSV(value){ + let text=String(value??''); + // Prevent formula injection when server names become CSV cells. + if(/^[\s]*[=+\-@]/.test(text))text="'"+text; + return '"'+text.replace(/"/g,'""')+'"'; + } + function exportCSV(){ + const rows=[['chart','server / series','timestamp (UTC)','value','range','downsampling']]; + for(const canvas of canvases){ + const info=chartData.get(canvas); + if(!info)continue; + const chart=canvas.dataset.dnsChart; + const opts=choices(canvas); + for(const series of seriesFor(canvas))for(const point of series.points){ + if(point.value!==null && point.time>=info.from && point.time<=info.to) + rows.push([chart,series.label,new Date(point.time).toISOString(),point.value,opts.range,opts.step]); + } + } + if(rows.length===1){alert('No measured samples are available to export.');return;} + const blob=new Blob(['\ufeff'+rows.map(row=>row.map(quoteCSV).join(',')).join('\r\n')],{type:'text/csv;charset=utf-8'}); + const url=URL.createObjectURL(blob); + const link=document.createElement('a');link.href=url;link.download=`easydns-web-metrics-${new Date().toISOString().slice(0,10)}.csv`; + document.body.append(link);link.click();link.remove();URL.revokeObjectURL(url); + } + for(const select of [globalRange,globalStep])select?.addEventListener('change',()=>{savePrefs();poll();}); + toolbar?.querySelector('[data-telemetry-refresh]')?.addEventListener('click',()=>location.reload()); + toolbar?.querySelector('[data-telemetry-export]')?.addEventListener('click',exportCSV); + const observer=typeof ResizeObserver==='function'?new ResizeObserver(entries=>entries.forEach(e=>render(e.target))):null; + if(observer)canvases.forEach(c=>observer.observe(c)); + else addEventListener('resize',()=>canvases.forEach(render)); + poll(); + setInterval(()=>{if(!document.hidden)poll();},15000); + document.addEventListener('visibilitychange',()=>{if(!document.hidden)poll();}); })(); diff --git a/internal/server/web/templates/base.gohtml b/internal/server/web/templates/base.gohtml index 03df746..87bee86 100644 --- a/internal/server/web/templates/base.gohtml +++ b/internal/server/web/templates/base.gohtml @@ -30,7 +30,14 @@ {{end}}DocumentationAuditConfiguration
-

{{if .MultiServer}}Managing {{.SelectedNode.Name}} · {{.SelectedNode.Role}} label{{else}}EasyDNS control room{{end}}

{{.Title}}

{{.Subtitle}}

{{.User}}
+

{{if .MultiServer}}Managing {{.SelectedNode.Name}} · {{.SelectedNode.Role}} label{{else}}EasyDNS control room{{end}}

{{.Title}}

{{.Subtitle}}

{{if or (eq .Active "overview") (eq .Active "metrics")}} +
+ + + + {{if eq .Active "metrics"}}{{else}}All metrics{{end}} +
+ {{else}}{{.User}}{{end}}
{{if and .MultiServer (ne .Active "servers")}}
{{if and (eq .Active "metrics") (ne .Data.MetricsMode "single")}}FLEET METRICSAll configured serversCharts compare servers; the top selector still controls other DNS pages.{{else}}ACTIVE SERVER{{.SelectedNode.Name}}{{.SelectedNode.Role}} label{{.SelectedNode.URL}}All DNS data and actions on this page target this server only.{{end}}
{{end}} {{if .Message}}{{end}} {{template "content" .}} @@ -40,3 +47,18 @@ {{end}} + +{{define "chart_controls"}} +
+ + +
+{{end}} + +{{define "metric_chart"}} +
+

{{.Title}}

{{.Description}}

{{template "chart_controls" .Title}}
+ +
Measured EasyDNS samples
+
+{{end}} diff --git a/internal/server/web/templates/pages/metrics.gohtml b/internal/server/web/templates/pages/metrics.gohtml index f05ae81..0199cfb 100644 --- a/internal/server/web/templates/pages/metrics.gohtml +++ b/internal/server/web/templates/pages/metrics.gohtml @@ -1,75 +1,84 @@ {{define "content"}} {{if and .MultiServer (gt (len .Nodes) 1)}}
-
METRICS SCOPE{{if eq .Data.MetricsMode "aggregate"}}All servers · aggregate{{else if eq .Data.MetricsMode "split"}}All servers · comparison{{else}}{{.SelectedNode.Name}} · single server{{end}}Choose how EasyDNS samples are presented. This does not change the DNS configuration.
- +
METRICS SCOPE{{if eq .Data.MetricsMode "aggregate"}}All servers · aggregate{{else if eq .Data.MetricsMode "split"}}All servers · comparison{{else}}{{.SelectedNode.Name}} · single server{{end}}Compare real per-node counters; changing view does not change DNS configuration.
+
{{end}}
{{if eq .Data.MetricsMode "single"}} -
DNS QUERIES{{int .Data.Stats.QueriesTotal}}Cumulative counter
CACHE HIT RATE{{pct .Data.Stats.CacheHitRate}}Latest cache ratio
P50 LATENCY{{ms .Data.Stats.LatencyP50S}}Live histogram
P95 LATENCY{{ms .Data.Stats.LatencyP95S}}Live histogram
P99 LATENCY{{ms .Data.Stats.LatencyP99S}}Live histogram
RATE LIMITED{{int .Data.Stats.RateLimited}}Cumulative count
-

DNS query throughput

Measured requests per second

DNS queries / s
-

Response codes

Rates from cumulative result counters

NOERROR NXDOMAIN SERVFAIL
-

Cache efficiency

Hit share calculated per poll

Cache hit %
-

Resolver latency

p50 / p95 / p99 snapshot history

p50 p95 p99
-

Blocked query rate

Derived from blocked counter

Blocked / s
-

Response count mix

Actual cumulative EasyDNS counters

{{range $key,$v:=.Data.Stats.Responses}}
{{$key}}
{{int $v}}
{{else}}
No response counts available.
{{end}}
-

Query sources

{{range $key,$v:=.Data.Stats.Sources}}{{else}}{{end}}
SOURCECOUNT (CUMULATIVE)
{{$key}}{{int $v}}
No query source counters.
-

Cache counters

Entries{{int .Data.Stats.Cache.Entries}}
Hits{{int .Data.Stats.Cache.Hits}}
Misses{{int .Data.Stats.Cache.Misses}}
Evictions{{int .Data.Stats.Cache.Evictions}}
-

Telemetry sampling

Samples stored in UI memory{{.Data.SamplingCount}}
Polling frequency15 s
Last sample{{if .Data.SamplingTime.IsZero}}—{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{end}}
No artificial 24-hour chart data. Samples are collected only while the Go service runs, and reset on restart.
+
+
DNS QUERIES{{int .Data.Stats.QueriesTotal}}Total since server start
+
QPS (LATEST){{if .Data.RecentQueryRate}}{{float .Data.RecentQueryRate}} /s{{else}}—{{end}}Measured 15 s sample
+
CACHE HIT RATE{{pct .Data.Stats.CacheHitRate}}Native counter ratio
+
P95 RESOLVER LATENCY{{ms .Data.Stats.LatencyP95S}}Latest quantile snapshot
+
BLOCKED QUERIES{{int .Data.Stats.Blocked}}Rejected by policy
+
RATE LIMITED{{int .Data.Stats.RateLimited}}Cumulative count
+
{{else}}
-
{{.Data.MetricOnline}} / {{.Data.MetricTotal}} respondingCurrent /api/v1/stats snapshot
-
{{if eq .Data.MetricsMode "aggregate"}}Additive counters are summed across responding servers. Charts need fresh readings from every server.{{else}}Each server has its own chart line; missing data stays missing.{{end}}
+
{{.Data.MetricOnline}} / {{.Data.MetricTotal}} respondingCurrent native /api/v1/stats snapshot
+
{{if eq .Data.MetricsMode "aggregate"}}Rates are summed only with complete, fresh per-node coverage.{{else}}Each server has independent real samples, with gaps for missing data.{{end}}
-{{if lt .Data.MetricOnline .Data.MetricTotal}}
Partial data: at least one server is unavailable. Counter totals below include only responding servers. Aggregate rate charts show gaps instead of misleading reduced totals.
{{end}} - +{{if lt .Data.MetricOnline .Data.MetricTotal}}
Partial data: at least one node is unavailable. Counters below include responding nodes only; aggregate rate charts show gaps rather than reduced totals.
{{end}} {{if eq .Data.MetricsMode "aggregate"}}
-
RESPONDING SERVERS{{.Data.MetricOnline}} / {{.Data.MetricTotal}}Live API reachability
-
DNS QUERIES{{if .Data.MetricOnline}}{{int .Data.MetricTotals.QueriesTotal}}{{else}}—{{end}}Sum of current counters
-
WEIGHTED CACHE HIT{{if .Data.MetricHasCache}}{{pct .Data.MetricTotals.CacheHitRate}}{{else}}—{{end}}Hits / total cache lookups
+
SERVERS REACHABLE{{.Data.MetricOnline}} / {{.Data.MetricTotal}}Native API availability
+
DNS QUERIES{{if .Data.MetricOnline}}{{int .Data.MetricTotals.QueriesTotal}}{{else}}—{{end}}Sum of counters
+
CACHE HIT RATE{{if .Data.MetricHasCache}}{{pct .Data.MetricTotals.CacheHitRate}}{{else}}—{{end}}Weighted by cache lookups
BLOCKED QUERIES{{if .Data.MetricOnline}}{{int .Data.MetricTotals.Blocked}}{{else}}—{{end}}Sum of counters
RATE LIMITED{{if .Data.MetricOnline}}{{int .Data.MetricTotals.RateLimited}}{{else}}—{{end}}Sum of counters
-
P95 LATENCYPer serverPercentiles cannot be added
+
P95 LATENCYPer serverPercentiles cannot be summed
{{else}} -

Server metrics

Direct snapshots from each configured EasyDNS API. The selected server in the header does not filter this fleet view.

-
-{{range $i, $n := .Data.MetricNodes}}{{end}} -
SERVERROLE (PANEL LABEL)APIQUERIESCACHE HITP95BLOCKEDSAMPLES
{{$n.Node.Name}}{{$n.Node.Role}}{{if $n.Available}}Responding{{else}}Unavailable{{end}}{{if $n.Available}}{{int $n.Stats.QueriesTotal}}{{else}}—{{end}}{{if $n.Available}}{{pct $n.Stats.CacheHitRate}}{{else}}—{{end}}{{if $n.Available}}{{ms $n.Stats.LatencyP95S}}{{else}}—{{end}}{{if $n.Available}}{{int $n.Stats.Blocked}}{{else}}—{{end}}{{$n.Samples}}
+

Server metrics

Live API snapshots. The selected server in the header does not filter this fleet view.

+
+{{range $i,$n:=.Data.MetricNodes}}{{end}} +
SERVERROLE LABELAPIQUERIESCACHE HITP95BLOCKEDSAMPLES
{{$n.Node.Name}}{{$n.Node.Role}}{{if $n.Available}}Responding{{else}}Unavailable{{end}}{{if $n.Available}}{{int $n.Stats.QueriesTotal}}{{else}}—{{end}}{{if $n.Available}}{{pct $n.Stats.CacheHitRate}}{{else}}—{{end}}{{if $n.Available}}{{ms $n.Stats.LatencyP95S}}{{else}}—{{end}}{{if $n.Available}}{{int $n.Stats.Blocked}}{{else}}—{{end}}{{$n.Samples}}
+{{end}} {{end}} -
-

DNS query throughput

{{if eq .Data.MetricsMode "aggregate"}}Sum of per-server QPS where all servers have fresh samples{{else}}Measured QPS for each server{{end}}

Only real poll samples
-

{{if eq .Data.MetricsMode "aggregate"}}Response codes{{else}}NOERROR by server{{end}}

Per-second result counter changes

Only real poll samples
-

Cache efficiency

{{if eq .Data.MetricsMode "aggregate"}}Weighted by cache hit/miss operation rates{{else}}Per-server cache hit percentage{{end}}

Only real poll samples
+ {{template "metric_chart" (chart "queries" "DNS query throughput" "Measured requests per second")}} + {{if eq .Data.MetricsMode "split"}}{{template "metric_chart" (chart "responses" "NOERROR by server" "Per-node response rate, measured QPS")}}{{else}}{{template "metric_chart" (chart "responses" "Response codes" "NOERROR, NXDOMAIN, SERVFAIL and REFUSED QPS")}}{{end}} + {{template "metric_chart" (chart "cache" "Cache efficiency" "Cache hit ratio from counter deltas")}}
-

Resolver latency p95

Individual server p95 snapshots — never aggregated

Per-server observations
-

Blocked query rate

{{if eq .Data.MetricsMode "aggregate"}}Sum of blocked QPS{{else}}Per-server blocked QPS{{end}}

Only real poll samples
- {{if eq .Data.MetricsMode "split"}} -

NXDOMAIN by server

Per-second counter changes

Only real poll samples
- {{else}} -

Response count mix

Summed cumulative counters from responding servers

{{range $key,$v:=.Data.MetricTotals.Responses}}
{{$key}}
{{int $v}}
{{else}}
No available response counters.
{{end}}
- {{end}} + {{template "metric_chart" (chart "latency" "DNS response latency" "p50/p95/p99 API histogram snapshots · ms")}} + {{template "metric_chart" (chart "sources" "Authoritative vs. recursive" "Query rates by DNS handling source")}} + {{template "metric_chart" (chart "cacheTraffic" "Cache traffic" "Hit and miss rates over time")}} +
+
+ {{template "metric_chart" (chart "blocked" "Blocked query rate" "Policy-blocked DNS queries per second")}} + {{template "metric_chart" (chart "rateLimited" "Rate-limited queries" "Queries limited per second")}} + {{template "metric_chart" (chart "nxdomain" "NXDOMAIN by server" "Unknown-domain response rate")}} +
+
+ {{template "metric_chart" (chart "servfail" "SERVFAIL response rate" "Server failure responses per second")}} + {{template "metric_chart" (chart "cacheEntries" "Cache entries" "Number of entries at each poll")}} + {{template "metric_chart" (chart "errorRate" "Error response share" "SERVFAIL + REFUSED as share of sampled QPS")}} +
+
+ {{template "metric_chart" (chart "cacheEvictions" "Cache evictions" "Evicted cache entries per second")}} + {{template "metric_chart" (chart "refused" "REFUSED response rate" "Refused DNS responses per second")}} + {{template "metric_chart" (chart "queryTotal" "Overall DNS traffic" "Total DNS requests per second")}}
-
-

{{if eq .Data.MetricsMode "aggregate"}}Summed query sources{{else}}Server sample health{{end}}

- {{if eq .Data.MetricsMode "aggregate"}}
{{range $key,$v:=.Data.MetricTotals.Sources}}{{else}}{{end}}
SOURCECOUNT
{{$key}}{{int $v}}
No source counters.
- {{else}}
{{range .Data.MetricNodes}}
{{.Node.Name}}{{if .LastPoll.IsZero}}Waiting for samples{{else}}{{.LastPoll.Format "15:04:05 UTC"}}{{if .LastError}} · poll failed{{end}}{{end}}
{{end}}
{{end}} -
-

{{if eq .Data.MetricsMode "aggregate"}}Summed cache counters{{else}}Latency by node{{end}}

- {{if eq .Data.MetricsMode "aggregate"}}
Entries{{int .Data.MetricTotals.Cache.Entries}}
Hits{{int .Data.MetricTotals.Cache.Hits}}
Misses{{int .Data.MetricTotals.Cache.Misses}}
Evictions{{int .Data.MetricTotals.Cache.Evictions}}
- {{else}}
{{range .Data.MetricNodes}}{{end}}
SERVERP50P95P99
{{.Node.Name}}{{if .Available}}{{ms .Stats.LatencyP50S}}{{else}}—{{end}}{{if .Available}}{{ms .Stats.LatencyP95S}}{{else}}—{{end}}{{if .Available}}{{ms .Stats.LatencyP99S}}{{else}}—{{end}}
{{end}} -
-

How fleet metrics work

Poll interval15 seconds
HistoryUp to 6 hours, in RAM
Chart gapsMissing or stale readings
Counters reset on each DNS service restart. Cumulative totals sum each server's current counters, not a common 24-hour interval. Aggregate QPS requires every registered node; no synthetic zeros. Cache hit % is calculated from hit/miss rates. Latency percentiles are shown separately for each node.
-
-{{end}} + {{if eq .Data.MetricsMode "single"}} +

Response code breakdown

{{range $key,$v:=.Data.Stats.Responses}}
{{$key}}
{{int $v}}
{{else}}
No response counters returned.
{{end}}
+

Cache counters

Entries{{int .Data.Stats.Cache.Entries}}
Hits{{int .Data.Stats.Cache.Hits}}
Misses{{int .Data.Stats.Cache.Misses}}
Evictions{{int .Data.Stats.Cache.Evictions}}
+ {{else if eq .Data.MetricsMode "aggregate"}} +

Response code breakdown

{{range $key,$v:=.Data.MetricTotals.Responses}}
{{$key}}
{{int $v}}
{{else}}
No response counters returned.
{{end}}
+

Summed cache counters

Entries{{int .Data.MetricTotals.Cache.Entries}}
Hits{{int .Data.MetricTotals.Cache.Hits}}
Misses{{int .Data.MetricTotals.Cache.Misses}}
Evictions{{int .Data.MetricTotals.Cache.Evictions}}
+ {{else}} +

Latency per server

{{range .Data.MetricNodes}}{{end}}
SERVERP50P95P99
{{.Node.Name}}{{if .Available}}{{ms .Stats.LatencyP50S}}{{else}}—{{end}}{{if .Available}}{{ms .Stats.LatencyP95S}}{{else}}—{{end}}{{if .Available}}{{ms .Stats.LatencyP99S}}{{else}}—{{end}}
+

Telemetry by node

{{range .Data.MetricNodes}}
{{.Node.Name}}{{if .LastPoll.IsZero}}No reading yet{{else}}{{.LastPoll.Format "15:04:05 UTC"}}{{if .LastError}} · poll error{{end}}{{end}}
{{end}}
+ {{end}} +

Sampling & export

Poll interval15 seconds
RetentionUp to 24 h in panel RAM
Samples held (active server){{.Data.SamplingCount}}
Last poll{{if .Data.SamplingTime.IsZero}}No samples{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{end}}
The chart controls request a selected time range and bucket size from the Go panel. All values come from the existing DNS REST /api/v1/stats counters. CSV export includes measured chart values only. Gaps are not replaced with zeros.
+
+{{if ne .Data.MetricsMode "single"}}
Fleet throughput is added only when all nodes reported fresh values. Cache percentages are weighted by cache operations. Latency quantiles are charted by server, not summed. Cumulative counters may cover different uptimes.
{{end}} {{end}} diff --git a/internal/server/web/templates/pages/overview.gohtml b/internal/server/web/templates/pages/overview.gohtml index c3e1485..9101e2e 100644 --- a/internal/server/web/templates/pages/overview.gohtml +++ b/internal/server/web/templates/pages/overview.gohtml @@ -1,34 +1,46 @@ {{define "content"}}
-
{{if eq .Data.Health.Status "ok"}}DNS service operational{{else if eq .Data.Health.Status "degraded"}}DNS service degraded{{else}}Status unavailable{{end}}
Health: {{if .Data.Health.Status}}{{.Data.Health.Status}}{{else}}Unknown{{end}} · {{if .Data.Status.Roles.Recursive}}Resolver enabled{{else}}No recursive resolver{{end}}
-
SERVER MODE{{if .Data.Status.Mode}}{{.Data.Status.Mode}}{{else}}—{{end}}
-
UPTIME{{uptime .Data.Status.UptimeSeconds}}
-
ZONES{{int .Data.Status.Roles.Primary}} primary / {{int .Data.Status.Roles.Secondary}} secondary
-
VERSION{{if .Data.Status.Version}}{{.Data.Status.Version}}{{else}}—{{end}}
+
{{if eq .Data.Health.Status "ok"}}DNS service operational{{else if eq .Data.Health.Status "degraded"}}DNS service degraded{{else}}DNS service status unavailable{{end}}
Authoritative and resolver health from the active EasyDNS API.
+
SERVER MODE{{if .Data.Status.Mode}}{{.Data.Status.Mode}}{{else}}—{{end}}
+
UPTIME{{uptime .Data.Status.UptimeSeconds}}
+
ZONE ROLES{{int .Data.Status.Roles.Primary}} primary / {{int .Data.Status.Roles.Secondary}} secondary
+
DNS VERSION{{if .Data.Status.Version}}{{.Data.Status.Version}}{{else}}—{{end}}
-
DNS QUERIES{{int .Data.Stats.QueriesTotal}}Cumulative since startup
-
CACHE HIT RATIO{{pct .Data.Stats.CacheHitRate}}Hits / (hits + misses)
-
RESOLVER LATENCY P95{{ms .Data.Stats.LatencyP95S}}Latest API histogram
+
DNS QUERIES{{int .Data.Stats.QueriesTotal}}Since DNS service startup
+
QUERY RATE (LATEST){{if .Data.RecentQueryRate}}{{float .Data.RecentQueryRate}} /s{{else}}—{{end}}Last measured 15 s interval
+
CACHE HIT RATIO{{pct .Data.Stats.CacheHitRate}}From EasyDNS cache counters
+
RESOLVER LATENCY P95{{ms .Data.Stats.LatencyP95S}}Latest quantile snapshot
BLOCKED QUERIES{{int .Data.Stats.Blocked}}Cumulative policy count
-
RATE LIMITED{{int .Data.Stats.RateLimited}}Cumulative count
-
ZONE HEALTH{{if eq .Data.Health.Status "ok"}}Healthy{{else if eq .Data.Health.Status "degraded"}}Degraded{{else}}Unknown{{end}}{{len .Data.Health.ExpiredZones}} expired zones
+
RATE LIMITED{{int .Data.Stats.RateLimited}}Cumulative rate-limit count
-

Query rate

Calculated from real /stats counter deltas.

PANEL SAMPLES
Queries / s
-

Cache hit ratio

Derived from cache hit/miss deltas.

Hits / all lookups
-

Resolver latency

Live p50 and p95, milliseconds.

p95 p50
+ {{template "metric_chart" (chart "queries" "Query rate" "Recursive and authoritative requests per second")}} + {{template "metric_chart" (chart "cache" "Cache hit ratio" "Share of hits among observed cache lookups")}} + {{template "metric_chart" (chart "latency" "Resolver latency" "p50, p95 and p99 · observed milliseconds")}} +
+
+ {{template "metric_chart" (chart "responses" "Response codes" "NOERROR, NXDOMAIN, SERVFAIL and REFUSED QPS")}} + {{template "metric_chart" (chart "cacheTraffic" "Cache traffic" "Cache hits and misses per second")}} + {{template "metric_chart" (chart "security" "Policy activity" "Blocked and rate-limited requests per second")}}
-

Response codes

Cumulative DNS results since startup

Metrics →
- {{range $key,$v := .Data.Stats.Responses}}
{{$key}}
{{int $v}}
{{else}}
No response statistics available.
{{end}} +

Upstream health

Real resolver statistics

View upstreams →
+ {{range .Data.Upstreams}}{{range .Servers}}
{{.Address}}{{if .Stats.EWMARTTMS}}{{float .Stats.EWMARTTMS}} ms{{else}}RTT unavailable{{end}}
{{else}}
No servers in this upstream group
{{end}}{{else}}
No upstream measurements available from API.
{{end}}
-

Zone state

Reported by EasyDNS

View zones →
-
Primary zones{{int .Data.Status.Roles.Primary}}
Secondary zones{{int .Data.Status.Roles.Secondary}}
Recursive resolver{{if .Data.Status.Roles.Recursive}}Enabled{{else}}Disabled{{end}}
Forwarder{{if .Data.Status.Roles.Forwarder}}Enabled{{else}}Disabled{{end}}
Expired zones{{len .Data.Health.ExpiredZones}}
+

Response outcomes

Real cumulative result counters

All metrics →
+ {{range $key,$v:=.Data.Stats.Responses}}
{{$key}}
{{int $v}}
{{else}}
No response counters returned.
{{end}} +
+

System & cache health

DNS service counters, not host CPU estimates

Server status →
+
Cache entries{{int .Data.Stats.Cache.Entries}}
+
Cache evictions{{int .Data.Stats.Cache.Evictions}}
+
Expired zones{{len .Data.Health.ExpiredZones}}
+
Samples held{{.Data.SamplingCount}} · 15 s cadence
+
Sampling{{if .Data.SamplingTime.IsZero}}Waiting for API{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{if .Data.SamplingError}} · API error{{end}}{{end}}
-

Polling status

UI sampling, not server-side history

Samples{{.Data.SamplingCount}}
Interval15 seconds
Most recent{{if .Data.SamplingTime.IsZero}}No sample{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{end}}
Charts populate only after successful live polls.
-

Recent audit events

Changes and administration activity

Audit log →
+

Recent audit events

Administrative changes reported by EasyDNS

Audit log →
TIMEACTIONTARGETRESULTDETAIL
{{range .Data.Audit}}{{else}}{{end}}
TIMEACTIONTARGETRESULTDETAIL
{{when .TimeUnix}}{{.Action}}{{.Target}}{{.Result}}{{.Detail}}
No audit events returned by EasyDNS.
+
Time-series charts are sampled by EasyDNS Web from the existing /api/v1/stats endpoint. At most 24 hours are retained in panel memory; history starts when the panel begins polling and resets on restart.
{{end}} diff --git a/internal/server/web/templates/pages/servers.gohtml b/internal/server/web/templates/pages/servers.gohtml index e3f8490..94120d0 100644 --- a/internal/server/web/templates/pages/servers.gohtml +++ b/internal/server/web/templates/pages/servers.gohtml @@ -7,7 +7,7 @@

Topology

Primary and Secondary are panel labels. The real DNS role is reported separately per installation.

- +

PRIMARY · MANAGEMENT LABEL

@@ -16,7 +16,7 @@

{{.Node.Name}}

{{.Node.URL}}

Server version{{if .Status.Version}}{{.Status.Version}}{{else}}Unavailable{{end}}
Actual primary zones{{.Status.Roles.Primary}}
Actual secondary zones{{.Status.Roles.Secondary}}
{{if .Error}}

{{.Error}}

{{end}} -
Details ↓
+ {{end}}{{end}}
@@ -25,7 +25,7 @@
SECONDARY{{.State}}

{{.Node.Name}}

{{.Node.URL}}

Version{{if .Status.Version}}{{.Status.Version}}{{else}}Unavailable{{end}}
Actual secondary zones{{.Status.Roles.Secondary}}
Actual primary zones{{.Status.Roles.Primary}}
{{if .Error}}

{{.Error}}

{{end}} -
+ {{end}}{{end}}
@@ -33,7 +33,7 @@

* Diagram indicates the intended topology, not a detected transfer connection. EasyDNS primary/secondary zone relationships must be configured on the DNS servers. The UI cannot create secondary zones through REST.

Managed installations

Change local display roles, switch context, or remove a remote connection. These actions do not reconfigure DNS.

-{{range .Data.ServerProbes}} +{{range .Data.ServerProbes}} {{end}}
SERVERAPI URLSTATUSPRIMARY ZONES*SECONDARY ZONES*LABELACTIONS
{{.Node.Name}}{{if .Node.Local}}LOCAL{{else}}REMOTE{{end}}{{.Node.URL}}{{.State}}{{if eq .State "offline"}}—{{else}}{{.Status.Roles.Primary}}{{end}}{{if eq .State "offline"}}—{{else}}{{.Status.Roles.Secondary}}{{end}}{{if or .Node.Managed (and .Node.Local $.LocalRoleConfigured)}}{{if eq .Node.Role "primary"}}Primary{{else if eq .Node.Role "secondary"}}Secondary{{else}}Unassigned{{end}}{{else}}
{{end}}
{{if and (not .Node.Local) (not .Node.Managed)}}Remove{{end}}
{{.Node.Name}}{{if .Node.Local}}LOCAL{{else}}REMOTE{{end}}{{.Node.URL}}{{.State}}{{if eq .State "offline"}}—{{else}}{{.Status.Roles.Primary}}{{end}}{{if eq .State "offline"}}—{{else}}{{.Status.Roles.Secondary}}{{end}}{{if or .Node.Managed (and .Node.Local $.LocalRoleConfigured)}}{{if eq .Node.Role "primary"}}Primary{{else if eq .Node.Role "secondary"}}Secondary{{else}}Unassigned{{end}}{{else}}
{{end}}
{{if and (not .Node.Local) (not .Node.Managed)}}Remove{{end}}
* Zone counts are read from each server's actual /api/v1/status response. An offline node's DNS role cannot be verified. No cluster quorum, leader election, or automated replication is implied.
diff --git a/internal/server/web/templates/pages/status.gohtml b/internal/server/web/templates/pages/status.gohtml index ea55645..2003ddb 100644 --- a/internal/server/web/templates/pages/status.gohtml +++ b/internal/server/web/templates/pages/status.gohtml @@ -2,4 +2,5 @@

DNS roles

Primary zones{{int .Data.Status.Roles.Primary}}
Secondary zones{{int .Data.Status.Roles.Secondary}}
Recursive role{{.Data.Status.Roles.Recursive}}
Forwarder role{{.Data.Status.Roles.Forwarder}}
Forward zones{{.Data.Status.Roles.ForwardZones}}
Default resolution{{.Data.Status.Roles.DefaultResolution}}

Bound listeners

{{range $key,$v:=.Data.Status.Listeners}}
{{$key}}{{string $v}}
{{else}}
No listener information.
{{end}}

Health / expired zones

Health{{.Data.Health.Status}}
Expired zones{{len .Data.Health.ExpiredZones}}
{{range .Data.Health.ExpiredZones}}
{{.}}
{{else}}

No expired zones returned.

{{end}}
+{{if .MultiServer}}{{end}}

Per-zone runtime state

{{range .Data.Status.Zones}}{{else}}{{end}}
NAMEROLELOADEDEXPIREDSERIALRECORDSLAST SYNC
{{.Name}}{{.Kind}}{{.Loaded}}{{.Expired}}{{.SerialText}}{{.Records}}{{.LastSync}}
No zones in status response.
{{end}} diff --git a/internal/server/web/templates/pages/zone.gohtml b/internal/server/web/templates/pages/zone.gohtml index f8f398e..6e9632a 100644 --- a/internal/server/web/templates/pages/zone.gohtml +++ b/internal/server/web/templates/pages/zone.gohtml @@ -22,11 +22,38 @@ {{else if eq .Data.Tab "records"}} -
-
{{.Data.Pagination.Total}} records{{if .Data.IsPrimary}}Add record{{else}}Secondary · read-only{{end}}
-
{{if .Data.IsPrimary}}{{end}} -{{range .Data.Records}}{{if $.Data.IsPrimary}}{{end}}{{else}}{{end}} -
NAMETYPERDATATTLACTIONS
{{.Name}}{{.Type}}{{.Data}}{{.TTL}}{{if ne .Type "SOA"}}
{{else}}Managed{{end}}
No records returned for this filter.
+
+
+
+ + + + +
+
+ {{if .Data.HideDNSSEC}}DNSSEC records hidden{{else}}{{int .Data.Pagination.Total}} records{{end}} + {{if .Data.IsPrimary}}Add record{{else}}Secondary · read-only{{end}} +
+
+
{{if .Data.IsPrimary}}{{end}} + {{range .Data.Records}} + {{if $.Data.IsPrimary}}{{end}} + {{else}}{{end}} +
NAMETYPERDATATTLACTIONS
{{.Name}}{{.Type}}{{.Data}}{{.TTL}}{{if ne .Type "SOA"}}
{{else}}Managed{{end}}
{{if .Data.HideDNSSEC}}No non-DNSSEC records match these filters. Uncheck the box to show all records.{{else}}No records returned for this filter.{{end}}
+ +
Writes are protected with the zone serial ETag. SOA records are managed through whole-zone replacement; secondaries are read-only.
{{else if eq .Data.Tab "transfers"}}

Zone transfer history

Recorded inbound and outbound AXFR / IXFR events

{{range .Data.Transfers}}{{else}}{{end}}
TIMEDIRECTIONTYPEPEERSERIALRECORDSDURATIONRESULT
{{when .TimeUnix}}{{.Direction}}{{.Kind}}{{.Peer}}{{if .Serial}}{{.Serial}}{{else}}—{{end}}{{.Records}}{{.DurationMS}} ms{{if .OK}}Completed{{else}}{{if .Error}}{{.Error}}{{else}}Failed{{end}}{{end}}
No recorded transfers. This API provides history, not a live transfer queue.
diff --git a/internal/telemetry/fleet.go b/internal/telemetry/fleet.go index fd72eb3..f2fc13c 100644 --- a/internal/telemetry/fleet.go +++ b/internal/telemetry/fleet.go @@ -20,15 +20,25 @@ type FleetNode struct { // valid. Percentile latency is intentionally excluded: it cannot be computed // from separately reported per-node p50/p95/p99 values. type FleetPoint struct { - Time time.Time `json:"time"` - QueryRate *float64 `json:"queryRate"` - NoErrorRate *float64 `json:"noerror"` - NXDomainRate *float64 `json:"nxdomain"` - ServFailRate *float64 `json:"servfail"` - RefusedRate *float64 `json:"refused"` - BlockedRate *float64 `json:"blocked"` - CacheHitRate *float64 `json:"cacheHitRate"` - Contributors int `json:"contributors"` + Time time.Time `json:"time"` + QueryRate *float64 `json:"queryRate"` + NoErrorRate *float64 `json:"noerror"` + NXDomainRate *float64 `json:"nxdomain"` + ServFailRate *float64 `json:"servfail"` + RefusedRate *float64 `json:"refused"` + BlockedRate *float64 `json:"blocked"` + RateLimitedRate *float64 `json:"rateLimitedRate"` + SourceAuthRate *float64 `json:"authoritativeRate"` + SourceRecursiveRate *float64 `json:"recursiveRate"` + SourceForwardRate *float64 `json:"forwardRate"` + SourceCacheRate *float64 `json:"cacheSourceRate"` + CacheHitsRate *float64 `json:"cacheHitsRate"` + CacheMissesRate *float64 `json:"cacheMissesRate"` + CacheEvictionsRate *float64 `json:"cacheEvictionsRate"` + CacheEntries *float64 `json:"cacheEntries"` + ErrorRate *float64 `json:"errorRate"` + CacheHitRate *float64 `json:"cacheHitRate"` + Contributors int `json:"contributors"` } const fleetStep = 15 * time.Second @@ -63,7 +73,7 @@ func AggregateFleet(nodes []FleetNode) []FleetPoint { if end.Before(start) { return nil } - // Bound comparison data to the same six-hour, 1440-poll memory horizon as + // Bound comparison data to the same 24-hour rolling memory horizon as // each node's History. Never add empty points before the first poll. if end.Sub(start) > time.Duration(maxSamples-1)*fleetStep { start = end.Add(-time.Duration(maxSamples-1) * fleetStep) @@ -73,8 +83,10 @@ func AggregateFleet(nodes []FleetNode) []FleetPoint { for t := start; !t.After(end); t = t.Add(fleetStep) { point := FleetPoint{Time: t} var query, noerror, nxdomain, servfail, refused, blocked float64 - var hitQPS, missQPS float64 + var hitQPS, missQPS, evictQPS, cacheEntries float64 + var limit, auth, recursive, forward, cached float64 cacheComplete := true + extraComplete := true for i, n := range nodes { for index[i] < len(n.Samples) && !n.Samples[index[i]].Time.After(t) { index[i]++ @@ -95,20 +107,38 @@ func AggregateFleet(nodes []FleetNode) []FleetPoint { servfail += *sample.ServFailRate refused += *sample.RefusedRate blocked += *sample.BlockedRate - if sample.cacheHitQPS == nil || sample.cacheMissQPS == nil { + if sample.CacheHitsRate == nil || sample.CacheMissesRate == nil { cacheComplete = false } else { - hitQPS += *sample.cacheHitQPS - missQPS += *sample.cacheMissQPS + hitQPS += *sample.CacheHitsRate + missQPS += *sample.CacheMissesRate } + if sample.RateLimitedRate == nil || sample.SourceAuthRate == nil || sample.SourceRecursiveRate == nil || sample.SourceForwardRate == nil || sample.SourceCacheRate == nil || sample.CacheEvictionsRate == nil { + extraComplete = false + } else { + limit += *sample.RateLimitedRate + auth += *sample.SourceAuthRate + recursive += *sample.SourceRecursiveRate + forward += *sample.SourceForwardRate + cached += *sample.SourceCacheRate + evictQPS += *sample.CacheEvictionsRate + } + cacheEntries += sample.CacheEntries } if point.Contributors == len(nodes) { point.QueryRate, point.NoErrorRate, point.NXDomainRate = &query, &noerror, &nxdomain point.ServFailRate, point.RefusedRate, point.BlockedRate = &servfail, &refused, &blocked - if cacheComplete && hitQPS+missQPS > 0 { - ratio := 100 * hitQPS / (hitQPS + missQPS) - point.CacheHitRate = &ratio + if cacheComplete { + point.CacheHitsRate, point.CacheMissesRate = &hitQPS, &missQPS + point.CacheHitRate = cachePercent(point.CacheHitsRate, point.CacheMissesRate) } + point.CacheEntries = &cacheEntries + if extraComplete { + point.RateLimitedRate, point.SourceAuthRate = &limit, &auth + point.SourceRecursiveRate, point.SourceForwardRate = &recursive, &forward + point.SourceCacheRate, point.CacheEvictionsRate = &cached, &evictQPS + } + point.ErrorRate = errorPercent(point.QueryRate, point.ServFailRate, point.RefusedRate) } points = append(points, point) } diff --git a/internal/telemetry/history.go b/internal/telemetry/history.go index 24255ca..ce4d927 100644 --- a/internal/telemetry/history.go +++ b/internal/telemetry/history.go @@ -1,5 +1,5 @@ -// Package telemetry derives time series from real EasyDNS counter polls. -// EasyDNS REST does not expose history; no datapoints are synthesized. +// Package telemetry derives time series from genuine EasyDNS REST counter polls. +// This is panel memory, not Prometheus or an invented DNS history endpoint. package telemetry import ( @@ -10,33 +10,47 @@ import ( "git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns" ) -const maxSamples = 1440 // six hours at a fifteen-second sampling interval +const PollInterval = 15 * time.Second +const MaxHistory = 24 * time.Hour +const maxSamples = int(MaxHistory/PollInterval) + 1 type Sample struct { - Time time.Time `json:"time"` - QueriesTotal uint64 `json:"-"` - NoError uint64 `json:"-"` - NXDomain uint64 `json:"-"` - ServFail uint64 `json:"-"` - Refused uint64 `json:"-"` - Blocked uint64 `json:"-"` - RateLimited uint64 `json:"-"` - CacheHits uint64 `json:"-"` - CacheMisses uint64 `json:"-"` - QueryRate *float64 `json:"queryRate"` - NoErrorRate *float64 `json:"noerror"` - NXDomainRate *float64 `json:"nxdomain"` - ServFailRate *float64 `json:"servfail"` - RefusedRate *float64 `json:"refused"` - BlockedRate *float64 `json:"blocked"` - CacheHitRate *float64 `json:"cacheHitRate"` - P50MS float64 `json:"p50ms"` - P95MS float64 `json:"p95ms"` - P99MS float64 `json:"p99ms"` - // Per-second cache increments allow mathematically weighted fleet cache - // ratios. These are derived from real counters and never sent to the browser. - cacheHitQPS *float64 - cacheMissQPS *float64 + Time time.Time `json:"time"` + QueriesTotal uint64 `json:"-"` + NoError uint64 `json:"-"` + NXDomain uint64 `json:"-"` + ServFail uint64 `json:"-"` + Refused uint64 `json:"-"` + Blocked uint64 `json:"-"` + RateLimited uint64 `json:"-"` + CacheHits uint64 `json:"-"` + CacheMisses uint64 `json:"-"` + CacheEvictions uint64 `json:"-"` + Authoritative uint64 `json:"-"` + Recursive uint64 `json:"-"` + Forward uint64 `json:"-"` + Cached uint64 `json:"-"` + + QueryRate *float64 `json:"queryRate"` + NoErrorRate *float64 `json:"noerror"` + NXDomainRate *float64 `json:"nxdomain"` + ServFailRate *float64 `json:"servfail"` + RefusedRate *float64 `json:"refused"` + BlockedRate *float64 `json:"blocked"` + RateLimitedRate *float64 `json:"rateLimitedRate"` + SourceAuthRate *float64 `json:"authoritativeRate"` + SourceRecursiveRate *float64 `json:"recursiveRate"` + SourceForwardRate *float64 `json:"forwardRate"` + SourceCacheRate *float64 `json:"cacheSourceRate"` + CacheHitsRate *float64 `json:"cacheHitsRate"` + CacheMissesRate *float64 `json:"cacheMissesRate"` + CacheEvictionsRate *float64 `json:"cacheEvictionsRate"` + CacheHitRate *float64 `json:"cacheHitRate"` + ErrorRate *float64 `json:"errorRate"` + CacheEntries float64 `json:"cacheEntries"` + P50MS float64 `json:"p50ms"` + P95MS float64 `json:"p95ms"` + P99MS float64 `json:"p99ms"` } type History struct { @@ -54,8 +68,28 @@ func delta(a, b uint64, secs float64) *float64 { v := float64(b-a) / secs return &v } +func cachePercent(hits, misses *float64) *float64 { + if hits == nil || misses == nil || *hits+*misses <= 0 { + return nil + } + v := 100 * *hits / (*hits + *misses) + return &v +} +func errorPercent(total, servfail, refused *float64) *float64 { + if total == nil || servfail == nil || refused == nil || *total <= 0 { + return nil + } + v := 100 * (*servfail + *refused) / *total + return &v +} func (h *History) Record(t time.Time, s easydns.Stats) { - p := Sample{Time: t, QueriesTotal: s.QueriesTotal, NoError: s.Responses["noerror"], NXDomain: s.Responses["nxdomain"], ServFail: s.Responses["servfail"], Refused: s.Responses["refused"], Blocked: s.Blocked, RateLimited: s.RateLimited, CacheHits: s.Cache.Hits, CacheMisses: s.Cache.Misses, P50MS: s.LatencyP50S * 1000, P95MS: s.LatencyP95S * 1000, P99MS: s.LatencyP99S * 1000} + p := Sample{ + Time: t, QueriesTotal: s.QueriesTotal, NoError: s.Responses["noerror"], NXDomain: s.Responses["nxdomain"], + ServFail: s.Responses["servfail"], Refused: s.Responses["refused"], Blocked: s.Blocked, RateLimited: s.RateLimited, + CacheHits: s.Cache.Hits, CacheMisses: s.Cache.Misses, CacheEvictions: s.Cache.Evictions, + Authoritative: s.Sources["authoritative"], Recursive: s.Sources["recursive"], Forward: s.Sources["forward"], Cached: s.Sources["cache"], + CacheEntries: float64(s.Cache.Entries), P50MS: s.LatencyP50S * 1000, P95MS: s.LatencyP95S * 1000, P99MS: s.LatencyP99S * 1000, + } h.mu.Lock() defer h.mu.Unlock() if len(h.samples) > 0 { @@ -67,19 +101,20 @@ func (h *History) Record(t time.Time, s easydns.Stats) { p.ServFailRate = delta(prev.ServFail, p.ServFail, secs) p.RefusedRate = delta(prev.Refused, p.Refused, secs) p.BlockedRate = delta(prev.Blocked, p.Blocked, secs) - if p.CacheHits >= prev.CacheHits && p.CacheMisses >= prev.CacheMisses { - hits := p.CacheHits - prev.CacheHits - misses := p.CacheMisses - prev.CacheMisses - p.cacheHitQPS = delta(prev.CacheHits, p.CacheHits, secs) - p.cacheMissQPS = delta(prev.CacheMisses, p.CacheMisses, secs) - if hits+misses > 0 { - v := 100 * float64(hits) / float64(hits+misses) - p.CacheHitRate = &v - } - } + p.RateLimitedRate = delta(prev.RateLimited, p.RateLimited, secs) + p.SourceAuthRate = delta(prev.Authoritative, p.Authoritative, secs) + p.SourceRecursiveRate = delta(prev.Recursive, p.Recursive, secs) + p.SourceForwardRate = delta(prev.Forward, p.Forward, secs) + p.SourceCacheRate = delta(prev.Cached, p.Cached, secs) + p.CacheHitsRate = delta(prev.CacheHits, p.CacheHits, secs) + p.CacheMissesRate = delta(prev.CacheMisses, p.CacheMisses, secs) + p.CacheEvictionsRate = delta(prev.CacheEvictions, p.CacheEvictions, secs) + p.CacheHitRate = cachePercent(p.CacheHitsRate, p.CacheMissesRate) + p.ErrorRate = errorPercent(p.QueryRate, p.ServFailRate, p.RefusedRate) } h.samples = append(h.samples, p) if len(h.samples) > maxSamples { + // Copy to free old backing arrays rather than retaining unbounded memory. h.samples = append([]Sample(nil), h.samples[len(h.samples)-maxSamples:]...) } h.lastPoll = t @@ -89,22 +124,21 @@ func (h *History) Failed(msg string) { h.mu.Lock(); defer h.mu.Unlock(); h.lastE func (h *History) Snapshot() ([]Sample, string, time.Time) { h.mu.RLock() defer h.mu.RUnlock() - v := append([]Sample(nil), h.samples...) - return v, h.lastErr, h.lastPoll + return append([]Sample(nil), h.samples...), h.lastErr, h.lastPoll } func (h *History) Run(ctx context.Context, c *easydns.Client) { poll := func() { var stats easydns.Stats - ctxReq, cancel := context.WithTimeout(ctx, 8*time.Second) + requestCtx, cancel := context.WithTimeout(ctx, 8*time.Second) defer cancel() - if _, err := c.Get(ctxReq, "/api/v1/stats", &stats); err != nil { + if _, err := c.Get(requestCtx, "/api/v1/stats", &stats); err != nil { h.Failed("API sampling unavailable") return } h.Record(time.Now().UTC(), stats) } poll() - ticker := time.NewTicker(15 * time.Second) + ticker := time.NewTicker(PollInterval) defer ticker.Stop() for { select { diff --git a/internal/telemetry/window.go b/internal/telemetry/window.go new file mode 100644 index 0000000..328ea0f --- /dev/null +++ b/internal/telemetry/window.go @@ -0,0 +1,179 @@ +package telemetry + +import "time" + +// Window specifies only measured history from the Go panel's authenticated +// telemetry endpoint. An explicit step enables server-side downsampling. +// The legacy API with no step parameter keeps its original raw 15 s samples. +type Window struct { + Range string `json:"range"` + Step string `json:"step"` + Span time.Duration `json:"-"` + Bucket time.Duration `json:"-"` + From time.Time `json:"from"` + To time.Time `json:"to"` + StepSeconds int `json:"stepSeconds"` +} + +func ParseWindow(rangeValue, stepValue string, now time.Time) Window { + spans := map[string]time.Duration{"15m": 15 * time.Minute, "1h": time.Hour, "6h": 6 * time.Hour, "12h": 12 * time.Hour, "24h": 24 * time.Hour} + span, ok := spans[rangeValue] + if !ok { + rangeValue = "24h" + span = 24 * time.Hour + } + steps := map[string]time.Duration{"15s": 15 * time.Second, "30s": 30 * time.Second, "1m": time.Minute, "5m": 5 * time.Minute, "15m": 15 * time.Minute, "1h": time.Hour} + if stepValue == "" { + stepValue = "15s" + } // preserve old /ui/telemetry callers + bucket, ok := steps[stepValue] + if stepValue == "auto" { + switch { + case span <= time.Hour: + bucket = 15 * time.Second + case span <= 6*time.Hour: + bucket = time.Minute + default: + bucket = 5 * time.Minute + } + } else if !ok { + stepValue = "auto" + bucket = 5 * time.Minute + if span <= 6*time.Hour { + bucket = time.Minute + } + if span <= time.Hour { + bucket = 15 * time.Second + } + } + if bucket < PollInterval { + bucket = PollInterval + } + return Window{Range: rangeValue, Step: stepValue, Span: span, Bucket: bucket, From: now.Add(-span).UTC(), To: now.UTC(), StepSeconds: int(bucket / time.Second)} +} + +func WindowSamples(samples []Sample, w Window) []Sample { + // Do not exclude a positive clock skew in future samples: the window + // is a lower bound. Visual time clipping uses the independently returned + // 'to' value, so future clocks cannot extend the drawn chart backwards. + filtered := make([]Sample, 0, len(samples)) + for _, p := range samples { + if !p.Time.Before(w.From) { + filtered = append(filtered, p) + } + } + if w.Bucket <= PollInterval { + return filtered + } + out := make([]Sample, 0, len(filtered)) + for start := 0; start < len(filtered); { + end := start + 1 + bucket := filtered[start].Time.UnixNano() / w.Bucket.Nanoseconds() + for end < len(filtered) && filtered[end].Time.UnixNano()/w.Bucket.Nanoseconds() == bucket { + end++ + } + group := filtered[start:end] + point := group[len(group)-1] + avg := func(pick func(Sample) *float64) *float64 { + sum := 0.0 + for _, p := range group { + v := pick(p) + if v == nil { + return nil + } + sum += *v + } + value := sum / float64(len(group)) + return &value + } + point.QueryRate = avg(func(p Sample) *float64 { return p.QueryRate }) + point.NoErrorRate = avg(func(p Sample) *float64 { return p.NoErrorRate }) + point.NXDomainRate = avg(func(p Sample) *float64 { return p.NXDomainRate }) + point.ServFailRate = avg(func(p Sample) *float64 { return p.ServFailRate }) + point.RefusedRate = avg(func(p Sample) *float64 { return p.RefusedRate }) + point.BlockedRate = avg(func(p Sample) *float64 { return p.BlockedRate }) + point.RateLimitedRate = avg(func(p Sample) *float64 { return p.RateLimitedRate }) + point.SourceAuthRate = avg(func(p Sample) *float64 { return p.SourceAuthRate }) + point.SourceRecursiveRate = avg(func(p Sample) *float64 { return p.SourceRecursiveRate }) + point.SourceForwardRate = avg(func(p Sample) *float64 { return p.SourceForwardRate }) + point.SourceCacheRate = avg(func(p Sample) *float64 { return p.SourceCacheRate }) + point.CacheHitsRate = avg(func(p Sample) *float64 { return p.CacheHitsRate }) + point.CacheMissesRate = avg(func(p Sample) *float64 { return p.CacheMissesRate }) + point.CacheEvictionsRate = avg(func(p Sample) *float64 { return p.CacheEvictionsRate }) + point.CacheHitRate = cachePercent(point.CacheHitsRate, point.CacheMissesRate) + point.ErrorRate = errorPercent(point.QueryRate, point.ServFailRate, point.RefusedRate) + for _, p := range group { + if p.P50MS > point.P50MS { + point.P50MS = p.P50MS + } + if p.P95MS > point.P95MS { + point.P95MS = p.P95MS + } + if p.P99MS > point.P99MS { + point.P99MS = p.P99MS + } + } + out = append(out, point) + start = end + } + return out +} + +func WindowFleet(points []FleetPoint, w Window) []FleetPoint { + filtered := make([]FleetPoint, 0, len(points)) + for _, p := range points { + if !p.Time.Before(w.From) { + filtered = append(filtered, p) + } + } + if w.Bucket <= PollInterval { + return filtered + } + out := make([]FleetPoint, 0, len(filtered)) + for start := 0; start < len(filtered); { + end := start + 1 + b := filtered[start].Time.UnixNano() / w.Bucket.Nanoseconds() + for end < len(filtered) && filtered[end].Time.UnixNano()/w.Bucket.Nanoseconds() == b { + end++ + } + group := filtered[start:end] + p := group[len(group)-1] + avg := func(pick func(FleetPoint) *float64) *float64 { + sum := 0.0 + for _, q := range group { + v := pick(q) + if v == nil { + return nil + } + sum += *v + } + v := sum / float64(len(group)) + return &v + } + p.QueryRate = avg(func(s FleetPoint) *float64 { return s.QueryRate }) + p.NoErrorRate = avg(func(s FleetPoint) *float64 { return s.NoErrorRate }) + p.NXDomainRate = avg(func(s FleetPoint) *float64 { return s.NXDomainRate }) + p.ServFailRate = avg(func(s FleetPoint) *float64 { return s.ServFailRate }) + p.RefusedRate = avg(func(s FleetPoint) *float64 { return s.RefusedRate }) + p.BlockedRate = avg(func(s FleetPoint) *float64 { return s.BlockedRate }) + p.RateLimitedRate = avg(func(s FleetPoint) *float64 { return s.RateLimitedRate }) + p.SourceAuthRate = avg(func(s FleetPoint) *float64 { return s.SourceAuthRate }) + p.SourceRecursiveRate = avg(func(s FleetPoint) *float64 { return s.SourceRecursiveRate }) + p.SourceForwardRate = avg(func(s FleetPoint) *float64 { return s.SourceForwardRate }) + p.SourceCacheRate = avg(func(s FleetPoint) *float64 { return s.SourceCacheRate }) + p.CacheHitsRate = avg(func(s FleetPoint) *float64 { return s.CacheHitsRate }) + p.CacheMissesRate = avg(func(s FleetPoint) *float64 { return s.CacheMissesRate }) + p.CacheEvictionsRate = avg(func(s FleetPoint) *float64 { return s.CacheEvictionsRate }) + p.CacheEntries = avg(func(s FleetPoint) *float64 { return s.CacheEntries }) + p.CacheHitRate = cachePercent(p.CacheHitsRate, p.CacheMissesRate) + p.ErrorRate = errorPercent(p.QueryRate, p.ServFailRate, p.RefusedRate) + for _, q := range group { + if q.Contributors < p.Contributors { + p.Contributors = q.Contributors + } + } + out = append(out, p) + start = end + } + return out +} diff --git a/internal/telemetry/window_test.go b/internal/telemetry/window_test.go new file mode 100644 index 0000000..29b93e2 --- /dev/null +++ b/internal/telemetry/window_test.go @@ -0,0 +1,86 @@ +package telemetry + +import ( + "math" + "testing" + "time" + + "git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns" +) + +func TestWindowParsingAndBoundedSampling(t *testing.T) { + now := time.Date(2026, 11, 30, 18, 0, 0, 0, time.UTC) + cases := []struct { + span, step string + seconds int + }{ + {"15m", "auto", 15}, {"1h", "auto", 15}, {"6h", "auto", 60}, {"12h", "auto", 300}, {"24h", "auto", 300}, {"24h", "1h", 3600}, {"invalid", "invalid", 300}, + } + for _, tc := range cases { + w := ParseWindow(tc.span, tc.step, now) + if w.StepSeconds != tc.seconds || w.Span > 24*time.Hour || w.Span < 15*time.Minute || w.From.After(w.To) { + t.Errorf("bad window %+v", w) + } + } + // An old telemetry consumer without step= keeps the original measured rows. + if v := ParseWindow("", "", now); v.StepSeconds != 15 { + t.Fatalf("legacy endpoint changed resolution: %+v", v) + } + h := New() + stats := easydns.Stats{Responses: map[string]uint64{}, Sources: map[string]uint64{}} + for i := 0; i < maxSamples+12; i++ { + stats.QueriesTotal += 15 + h.Record(now.Add(time.Duration(i)*PollInterval), stats) + } + samples, _, _ := h.Snapshot() + if len(samples) != maxSamples { + t.Fatalf("bounded history retained %d not %d", len(samples), maxSamples) + } +} +func TestDownsampleOnlyMeasuredBucketsAndWeightedCache(t *testing.T) { + h := New() + start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC) + mk := func(q, hits, miss uint64, p95 float64) easydns.Stats { + return easydns.Stats{QueriesTotal: q, Responses: map[string]uint64{"noerror": q}, Sources: map[string]uint64{"recursive": q / 2}, Cache: easydns.Cache{Hits: hits, Misses: miss, Entries: 12}, LatencyP95S: p95} + } + h.Record(start.Add(-15*time.Second), mk(100, 0, 0, .005)) + h.Record(start, mk(115, 15, 0, .015)) // 1 QPS, cache 100% + h.Record(start.Add(15*time.Second), mk(145, 15, 30, .030)) // 2 QPS, cache 0% + h.Record(start.Add(61*time.Second), mk(177, 15, 62, .015)) // measured later than 30s + w := ParseWindow("1h", "1m", start.Add(2*time.Minute)) + pts := WindowSamples(historySamples(h), w) + if len(pts) != 3 { + t.Fatalf("expected three observed buckets, got %d: %+v", len(pts), pts) + } + p := pts[1] + if p.QueryRate == nil || math.Abs(*p.QueryRate-1.5) > 1e-8 { + t.Fatalf("downsample must average actual rates, got %+v", p.QueryRate) + } + if p.CacheHitRate == nil || math.Abs(*p.CacheHitRate-100.0/3) > 1e-8 { + t.Fatalf("cache bucket must use weighted hits/misses, got %+v", p.CacheHitRate) + } + if p.P95MS != 30 { + t.Fatalf("peak p95 within bucket lost, got %v", p.P95MS) + } + if p.Time != start.Add(15*time.Second) { + t.Fatalf("bucket fabricated a timestamp: %v", p.Time) + } + // A counter reset marks its bucket as missing, not negative or zero. + h.Record(start.Add(2*time.Minute), mk(0, 0, 0, .005)) + pts = WindowSamples(historySamples(h), w) + for _, pt := range pts { + if pt.Time == start.Add(2*time.Minute) && pt.QueryRate != nil { + t.Fatal("counter reset was turned into a rate") + } + } +} +func TestFleetDownsamplingPreservesIncompleteBuckets(t *testing.T) { + t0 := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC) + x := 1.0 + points := []FleetPoint{{Time: t0, QueryRate: &x, Contributors: 2}, {Time: t0.Add(15 * time.Second), QueryRate: nil, Contributors: 1}} + w := ParseWindow("1h", "1m", t0.Add(time.Minute)) + reduced := WindowFleet(points, w) + if len(reduced) != 1 || reduced[0].QueryRate != nil || reduced[0].Contributors != 1 { + t.Fatalf("missing node hidden by downsample: %+v", reduced) + } +} diff --git a/packaging/easydns-ui.toml b/packaging/easydns-ui.toml index 877cf8b..4242a04 100644 --- a/packaging/easydns-ui.toml +++ b/packaging/easydns-ui.toml @@ -1,4 +1,4 @@ -# EasyDNS Web 0.1.1 — Debian panel configuration. +# EasyDNS Web 0.1.2 — Debian panel configuration. # File: /etc/easydns-ui/config.toml # Edit with sudo; secrets must remain readable only by root and the panel group. # sudo chown root:easydns-ui /etc/easydns-ui/config.toml diff --git a/scripts/build-deb.sh b/scripts/build-deb.sh index 826cd10..ef7854a 100755 --- a/scripts/build-deb.sh +++ b/scripts/build-deb.sh @@ -3,7 +3,7 @@ set -eu ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) ARCH=${GOARCH:-amd64} -VERSION=${VERSION:-0.1.1} +VERSION=${VERSION:-0.1.2-1} case "$ARCH" in amd64|arm64) ;; *) echo "Unsupported architecture: $ARCH (use amd64 or arm64)" >&2; exit 1 ;; @@ -17,7 +17,7 @@ chmod 0755 "$STAGING" mkdir -p "$STAGING/DEBIAN" "$STAGING/usr/bin" "$STAGING/lib/systemd/system" "$STAGING/etc/easydns-ui" "$ROOT/dist" cd "$ROOT" # Each build embeds its own fingerprint into the static asset filenames. -# The package release remains 0.1.1 unless the operator explicitly changes it. +# The package release defaults to 0.1.2-1 unless explicitly overridden. BUILD_ID=${BUILD_ID:-$(date -u +%Y%m%dT%H%M%S)-$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')} case "$BUILD_ID" in ''|*[!A-Za-z0-9._-]*) echo 'Invalid BUILD_ID' >&2; exit 1 ;; diff --git a/scripts/build_deb.sh b/scripts/build_deb.sh index 88c2db4..c49ecb3 100755 --- a/scripts/build_deb.sh +++ b/scripts/build_deb.sh @@ -5,7 +5,7 @@ set -eu ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) IMAGE=${IMAGE:-golang:1.23-bookworm} BUILD_ID=${BUILD_ID:-} -VERSION=${VERSION:-0.1.1} +VERSION=${VERSION:-0.1.2-1} ARCH=${ARCH:-${GOARCH:-all}} usage() { @@ -17,7 +17,7 @@ on the host; Go, dpkg-deb, and cross-compilation tools run in the container. Options: --arch Architectures to build (default: all = amd64 + arm64) - --version Debian package version (default: 0.1.1) + --version Debian package version (default: 0.1.2-1) --image Debian-based Go image (default: golang:1.23-bookworm) --build-id Optional unique build stamp for hashed static filenames -h, --help Show this message @@ -27,7 +27,7 @@ Packages are written to ./dist/easydns-ui_VERSION_ARCH.deb. Examples: ./scripts/build_deb.sh - ./scripts/build_deb.sh --arch amd64 --version 0.1.1 + ./scripts/build_deb.sh --arch amd64 --version 0.1.2-1 IMAGE=golang:1.23-bookworm ./scripts/build_deb.sh --arch arm64 HELP }