Registry: trend chart, always-pass indicator, subnet columns in the address list dialog
- Registry: "Динамика по запускам" chart (Chart.js 4.5.1, vendored) over finalized runs per target or site, % or count, subnet and calendar period filters; GET /admin/registry/trend - Registry: clickable "Всегда проходили" indicator with the address list and CSV; GET /admin/registry/always-pass and /always-pass/list - Address list dialog: "Подсеть" and "Метка подсети" columns from the administrator's subnet list (shared db.SubnetMatcher), per-subnet summary chips with a client-side filter; "прочие" renamed to "вне списка подсетей" - Rebuild control-api and admin-dashboard binaries; plans and summaries in docs/changes, README, API and USAGE updated Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c13139cd41
commit
1536723196
50 files changed
+3560
-154
No files matched your search
@@ -97,8 +97,8 @@ func TestRouteTableIsClassified(t *testing.T) {
|
||||
t.Fatalf("admin route %q is %s, want admin", rt.Pattern, rt.Access)
|
||||
}
|
||||
}
|
||||
if counts["admin"] != 43 || counts["agent"] != 5 || counts["open"] != 8 {
|
||||
t.Fatalf("access counts = %v, want admin=43 agent=5 open=8", counts)
|
||||
if counts["admin"] != 46 || counts["agent"] != 5 || counts["open"] != 8 {
|
||||
t.Fatalf("access counts = %v, want admin=46 agent=5 open=8", counts)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,59 @@ type breakdownRowDTO struct {
|
||||
OK int `json:"ok"`
|
||||
}
|
||||
|
||||
// registryTrendDTO is GET /admin/registry/trend: the checks of one direction
|
||||
// (and protocol) per target (group "target", egress) or site (group "site",
|
||||
// ingress) in each finalized run, oldest run first. From and To echo the period
|
||||
// (YYYY-MM-DD, empty = open); Truncated says that older runs than Runs were left
|
||||
// out. A series has a point only for the runs where its key has checks; Total
|
||||
// counts checks, OK the successful ones.
|
||||
type registryTrendDTO struct {
|
||||
Group string `json:"group"`
|
||||
Direction string `json:"direction"`
|
||||
Protocol string `json:"protocol"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Runs []trendRunDTO `json:"runs"`
|
||||
Series []trendSeriesDTO `json:"series"`
|
||||
}
|
||||
|
||||
// registryAlwaysPassDTO is GET /admin/registry/always-pass: of the Addresses that
|
||||
// have checks of the direction (and protocol) in the Runs of the period, how
|
||||
// many never failed one. From and To echo the period; FirstRunAt and LastRunAt
|
||||
// are the start of the oldest and the newest run (null without runs).
|
||||
type registryAlwaysPassDTO struct {
|
||||
Direction string `json:"direction"`
|
||||
Protocol string `json:"protocol"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Runs int `json:"runs"`
|
||||
FirstRunAt *time.Time `json:"first_run_at"`
|
||||
LastRunAt *time.Time `json:"last_run_at"`
|
||||
Addresses int `json:"addresses"`
|
||||
AlwaysPass int `json:"always_pass"`
|
||||
}
|
||||
|
||||
type trendRunDTO struct {
|
||||
ID int64 `json:"id"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinalizedAt *time.Time `json:"finalized_at"`
|
||||
Addresses int `json:"addresses"`
|
||||
}
|
||||
|
||||
type trendSeriesDTO struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Points []trendPointDTO `json:"points"`
|
||||
}
|
||||
|
||||
type trendPointDTO struct {
|
||||
RunID int64 `json:"run_id"`
|
||||
Total int `json:"total"`
|
||||
OK int `json:"ok"`
|
||||
}
|
||||
|
||||
// registryDTO is one row of the durable per-address registry — see
|
||||
// db.RegistrySummary.
|
||||
type registryDTO struct {
|
||||
|
||||
@@ -232,7 +232,7 @@ func TestAnalyticsCompareEndpoints(t *testing.T) {
|
||||
}
|
||||
resp, body = fc.do(http.MethodGet, cmp+"/lists/changed"+q, nil)
|
||||
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || l.Group != "changed" || len(l.Rows) != 1 ||
|
||||
l.Rows[0][0] != "9.9.9.2" || !strings.HasPrefix(l.Rows[0][2], "partial → pass") {
|
||||
l.Rows[0][0] != "9.9.9.2" || !strings.HasPrefix(l.Rows[0][3], "partial → pass") {
|
||||
t.Fatalf("changed list: %d %s", resp.StatusCode, body)
|
||||
}
|
||||
resp, body = fc.do(http.MethodGet, cmp+"/lists/new"+q+"&indicator=verdict_partial", nil)
|
||||
@@ -535,7 +535,7 @@ func TestRegistryBreakdownEndpoints(t *testing.T) {
|
||||
if err := json.Unmarshal(body, &l); err != nil || resp.StatusCode != http.StatusOK || len(l.Rows) != 2 || len(l.Rows[0]) != len(l.Columns) {
|
||||
t.Fatalf("list: %d %s", resp.StatusCode, body)
|
||||
}
|
||||
if r := l.Rows[0]; r[0] != "9.9.9.2" || r[1] != "провал" || r[3] != "rxmsk" || r[5] != "dial tcp: i/o timeout" {
|
||||
if r := l.Rows[0]; r[0] != "9.9.9.2" || r[1] != "9.9.9.0/24" || r[3] != "провал" || r[5] != "rxmsk" || r[7] != "dial tcp: i/o timeout" {
|
||||
t.Errorf("failure must come first: %v", r)
|
||||
}
|
||||
resp, body = fc.do(http.MethodGet, listURL+"&format=csv", nil)
|
||||
@@ -547,3 +547,68 @@ func TestRegistryBreakdownEndpoints(t *testing.T) {
|
||||
t.Errorf("unknown key: %d, want 404", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// The trend endpoint: 400 without a direction, with a malformed or reversed
|
||||
// period, and the shape of the series (site names, run list).
|
||||
func TestRegistryTrendEndpoint(t *testing.T) {
|
||||
fc, d, _, _ := newConfigTestHarness(t)
|
||||
fc.do(http.MethodPut, "/api/v1/admin/config/sites/1", putSiteRequest{SiteID: "rxmsk"})
|
||||
id := finishedRun(t, d)
|
||||
const base = "/api/v1/admin/registry/trend"
|
||||
|
||||
for _, bad := range []string{"", "?protocol=ssh", "?direction=up", "?direction=egress&from=2026-13-01", "?direction=egress&from=2026-10-02&to=2026-10-01"} {
|
||||
if resp, _ := fc.do(http.MethodGet, base+bad, nil); resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("%q: %d, want 400", bad, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
resp, body := fc.do(http.MethodGet, base+"?direction=ingress&protocol=ssh&run=999", nil)
|
||||
var tr registryTrendDTO
|
||||
if err := json.Unmarshal(body, &tr); err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("trend: %d %s", resp.StatusCode, body)
|
||||
}
|
||||
if tr.Group != "site" || tr.Direction != "ingress" || tr.Protocol != "ssh" || tr.Truncated || len(tr.Runs) != 1 || tr.Runs[0].ID != id || tr.Runs[0].Addresses != 2 ||
|
||||
len(tr.Series) != 1 || tr.Series[0].Label != "rxmsk" || !reflect.DeepEqual(tr.Series[0].Points, []trendPointDTO{{RunID: id, Total: 2, OK: 1}}) {
|
||||
t.Errorf("trend = %+v", tr)
|
||||
}
|
||||
if resp, body = fc.do(http.MethodGet, base+"?direction=egress&from=2000-01-01&to=2000-01-02", nil); resp.StatusCode != http.StatusOK ||
|
||||
!strings.Contains(string(body), `"runs":[]`) || !strings.Contains(string(body), `"series":[]`) {
|
||||
t.Errorf("empty period: %d %s", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
// The always-pass endpoints: 400 without a direction or with a bad period, the
|
||||
// shape of the counts, and the list and its CSV by ascending IP.
|
||||
func TestRegistryAlwaysPassEndpoint(t *testing.T) {
|
||||
fc, d, _, _ := newConfigTestHarness(t)
|
||||
id := finishedRun(t, d)
|
||||
const base = "/api/v1/admin/registry/always-pass"
|
||||
|
||||
for _, bad := range []string{"", "?protocol=ssh", "?direction=egress&from=2026-13-01", "?direction=egress&from=2026-10-02&to=2026-10-01"} {
|
||||
for _, p := range []string{base, base + "/list"} {
|
||||
if resp, _ := fc.do(http.MethodGet, p+bad, nil); resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("%s%q: %d, want 400", p, bad, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
resp, body := fc.do(http.MethodGet, base+"?direction=ingress&protocol=ssh&run=999&status=fail", nil)
|
||||
var ap registryAlwaysPassDTO
|
||||
if err := json.Unmarshal(body, &ap); err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("always-pass: %d %s", resp.StatusCode, body)
|
||||
}
|
||||
if ap.Direction != "ingress" || ap.Protocol != "ssh" || ap.Runs != 1 || ap.Addresses != 2 || ap.AlwaysPass != 1 || ap.FirstRunAt == nil || ap.LastRunAt == nil || ap.Truncated {
|
||||
t.Errorf("always-pass = %+v (run %d)", ap, id)
|
||||
}
|
||||
resp, body = fc.do(http.MethodGet, base+"/list?direction=ingress&protocol=ssh", nil)
|
||||
var l struct {
|
||||
Columns []string `json:"columns"`
|
||||
Rows [][]string `json:"rows"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &l); err != nil || resp.StatusCode != http.StatusOK || len(l.Columns) != 8 || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.1" || l.Rows[0][1] != "9.9.9.0/24" || l.Rows[0][3] != "1" {
|
||||
t.Errorf("list: %d %s", resp.StatusCode, body)
|
||||
}
|
||||
resp, body = fc.do(http.MethodGet, base+"/list?direction=egress&format=csv", nil)
|
||||
if !strings.HasPrefix(string(body), "\xef\xbb\xbf") || !strings.Contains(string(body), "9.9.9.1") || !strings.Contains(string(body), "9.9.9.2") ||
|
||||
!strings.Contains(resp.Header.Get("Content-Disposition"), "registry_always_pass_egress_.csv") {
|
||||
t.Errorf("csv: %v %q", resp.Header, body)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cloudipvalidator/internal/analytics"
|
||||
"cloudipvalidator/internal/db"
|
||||
@@ -240,11 +241,17 @@ func (s *Server) handleAdminRegistryBreakdownList(w http.ResponseWriter, r *http
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
subnets, err := s.DB.ListSubnets(r.Context())
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
matcher := db.NewSubnetMatcher(subnets)
|
||||
group := db.BreakdownTarget
|
||||
columns := []string{"Адрес", "Результат", "Тип проверки", "Цель", "Валидатор", "Задержка, мс", "Детали", "Проверено (UTC)"}
|
||||
columns := []string{"Адрес", "Подсеть", "Метка подсети", "Результат", "Тип проверки", "Цель", "Валидатор", "Задержка, мс", "Детали", "Проверено (UTC)"}
|
||||
if f.Level == db.LevelIngress {
|
||||
group = db.BreakdownSite
|
||||
columns = []string{"Адрес", "Результат", "Тип проверки", "Площадка", "Задержка, мс", "Детали", "Проверено (UTC)"}
|
||||
columns = []string{"Адрес", "Подсеть", "Метка подсети", "Результат", "Тип проверки", "Площадка", "Задержка, мс", "Детали", "Проверено (UTC)"}
|
||||
}
|
||||
rows := make([][]string, len(checks))
|
||||
for i, c := range checks {
|
||||
@@ -252,7 +259,8 @@ func (s *Server) handleAdminRegistryBreakdownList(w http.ResponseWriter, r *http
|
||||
if c.Success {
|
||||
result = "успешно"
|
||||
}
|
||||
row := []string{c.IPAddress, result, c.CheckType, breakdownLabel(group, key, names)}
|
||||
cidr, label := matcher.Lookup(c.IPAddress)
|
||||
row := []string{c.IPAddress, cidr, label, result, c.CheckType, breakdownLabel(group, key, names)}
|
||||
if group == db.BreakdownTarget {
|
||||
row = append(row, analytics.ShortValidator(c.ValidatorID))
|
||||
}
|
||||
@@ -267,3 +275,146 @@ func (s *Server) handleAdminRegistryBreakdownList(w http.ResponseWriter, r *http
|
||||
Rows [][]string `json:"rows"`
|
||||
}{columns, rows})
|
||||
}
|
||||
|
||||
// parseTrendDate reads a YYYY-MM-DD parameter of the trend; empty is nil.
|
||||
func parseTrendDate(q url.Values, name string) (*time.Time, string) {
|
||||
v := q.Get(name)
|
||||
if v == "" {
|
||||
return nil, ""
|
||||
}
|
||||
t, err := time.Parse("2006-01-02", v)
|
||||
if err != nil {
|
||||
return nil, "invalid " + name + " " + strconv.Quote(v) + " (YYYY-MM-DD is expected)"
|
||||
}
|
||||
return &t, ""
|
||||
}
|
||||
|
||||
// periodFor reads the filter and the period (from/to, YYYY-MM-DD) of the trend
|
||||
// and always-pass endpoints, which need a direction, and writes the 400
|
||||
// response itself when it cannot.
|
||||
func periodFor(w http.ResponseWriter, r *http.Request) (f db.RegistryFilter, from, to *time.Time, ok bool) {
|
||||
q := r.URL.Query()
|
||||
f, msg := parseRegistryFilter(q)
|
||||
if msg == "" && f.Level == "" {
|
||||
msg = "direction is required"
|
||||
}
|
||||
from, fmsg := parseTrendDate(q, "from")
|
||||
to, tmsg := parseTrendDate(q, "to")
|
||||
switch {
|
||||
case msg != "":
|
||||
case fmsg != "":
|
||||
msg = fmsg
|
||||
case tmsg != "":
|
||||
msg = tmsg
|
||||
case from != nil && to != nil && from.After(*to):
|
||||
msg = "from is after to"
|
||||
}
|
||||
if msg != "" {
|
||||
writeError(w, http.StatusBadRequest, msg)
|
||||
return f, nil, nil, false
|
||||
}
|
||||
return f, from, to, true
|
||||
}
|
||||
|
||||
// handleAdminRegistryTrend returns the dynamics of the checks of one direction
|
||||
// (required) and protocol over the finalized runs: a series per target (egress)
|
||||
// or site (ingress). Filters: direction, protocol, subnet and the period
|
||||
// from/to (YYYY-MM-DD, UTC, to inclusive); the run, status and address filters
|
||||
// are ignored. Without a period the last 30 runs are returned, at most 200
|
||||
// with one; see db.RegistryTrend.
|
||||
func (s *Server) handleAdminRegistryTrend(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
f, from, to, ok := periodFor(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
t, err := s.DB.RegistryTrend(r.Context(), f, from, to)
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
names, err := s.siteNames(r)
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
out := registryTrendDTO{Group: t.Group, Direction: f.Level, Protocol: f.Family, From: q.Get("from"), To: q.Get("to"),
|
||||
Truncated: t.Truncated, Runs: make([]trendRunDTO, len(t.Runs)), Series: []trendSeriesDTO{}}
|
||||
for i, x := range t.Runs {
|
||||
out.Runs[i] = trendRunDTO{ID: x.ID, StartedAt: x.StartedAt, FinalizedAt: x.FinalizedAt, Addresses: x.Addresses}
|
||||
}
|
||||
// Points arrive grouped by key; the series are ordered by successful checks,
|
||||
// most first, then by label, as the breakdown rows.
|
||||
okSum := map[string]int{}
|
||||
for _, p := range t.Points {
|
||||
if n := len(out.Series); n == 0 || out.Series[n-1].Key != p.Key {
|
||||
out.Series = append(out.Series, trendSeriesDTO{Key: p.Key, Label: breakdownLabel(t.Group, p.Key, names)})
|
||||
}
|
||||
sr := &out.Series[len(out.Series)-1]
|
||||
sr.Points = append(sr.Points, trendPointDTO{RunID: p.RunID, Total: p.Total, OK: p.OK})
|
||||
okSum[p.Key] += p.OK
|
||||
}
|
||||
sort.SliceStable(out.Series, func(i, j int) bool {
|
||||
a, b := out.Series[i], out.Series[j]
|
||||
if okSum[a.Key] != okSum[b.Key] {
|
||||
return okSum[a.Key] > okSum[b.Key]
|
||||
}
|
||||
return a.Label < b.Label
|
||||
})
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// handleAdminRegistryAlwaysPass counts the addresses that passed every check of
|
||||
// one direction (required) and protocol during the period: the same runs as
|
||||
// the trend, filters direction, protocol, subnet, q and from/to; the run and
|
||||
// status filters are ignored. See db.RegistryAlwaysPass.
|
||||
func (s *Server) handleAdminRegistryAlwaysPass(w http.ResponseWriter, r *http.Request) {
|
||||
f, from, to, ok := periodFor(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ap, err := s.DB.RegistryAlwaysPass(r.Context(), f, from, to)
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
writeJSON(w, http.StatusOK, registryAlwaysPassDTO{Direction: f.Level, Protocol: f.Family, From: q.Get("from"), To: q.Get("to"),
|
||||
Truncated: ap.Truncated, Runs: ap.Runs, FirstRunAt: ap.FirstRunAt, LastRunAt: ap.LastRunAt, Addresses: ap.Addresses, AlwaysPass: ap.Passed})
|
||||
}
|
||||
|
||||
// handleAdminRegistryAlwaysPassList serves the addresses behind the always-pass
|
||||
// indicator (same parameters) as a table by ascending IP, or with ?format=csv
|
||||
// as a downloadable CSV file.
|
||||
func (s *Server) handleAdminRegistryAlwaysPassList(w http.ResponseWriter, r *http.Request) {
|
||||
f, from, to, ok := periodFor(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
list, runs, err := s.DB.RegistryAlwaysPassList(r.Context(), f, from, to)
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
subnets, err := s.DB.ListSubnets(r.Context())
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
matcher := db.NewSubnetMatcher(subnets)
|
||||
columns := []string{"Адрес", "Подсеть", "Метка подсети", "Запусков с проверками", "Запусков в периоде", "Проверок (все успешны)", "Первый запуск (UTC)", "Последний запуск (UTC)"}
|
||||
rows := make([][]string, len(list))
|
||||
for i, x := range list {
|
||||
cidr, label := matcher.Lookup(x.IPAddress)
|
||||
rows[i] = []string{x.IPAddress, cidr, label, strconv.Itoa(x.RunsChecked), strconv.Itoa(runs), strconv.Itoa(x.Checks),
|
||||
x.FirstRunAt.UTC().Format("2006-01-02 15:04:05"), x.LastRunAt.UTC().Format("2006-01-02 15:04:05")}
|
||||
}
|
||||
if r.URL.Query().Get("format") == "csv" {
|
||||
writeCSV(w, columns, rows, fmt.Sprintf("registry_always_pass_%s_%s.csv", f.Level, f.Family))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Columns []string `json:"columns"`
|
||||
Rows [][]string `json:"rows"`
|
||||
}{columns, rows})
|
||||
}
|
||||
@@ -66,6 +66,9 @@ func (s *Server) routeTable() []route {
|
||||
{"GET /api/v1/admin/registry", s.handleAdminRegistry, accessAdmin},
|
||||
{"GET /api/v1/admin/registry/breakdown", s.handleAdminRegistryBreakdown, accessAdmin},
|
||||
{"GET /api/v1/admin/registry/breakdown/list", s.handleAdminRegistryBreakdownList, accessAdmin},
|
||||
{"GET /api/v1/admin/registry/always-pass", s.handleAdminRegistryAlwaysPass, accessAdmin},
|
||||
{"GET /api/v1/admin/registry/always-pass/list", s.handleAdminRegistryAlwaysPassList, accessAdmin},
|
||||
{"GET /api/v1/admin/registry/trend", s.handleAdminRegistryTrend, accessAdmin},
|
||||
{"GET /api/v1/admin/registry/{ip}", s.handleAdminRegistryHistory, accessAdmin},
|
||||
{"GET /api/v1/admin/analytics/runs", s.handleAnalyticsRuns, accessAdmin},
|
||||
{"GET /api/v1/admin/analytics/runs/{id}", s.handleAnalyticsRun, accessAdmin},
|
||||
|
||||
Reference in new issue
Block a user