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
@@ -0,0 +1,145 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AlwaysPass is the always-pass indicator of a registry period: of the
|
||||
// Addresses that have checks in the slice during the Runs of the period, Passed
|
||||
// never failed one. FirstRunAt and LastRunAt are the start of the oldest and the
|
||||
// newest run of the period (nil without runs).
|
||||
type AlwaysPass struct {
|
||||
Runs int
|
||||
Truncated bool
|
||||
FirstRunAt *time.Time
|
||||
LastRunAt *time.Time
|
||||
Addresses int
|
||||
Passed int
|
||||
}
|
||||
|
||||
// AlwaysPassRow is one address that passed every check of the slice: in how many
|
||||
// runs it was checked, how many checks that made, and the first and the last of
|
||||
// those runs.
|
||||
type AlwaysPassRow struct {
|
||||
IPAddress string
|
||||
RunsChecked int
|
||||
Checks int
|
||||
FirstRunAt time.Time
|
||||
LastRunAt time.Time
|
||||
}
|
||||
|
||||
// alwaysPassScan is the per-address result of alwaysPassRows.
|
||||
type alwaysPassScan struct {
|
||||
ip string
|
||||
runs, total, ok int
|
||||
first, last time.Time
|
||||
}
|
||||
|
||||
// alwaysPassRows reads, for the runs of the period [from, to] (as in
|
||||
// RegistryTrend), the checks of f.Level (required, else ErrValidation) and
|
||||
// optionally f.Family of every address inside f.Subnet whose IP contains
|
||||
// f.Query, one row per address with at least one such check, ordered by IP. As
|
||||
// in RegistryTrend it reads the address's cycle in the run.
|
||||
func (d *DB) alwaysPassRows(ctx context.Context, f RegistryFilter, from, to *time.Time) ([]TrendRun, bool, []alwaysPassScan, error) {
|
||||
sl := registrySlice{Level: f.Level, Family: f.Family}
|
||||
if err := sl.validate(); err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
if sl.Level == "" {
|
||||
return nil, false, nil, fmt.Errorf("direction is required: %w", ErrValidation)
|
||||
}
|
||||
runs, truncated, err := d.trendRuns(ctx, from, to)
|
||||
if err != nil || len(runs) == 0 {
|
||||
return runs, truncated, nil, err
|
||||
}
|
||||
cond, args, ok, err := d.trendRunsCond(ctx, runs, f.Subnet)
|
||||
if err != nil || !ok {
|
||||
return runs, truncated, nil, err
|
||||
}
|
||||
if f.Query != "" {
|
||||
cond += ` AND instr(r.ip_address, ?) > 0`
|
||||
args = append(args, f.Query)
|
||||
}
|
||||
started := make(map[int64]time.Time, len(runs))
|
||||
for _, r := range runs {
|
||||
started[r.ID] = r.StartedAt
|
||||
}
|
||||
|
||||
// CROSS JOIN keeps the checks as the inner table, as in RegistryTrend: the
|
||||
// run's results drive the lookups over idx_checks_run.
|
||||
sc, scArgs := sl.scopeCond()
|
||||
rows, err := d.QueryContext(ctx, `
|
||||
SELECT r.ip_address, COUNT(DISTINCT rr.run_id), COUNT(*), COALESCE(SUM(c.success), 0), MIN(rr.run_id), MAX(rr.run_id)
|
||||
FROM run_results rr
|
||||
JOIN ip_registry r ON r.id = rr.registry_id
|
||||
CROSS JOIN checks c ON c.run_id = rr.run_id AND c.registry_id = rr.registry_id AND c.cycle_id = rr.cycle_id
|
||||
WHERE `+cond+` AND `+sc+` GROUP BY rr.registry_id`, append(args, scArgs...)...)
|
||||
if err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []alwaysPassScan
|
||||
for rows.Next() {
|
||||
var s alwaysPassScan
|
||||
var first, last int64
|
||||
if err := rows.Scan(&s.ip, &s.runs, &s.total, &s.ok, &first, &last); err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
s.first, s.last = started[first], started[last]
|
||||
out = append(out, s)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
a, errA := netip.ParseAddr(out[i].ip)
|
||||
b, errB := netip.ParseAddr(out[j].ip)
|
||||
if errA != nil || errB != nil {
|
||||
return out[i].ip < out[j].ip
|
||||
}
|
||||
return a.Less(b)
|
||||
})
|
||||
return runs, truncated, out, nil
|
||||
}
|
||||
|
||||
// RegistryAlwaysPass counts, over the finalized runs of the period [from, to]
|
||||
// (as RegistryTrend picks them), the addresses that have checks of f.Level
|
||||
// (required) and f.Family in the slice and the ones among them that never
|
||||
// failed one. Subnet, Level, Family and Query of f count; the run and status
|
||||
// filters do not, as a verdict of the current cycle says nothing of a history.
|
||||
func (d *DB) RegistryAlwaysPass(ctx context.Context, f RegistryFilter, from, to *time.Time) (*AlwaysPass, error) {
|
||||
runs, truncated, scans, err := d.alwaysPassRows(ctx, f, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ap := &AlwaysPass{Runs: len(runs), Truncated: truncated, Addresses: len(scans)}
|
||||
if n := len(runs); n > 0 {
|
||||
ap.FirstRunAt, ap.LastRunAt = &runs[0].StartedAt, &runs[n-1].StartedAt
|
||||
}
|
||||
for _, s := range scans {
|
||||
if s.ok == s.total {
|
||||
ap.Passed++
|
||||
}
|
||||
}
|
||||
return ap, nil
|
||||
}
|
||||
|
||||
// RegistryAlwaysPassList returns the addresses RegistryAlwaysPass counts as
|
||||
// passed, by ascending IP, and the number of runs in the period.
|
||||
func (d *DB) RegistryAlwaysPassList(ctx context.Context, f RegistryFilter, from, to *time.Time) ([]AlwaysPassRow, int, error) {
|
||||
runs, _, scans, err := d.alwaysPassRows(ctx, f, from, to)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var out []AlwaysPassRow
|
||||
for _, s := range scans {
|
||||
if s.ok == s.total {
|
||||
out = append(out, AlwaysPassRow{IPAddress: s.ip, RunsChecked: s.runs, Checks: s.total, FirstRunAt: s.first, LastRunAt: s.last})
|
||||
}
|
||||
}
|
||||
return out, len(runs), nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RegistryAlwaysPass and its list over two finalized runs and an open one: an
|
||||
// address checked in only some runs still counts, one failure rules it out, an
|
||||
// address without checks of the slice is not counted; the filters, the period
|
||||
// and validation.
|
||||
func TestRegistryAlwaysPass(t *testing.T) {
|
||||
d, ctx := newTestDB(t)
|
||||
const a1, a2, a3, a4, a5 = "10.0.0.1", "10.0.0.2", "10.0.1.1", "10.0.1.2", "10.0.0.5"
|
||||
// run 1: a2 fails T2 (and passes in run 2); a4 has only an ingress check.
|
||||
submit(t, d, RunManual, a1, a2, a3, a4)
|
||||
addCheck(t, d, a1, SourceEgress, "https", "T1", true)
|
||||
addCheck(t, d, a1, SourceEgress, "https", "T2", true)
|
||||
addCheck(t, d, a2, SourceEgress, "https", "T1", true)
|
||||
addCheck(t, d, a2, SourceEgress, "https", "T2", false)
|
||||
addCheck(t, d, a3, SourceEgress, "https", "T1", true)
|
||||
addCheck(t, d, a4, InboundSource(1), "tcp-22", a4, true)
|
||||
for _, a := range []string{a1, a2, a3, a4} {
|
||||
finish(t, d, a, ResultPartial, -1)
|
||||
}
|
||||
// run 2: a1 only on T1, a2 clean, a5 is new.
|
||||
submit(t, d, RunManual, a1, a2, a5)
|
||||
for _, a := range []string{a1, a2, a5} {
|
||||
addCheck(t, d, a, SourceEgress, "https", "T1", true)
|
||||
finish(t, d, a, ResultPass, -1)
|
||||
}
|
||||
submit(t, d, RunManual, a1) // open: never counted
|
||||
rs := runs(t, d)
|
||||
if len(rs) != 3 || rs[0].State != RunOpen {
|
||||
t.Fatalf("runs: %+v", rs)
|
||||
}
|
||||
r1, r2 := rs[2].ID, rs[1].ID
|
||||
for i, day := range []string{"2026-09-01T10:00:00Z", "2026-09-05T12:00:00Z"} {
|
||||
if _, err := d.ExecContext(ctx, `UPDATE check_runs SET started_at = ? WHERE id = ?`, day, []int64{r1, r2}[i]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
day := func(s string) *time.Time {
|
||||
v, err := time.Parse("2006-01-02", s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &v
|
||||
}
|
||||
eg := RegistryFilter{Level: LevelEgress, Family: "https"}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
f RegistryFilter
|
||||
from, to *time.Time
|
||||
runs, m int
|
||||
passed []string
|
||||
checksFirst int // checks of the first passed address
|
||||
runsOfFirst int
|
||||
firstRunDate string
|
||||
}{
|
||||
{"all runs", eg, nil, nil, 2, 4, []string{a1, a5, a3}, 3, 2, "2026-09-01"},
|
||||
{"no protocol, run and status ignored", RegistryFilter{Level: LevelEgress, RunID: 99, LastResult: ResultFail}, nil, nil, 2, 4, []string{a1, a5, a3}, 3, 2, "2026-09-01"},
|
||||
{"subnet", RegistryFilter{Level: LevelEgress, Family: "https", Subnet: "10.0.1.0/24"}, nil, nil, 2, 1, []string{a3}, 1, 1, "2026-09-01"},
|
||||
{"address search", RegistryFilter{Level: LevelEgress, Query: "0.0.5"}, nil, nil, 2, 1, []string{a5}, 1, 1, "2026-09-05"},
|
||||
{"period: the failure is outside", eg, day("2026-09-02"), day("2026-09-05"), 1, 3, []string{a1, a2, a5}, 1, 1, "2026-09-05"},
|
||||
{"ingress", RegistryFilter{Level: LevelIngress, Family: "tcp"}, nil, nil, 2, 1, []string{a4}, 1, 1, "2026-09-01"},
|
||||
{"protocol without checks", RegistryFilter{Level: LevelEgress, Family: "icmp"}, nil, nil, 2, 0, nil, 0, 0, ""},
|
||||
{"subnet without addresses", RegistryFilter{Level: LevelEgress, Subnet: "192.0.2.0/24"}, nil, nil, 2, 0, nil, 0, 0, ""},
|
||||
{"no runs in the period", eg, day("2000-01-01"), day("2000-01-02"), 0, 0, nil, 0, 0, ""},
|
||||
} {
|
||||
got, err := d.RegistryAlwaysPass(ctx, tc.f, tc.from, tc.to)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", tc.name, err)
|
||||
}
|
||||
list, nruns, err := d.RegistryAlwaysPassList(ctx, tc.f, tc.from, tc.to)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", tc.name, err)
|
||||
}
|
||||
var ips []string
|
||||
for _, r := range list {
|
||||
ips = append(ips, r.IPAddress)
|
||||
}
|
||||
if got.Runs != tc.runs || got.Addresses != tc.m || got.Passed != len(tc.passed) || got.Truncated || !reflect.DeepEqual(ips, tc.passed) || nruns != tc.runs {
|
||||
t.Errorf("%s: %+v list=%v runs=%d, want runs=%d M=%d passed=%v", tc.name, got, ips, nruns, tc.runs, tc.m, tc.passed)
|
||||
}
|
||||
if len(list) > 0 && (list[0].Checks != tc.checksFirst || list[0].RunsChecked != tc.runsOfFirst || list[0].FirstRunAt.Format("2006-01-02") != tc.firstRunDate) {
|
||||
t.Errorf("%s: first row %+v", tc.name, list[0])
|
||||
}
|
||||
}
|
||||
for _, f := range []RegistryFilter{{}, {Family: "https"}, {Level: "sideways"}, {Level: LevelEgress, Family: "dns"}, {Level: LevelEgress, Subnet: "nonsense"}} {
|
||||
if _, err := d.RegistryAlwaysPass(ctx, f, nil, nil); !errors.Is(err, ErrValidation) {
|
||||
t.Errorf("%+v: %v", f, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limits of a RegistryTrend: the runs shown without a period, and the most any
|
||||
// period returns.
|
||||
const (
|
||||
TrendDefaultRuns = 30
|
||||
TrendMaxRuns = 200
|
||||
)
|
||||
|
||||
// TrendRun is one finalized run on the X axis of a RegistryTrend. Addresses is
|
||||
// the number of its addresses inside the filter's subnet.
|
||||
type TrendRun struct {
|
||||
ID int64
|
||||
StartedAt time.Time
|
||||
FinalizedAt *time.Time
|
||||
Addresses int
|
||||
}
|
||||
|
||||
// TrendPoint is one target or site in one run: Total checks recorded for it and
|
||||
// OK the successful ones.
|
||||
type TrendPoint struct {
|
||||
RunID int64
|
||||
Key string
|
||||
Total int
|
||||
OK int
|
||||
}
|
||||
|
||||
// Trend is the checks of one direction (and protocol) per target or site in
|
||||
// each finalized run. Runs are oldest first; Truncated says that more runs
|
||||
// matched than were returned (the oldest were dropped).
|
||||
type Trend struct {
|
||||
Group string // BreakdownTarget or BreakdownSite
|
||||
Truncated bool
|
||||
Runs []TrendRun
|
||||
Points []TrendPoint
|
||||
}
|
||||
|
||||
// RegistryTrend counts the checks of f.Level (required, else ErrValidation) and
|
||||
// optionally f.Family per target (egress) or site (ingress) in every finalized
|
||||
// run started within [from, to] (UTC calendar days, to inclusive; nil = no
|
||||
// bound). Only Subnet, Level and Family of f count: the run, status and
|
||||
// address filters describe the current state of an address, not a history.
|
||||
// Without a period the last TrendDefaultRuns runs are returned, with one at most
|
||||
// TrendMaxRuns. As in RegistryBreakdown, it counts checks, not addresses, and
|
||||
// reads the address's cycle in the run, so a re-check inside the run replaces
|
||||
// the earlier attempt.
|
||||
func (d *DB) RegistryTrend(ctx context.Context, f RegistryFilter, from, to *time.Time) (*Trend, error) {
|
||||
sl := registrySlice{Level: f.Level, Family: f.Family}
|
||||
if err := sl.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sl.Level == "" {
|
||||
return nil, fmt.Errorf("direction is required: %w", ErrValidation)
|
||||
}
|
||||
t := &Trend{Group: BreakdownTarget}
|
||||
group := "c.target"
|
||||
if sl.Level == LevelIngress {
|
||||
t.Group, group = BreakdownSite, "c.source"
|
||||
}
|
||||
|
||||
runs, truncated, err := d.trendRuns(ctx, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Runs, t.Truncated = runs, truncated
|
||||
if len(t.Runs) == 0 {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
cond, cargs, ok, err := d.trendRunsCond(ctx, t.Runs, f.Subnet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return t, nil
|
||||
}
|
||||
pos := make(map[int64]int, len(t.Runs))
|
||||
for i, r := range t.Runs {
|
||||
pos[r.ID] = i
|
||||
}
|
||||
|
||||
// The addresses of each run, for the "of N addresses" of the axis.
|
||||
arows, err := d.QueryContext(ctx, `SELECT rr.run_id, COUNT(*) FROM run_results rr WHERE `+cond+` GROUP BY rr.run_id`, cargs...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer arows.Close()
|
||||
for arows.Next() {
|
||||
var id int64
|
||||
var n int
|
||||
if err := arows.Scan(&id, &n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Runs[pos[id]].Addresses = n
|
||||
}
|
||||
if err := arows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// CROSS JOIN keeps the checks as the inner table: the run's results drive the
|
||||
// lookups over idx_checks_run (run_id, registry_id, cycle_id).
|
||||
sc, scArgs := sl.scopeCond()
|
||||
prows, err := d.QueryContext(ctx, `
|
||||
SELECT rr.run_id, `+group+`, COUNT(*), COALESCE(SUM(c.success), 0)
|
||||
FROM run_results rr
|
||||
CROSS JOIN checks c ON c.run_id = rr.run_id AND c.registry_id = rr.registry_id AND c.cycle_id = rr.cycle_id
|
||||
WHERE `+cond+` AND `+sc+` GROUP BY rr.run_id, `+group+` ORDER BY `+group+`, rr.run_id`, append(cargs, scArgs...)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer prows.Close()
|
||||
for prows.Next() {
|
||||
var p TrendPoint
|
||||
if err := prows.Scan(&p.RunID, &p.Key, &p.Total, &p.OK); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Points = append(t.Points, p)
|
||||
}
|
||||
return t, prows.Err()
|
||||
}
|
||||
|
||||
// trendRuns selects the runs of a period: finalized ones started within
|
||||
// [from, to] (UTC calendar days, to inclusive; nil = no bound), oldest first.
|
||||
// Without a period the last TrendDefaultRuns runs, with one at most
|
||||
// TrendMaxRuns; truncated says that older runs matched too. The runs of the
|
||||
// trend chart and of the always-pass indicator come from here.
|
||||
func (d *DB) trendRuns(ctx context.Context, from, to *time.Time) (runs []TrendRun, truncated bool, err error) {
|
||||
// started_at is UTC RFC3339Nano text; the bounds without the zone sort just
|
||||
// before every instant of their second, so the comparison is exact.
|
||||
const dayLayout = "2006-01-02T15:04:05"
|
||||
where, args, limit := `state = ?`, []any{RunFinalized}, TrendDefaultRuns
|
||||
if from != nil {
|
||||
where += ` AND started_at >= ?`
|
||||
args = append(args, from.UTC().Truncate(24*time.Hour).Format(dayLayout))
|
||||
limit = TrendMaxRuns
|
||||
}
|
||||
if to != nil {
|
||||
where += ` AND started_at < ?`
|
||||
args = append(args, to.UTC().Truncate(24*time.Hour).AddDate(0, 0, 1).Format(dayLayout))
|
||||
limit = TrendMaxRuns
|
||||
}
|
||||
rows, err := d.QueryContext(ctx, `SELECT id, started_at, finalized_at FROM check_runs WHERE `+where+` ORDER BY id DESC LIMIT ?`, append(args, limit+1)...)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r TrendRun
|
||||
var started string
|
||||
var finalized sql.NullString
|
||||
if err := rows.Scan(&r.ID, &started, &finalized); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if r.StartedAt, err = dbToTime(started); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if r.FinalizedAt, err = nullStringToTimePtr(finalized); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
runs = append(runs, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if truncated = len(runs) > limit; truncated {
|
||||
runs = runs[:limit]
|
||||
}
|
||||
// Oldest first, the order of the X axis.
|
||||
for i, j := 0, len(runs)-1; i < j; i, j = i+1, j-1 {
|
||||
runs[i], runs[j] = runs[j], runs[i]
|
||||
}
|
||||
return runs, truncated, nil
|
||||
}
|
||||
|
||||
// trendRunsCond is the condition over `run_results rr` for the addresses of
|
||||
// runs, inside subnet when it is set. ok is false when the subnet has no
|
||||
// addresses, so nothing can match.
|
||||
func (d *DB) trendRunsCond(ctx context.Context, runs []TrendRun, subnet string) (cond string, args []any, ok bool, err error) {
|
||||
ids := make([]int64, len(runs))
|
||||
for i, r := range runs {
|
||||
ids[i] = r.ID
|
||||
}
|
||||
runsJSON, err := json.Marshal(ids)
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
}
|
||||
// One JSON parameter per list, as in registryFilterSQL, to stay under SQLite's
|
||||
// bound-variable limit.
|
||||
cond, args = `rr.run_id IN (SELECT value FROM json_each(?))`, []any{string(runsJSON)}
|
||||
if subnet != "" {
|
||||
sub, err := d.subnetIDs(ctx, subnet)
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
}
|
||||
if len(sub) == 0 {
|
||||
return "", nil, false, nil
|
||||
}
|
||||
b, err := json.Marshal(sub)
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
}
|
||||
cond += ` AND rr.registry_id IN (SELECT value FROM json_each(?))`
|
||||
args = append(args, string(b))
|
||||
}
|
||||
return cond, args, true, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RegistryTrend over three finalized runs and one open one: the points per
|
||||
// target or site, the subnet, the period, the run cap and validation.
|
||||
func TestRegistryTrend(t *testing.T) {
|
||||
d, ctx := newTestDB(t)
|
||||
const a1, a2, a3 = "10.0.0.1", "10.0.0.2", "10.0.1.1"
|
||||
s1 := InboundSource(1)
|
||||
// run 1: three addresses; run 2: a re-check of a1 (T2 missing); run 3: a1, a2.
|
||||
submit(t, d, RunManual, a1, a2, a3)
|
||||
for _, c := range []struct {
|
||||
addr, source, typ, target string
|
||||
ok bool
|
||||
}{
|
||||
{a1, SourceEgress, "https", "T1", true}, {a1, SourceEgress, "https", "T2", false}, {a1, s1, "tcp-22", a1, true},
|
||||
{a2, SourceEgress, "https", "T1", false}, {a2, SourceEgress, "https", "T2", true},
|
||||
{a3, SourceEgress, "https", "T1", true}, {a3, SourceEgress, "https", "T2", true},
|
||||
} {
|
||||
addCheck(t, d, c.addr, c.source, c.typ, c.target, c.ok)
|
||||
}
|
||||
finish(t, d, a1, ResultPartial, -1)
|
||||
finish(t, d, a2, ResultPartial, -1)
|
||||
finish(t, d, a3, ResultPass, -1)
|
||||
|
||||
submit(t, d, RunManual, a1)
|
||||
addCheck(t, d, a1, SourceEgress, "https", "T1", true)
|
||||
finish(t, d, a1, ResultPass, -1)
|
||||
|
||||
submit(t, d, RunManual, a1, a2)
|
||||
for _, a := range []string{a1, a2} {
|
||||
addCheck(t, d, a, SourceEgress, "https", "T1", false)
|
||||
addCheck(t, d, a, SourceEgress, "https", "T2", true)
|
||||
finish(t, d, a, ResultPartial, -1)
|
||||
}
|
||||
submit(t, d, RunManual, a1) // open: never on the chart
|
||||
rs := runs(t, d)
|
||||
if len(rs) != 4 || rs[0].State != RunOpen {
|
||||
t.Fatalf("runs: %+v", rs)
|
||||
}
|
||||
r1, r2, r3 := rs[3].ID, rs[2].ID, rs[1].ID
|
||||
for i, day := range []string{"2026-09-01T10:00:00Z", "2026-09-05T23:59:59Z", "2026-09-06T00:00:00.5Z"} {
|
||||
if _, err := d.ExecContext(ctx, `UPDATE check_runs SET started_at = ? WHERE id = ?`, day, []int64{r1, r2, r3}[i]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
day := func(s string) *time.Time {
|
||||
v, err := time.Parse("2006-01-02", s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &v
|
||||
}
|
||||
eg := RegistryFilter{Level: LevelEgress, Family: "https"}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
f RegistryFilter
|
||||
from, to *time.Time
|
||||
runs []int64
|
||||
addrs []int
|
||||
points []TrendPoint
|
||||
}{
|
||||
{"all runs, the open one absent", eg, nil, nil, []int64{r1, r2, r3}, []int{3, 1, 2},
|
||||
[]TrendPoint{{r1, "T1", 3, 2}, {r2, "T1", 1, 1}, {r3, "T1", 2, 0}, {r1, "T2", 3, 2}, {r3, "T2", 2, 2}}},
|
||||
{"subnet", RegistryFilter{Level: LevelEgress, Family: "https", Subnet: "10.0.1.0/24"}, nil, nil, []int64{r1, r2, r3}, []int{1, 0, 0},
|
||||
[]TrendPoint{{r1, "T1", 1, 1}, {r1, "T2", 1, 1}}},
|
||||
{"period, to inclusive", eg, day("2026-09-02"), day("2026-09-05"), []int64{r2}, []int{1},
|
||||
[]TrendPoint{{r2, "T1", 1, 1}}},
|
||||
{"ingress by site, tcp", RegistryFilter{Level: LevelIngress, Family: "tcp"}, nil, nil, []int64{r1, r2, r3}, []int{3, 1, 2},
|
||||
[]TrendPoint{{r1, s1, 1, 1}}},
|
||||
{"no protocol: all checks of the direction", RegistryFilter{Level: LevelEgress, RunID: r1, Query: "x", LastResult: ResultFail}, day("2026-09-06"), nil, []int64{r3}, []int{2},
|
||||
[]TrendPoint{{r3, "T1", 2, 0}, {r3, "T2", 2, 2}}},
|
||||
{"subnet without addresses", RegistryFilter{Level: LevelEgress, Subnet: "192.0.2.0/24"}, nil, nil, []int64{r1, r2, r3}, []int{0, 0, 0}, nil},
|
||||
} {
|
||||
got, err := d.RegistryTrend(ctx, tc.f, tc.from, tc.to)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", tc.name, err)
|
||||
}
|
||||
var ids []int64
|
||||
var addrs []int
|
||||
for _, r := range got.Runs {
|
||||
ids, addrs = append(ids, r.ID), append(addrs, r.Addresses)
|
||||
}
|
||||
if !reflect.DeepEqual(ids, tc.runs) || !reflect.DeepEqual(addrs, tc.addrs) || !reflect.DeepEqual(got.Points, tc.points) || got.Truncated {
|
||||
t.Errorf("%s: runs=%v addresses=%v points=%v truncated=%v, want %v %v %v", tc.name, ids, addrs, got.Points, got.Truncated, tc.runs, tc.addrs, tc.points)
|
||||
}
|
||||
}
|
||||
if g, _ := d.RegistryTrend(ctx, RegistryFilter{Level: LevelIngress}, nil, nil); g.Group != BreakdownSite {
|
||||
t.Errorf("ingress group: %q", g.Group)
|
||||
}
|
||||
for _, f := range []RegistryFilter{{}, {Family: "https"}, {Level: "sideways"}, {Level: LevelEgress, Family: "dns"}, {Level: LevelEgress, Subnet: "nonsense"}} {
|
||||
if _, err := d.RegistryTrend(ctx, f, nil, nil); !errors.Is(err, ErrValidation) {
|
||||
t.Errorf("%+v: %v", f, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -466,6 +466,21 @@ func TestScaleSmoke6440(t *testing.T) {
|
||||
if bd, err = d.RegistryBreakdown(ctx, RegistryFilter{Level: LevelEgress, Family: "https"}); err != nil || bd.Addresses != 100 || len(bd.Rows) != 6 {
|
||||
t.Fatalf("breakdown, newest cycle: %+v err=%v", bd, err)
|
||||
}
|
||||
// The trend of the run, finalized for the purpose: the same 3 sites, with the whole registry as the subnet.
|
||||
if _, err := d.ExecContext(ctx, `UPDATE check_runs SET state = ? WHERE id = ?`, RunFinalized, runID); err != nil {
|
||||
t.Fatalf("finalize run: %v", err)
|
||||
}
|
||||
tr, err := d.RegistryTrend(ctx, RegistryFilter{Subnet: "10.0.0.0/8", Level: LevelIngress, Family: "tcp"}, nil, nil)
|
||||
if err != nil || len(tr.Runs) != 1 || tr.Runs[0].Addresses != 100 || len(tr.Points) != 3 || tr.Points[0].Total != 600 {
|
||||
t.Fatalf("trend: %+v err=%v", tr, err)
|
||||
}
|
||||
ap, err := d.RegistryAlwaysPass(ctx, RegistryFilter{Subnet: "10.0.0.0/8", Level: LevelIngress, Family: "tcp"}, nil, nil)
|
||||
if err != nil || ap.Runs != 1 || ap.Addresses != 100 || ap.Passed != 0 {
|
||||
t.Fatalf("always pass: %+v err=%v", ap, err)
|
||||
}
|
||||
if l, n, err := d.RegistryAlwaysPassList(ctx, RegistryFilter{Subnet: "10.0.0.0/8", Level: LevelIngress, Family: "tcp"}, nil, nil); err != nil || n != 1 || len(l) != ap.Passed {
|
||||
t.Fatalf("always pass list: len=%d runs=%d err=%v", len(l), n, err)
|
||||
}
|
||||
registryDur := time.Since(start)
|
||||
|
||||
start = time.Now()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// SubnetOutside is the group name of an address that matches no configured
|
||||
// subnet (or is not an IP address at all).
|
||||
const SubnetOutside = "вне списка подсетей"
|
||||
|
||||
// SubnetMatcher maps an address to the most specific configured subnet.
|
||||
type SubnetMatcher struct {
|
||||
list []subnetEntry
|
||||
}
|
||||
|
||||
type subnetEntry struct {
|
||||
p netip.Prefix
|
||||
label string
|
||||
}
|
||||
|
||||
// NewSubnetMatcher builds a matcher from the administrator's subnet list.
|
||||
// Entries that are not valid CIDR are skipped.
|
||||
func NewSubnetMatcher(subnets []Subnet) *SubnetMatcher {
|
||||
m := &SubnetMatcher{}
|
||||
for _, s := range subnets {
|
||||
if p, err := netip.ParsePrefix(s.CIDR); err == nil {
|
||||
m.list = append(m.list, subnetEntry{p.Masked(), s.Label})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(m.list, func(i, j int) bool { return m.list[i].p.Bits() > m.list[j].p.Bits() })
|
||||
return m
|
||||
}
|
||||
|
||||
// Lookup returns the CIDR and the label of the most specific subnet that
|
||||
// contains ip. With an empty list the address is grouped by /24 (/64 for
|
||||
// IPv6) without a label. An address outside the list gets SubnetOutside.
|
||||
func (m *SubnetMatcher) Lookup(ip string) (cidr, label string) {
|
||||
a, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
return SubnetOutside, ""
|
||||
}
|
||||
if len(m.list) == 0 {
|
||||
bits := 24
|
||||
if a.Is6() {
|
||||
bits = 64
|
||||
}
|
||||
p, _ := a.Prefix(bits)
|
||||
return p.String(), ""
|
||||
}
|
||||
for _, e := range m.list {
|
||||
if e.p.Contains(a) {
|
||||
return e.p.String(), e.label
|
||||
}
|
||||
}
|
||||
return SubnetOutside, ""
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSubnetMatcher(t *testing.T) {
|
||||
nested := []Subnet{{CIDR: "10.0.0.0/8", Label: "wide"}, {CIDR: "10.1.0.0/16", Label: "narrow"}, {CIDR: "2001:db8::/32"}}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
list []Subnet
|
||||
ip string
|
||||
cidr string
|
||||
label string
|
||||
}{
|
||||
{"most specific", nested, "10.1.2.3", "10.1.0.0/16", "narrow"},
|
||||
{"outer only", nested, "10.2.0.1", "10.0.0.0/8", "wide"},
|
||||
{"outside", nested, "192.0.2.1", SubnetOutside, ""},
|
||||
{"garbage", nested, "garbage", SubnetOutside, ""},
|
||||
{"ipv6 in list", nested, "2001:db8::1", "2001:db8::/32", ""},
|
||||
{"empty list v4", nil, "203.0.113.77", "203.0.113.0/24", ""},
|
||||
{"empty list v6", nil, "2001:db8:1:2:3::1", "2001:db8:1:2::/64", ""},
|
||||
} {
|
||||
cidr, label := NewSubnetMatcher(c.list).Lookup(c.ip)
|
||||
if cidr != c.cidr || label != c.label {
|
||||
t.Errorf("%s: got %q/%q, want %q/%q", c.name, cidr, label, c.cidr, c.label)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user