164 lines
5.5 KiB
Go
164 lines
5.5 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"math"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
|
|
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/multiserver"
|
|
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry"
|
|
)
|
|
|
|
const metricsModeCookie = "easydns_ui_metrics_mode"
|
|
|
|
// The mode is a presentation setting, not a DNS configuration operation.
|
|
// With Multi-server disabled the legacy single-node view is unchanged.
|
|
func (s *Server) metricsMode(w http.ResponseWriter, r *http.Request) string {
|
|
if !s.nodes.Enabled() || len(s.nodes.All()) < 2 {
|
|
return "single"
|
|
}
|
|
if _, explicit := r.URL.Query()["mode"]; explicit {
|
|
v := r.URL.Query().Get("mode")
|
|
if validMetricsMode(v) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: metricsModeCookie, Value: v, Path: "/metrics", HttpOnly: true,
|
|
Secure: s.cfg.CookieSecure, SameSite: http.SameSiteLaxMode,
|
|
MaxAge: 365 * 24 * 60 * 60,
|
|
})
|
|
return v
|
|
}
|
|
}
|
|
if c, err := r.Cookie(metricsModeCookie); err == nil && validMetricsMode(c.Value) {
|
|
return c.Value
|
|
}
|
|
return "aggregate"
|
|
}
|
|
|
|
func validMetricsMode(s string) bool {
|
|
return s == "single" || s == "split" || s == "aggregate"
|
|
}
|
|
|
|
type FleetMetricsNode struct {
|
|
Node multiserver.Node
|
|
Stats easydns.Stats
|
|
Available bool
|
|
Error string
|
|
Samples int
|
|
LastPoll time.Time
|
|
LastError string
|
|
}
|
|
|
|
// fetchFleetMetrics reads the *existing* EasyDNS /api/v1/stats endpoint on
|
|
// each node concurrently, never writes to DNS. Incomplete fleet totals are
|
|
// explicitly marked as partial in the UI; nonadditive latency is not summed.
|
|
func (s *Server) fetchFleetMetrics(ctx context.Context) ([]FleetMetricsNode, easydns.Stats, int, bool) {
|
|
all := s.nodes.All()
|
|
result := make([]FleetMetricsNode, len(all))
|
|
var wg sync.WaitGroup
|
|
for i, n := range all {
|
|
wg.Add(1)
|
|
go func(i int, node multiserver.Node) {
|
|
defer wg.Done()
|
|
item := FleetMetricsNode{Node: node}
|
|
_, api, history, ok := s.nodes.Get(node.ID)
|
|
if !ok {
|
|
item.Error = "Server connection was removed"
|
|
result[i] = item
|
|
return
|
|
}
|
|
current, sampleError, last := history.Snapshot()
|
|
item.LastPoll, item.LastError = last, sampleError
|
|
item.Samples = len(current)
|
|
reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if _, err := api.Get(reqCtx, "/api/v1/stats", &item.Stats); err != nil {
|
|
item.Error = "Stats request failed: " + err.Error()
|
|
} else {
|
|
item.Available = true
|
|
}
|
|
result[i] = item
|
|
}(i, n)
|
|
}
|
|
wg.Wait()
|
|
|
|
total := easydns.Stats{Responses: map[string]uint64{}, Sources: map[string]uint64{}}
|
|
online := 0
|
|
for _, n := range result {
|
|
if !n.Available {
|
|
continue
|
|
}
|
|
online++
|
|
st := n.Stats
|
|
total.QueriesTotal = saturatingAdd(total.QueriesTotal, st.QueriesTotal)
|
|
total.Blocked = saturatingAdd(total.Blocked, st.Blocked)
|
|
total.RateLimited = saturatingAdd(total.RateLimited, st.RateLimited)
|
|
for k, v := range st.Responses {
|
|
total.Responses[k] = saturatingAdd(total.Responses[k], v)
|
|
}
|
|
for k, v := range st.Sources {
|
|
total.Sources[k] = saturatingAdd(total.Sources[k], v)
|
|
}
|
|
total.Cache.Entries = saturatingAdd(total.Cache.Entries, st.Cache.Entries)
|
|
total.Cache.Hits = saturatingAdd(total.Cache.Hits, st.Cache.Hits)
|
|
total.Cache.Misses = saturatingAdd(total.Cache.Misses, st.Cache.Misses)
|
|
total.Cache.Evictions = saturatingAdd(total.Cache.Evictions, st.Cache.Evictions)
|
|
}
|
|
var cacheRateAvailable bool
|
|
if total.Cache.Hits > 0 || total.Cache.Misses > 0 {
|
|
total.CacheHitRate = float64(total.Cache.Hits) / (float64(total.Cache.Hits) + float64(total.Cache.Misses))
|
|
cacheRateAvailable = true
|
|
}
|
|
return result, total, online, cacheRateAvailable
|
|
}
|
|
|
|
func saturatingAdd(a, b uint64) uint64 {
|
|
if math.MaxUint64-a < b {
|
|
return math.MaxUint64
|
|
}
|
|
return a + b
|
|
}
|
|
|
|
// 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, 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 {
|
|
_, _, history, ok := s.nodes.Get(n.ID)
|
|
if !ok {
|
|
// Preserve the node as a missing contributor when it is removed
|
|
// concurrently with this request. Never display a partial total.
|
|
nodes = append(nodes, telemetry.FleetNode{ID: n.ID, Name: n.Name, Role: n.Role, Error: "Server connection no longer available"})
|
|
continue
|
|
}
|
|
samples, errText, last := history.Snapshot()
|
|
nodes = append(nodes, telemetry.FleetNode{
|
|
ID: n.ID, Name: n.Name, Role: n.Role,
|
|
Samples: samples, Error: errText, LastPoll: last,
|
|
})
|
|
}
|
|
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" {
|
|
// 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)
|
|
}
|