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
@@ -152,12 +152,13 @@ type failedIngress struct {
|
||||
|
||||
// addr is everything known about one address of the run.
|
||||
type addr struct {
|
||||
res db.RunResult
|
||||
subnet string
|
||||
egress typeStat
|
||||
ingress typeStat
|
||||
stored int
|
||||
https struct {
|
||||
res db.RunResult
|
||||
subnet string
|
||||
subnetLabel string
|
||||
egress typeStat
|
||||
ingress typeStat
|
||||
stored int
|
||||
https struct {
|
||||
typeStat
|
||||
validator string
|
||||
failedTargets []string
|
||||
@@ -187,7 +188,7 @@ type Analysis struct {
|
||||
func Compute(in Input) (*Analysis, error) {
|
||||
byReg := make(map[int64]*addr, len(in.Results))
|
||||
var addrs []*addr
|
||||
subnetOf := newSubnetMatcher(in.Subnets)
|
||||
matcher := db.NewSubnetMatcher(in.Subnets)
|
||||
runAddrs := 0
|
||||
for _, r := range in.Results {
|
||||
if r.Verdict != db.ResultCancelled {
|
||||
@@ -199,7 +200,8 @@ func Compute(in Input) (*Analysis, error) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
a := &addr{res: r, subnet: subnetOf(r.IPAddress), failedTargets: map[string]bool{}}
|
||||
cidr, label := matcher.Lookup(r.IPAddress)
|
||||
a := &addr{res: r, subnet: cidr, subnetLabel: label, failedTargets: map[string]bool{}}
|
||||
a.ssh.errs = map[string]bool{}
|
||||
byReg[r.RegistryID] = a
|
||||
addrs = append(addrs, a)
|
||||
@@ -623,43 +625,6 @@ func normalizeTarget(t string) string {
|
||||
return strings.TrimSuffix(t, "/")
|
||||
}
|
||||
|
||||
// newSubnetMatcher returns a function that maps an address to the most
|
||||
// specific configured subnet. With no subnets configured addresses group by
|
||||
// /24 (/64 for IPv6). An address outside the list goes to "прочие".
|
||||
func newSubnetMatcher(subnets []db.Subnet) func(string) string {
|
||||
type entry struct {
|
||||
p netip.Prefix
|
||||
name string
|
||||
}
|
||||
var list []entry
|
||||
for _, s := range subnets {
|
||||
if p, err := netip.ParsePrefix(s.CIDR); err == nil {
|
||||
list = append(list, entry{p.Masked(), p.Masked().String()})
|
||||
}
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].p.Bits() > list[j].p.Bits() })
|
||||
return func(ip string) string {
|
||||
a, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
return "прочие"
|
||||
}
|
||||
if len(list) == 0 {
|
||||
bits := 24
|
||||
if a.Is6() {
|
||||
bits = 64
|
||||
}
|
||||
p, _ := a.Prefix(bits)
|
||||
return p.String()
|
||||
}
|
||||
for _, e := range list {
|
||||
if e.p.Contains(a) {
|
||||
return e.name
|
||||
}
|
||||
}
|
||||
return "прочие"
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorClassOf names the class of a failed ingress check: the check type and
|
||||
// the reason, e.g. "SSH: таймаут", "ICMP: нет ответа".
|
||||
func ErrorClassOf(checkType, detail string) string {
|
||||
|
||||
@@ -211,20 +211,6 @@ func TestComputeNarrowedToSubnet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubnetMatching(t *testing.T) {
|
||||
in := []db.Subnet{{CIDR: "10.0.0.0/8"}, {CIDR: "10.1.0.0/16"}}
|
||||
m := newSubnetMatcher(in)
|
||||
for ip, want := range map[string]string{"10.1.2.3": "10.1.0.0/16", "10.2.0.1": "10.0.0.0/8", "192.0.2.1": "прочие", "garbage": "прочие"} {
|
||||
if got := m(ip); got != want {
|
||||
t.Errorf("%s -> %s, want %s", ip, got, want)
|
||||
}
|
||||
}
|
||||
auto := newSubnetMatcher(nil)
|
||||
if got := auto("203.0.113.77"); got != "203.0.113.0/24" {
|
||||
t.Errorf("without a list addresses group by /24, got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorClassOf(t *testing.T) {
|
||||
for _, c := range []struct{ typ, detail, want string }{
|
||||
{"ssh", `read banner: read tcp 1.2.3.4:5->6.7.8.9:22: i/o timeout`, "SSH: таймаут"},
|
||||
@@ -258,19 +244,19 @@ func TestListsAndShortValidator(t *testing.T) {
|
||||
if err != nil || len(l.Rows) != 2 || l.Rows[0][0] != "10.0.0.9" || l.Rows[1][0] != "10.0.0.10" { // numeric order
|
||||
t.Fatalf("any: %+v %v", l, err)
|
||||
}
|
||||
if l.Rows[0][2] != "v12" || l.Rows[0][3] != "2 из 2" || l.Rows[1][3] != "1 из 2" || l.Rows[1][4] != "b.test" {
|
||||
if l.Rows[0][3] != "v12" || l.Rows[0][4] != "2 из 2" || l.Rows[1][4] != "1 из 2" || l.Rows[1][5] != "b.test" {
|
||||
t.Errorf("any rows: %+v", l.Rows)
|
||||
}
|
||||
l, _ = an.List(ListEgressHTTPSAll, "")
|
||||
if len(l.Rows) != 1 || l.Rows[0][3] != "2" || l.Rows[0][4] != "a.test, b.test" {
|
||||
if len(l.Rows) != 1 || l.Rows[0][4] != "2" || l.Rows[0][5] != "a.test, b.test" {
|
||||
t.Errorf("all: %+v", l.Rows)
|
||||
}
|
||||
l, _ = an.List(ListIngressSSHAll, "")
|
||||
if len(l.Rows) != 1 || l.Rows[0][2] != "rxmsk, rxyc" || l.Rows[0][3] != "таймаут" { // sites in index order
|
||||
if len(l.Rows) != 1 || l.Rows[0][3] != "rxmsk, rxyc" || l.Rows[0][4] != "таймаут" { // sites in index order
|
||||
t.Errorf("ssh all: %+v", l.Rows)
|
||||
}
|
||||
l, _ = an.List(ListError, "SSH: таймаут")
|
||||
if len(l.Rows) != 2 || l.Rows[0][2] != "rxmsk" || l.Rows[0][5] != "провал, после вердикта" || l.Rows[1][5] != "провал, в вердикте" {
|
||||
if len(l.Rows) != 2 || l.Rows[0][3] != "rxmsk" || l.Rows[0][6] != "провал, после вердикта" || l.Rows[1][6] != "провал, в вердикте" {
|
||||
t.Errorf("error list: %+v", l.Rows)
|
||||
}
|
||||
if _, err := an.List(ListError, ""); err == nil {
|
||||
@@ -337,32 +323,32 @@ func TestVerdictLists(t *testing.T) {
|
||||
t.Errorf("pass order: %v", p)
|
||||
}
|
||||
l, _ := an.List(ListVerdictPass, "")
|
||||
if want := []string{"Адрес", "Подсеть", "Валидатор", "Egress", "Ingress", "Проверок в цикле"}; !reflect.DeepEqual(l.Columns, want) {
|
||||
if want := []string{"Адрес", "Подсеть", "Метка подсети", "Валидатор", "Egress", "Ingress", "Проверок в цикле"}; !reflect.DeepEqual(l.Columns, want) {
|
||||
t.Errorf("pass columns: %v", l.Columns)
|
||||
}
|
||||
// Levels count successful of all; the failed late ssh shows in ingress.
|
||||
if want := []string{"10.0.0.2", "10.0.0.0/24", "v1", "2 из 2", "2 из 2", "4 из 4"}; !reflect.DeepEqual(rows[ListVerdictPass][0], want) {
|
||||
if want := []string{"10.0.0.2", "10.0.0.0/24", "", "v1", "2 из 2", "2 из 2", "4 из 4"}; !reflect.DeepEqual(rows[ListVerdictPass][0], want) {
|
||||
t.Errorf("pass row: %v", rows[ListVerdictPass][0])
|
||||
}
|
||||
if r := rows[ListVerdictPass][1]; r[3] != "2 из 2" || r[4] != "1 из 2" || r[5] != "4 из 4" {
|
||||
if r := rows[ListVerdictPass][1]; r[4] != "2 из 2" || r[5] != "1 из 2" || r[6] != "4 из 4" {
|
||||
t.Errorf("pass with a late failure: %v", r)
|
||||
}
|
||||
|
||||
// Partial has the reason of the "why partial" block; a short set shows stored of expected,
|
||||
// an unknown expectation only the stored number.
|
||||
l, _ = an.List(ListVerdictPartial, "")
|
||||
if len(l.Columns) != 7 || l.Columns[6] != "Причина" {
|
||||
if len(l.Columns) != 8 || l.Columns[7] != "Причина" {
|
||||
t.Errorf("partial columns: %v", l.Columns)
|
||||
}
|
||||
if want := []string{"10.0.0.3", "10.0.0.0/24", "v3", "1 из 1", "0 из 1", "2", "Только ingress"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
if want := []string{"10.0.0.3", "10.0.0.0/24", "", "v3", "1 из 1", "0 из 1", "2", "Только ingress"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
t.Errorf("partial unknown expected: %v", l.Rows[0])
|
||||
}
|
||||
if want := []string{"10.0.0.9", "10.0.0.0/24", "v12", "0 из 2", "1 из 1", "3 из 4", "Egress и неполный набор"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
if want := []string{"10.0.0.9", "10.0.0.0/24", "", "v12", "0 из 2", "1 из 1", "3 из 4", "Egress и неполный набор"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
t.Errorf("partial incomplete: %v", l.Rows[1])
|
||||
}
|
||||
byReason := map[string]int{}
|
||||
for _, r := range l.Rows {
|
||||
byReason[r[6]]++
|
||||
byReason[r[7]]++
|
||||
}
|
||||
for _, x := range an.Report.Reasons {
|
||||
if byReason[x.Name] != x.Count {
|
||||
@@ -372,13 +358,13 @@ func TestVerdictLists(t *testing.T) {
|
||||
|
||||
// A level without checks shows a dash, so does a missing validator.
|
||||
l, _ = an.List(ListVerdictFail, "")
|
||||
if len(l.Columns) != 6 {
|
||||
if len(l.Columns) != 7 {
|
||||
t.Errorf("fail columns: %v", l.Columns)
|
||||
}
|
||||
if want := []string{"10.0.0.4", "10.0.0.0/24", "v5", "0 из 1", "0 из 1", "2 из 2"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
if want := []string{"10.0.0.4", "10.0.0.0/24", "", "v5", "0 из 1", "0 из 1", "2 из 2"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
t.Errorf("fail row: %v", l.Rows[0])
|
||||
}
|
||||
if want := []string{"10.0.0.5", "10.0.0.0/24", "—", "—", "0 из 1", "1 из 1"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
if want := []string{"10.0.0.5", "10.0.0.0/24", "", "—", "—", "0 из 1", "1 из 1"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
t.Errorf("fail row without egress: %v", l.Rows[1])
|
||||
}
|
||||
}
|
||||
@@ -289,9 +289,9 @@ func (c *Comparison) List(group string, f CompareFilter) (*CompareList, error) {
|
||||
|
||||
l := &CompareList{Group: group, Indicator: f.Indicator, Rows: [][]string{}}
|
||||
if group == GroupNew || group == GroupLeft {
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Вердикт", "Egress", "Ingress", "Индикаторы"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Вердикт", "Egress", "Ingress", "Индикаторы"}
|
||||
} else {
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Вердикт (A → B)", "Egress (A → B)", "Ingress (A → B)", "Что изменилось"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Вердикт (A → B)", "Egress (A → B)", "Ingress (A → B)", "Что изменилось"}
|
||||
}
|
||||
for _, r := range c.rows {
|
||||
var ok bool
|
||||
@@ -322,11 +322,11 @@ func (c *Comparison) List(group string, f CompareFilter) (*CompareList, error) {
|
||||
}
|
||||
switch {
|
||||
case r.a == nil:
|
||||
l.Rows = append(l.Rows, []string{r.ip, r.b.subnet, r.b.res.Verdict, okOf(r.b.egress), okOf(r.b.ingress), indicatorsCell(r.mb)})
|
||||
l.Rows = append(l.Rows, []string{r.ip, r.b.subnet, r.b.subnetLabel, r.b.res.Verdict, okOf(r.b.egress), okOf(r.b.ingress), indicatorsCell(r.mb)})
|
||||
case r.b == nil:
|
||||
l.Rows = append(l.Rows, []string{r.ip, r.a.subnet, r.a.res.Verdict, okOf(r.a.egress), okOf(r.a.ingress), indicatorsCell(r.ma)})
|
||||
l.Rows = append(l.Rows, []string{r.ip, r.a.subnet, r.a.subnetLabel, r.a.res.Verdict, okOf(r.a.egress), okOf(r.a.ingress), indicatorsCell(r.ma)})
|
||||
default:
|
||||
l.Rows = append(l.Rows, []string{r.ip, r.b.subnet, arrow(r.a.res.Verdict, r.b.res.Verdict),
|
||||
l.Rows = append(l.Rows, []string{r.ip, r.b.subnet, r.b.subnetLabel, arrow(r.a.res.Verdict, r.b.res.Verdict),
|
||||
arrow(okOf(r.a.egress), okOf(r.b.egress)), arrow(okOf(r.a.ingress), okOf(r.b.ingress)), c.changeText(r)})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,13 +156,13 @@ func TestCompareLists(t *testing.T) {
|
||||
|
||||
// New and left: the state in the run the address is in; numeric order.
|
||||
l := mustList(t, c, GroupNew, CompareFilter{})
|
||||
if want := []string{"Адрес", "Подсеть", "Вердикт", "Egress", "Ingress", "Индикаторы"}; !reflect.DeepEqual(l.Columns, want) {
|
||||
if want := []string{"Адрес", "Подсеть", "Метка подсети", "Вердикт", "Egress", "Ingress", "Индикаторы"}; !reflect.DeepEqual(l.Columns, want) {
|
||||
t.Errorf("new columns: %v", l.Columns)
|
||||
}
|
||||
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.11", "10.0.0.12", "10.0.0.13"}) {
|
||||
t.Errorf("new: %v", got)
|
||||
}
|
||||
if want := []string{"10.0.0.11", "10.0.0.0/24", "partial", "0 из 2", "2 из 2", "partial, Egress https: есть провалы, Egress https: все провалены"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
if want := []string{"10.0.0.11", "10.0.0.0/24", "", "partial", "0 из 2", "2 из 2", "partial, Egress https: есть провалы, Egress https: все провалены"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
t.Errorf("new row: %v", l.Rows[0])
|
||||
}
|
||||
if got := ips(mustList(t, c, GroupNew, CompareFilter{Indicator: ListVerdictPass})); !reflect.DeepEqual(got, []string{"10.0.0.12", "10.0.0.13"}) {
|
||||
@@ -175,7 +175,7 @@ func TestCompareLists(t *testing.T) {
|
||||
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.10", "10.0.0.14"}) {
|
||||
t.Errorf("left: %v", got)
|
||||
}
|
||||
if want := "fail"; l.Rows[0][2] != want || l.Rows[0][5] != "fail, Egress https: есть провалы, Egress https: все провалены, Ingress ssh: есть провалы, Ingress ssh: все провалены" {
|
||||
if want := "fail"; l.Rows[0][3] != want || l.Rows[0][6] != "fail, Egress https: есть провалы, Egress https: все провалены, Ingress ssh: есть провалы, Ingress ssh: все провалены" {
|
||||
t.Errorf("left row: %v", l.Rows[0])
|
||||
}
|
||||
if got := ips(mustList(t, c, GroupLeft, CompareFilter{Indicator: ListVerdictPass})); !reflect.DeepEqual(got, []string{"10.0.0.14"}) {
|
||||
@@ -187,14 +187,14 @@ func TestCompareLists(t *testing.T) {
|
||||
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.2", "10.0.0.3"}) {
|
||||
t.Fatalf("changed: %v", got)
|
||||
}
|
||||
if l.Columns[2] != "Вердикт (A → B)" || l.Columns[5] != "Что изменилось" {
|
||||
if l.Columns[3] != "Вердикт (A → B)" || l.Columns[6] != "Что изменилось" {
|
||||
t.Errorf("changed columns: %v", l.Columns)
|
||||
}
|
||||
if want := []string{"10.0.0.2", "10.0.0.0/24", "partial → pass", "0 из 2 → 2 из 2", "2 из 2 → 2 из 2",
|
||||
if want := []string{"10.0.0.2", "10.0.0.0/24", "", "partial → pass", "0 из 2 → 2 из 2", "2 из 2 → 2 из 2",
|
||||
"вердикт partial → pass; вышел из: Egress https: есть провалы, Egress https: все провалены; https: провалены цели −a.test −b.test; валидатор v2 → v5"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||
t.Errorf("changed row 1: %v", l.Rows[0])
|
||||
}
|
||||
if want := []string{"10.0.0.3", "10.0.0.0/24", "pass → partial", "2 из 2 → 2 из 2", "2 из 2 → 1 из 2",
|
||||
if want := []string{"10.0.0.3", "10.0.0.0/24", "", "pass → partial", "2 из 2 → 2 из 2", "2 из 2 → 1 из 2",
|
||||
"вердикт pass → partial; вошёл в: Ingress ssh: есть провалы; ssh: площадки +rxmsk"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
t.Errorf("changed row 2: %v", l.Rows[1])
|
||||
}
|
||||
@@ -211,7 +211,7 @@ func TestCompareLists(t *testing.T) {
|
||||
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.1", "10.0.0.20"}) {
|
||||
t.Fatalf("same: %v", got)
|
||||
}
|
||||
if want := []string{"10.0.0.20", "10.0.0.0/24", "partial → partial", "1 из 2 → 1 из 2", "2 из 2 → 2 из 2", "без изменений"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
if want := []string{"10.0.0.20", "10.0.0.0/24", "", "partial → partial", "1 из 2 → 1 из 2", "2 из 2 → 2 из 2", "без изменений"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||
t.Errorf("same row: %v", l.Rows[1])
|
||||
}
|
||||
if got := ips(mustList(t, c, GroupSame, CompareFilter{Indicator: ListEgressHTTPSAny})); !reflect.DeepEqual(got, []string{"10.0.0.20"}) {
|
||||
@@ -220,7 +220,7 @@ func TestCompareLists(t *testing.T) {
|
||||
|
||||
// Common is changed + same, in address order.
|
||||
l = mustList(t, c, GroupCommon, CompareFilter{})
|
||||
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.20"}) || l.Rows[3][5] != "без изменений" {
|
||||
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.20"}) || l.Rows[3][6] != "без изменений" {
|
||||
t.Errorf("common: %v", l.Rows)
|
||||
}
|
||||
|
||||
|
||||
+10
-10
@@ -40,7 +40,7 @@ func (an *Analysis) List(kind, class string) (*List, error) {
|
||||
l := &List{Kind: kind, Class: class, Rows: [][]string{}}
|
||||
switch kind {
|
||||
case ListEgressHTTPSAny, ListEgressHTTPSAll:
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Валидатор", "https-проверок", "Проваленные цели"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Валидатор", "https-проверок", "Проваленные цели"}
|
||||
if kind == ListEgressHTTPSAny {
|
||||
l.Columns[3] = "Провалено https"
|
||||
}
|
||||
@@ -54,12 +54,12 @@ func (an *Analysis) List(kind, class string) (*List, error) {
|
||||
if kind == ListEgressHTTPSAny {
|
||||
count = fmt.Sprintf("%d из %d", a.https.n-a.https.ok, a.https.n)
|
||||
}
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, ShortValidator(a.https.validator), count, strings.Join(targets, ", ")})
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, a.subnetLabel, ShortValidator(a.https.validator), count, strings.Join(targets, ", ")})
|
||||
}
|
||||
case ListIngressSSHAny, ListIngressSSHAll:
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Провалено ssh", "Площадки с провалом", "Ошибка"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Провалено ssh", "Площадки с провалом", "Ошибка"}
|
||||
if kind == ListIngressSSHAll {
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Площадки с провалом ssh", "Ошибка"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Площадки с провалом ssh", "Ошибка"}
|
||||
}
|
||||
for _, a := range an.sorted() {
|
||||
if a.ssh.n == 0 || a.ssh.ok == a.ssh.n || (kind == ListIngressSSHAll && a.ssh.ok != 0) {
|
||||
@@ -72,14 +72,14 @@ func (an *Analysis) List(kind, class string) (*List, error) {
|
||||
}
|
||||
sort.Strings(errs)
|
||||
if kind == ListIngressSSHAny {
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, fmt.Sprintf("%d из %d", len(a.ssh.sites), a.ssh.n), strings.Join(sites, ", "), strings.Join(errs, ", ")})
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, a.subnetLabel, fmt.Sprintf("%d из %d", len(a.ssh.sites), a.ssh.n), strings.Join(sites, ", "), strings.Join(errs, ", ")})
|
||||
} else {
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, strings.Join(sites, ", "), strings.Join(errs, ", ")})
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, a.subnetLabel, strings.Join(sites, ", "), strings.Join(errs, ", ")})
|
||||
}
|
||||
}
|
||||
case ListVerdictPass, ListVerdictPartial, ListVerdictFail:
|
||||
verdict := strings.TrimPrefix(kind, "verdict_")
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Валидатор", "Egress", "Ingress", "Проверок в цикле"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Валидатор", "Egress", "Ingress", "Проверок в цикле"}
|
||||
if kind == ListVerdictPartial {
|
||||
l.Columns = append(l.Columns, "Причина")
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func (an *Analysis) List(kind, class string) (*List, error) {
|
||||
if a.res.Verdict != verdict {
|
||||
continue
|
||||
}
|
||||
row := []string{a.res.IPAddress, a.subnet, orDash(ShortValidator(a.https.validator)), okOf(a.egress), okOf(a.ingress), a.checksCell()}
|
||||
row := []string{a.res.IPAddress, a.subnet, a.subnetLabel, orDash(ShortValidator(a.https.validator)), okOf(a.egress), okOf(a.ingress), a.checksCell()}
|
||||
if kind == ListVerdictPartial {
|
||||
row = append(row, reasonName(a.egress.ok < a.egress.n, a.ingress.ok < a.ingress.n, a.incomplete()))
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func (an *Analysis) List(kind, class string) (*List, error) {
|
||||
if class == "" {
|
||||
return nil, ErrUnknownList("error without class")
|
||||
}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Площадка", "Валидатор", "Вердикт адреса", "Статус проверки"}
|
||||
l.Columns = []string{"Адрес", "Подсеть", "Метка подсети", "Площадка", "Валидатор", "Вердикт адреса", "Статус проверки"}
|
||||
for _, a := range an.sorted() {
|
||||
fs := append([]failedIngress(nil), a.failedIngress...)
|
||||
sort.SliceStable(fs, func(i, j int) bool { return an.siteIndex(fs[i].site) < an.siteIndex(fs[j].site) })
|
||||
@@ -109,7 +109,7 @@ func (an *Analysis) List(kind, class string) (*List, error) {
|
||||
if f.late {
|
||||
status = "провал, после вердикта"
|
||||
}
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, f.site, ShortValidator(f.validator), a.res.Verdict, status})
|
||||
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, a.subnetLabel, f.site, ShortValidator(f.validator), a.res.Verdict, status})
|
||||
}
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -329,6 +329,75 @@ func (c *client) GetRegistryBreakdownCSV(ctx context.Context, q registryQuery, k
|
||||
return c.getCSV(ctx, registryBreakdownPath(q, key, true, true))
|
||||
}
|
||||
|
||||
// GetRegistryTrend returns the checks of the query's direction (and protocol)
|
||||
// per target or site in each finalized run, within the subnet and the period
|
||||
// from/to (YYYY-MM-DD, empty = open). The run, status and address filters of
|
||||
// the query do not apply to a history.
|
||||
func (c *client) GetRegistryTrend(ctx context.Context, q registryQuery, from, to string) (registryTrend, error) {
|
||||
v, f := url.Values{}, q.filter()
|
||||
for _, k := range []string{"subnet", "direction", "protocol"} {
|
||||
if x := f.Get(k); x != "" {
|
||||
v.Set(k, x)
|
||||
}
|
||||
}
|
||||
if from != "" {
|
||||
v.Set("from", from)
|
||||
}
|
||||
if to != "" {
|
||||
v.Set("to", to)
|
||||
}
|
||||
var out registryTrend
|
||||
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry/trend?"+v.Encode(), nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// alwaysPassPath is the path of GET /admin/registry/always-pass, or of its list
|
||||
// when list is set, as a CSV file when csv is. The query's subnet, direction,
|
||||
// protocol and address search count, with the period from/to (YYYY-MM-DD).
|
||||
func alwaysPassPath(q registryQuery, from, to string, list, csv bool) string {
|
||||
v, f := url.Values{}, q.filter()
|
||||
for _, k := range []string{"q", "subnet", "direction", "protocol"} {
|
||||
if x := f.Get(k); x != "" {
|
||||
v.Set(k, x)
|
||||
}
|
||||
}
|
||||
if from != "" {
|
||||
v.Set("from", from)
|
||||
}
|
||||
if to != "" {
|
||||
v.Set("to", to)
|
||||
}
|
||||
p := "/api/v1/admin/registry/always-pass"
|
||||
if list {
|
||||
p += "/list"
|
||||
if csv {
|
||||
v.Set("format", "csv")
|
||||
}
|
||||
}
|
||||
return p + "?" + v.Encode()
|
||||
}
|
||||
|
||||
// GetRegistryAlwaysPass returns how many addresses never failed a check of the
|
||||
// query's direction (and protocol) in the finalized runs of the period.
|
||||
func (c *client) GetRegistryAlwaysPass(ctx context.Context, q registryQuery, from, to string) (registryAlwaysPass, error) {
|
||||
var out registryAlwaysPass
|
||||
err := c.do(ctx, http.MethodGet, alwaysPassPath(q, from, to, false, false), nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// GetRegistryAlwaysPassList returns the table (JSON) of those addresses.
|
||||
func (c *client) GetRegistryAlwaysPassList(ctx context.Context, q registryQuery, from, to string) (json.RawMessage, error) {
|
||||
var out json.RawMessage
|
||||
err := c.do(ctx, http.MethodGet, alwaysPassPath(q, from, to, true, false), nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// GetRegistryAlwaysPassCSV returns the CSV file of that table, with the file
|
||||
// name control-api proposed.
|
||||
func (c *client) GetRegistryAlwaysPassCSV(ctx context.Context, q registryQuery, from, to string) ([]byte, string, error) {
|
||||
return c.getCSV(ctx, alwaysPassPath(q, from, to, true, true))
|
||||
}
|
||||
|
||||
// GetRegistryHistory returns one address's registry record plus its full
|
||||
// retained check history across every cycle still kept.
|
||||
func (c *client) GetRegistryHistory(ctx context.Context, ip string) (registryHistoryResponse, error) {
|
||||
|
||||
@@ -67,6 +67,10 @@ type fakeControlAPI struct {
|
||||
breakdownStatus int
|
||||
breakdownList string
|
||||
breakdownReqs []string
|
||||
trend registryTrend // GET /registry/trend
|
||||
trendReqs []string
|
||||
alwaysPass registryAlwaysPass // GET /registry/always-pass
|
||||
alwaysPassReqs []string // its queries, the list's and the CSV's
|
||||
|
||||
// Scan job state machine (see the scan handlers): POST starts a job that
|
||||
// stays "running" for scanRunPolls GET polls (0 = finishes at once), then
|
||||
@@ -500,6 +504,30 @@ func (f *fakeControlAPI) handler() http.Handler {
|
||||
}
|
||||
writeJSON(w, http.StatusOK, f.breakdown)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/admin/registry/trend", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.trendReqs = append(f.trendReqs, r.URL.RequestURI())
|
||||
writeJSON(w, http.StatusOK, f.trend)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/admin/registry/always-pass", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.alwaysPassReqs = append(f.alwaysPassReqs, r.URL.RequestURI())
|
||||
writeJSON(w, http.StatusOK, f.alwaysPass)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/admin/registry/always-pass/list", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.alwaysPassReqs = append(f.alwaysPassReqs, r.URL.RequestURI())
|
||||
if r.URL.Query().Get("format") == "csv" {
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="registry_always_pass_egress_https.csv"`)
|
||||
_, _ = w.Write([]byte("Адрес\r\n1.2.3.4\r\n"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"columns": []string{"Адрес"}, "rows": [][]string{{"1.2.3.4"}}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/admin/registry/breakdown/list", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
@@ -163,6 +163,45 @@ type breakdownRow struct {
|
||||
OK int `json:"ok"`
|
||||
}
|
||||
|
||||
// registryTrend is GET /admin/registry/trend: the checks of one direction (and
|
||||
// protocol) per target or site in each finalized run, oldest run first.
|
||||
type registryTrend struct {
|
||||
Group string `json:"group"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Runs []trendRun `json:"runs"`
|
||||
Series []trendSeries `json:"series"`
|
||||
}
|
||||
|
||||
// registryAlwaysPass is GET /admin/registry/always-pass: of Addresses with
|
||||
// checks in the Runs of the period, AlwaysPass never failed one.
|
||||
type registryAlwaysPass struct {
|
||||
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 trendRun struct {
|
||||
ID int64 `json:"id"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinalizedAt *time.Time `json:"finalized_at"`
|
||||
Addresses int `json:"addresses"`
|
||||
}
|
||||
|
||||
type trendSeries struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Points []trendPoint `json:"points"`
|
||||
}
|
||||
|
||||
type trendPoint struct {
|
||||
RunID int64 `json:"run_id"`
|
||||
Total int `json:"total"`
|
||||
OK int `json:"ok"`
|
||||
}
|
||||
|
||||
// scanStatusDTO is the state of control-api's background floating-IP scan job
|
||||
// (POST/GET /api/v1/admin/ips/scan).
|
||||
type scanStatusDTO struct {
|
||||
|
||||
@@ -612,3 +612,82 @@ func TestRegistryBreakdownChartAndProxy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The trend chart of /registry: its frame is on the page only with a direction
|
||||
// and carries the period; the data block is a separate request that passes just
|
||||
// the subnet, direction, protocol and period to control-api.
|
||||
func TestRegistryTrendBlock(t *testing.T) {
|
||||
fake, ts := analyticsFake(t)
|
||||
now := time.Now().UTC()
|
||||
fake.trend = registryTrend{Group: "target", Runs: []trendRun{{ID: 4, StartedAt: now, Addresses: 3}, {ID: 5, StartedAt: now, Addresses: 3}},
|
||||
Series: []trendSeries{{Key: "https://a.test", Label: "a.test", Points: []trendPoint{{RunID: 5, Total: 3, OK: 2}}}}}
|
||||
|
||||
page := get(t, ts, "/registry?direction=egress&protocol=https&subnet=9.9.9.0/24&trend_from=2026-09-01&trend_view=count&run=1&q=9")
|
||||
for _, want := range []string{`id="registry-trend-panel"`, "Динамика по запускам · Egress · https", `value="2026-09-01"`, `name="trend_view" value="count"`,
|
||||
`hx-get="/registry/trend?direction=egress&protocol=https&subnet=9.9.9.0%2F24&trend_from=2026-09-01"`} {
|
||||
if !strings.Contains(page, want) {
|
||||
t.Errorf("expected %q in the page", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(get(t, ts, "/registry?protocol=https"), `id="registry-trend-panel"`) {
|
||||
t.Error("no trend frame without a direction")
|
||||
}
|
||||
|
||||
frag := get(t, ts, "/registry/trend?direction=egress&protocol=https&run=1&q=9&trend_to=2026-09-30&trend_to_x=1")
|
||||
if !strings.Contains(frag, `data-trend="`) || !strings.Contains(frag, "a.test") || !strings.Contains(frag, "2 из 3") {
|
||||
t.Errorf("fragment lacks the data: %s", frag)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
req := fake.trendReqs[len(fake.trendReqs)-1]
|
||||
fake.mu.Unlock()
|
||||
if !strings.Contains(req, "direction=egress") || !strings.Contains(req, "to=2026-09-30") || strings.Contains(req, "run=") || strings.Contains(req, "q=") {
|
||||
t.Errorf("trend request %q", req)
|
||||
}
|
||||
if frag = get(t, ts, "/registry/trend?protocol=https"); strings.Contains(frag, "data-trend") || !strings.Contains(frag, "Выберите направление") {
|
||||
t.Errorf("no direction: %s", frag)
|
||||
}
|
||||
}
|
||||
|
||||
// The "always passed" tile of /registry: its slot is in the trend frame only
|
||||
// with a direction; the fragment is a button with the numbers, passes the
|
||||
// search and the period to control-api (not the run or the status), and the
|
||||
// list and CSV proxies need a direction.
|
||||
func TestRegistryAlwaysPassTile(t *testing.T) {
|
||||
fake, ts := analyticsFake(t)
|
||||
first, last := time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC), time.Date(2026, 9, 30, 10, 0, 0, 0, time.UTC)
|
||||
fake.alwaysPass = registryAlwaysPass{Runs: 22, FirstRunAt: &first, LastRunAt: &last, Addresses: 8, AlwaysPass: 3}
|
||||
|
||||
page := get(t, ts, "/registry?direction=egress&protocol=https&q=9&trend_from=2026-09-01")
|
||||
if !strings.Contains(page, `hx-get="/registry/always-pass?direction=egress&protocol=https&q=9&trend_from=2026-09-01"`) {
|
||||
t.Errorf("no tile slot in the page")
|
||||
}
|
||||
if strings.Contains(get(t, ts, "/registry?protocol=https"), `id="registry-always-pass"`) {
|
||||
t.Error("no tile slot without a direction")
|
||||
}
|
||||
|
||||
frag := get(t, ts, "/registry/always-pass?direction=egress&protocol=https&q=9&run=1&status=fail&trend_from=2026-09-01")
|
||||
for _, want := range []string{`class="ap-tile"`, `aria-label="Всегда проходили: 3 из 8 адресов, 37,5 %`, "из 8 адресов · 37,5 %", "за 22 запуска, 2026-09-01 — 2026-09-30", `data-ap-qs="`} {
|
||||
if !strings.Contains(frag, want) {
|
||||
t.Errorf("expected %q in %s", want, frag)
|
||||
}
|
||||
}
|
||||
fake.mu.Lock()
|
||||
req := fake.alwaysPassReqs[len(fake.alwaysPassReqs)-1]
|
||||
fake.mu.Unlock()
|
||||
if !strings.Contains(req, "q=9") || !strings.Contains(req, "from=2026-09-01") || strings.Contains(req, "run=") || strings.Contains(req, "last_result") {
|
||||
t.Errorf("always-pass request %q", req)
|
||||
}
|
||||
if frag = get(t, ts, "/registry/always-pass?protocol=https"); strings.Contains(frag, "ap-tile") || !strings.Contains(frag, "Выберите направление") {
|
||||
t.Errorf("no direction: %s", frag)
|
||||
}
|
||||
|
||||
if body := get(t, ts, "/registry/always-pass/list?direction=egress&protocol=https&trend_to=2026-09-30"); !strings.Contains(body, "1.2.3.4") {
|
||||
t.Errorf("list proxy: %s", body)
|
||||
}
|
||||
if body := get(t, ts, "/registry/always-pass/csv?direction=egress&protocol=https"); !strings.Contains(body, "1.2.3.4") {
|
||||
t.Errorf("csv proxy: %s", body)
|
||||
}
|
||||
if resp, err := http.Get(ts.URL + "/registry/always-pass/list?protocol=https"); err != nil || resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("list without a direction: %v %v", resp, err)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Values of the registry's direction and protocol filters; same as
|
||||
@@ -30,6 +32,8 @@ type registryPageData struct {
|
||||
Runs []runOption
|
||||
SubnetOptions []subnetOption
|
||||
Breakdown *breakdownView // nil unless a direction or protocol is chosen
|
||||
Trend *trendShell // nil without a direction
|
||||
TrendView string // trendViewPct or trendViewCount
|
||||
AnalyticsURL string // the analytics page of Run with the same subnet, direction and protocol
|
||||
Page, PerPage int
|
||||
Total int
|
||||
@@ -116,6 +120,10 @@ func (s *Server) handleRegistryPage(w http.ResponseWriter, r *http.Request) {
|
||||
PerPageOptions: perPageOptions,
|
||||
}
|
||||
data.ActiveNav = "registry"
|
||||
data.TrendView = parseTrendView(r.URL.Query().Get("trend_view"))
|
||||
if direction != "" {
|
||||
data.Trend = newTrendShell(query, data.TrendView, r.URL.Query())
|
||||
}
|
||||
if run > 0 {
|
||||
data.AnalyticsURL = analyticsURL(run, query)
|
||||
}
|
||||
@@ -344,3 +352,274 @@ func (s *Server) handleRegistryDetail(w http.ResponseWriter, r *http.Request) {
|
||||
data.Banner = bannerFor(err)
|
||||
s.renderPage(w, r, "registry_detail_page", data)
|
||||
}
|
||||
|
||||
// Values of the trend's ?trend_view=: the Y axis in percent or in checks.
|
||||
const (
|
||||
trendViewPct = "pct"
|
||||
trendViewCount = "count"
|
||||
)
|
||||
|
||||
func parseTrendView(v string) string {
|
||||
if v == trendViewCount {
|
||||
return trendViewCount
|
||||
}
|
||||
return trendViewPct
|
||||
}
|
||||
|
||||
// parseTrendDate reads ?trend_from= / ?trend_to= (YYYY-MM-DD); a value that is
|
||||
// not a date is dropped.
|
||||
func parseTrendDate(v string) string {
|
||||
if _, err := time.Parse("2006-01-02", v); err != nil {
|
||||
return ""
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// trendShell is the frame of the chart "dynamics over runs" on the registry
|
||||
// page: the controls render at once, the chart itself (registry_trend_data) is
|
||||
// loaded by htmx from /registry/trend, so the table does not wait for it. QS is
|
||||
// the query that request carries: the subnet, direction, protocol and period.
|
||||
type trendShell struct {
|
||||
Scope, View, From, To, QS string
|
||||
APQS string // the query of the always-pass tile: QS plus the address search
|
||||
}
|
||||
|
||||
func newTrendShell(q registryQuery, view string, v url.Values) *trendShell {
|
||||
t := &trendShell{View: view, From: parseTrendDate(v.Get("trend_from")), To: parseTrendDate(v.Get("trend_to"))}
|
||||
t.Scope = strings.ToUpper(q.Direction[:1]) + q.Direction[1:] + " · " + trendProtocol(q)
|
||||
p := url.Values{"direction": {q.Direction}}
|
||||
for k, x := range map[string]string{"protocol": q.Protocol, "subnet": q.Subnet, "trend_from": t.From, "trend_to": t.To} {
|
||||
if x != "" {
|
||||
p.Set(k, x)
|
||||
}
|
||||
}
|
||||
t.QS = p.Encode()
|
||||
if q.Q != "" {
|
||||
p.Set("q", q.Q)
|
||||
}
|
||||
t.APQS = p.Encode()
|
||||
return t
|
||||
}
|
||||
|
||||
func trendProtocol(q registryQuery) string {
|
||||
if q.Protocol == "" {
|
||||
return "все протоколы"
|
||||
}
|
||||
return q.Protocol
|
||||
}
|
||||
|
||||
// trendView is the loaded chart: the data for registry-trend.js (JSON, in the
|
||||
// element's data-trend), and the same numbers as a table for screen readers.
|
||||
// With Err set the chart could not be loaded, with Empty there is nothing to draw.
|
||||
type trendView struct {
|
||||
Err, Note, JSON string
|
||||
Empty bool
|
||||
Runs []trendRunView
|
||||
Rows []trendRowView
|
||||
}
|
||||
|
||||
type trendRunView struct {
|
||||
ID int64
|
||||
Date string
|
||||
Addresses int
|
||||
}
|
||||
|
||||
type trendRowView struct {
|
||||
Label string
|
||||
Cells []string
|
||||
}
|
||||
|
||||
// trendClientData is what registry-trend.js draws: runs oldest first, and per
|
||||
// target or site its points [index of the run, successful, all checks].
|
||||
type trendClientData struct {
|
||||
Runs []trendClientRun `json:"runs"`
|
||||
Series []trendClientSeries `json:"series"`
|
||||
}
|
||||
|
||||
type trendClientRun struct {
|
||||
ID int64 `json:"id"`
|
||||
At string `json:"at"`
|
||||
Addresses int `json:"n"`
|
||||
}
|
||||
|
||||
type trendClientSeries struct {
|
||||
Label string `json:"l"`
|
||||
Points [][3]int `json:"p"`
|
||||
}
|
||||
|
||||
// handleRegistryTrend serves the loaded chart as an htmx fragment: the page's
|
||||
// subnet, direction and protocol plus the period (?trend_from=&trend_to=). An
|
||||
// error of control-api shows in the fragment, not as a banner.
|
||||
func (s *Server) handleRegistryTrend(w http.ResponseWriter, r *http.Request) {
|
||||
q := parseSliceFilter(r.URL.Query())
|
||||
v := &trendView{}
|
||||
if q.Direction == "" {
|
||||
v.Err = "Выберите направление, чтобы увидеть динамику по запускам."
|
||||
} else {
|
||||
from, to := parseTrendDate(r.URL.Query().Get("trend_from")), parseTrendDate(r.URL.Query().Get("trend_to"))
|
||||
t, err := s.CA.GetRegistryTrend(r.Context(), q, from, to)
|
||||
if err != nil {
|
||||
v.Err = "Не удалось получить динамику: " + err.Error()
|
||||
} else {
|
||||
s.fillTrendView(v, t, from != "" || to != "")
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if err := s.tmpl.ExecuteTemplate(w, "registry_trend_data", v); err != nil {
|
||||
s.Log.Error("render fragment", "template", "registry_trend_data", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) fillTrendView(v *trendView, t registryTrend, period bool) {
|
||||
if len(t.Runs) == 0 || len(t.Series) == 0 {
|
||||
v.Empty = true
|
||||
return
|
||||
}
|
||||
idx := make(map[int64]int, len(t.Runs))
|
||||
d := trendClientData{Runs: make([]trendClientRun, len(t.Runs)), Series: make([]trendClientSeries, len(t.Series))}
|
||||
for i, x := range t.Runs {
|
||||
idx[x.ID] = i
|
||||
d.Runs[i] = trendClientRun{ID: x.ID, At: x.StartedAt.UTC().Format(time.RFC3339), Addresses: x.Addresses}
|
||||
v.Runs = append(v.Runs, trendRunView{ID: x.ID, Date: x.StartedAt.UTC().Format("2006-01-02 15:04"), Addresses: x.Addresses})
|
||||
}
|
||||
for i, sr := range t.Series {
|
||||
row := trendRowView{Label: sr.Label, Cells: make([]string, len(t.Runs))}
|
||||
for j := range row.Cells {
|
||||
row.Cells[j] = "—"
|
||||
}
|
||||
d.Series[i].Label = sr.Label
|
||||
for _, p := range sr.Points {
|
||||
if j, ok := idx[p.RunID]; ok {
|
||||
d.Series[i].Points = append(d.Series[i].Points, [3]int{j, p.OK, p.Total})
|
||||
row.Cells[j] = strconv.Itoa(p.OK) + " из " + strconv.Itoa(p.Total)
|
||||
}
|
||||
}
|
||||
v.Rows = append(v.Rows, row)
|
||||
}
|
||||
b, _ := json.Marshal(d)
|
||||
v.JSON = string(b)
|
||||
v.Note = "Показаны завершённые запуски: " + strconv.Itoa(len(t.Runs)) + "."
|
||||
if t.Truncated {
|
||||
v.Note += " Запусков больше, чем помещается на график, — показаны самые поздние."
|
||||
if !period {
|
||||
v.Note += " Чтобы увидеть более ранние, задайте период."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// alwaysPassView is the tile "always passed" above the trend chart. With Err
|
||||
// set the tile could not be loaded; with Hint there is nothing to count. QS is
|
||||
// the query of its list (the filter and the period), Label the title of the
|
||||
// list's dialog and Slice what the count covers.
|
||||
type alwaysPassView struct {
|
||||
Err, Hint string
|
||||
N, M int
|
||||
Pct, Period, Label string
|
||||
Slice, Aria, QS string
|
||||
}
|
||||
|
||||
// pluralRuns declines "запуск" for n.
|
||||
func pluralRuns(n int) string {
|
||||
if n%100 >= 11 && n%100 <= 14 {
|
||||
return "запусков"
|
||||
}
|
||||
switch n % 10 {
|
||||
case 1:
|
||||
return "запуск"
|
||||
case 2, 3, 4:
|
||||
return "запуска"
|
||||
default:
|
||||
return "запусков"
|
||||
}
|
||||
}
|
||||
|
||||
// alwaysPassQuery reads the request of the tile and its list proxies: the
|
||||
// page's subnet, direction, protocol and address search, and the period
|
||||
// (?trend_from=&trend_to=); direction is required.
|
||||
func alwaysPassQuery(r *http.Request) (q registryQuery, from, to string, ok bool) {
|
||||
q = parseRegistryQuery(r)
|
||||
q.Run, q.LastResult = 0, "" // the run and the status describe the current state, not a history
|
||||
return q, parseTrendDate(r.URL.Query().Get("trend_from")), parseTrendDate(r.URL.Query().Get("trend_to")), q.Direction != ""
|
||||
}
|
||||
|
||||
// handleRegistryAlwaysPass serves the tile as an htmx fragment. An error of
|
||||
// control-api shows in the tile, not as a banner.
|
||||
func (s *Server) handleRegistryAlwaysPass(w http.ResponseWriter, r *http.Request) {
|
||||
q, from, to, ok := alwaysPassQuery(r)
|
||||
v := &alwaysPassView{}
|
||||
if !ok {
|
||||
v.Hint = "Выберите направление, чтобы увидеть, какие адреса всегда проходили проверку."
|
||||
} else if a, err := s.CA.GetRegistryAlwaysPass(r.Context(), q, from, to); err != nil {
|
||||
v.Err = "Не удалось получить показатель: " + err.Error()
|
||||
} else {
|
||||
fillAlwaysPassView(v, q, from, to, a)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if err := s.tmpl.ExecuteTemplate(w, "registry_always_pass", v); err != nil {
|
||||
s.Log.Error("render fragment", "template", "registry_always_pass", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func fillAlwaysPassView(v *alwaysPassView, q registryQuery, from, to string, a registryAlwaysPass) {
|
||||
v.N, v.M, v.Pct = a.AlwaysPass, a.Addresses, pct1(a.AlwaysPass, a.Addresses)
|
||||
v.Label = "Всегда проходили · " + strings.ToUpper(q.Direction[:1]) + q.Direction[1:] + " · " + trendProtocol(q)
|
||||
p := q.filter()
|
||||
p.Del("run")
|
||||
p.Del("last_result")
|
||||
if from != "" {
|
||||
p.Set("trend_from", from)
|
||||
}
|
||||
if to != "" {
|
||||
p.Set("trend_to", to)
|
||||
}
|
||||
v.QS = p.Encode()
|
||||
if a.Runs == 0 || a.FirstRunAt == nil || a.LastRunAt == nil {
|
||||
v.Period = "в этом периоде нет завершённых запусков"
|
||||
} else {
|
||||
v.Period = "за " + strconv.Itoa(a.Runs) + " " + pluralRuns(a.Runs) + ", " + a.FirstRunAt.UTC().Format("2006-01-02") + " — " + a.LastRunAt.UTC().Format("2006-01-02")
|
||||
}
|
||||
v.Slice = "Учтены направление, протокол, подсеть, поиск по IP и период. Не учтены запуск и статус. Берутся адреса, у которых в запусках периода есть проверки; адрес засчитан, если ни одна из них не провалена."
|
||||
if a.Truncated {
|
||||
v.Slice += " Запусков больше, чем учтено, — взяты самые поздние."
|
||||
}
|
||||
v.Aria = "Всегда проходили: " + strconv.Itoa(a.AlwaysPass) + " из " + strconv.Itoa(a.Addresses) + " адресов, " + v.Pct + " %, " + v.Period + ". Открыть список адресов."
|
||||
}
|
||||
|
||||
// handleRegistryAlwaysPassList proxies the addresses behind the tile as JSON.
|
||||
func (s *Server) handleRegistryAlwaysPassList(w http.ResponseWriter, r *http.Request) {
|
||||
q, from, to, ok := alwaysPassQuery(r)
|
||||
if !ok {
|
||||
http.Error(w, "direction is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
out, err := s.CA.GetRegistryAlwaysPassList(r.Context(), q, from, to)
|
||||
if err != nil {
|
||||
writeProxyError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = w.Write(out)
|
||||
}
|
||||
|
||||
// handleRegistryAlwaysPassCSV proxies the same table as a CSV download.
|
||||
func (s *Server) handleRegistryAlwaysPassCSV(w http.ResponseWriter, r *http.Request) {
|
||||
q, from, to, ok := alwaysPassQuery(r)
|
||||
if !ok {
|
||||
http.Error(w, "direction is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
body, disposition, err := s.CA.GetRegistryAlwaysPassCSV(r.Context(), q, from, to)
|
||||
if err != nil {
|
||||
writeProxyError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
if disposition != "" {
|
||||
w.Header().Set("Content-Disposition", disposition)
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
@@ -27,6 +27,10 @@ func (s *Server) routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /ips/clear", s.handleIPsClear)
|
||||
|
||||
mux.HandleFunc("GET /registry", s.handleRegistryPage)
|
||||
mux.HandleFunc("GET /registry/trend", s.handleRegistryTrend)
|
||||
mux.HandleFunc("GET /registry/always-pass", s.handleRegistryAlwaysPass)
|
||||
mux.HandleFunc("GET /registry/always-pass/list", s.handleRegistryAlwaysPassList)
|
||||
mux.HandleFunc("GET /registry/always-pass/csv", s.handleRegistryAlwaysPassCSV)
|
||||
mux.HandleFunc("GET /registry/{ip}", s.handleRegistryDetail)
|
||||
mux.HandleFunc("GET /registry/breakdown/list", s.handleRegistryBreakdownList)
|
||||
mux.HandleFunc("GET /registry/breakdown/csv", s.handleRegistryBreakdownCSV)
|
||||
|
||||
@@ -24,16 +24,16 @@
|
||||
exited: ['Вышли из индикатора', 'Общие адреса, которые в A входили в этот индикатор, а в B не входят.']
|
||||
};
|
||||
var HINT_ONE = {
|
||||
2: 'Вердикт адреса, который система выставила при агрегации, а не итог всех проверок.',
|
||||
3: 'Сколько egress-проверок адреса успешно из всех записанных в последнем цикле запуска. «—» — egress-проверок нет.',
|
||||
4: 'Сколько ingress-проверок адреса успешно из всех записанных в последнем цикле запуска. «—» — ingress-проверок нет.',
|
||||
5: 'Индикаторы страницы «Аналитика», в которые входит адрес. Один адрес может входить в несколько; вердикт — ровно в один из трёх.'
|
||||
3: 'Вердикт адреса, который система выставила при агрегации, а не итог всех проверок.',
|
||||
4: 'Сколько egress-проверок адреса успешно из всех записанных в последнем цикле запуска. «—» — egress-проверок нет.',
|
||||
5: 'Сколько ingress-проверок адреса успешно из всех записанных в последнем цикле запуска. «—» — ingress-проверок нет.',
|
||||
6: 'Индикаторы страницы «Аналитика», в которые входит адрес. Один адрес может входить в несколько; вердикт — ровно в один из трёх.'
|
||||
};
|
||||
var HINT_PAIR = {
|
||||
2: 'Вердикт адреса в запуске A и в запуске B.',
|
||||
3: 'Сколько egress-проверок адреса успешно из всех записанных в последнем цикле: в A → в B.',
|
||||
4: 'Сколько ingress-проверок адреса успешно из всех записанных в последнем цикле: в A → в B.',
|
||||
5: 'Что изменилось между запусками, по шагам: вердикт, вход в индикатор и выход из него, проваленные цели https и площадки ssh, валидатор. У адреса без изменений в индикаторах — «без изменений», даже если набор проваленных целей другой.'
|
||||
3: 'Вердикт адреса в запуске A и в запуске B.',
|
||||
4: 'Сколько egress-проверок адреса успешно из всех записанных в последнем цикле: в A → в B.',
|
||||
5: 'Сколько ingress-проверок адреса успешно из всех записанных в последнем цикле: в A → в B.',
|
||||
6: 'Что изменилось между запусками, по шагам: вердикт, вход в индикатор и выход из него, проваленные цели https и площадки ssh, валидатор. У адреса без изменений в индикаторах — «без изменений», даже если набор проваленных целей другой.'
|
||||
};
|
||||
|
||||
function describe(f) {
|
||||
|
||||
@@ -27,33 +27,86 @@
|
||||
if (d.showModal) d.showModal(); else d.setAttribute('open', '');
|
||||
}
|
||||
|
||||
/* m: title, note, scope ("Запуск" by default), runLabel, cols, rows, hints
|
||||
(column index -> text), cellHints (column index -> function of the value),
|
||||
dist (HTML above the table), csvURL (the file behind "Скачать CSV"). */
|
||||
function fill(m) {
|
||||
cur = m;
|
||||
$('an-dlg-title').textContent = m.title + ' · ' + fmt(m.rows.length);
|
||||
$('an-dlg-note').textContent = (m.scope || 'Запуск') + ': ' + m.runLabel + '. ' + m.note;
|
||||
$('an-dlg-dist').hidden = !m.dist;
|
||||
$('an-dlg-dist').innerHTML = m.dist || '';
|
||||
var hint = m.hints || {};
|
||||
$('an-dlg-tbl').innerHTML = '<thead><tr>' + m.cols.map(function (c, i) {
|
||||
return hint[i] ? '<th ' + tipAttr(hint[i]) + ' tabindex="0">' + esc(c) + '<span class="an-hint" aria-hidden="true">ⓘ</span></th>' : '<th>' + esc(c) + '</th>';
|
||||
}).join('') + '</tr></thead><tbody>' + m.rows.map(function (x) {
|
||||
var SUBNET_HINT = 'Подсеть из списка в настройках, в которую входит адрес (самая узкая из подходящих). «вне списка подсетей» — адрес не входит ни в одну; при пустом списке адреса группируются по /24.';
|
||||
var LABEL_HINT = 'Название подсети, которое задал администратор в настройках. Пусто, если метки нет.';
|
||||
var MAX_CHIPS = 8;
|
||||
var subIdx = -1; // index of the "Подсеть" column of the list shown, -1 if none
|
||||
var subSel = ''; // the subnet chosen in the summary, '' for all
|
||||
|
||||
function rowsHTML(m) {
|
||||
return m.rows.filter(function (x) { return !subSel || x[subIdx] === subSel; }).map(function (x) {
|
||||
return '<tr>' + x.map(function (v, i) {
|
||||
var h = m.cellHints && m.cellHints[i] ? m.cellHints[i](v) : '';
|
||||
return '<td class="' + (i < 2 ? 'an-a' : '') + '"' + (h ? ' ' + tipAttr(h) : '') + '>' + esc(v) + '</td>';
|
||||
}).join('') + '</tr>';
|
||||
}).join('') + '</tbody>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/* chips "subnet - N addresses": the largest MAX_CHIPS, a click filters the rows shown */
|
||||
function renderSubnets(m) {
|
||||
var box = $('an-dlg-subs');
|
||||
if (!box) {
|
||||
box = document.createElement('div');
|
||||
box.id = 'an-dlg-subs';
|
||||
box.className = 'an-subs';
|
||||
$('an-dlg-dist').insertAdjacentElement('afterend', box);
|
||||
}
|
||||
box.innerHTML = '';
|
||||
box.hidden = subIdx < 0 || !m.rows.length;
|
||||
if (box.hidden) return;
|
||||
var cnt = {};
|
||||
m.rows.forEach(function (x) { cnt[x[subIdx]] = (cnt[x[subIdx]] || 0) + 1; });
|
||||
var names = Object.keys(cnt).sort(function (a, b) { return cnt[b] - cnt[a] || (a < b ? -1 : 1); });
|
||||
var shown = names.slice(0, MAX_CHIPS);
|
||||
if (subSel && shown.indexOf(subSel) < 0) shown.push(subSel);
|
||||
var html = '<span class="an-subs-h">Подсети</span>' + shown.map(function (n) {
|
||||
return '<button type="button" class="an-sub-chip" data-sub="' + esc(n) + '" aria-pressed="' + (n === subSel) + '">' + esc(n) + ' — ' + fmt(cnt[n]) + '</button>';
|
||||
}).join('');
|
||||
if (names.length > shown.length) html += '<span class="an-subs-more">ещё ' + fmt(names.length - shown.length) + '</span>';
|
||||
if (subSel) html += '<span class="an-subs-more">показано ' + fmt(cnt[subSel]) + ' из ' + fmt(m.rows.length) + '</span>';
|
||||
box.innerHTML = html;
|
||||
}
|
||||
|
||||
/* m: title, note, scope ("Запуск" by default), runLabel, cols, rows, hints
|
||||
(column index -> text), cellHints (column index -> function of the value),
|
||||
dist (HTML above the table), csvURL (the file behind "Скачать CSV").
|
||||
A list with a "Подсеть" column gets the subnet summary and filter; copying
|
||||
and the CSV file always carry the whole list. */
|
||||
function fill(m) {
|
||||
cur = m;
|
||||
subSel = '';
|
||||
subIdx = m.cols.indexOf('Подсеть');
|
||||
$('an-dlg-title').textContent = m.title + ' · ' + fmt(m.rows.length);
|
||||
$('an-dlg-note').textContent = (m.scope || 'Запуск') + ': ' + m.runLabel + '. ' + m.note;
|
||||
$('an-dlg-dist').hidden = !m.dist;
|
||||
$('an-dlg-dist').innerHTML = m.dist || '';
|
||||
var hint = {};
|
||||
m.cols.forEach(function (c, i) {
|
||||
if (c === 'Подсеть') hint[i] = SUBNET_HINT; else if (c === 'Метка подсети') hint[i] = LABEL_HINT;
|
||||
});
|
||||
Object.keys(m.hints || {}).forEach(function (k) { hint[k] = m.hints[k]; });
|
||||
$('an-dlg-tbl').innerHTML = '<thead><tr>' + m.cols.map(function (c, i) {
|
||||
return hint[i] ? '<th ' + tipAttr(hint[i]) + ' tabindex="0">' + esc(c) + '<span class="an-hint" aria-hidden="true">ⓘ</span></th>' : '<th>' + esc(c) + '</th>';
|
||||
}).join('') + '</tr></thead><tbody>' + rowsHTML(m) + '</tbody>';
|
||||
renderSubnets(m);
|
||||
$('an-dlg-msg').textContent = '';
|
||||
}
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var c = e.target.closest ? e.target.closest('.an-sub-chip') : null;
|
||||
if (!c || !cur || subIdx < 0) return;
|
||||
subSel = subSel === c.dataset.sub ? '' : c.dataset.sub;
|
||||
$('an-dlg-tbl').querySelector('tbody').innerHTML = rowsHTML(cur);
|
||||
renderSubnets(cur);
|
||||
});
|
||||
|
||||
/* Opens the dialog with the title and "Загрузка…", fetches the list as JSON;
|
||||
resolves with it, or with null (and a message in the dialog) on a failure. */
|
||||
function load(url, title) {
|
||||
$('an-dlg-title').textContent = title;
|
||||
$('an-dlg-note').textContent = 'Загрузка…';
|
||||
$('an-dlg-dist').hidden = true;
|
||||
if ($('an-dlg-subs')) $('an-dlg-subs').hidden = true;
|
||||
$('an-dlg-tbl').innerHTML = '';
|
||||
$('an-dlg-msg').textContent = '';
|
||||
cur = null;
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
/* heat ramp: one blue hue, validated sequential steps (light = low) */
|
||||
--an-h1:#cde2fb; --an-h2:#9ec5f4; --an-h3:#6da7ec; --an-h4:#3987e5; --an-h5:#256abf; --an-h6:#184f95; --an-h7:#0d366b;
|
||||
--an-hi1:#12161F; --an-hi2:#12161F; --an-hi3:#12161F; --an-hi4:#FFFFFF; --an-hi5:#FFFFFF; --an-hi6:#FFFFFF; --an-hi7:#FFFFFF;
|
||||
/* trend chart: ten line colours, one per target or site */
|
||||
--tr-c0:#2a6fdb; --tr-c1:#d4540a; --tr-c2:#0b8f6a; --tr-c3:#b03a8c; --tr-c4:#8c6d00; --tr-c5:#0090b8; --tr-c6:#7a4fd1; --tr-c7:#c0392b; --tr-c8:#4d7c0f; --tr-c9:#5b6577;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
@@ -14,6 +16,7 @@
|
||||
--an-bar: #5C8CFF; --an-bar-track: #1D2430;
|
||||
--an-h1:#0d366b; --an-h2:#104281; --an-h3:#184f95; --an-h4:#256abf; --an-h5:#3987e5; --an-h6:#6da7ec; --an-h7:#9ec5f4;
|
||||
--an-hi1:#B8C9E8; --an-hi2:#C3D6F5; --an-hi3:#E7ECF5; --an-hi4:#FFFFFF; --an-hi5:#0A0D13; --an-hi6:#0A0D13; --an-hi7:#0A0D13;
|
||||
--tr-c0:#6ea2ff; --tr-c1:#ff8a4c; --tr-c2:#2fd0a0; --tr-c3:#e58ac4; --tr-c4:#e0b84a; --tr-c5:#4cc9ee; --tr-c6:#a58bff; --tr-c7:#ff6f61; --tr-c8:#a3d95b; --tr-c9:#a0abbd;
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
@@ -21,6 +24,7 @@
|
||||
--an-bar: #5C8CFF; --an-bar-track: #1D2430;
|
||||
--an-h1:#0d366b; --an-h2:#104281; --an-h3:#184f95; --an-h4:#256abf; --an-h5:#3987e5; --an-h6:#6da7ec; --an-h7:#9ec5f4;
|
||||
--an-hi1:#B8C9E8; --an-hi2:#C3D6F5; --an-hi3:#E7ECF5; --an-hi4:#FFFFFF; --an-hi5:#0A0D13; --an-hi6:#0A0D13; --an-hi7:#0A0D13;
|
||||
--tr-c0:#6ea2ff; --tr-c1:#ff8a4c; --tr-c2:#2fd0a0; --tr-c3:#e58ac4; --tr-c4:#e0b84a; --tr-c5:#4cc9ee; --tr-c6:#a58bff; --tr-c7:#ff6f61; --tr-c8:#a3d95b; --tr-c9:#a0abbd;
|
||||
}
|
||||
|
||||
.an { display: grid; gap: 16px; align-content: start; min-width: 0; font-family: var(--font-ui); font-size: 14px; line-height: 1.5; }
|
||||
@@ -136,3 +140,30 @@ button.an-bar-row:focus-visible { outline: 2px solid var(--accent); outline-offs
|
||||
.an tr, .an tbody tr { display: table-row; width: auto; padding: 0; border-bottom: 0; }
|
||||
.an td { display: table-cell; width: auto; padding: 6px 8px; border-bottom: 1px solid var(--border-soft); }
|
||||
}
|
||||
|
||||
/* trend chart of the registry (registry-trend.js): the plot scrolls sideways inside its block, never the page */
|
||||
.an-field input[type="date"] { font: 500 13px var(--font-mono); background: var(--surface); color: var(--text); border: 1px solid var(--border); border-radius: var(--an-radius); padding: 6px 10px; min-width: 0; }
|
||||
.tr-scroll { overflow-x: auto; max-width: 100%; }
|
||||
.tr-plot { position: relative; height: 260px; min-width: 520px; }
|
||||
.tr-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
@media (max-width: 640px) { .an-field input[type="date"] { width: 100%; } }
|
||||
|
||||
/* the "always passed" tile above the trend chart (registry.js): a button that opens the list of addresses */
|
||||
button.ap-tile { display: grid; gap: 2px; text-align: left; font: inherit; color: inherit; background: var(--surface-alt); border: 1px solid var(--border); border-left: 3px solid var(--success); border-radius: var(--an-radius); padding: 10px 14px; cursor: pointer; max-width: 100%; }
|
||||
button.ap-tile:hover { background: var(--surface); border-color: var(--accent); }
|
||||
button.ap-tile:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.ap-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
|
||||
.ap-t { font-weight: 600; }
|
||||
.ap-v { font: 700 22px var(--font-mono); font-variant-numeric: tabular-nums; color: var(--success); }
|
||||
.ap-of { font: 500 13px var(--font-mono); color: var(--text-muted); }
|
||||
.ap-sub { font-size: 12.5px; color: var(--text-muted); overflow-wrap: anywhere; }
|
||||
|
||||
/* subnet summary above the address list of the dialog */
|
||||
.an-dlg .an-subs { flex: 0 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; max-height: 5.5em; overflow: auto; }
|
||||
.an-subs .an-subs-h { font: 700 11px var(--font-mono); text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); }
|
||||
.an-subs .an-subs-more { font: 500 12px var(--font-mono); color: var(--text-muted); }
|
||||
.an-subs .an-sub-chip { font: 500 12px var(--font-mono); font-variant-numeric: tabular-nums; white-space: nowrap; background: var(--surface); color: var(--text); border: 1px solid var(--border); border-radius: 2px; padding: 2px 8px; cursor: pointer; }
|
||||
.an-subs .an-sub-chip:hover { background: var(--surface-alt); }
|
||||
.an-subs .an-sub-chip[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-strong); border-color: var(--accent); }
|
||||
.an-subs .an-sub-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
@media (max-height: 540px) { .an-dlg .an-subs { display: none; } }
|
||||
@@ -88,7 +88,7 @@
|
||||
$('an-subtbl').innerHTML = '<thead><tr><th>Подсеть</th><th class="an-r">Адресов</th><th class="an-r">pass</th><th class="an-r">Egress OK</th><th class="an-r">Ingress OK</th></tr></thead><tbody>' +
|
||||
shown.map(function (s) {
|
||||
var name = s.label ? s.cidr + ' · ' + s.label : s.cidr;
|
||||
var link = s.cidr === 'прочие' ? esc(name) : '<a href="' + M.registry_url + '&subnet=' + encodeURIComponent(s.cidr) + '" title="Открыть в реестре: запуск ' + M.run_id + ', подсеть ' + esc(s.cidr) + '">' + esc(name) + '</a>';
|
||||
var link = s.cidr === 'вне списка подсетей' ? esc(name) : '<a href="' + M.registry_url + '&subnet=' + encodeURIComponent(s.cidr) + '" title="Открыть в реестре: запуск ' + M.run_id + ', подсеть ' + esc(s.cidr) + '">' + esc(name) + '</a>';
|
||||
return '<tr><td class="an-a">' + link + '</td><td class="an-num an-r">' + fmt(s.addresses) + '</td>' +
|
||||
'<td class="an-r" ' + tipAttr(s.cidr + ': pass ' + fmt(s.pass) + ' из ' + fmt(s.addresses)) + '>' + pbar(s.pass, s.addresses) + '</td>' +
|
||||
'<td class="an-r" ' + tipAttr(s.cidr + ': egress OK ' + fmt(s.egress_ok) + ' из ' + fmt(s.addresses)) + '>' + pbar(s.egress_ok, s.addresses) + '</td>' +
|
||||
@@ -118,7 +118,7 @@
|
||||
$('an-matrix').innerHTML = '<thead><tr><th>Подсеть</th><th class="an-r">partial</th>' + T.targets.map(function (x) {
|
||||
return '<th class="an-r">' + esc(x.replace('.com', '').replace('.org', '')) + '</th>';
|
||||
}).join('') + '</tr></thead><tbody>' + rows.map(function (m) {
|
||||
var link = m.cidr === 'прочие' ? esc(m.cidr) : '<a href="' + M.registry_url + '&subnet=' + encodeURIComponent(m.cidr) + '" title="Открыть адреса в реестре">' + esc(m.cidr) + '</a>';
|
||||
var link = m.cidr === 'вне списка подсетей' ? esc(m.cidr) : '<a href="' + M.registry_url + '&subnet=' + encodeURIComponent(m.cidr) + '" title="Открыть адреса в реестре">' + esc(m.cidr) + '</a>';
|
||||
return '<tr><td class="an-a">' + link + '</td><td class="an-num an-r">' + fmt(m.partial) + '</td>' + m.percent.map(function (v, j) {
|
||||
return '<td class="an-c"><span class="an-cell ' + heatClass(v) + '" ' + tipAttr(m.cidr + ' → ' + T.targets[j] + ': ' + v + '% адресов partial провалили ' + t) + '>' + v + '%</span></td>';
|
||||
}).join('') + '</tr>';
|
||||
@@ -168,15 +168,15 @@
|
||||
|
||||
var VERDICT_NOTE = ' Это вердикт адреса, который система выставила при агрегации, а не итог всех проверок: после него могли прийти ещё результаты, поэтому у адреса pass бывают проваленные проверки. Столбцы Egress и Ingress показывают фактические проверки адреса.';
|
||||
var VERDICT_HINTS = {
|
||||
2: 'Валидатор, с которого шли egress-проверки адреса. «—» — у адреса нет https-проверок.',
|
||||
3: 'Сколько egress-проверок адреса успешно из всех записанных в цикле. «—» — egress-проверок нет.',
|
||||
4: 'Сколько ingress-проверок адреса успешно из всех записанных в цикле (со всех площадок и всех типов). «—» — ingress-проверок нет.',
|
||||
5: 'Сколько проверок записано в цикле из ожидаемых. Меньше ожидаемого значит, что часть результатов не пришла (неполный набор). Если ожидаемое число неизвестно, показано только записанное.'
|
||||
3: 'Валидатор, с которого шли egress-проверки адреса. «—» — у адреса нет https-проверок.',
|
||||
4: 'Сколько egress-проверок адреса успешно из всех записанных в цикле. «—» — egress-проверок нет.',
|
||||
5: 'Сколько ingress-проверок адреса успешно из всех записанных в цикле (со всех площадок и всех типов). «—» — ingress-проверок нет.',
|
||||
6: 'Сколько проверок записано в цикле из ожидаемых. Меньше ожидаемого значит, что часть результатов не пришла (неполный набор). Если ожидаемое число неизвестно, показано только записанное.'
|
||||
};
|
||||
function verdictList(title, note, reason) {
|
||||
var hints = {};
|
||||
Object.keys(VERDICT_HINTS).forEach(function (k) { hints[k] = VERDICT_HINTS[k]; });
|
||||
if (reason) hints[6] = 'Что не так у адреса: провалены egress-проверки, ingress-проверки или не хватает результатов (неполный набор). Те же названия, что в блоке «Почему partial».';
|
||||
if (reason) hints[7] = 'Что не так у адреса: провалены egress-проверки, ingress-проверки или не хватает результатов (неполный набор). Те же названия, что в блоке «Почему partial».';
|
||||
return { title: title, note: note + VERDICT_NOTE, hints: hints };
|
||||
}
|
||||
|
||||
@@ -190,22 +190,22 @@
|
||||
egress_https_any: {
|
||||
title: 'Egress https: адреса с проваленными проверками',
|
||||
note: 'Хотя бы одна egress-проверка https адреса провалена в последнем цикле запуска.',
|
||||
hints: { 2: 'Валидатор, с которого шли egress-проверки адреса.', 3: 'Сколько https-проверок адреса провалено из всех записанных в цикле.' }
|
||||
hints: { 3: 'Валидатор, с которого шли egress-проверки адреса.', 4: 'Сколько https-проверок адреса провалено из всех записанных в цикле.' }
|
||||
},
|
||||
ingress_ssh_any: {
|
||||
title: 'Ingress ssh: адреса с проваленными проверками',
|
||||
note: 'ssh провален хотя бы с одной площадки в последнем цикле запуска.',
|
||||
hints: { 2: 'Сколько площадок не смогли выполнить ssh-проверку адреса из всех, где она выполнялась.', 3: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 4: 'Класс ошибки: таймаут, баннер «Not allowed», нет маршрута.' }
|
||||
hints: { 3: 'Сколько площадок не смогли выполнить ssh-проверку адреса из всех, где она выполнялась.', 4: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 5: 'Класс ошибки: таймаут, баннер «Not allowed», нет маршрута.' }
|
||||
},
|
||||
egress_https_all: {
|
||||
title: 'Egress https: адреса, провалившие все проверки',
|
||||
note: 'Все записанные egress-проверки https адреса провалены в последнем цикле запуска.',
|
||||
hints: { 2: 'Валидатор, с которого шли egress-проверки адреса.', 3: 'Сколько https-проверок записано у адреса в цикле. Все они провалены. Меньше полного набора значит, что часть результатов не пришла.' }
|
||||
hints: { 3: 'Валидатор, с которого шли egress-проверки адреса.', 4: 'Сколько https-проверок записано у адреса в цикле. Все они провалены. Меньше полного набора значит, что часть результатов не пришла.' }
|
||||
},
|
||||
ingress_ssh_all: {
|
||||
title: 'Ingress ssh: адреса, провалившие все проверки',
|
||||
note: 'ssh провален со всех площадок, на которых он проверялся, в последнем цикле запуска.',
|
||||
hints: { 2: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 3: 'Класс ошибки ssh-проверки: таймаут, баннер «Not allowed», нет маршрута.' }
|
||||
hints: { 3: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 4: 'Класс ошибки ssh-проверки: таймаут, баннер «Not allowed», нет маршрута.' }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -232,11 +232,11 @@
|
||||
loadList('error', cls, { title: 'Ingress: ' + cls }).then(function (l) {
|
||||
if (!l) return;
|
||||
var rows = l.rows, labels = R.validators.map(function (v) { return vshort(v.validator); });
|
||||
rows.forEach(function (x) { if (labels.indexOf(x[3]) < 0) labels.push(x[3]); });
|
||||
var byVal = labels.map(function (lab) { return rows.filter(function (x) { return x[3] === lab; }).length; });
|
||||
rows.forEach(function (x) { if (labels.indexOf(x[4]) < 0) labels.push(x[4]); });
|
||||
var byVal = labels.map(function (lab) { return rows.filter(function (x) { return x[4] === lab; }).length; });
|
||||
var max = Math.max.apply(null, byVal.concat([1]));
|
||||
var late = rows.filter(function (x) { return x[5].indexOf('после') >= 0; }).length;
|
||||
var pass = rows.filter(function (x) { return x[4] === 'pass'; }).length;
|
||||
var late = rows.filter(function (x) { return x[6].indexOf('после') >= 0; }).length;
|
||||
var pass = rows.filter(function (x) { return x[5] === 'pass'; }).length;
|
||||
var grid = 'grid-template-columns:repeat(' + labels.length + ',minmax(0,1fr))';
|
||||
var dist = '<h2>Распределение по валидаторам</h2>' +
|
||||
'<div class="an-cols20" style="' + grid + '" role="img" aria-label="Число проваленных проверок по валидаторам">' + byVal.map(function (v, i) {
|
||||
@@ -248,8 +248,8 @@
|
||||
title: 'Ingress: ' + cls,
|
||||
note: 'Проваленные проверки этого класса в последнем цикле каждого адреса. Валидатор — тот, к которому был привязан адрес в этом цикле. «После вердикта» — результат пришёл позже агрегации и в вердикт адреса не вошёл.',
|
||||
cols: l.columns, rows: rows, runLabel: runLabel(), dist: dist, csvURL: listURL(M.csv_url, 'error', cls),
|
||||
hints: { 3: 'Валидатор, к которому был привязан адрес в этом цикле (берётся из события привязки Floating IP).', 4: VERDICT_HINT, 5: STATUS_HINT },
|
||||
cellHints: { 4: function (v) { return VERDICT_VAL[v] || ''; }, 5: statusVal }
|
||||
hints: { 4: 'Валидатор, к которому был привязан адрес в этом цикле (берётся из события привязки Floating IP).', 5: VERDICT_HINT, 6: STATUS_HINT },
|
||||
cellHints: { 5: function (v) { return VERDICT_VAL[v] || ''; }, 6: statusVal }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/* The chart "dynamics over runs" of the registry ("registry_trend" in
|
||||
registry.html): one line per target or site, one point per finished run, drawn
|
||||
by the vendored Chart.js. The data comes with the loaded block (data-trend of
|
||||
#registry-trend); the view (% / checks) and the period live in the address bar
|
||||
(trend_view, trend_from, trend_to). Listeners sit on the document, so they keep
|
||||
working after htmx replaces the block. */
|
||||
(function () {
|
||||
'use strict';
|
||||
if (window.registryTrendBound) return;
|
||||
window.registryTrendBound = true;
|
||||
|
||||
var STEP = 26;
|
||||
var data = null, chart = null;
|
||||
|
||||
function view() { return document.getElementById('registry-trend-view').value === 'count' ? 'count' : 'pct'; }
|
||||
function pad(n) { return (n < 10 ? '0' : '') + n; }
|
||||
function utc(iso, full) {
|
||||
var d = new Date(iso), s = pad(d.getUTCDate()) + '.' + pad(d.getUTCMonth() + 1);
|
||||
return full ? d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ' UTC' : s;
|
||||
}
|
||||
// the top of the count axis: the most checks in any point, rounded up so that four ticks are round numbers
|
||||
function niceMax(m) {
|
||||
var unit = m <= 40 ? 1 : Math.pow(10, Math.floor(Math.log10(m))) / 2;
|
||||
return Math.max(4, Math.ceil(m / (4 * unit)) * 4 * unit);
|
||||
}
|
||||
function css(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
|
||||
|
||||
// a run without checks of the target is null: a gap in the line, not a zero
|
||||
function values(s, pct) {
|
||||
var v = data.runs.map(function () { return null; });
|
||||
s.p.forEach(function (p) { v[p[0]] = pct ? p[1] * 100 / p[2] : p[1]; });
|
||||
return v;
|
||||
}
|
||||
function axis(opts, pct) {
|
||||
var most = 0;
|
||||
data.series.forEach(function (s) { s.p.forEach(function (p) { most = Math.max(most, p[2]); }); });
|
||||
var top = pct ? 100 : niceMax(most), y = opts.scales.y;
|
||||
y.max = top; y.ticks.stepSize = top / 4;
|
||||
y.ticks.callback = function (v) { return pct ? v + '%' : v; };
|
||||
}
|
||||
// colours come from the theme tokens, so they are read again when the theme changes
|
||||
function paint() {
|
||||
if (!chart) return;
|
||||
var text = css('--text-muted'), grid = css('--border-soft'), line = css('--border');
|
||||
chart.data.datasets.forEach(function (d, i) { d.borderColor = d.backgroundColor = d.pointBackgroundColor = css('--tr-c' + i % 10); d.pointBorderColor = css('--surface'); });
|
||||
var o = chart.options, y = o.scales.y, x = o.scales.x;
|
||||
x.ticks.color = y.ticks.color = o.plugins.legend.labels.color = text;
|
||||
x.grid.color = line; y.grid.color = grid;
|
||||
chart.update('none');
|
||||
}
|
||||
|
||||
function draw(root) {
|
||||
var canvas = root.querySelector('canvas'), pct = view() === 'pct';
|
||||
canvas.parentNode.style.minWidth = Math.max(520, data.runs.length * STEP) + 'px';
|
||||
var still = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
var opts = {
|
||||
responsive: true, maintainAspectRatio: false, spanGaps: false,
|
||||
animation: still ? false : { duration: 300 },
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
font: { family: css('--font-mono'), size: 11 },
|
||||
scales: {
|
||||
x: { grid: { drawOnChartArea: false }, ticks: { maxRotation: 0 } },
|
||||
y: { min: 0, ticks: {} }
|
||||
},
|
||||
plugins: {
|
||||
legend: { labels: { boxWidth: 12, boxHeight: 3, useBorderRadius: true, borderRadius: 2 } },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
title: function (it) { var r = data.runs[it[0].dataIndex]; return 'Запуск ' + r.id + ', ' + utc(r.at, true) + ' · адресов ' + r.n; },
|
||||
label: function (c) {
|
||||
var p = data.series[c.datasetIndex].p.filter(function (q) { return q[0] === c.dataIndex; })[0];
|
||||
return c.dataset.label + ': успешно ' + p[1] + ' из ' + p[2] + ' · ' + Math.round(p[1] * 1000 / p[2]) / 10 + '%';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
axis(opts, pct);
|
||||
chart = new Chart(canvas, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: data.runs.map(function (r) { return ['#' + r.id, utc(r.at)]; }),
|
||||
datasets: data.series.map(function (s, i) {
|
||||
return { label: s.l, data: values(s, pct), borderWidth: 2, pointRadius: 3, pointHoverRadius: 5, tension: 0, borderDash: i >= 10 ? [6, 3] : [] };
|
||||
})
|
||||
},
|
||||
options: opts
|
||||
});
|
||||
paint();
|
||||
}
|
||||
|
||||
// the view switch only changes the values and the axis
|
||||
function refresh() {
|
||||
var pct = view() === 'pct';
|
||||
chart.data.datasets.forEach(function (d, i) { d.data = values(data.series[i], pct); });
|
||||
axis(chart.options, pct);
|
||||
chart.update();
|
||||
}
|
||||
|
||||
function init() {
|
||||
var root = document.getElementById('registry-trend');
|
||||
if (chart && root && root.contains(chart.canvas)) return; // htmx:load of something else
|
||||
if (chart) { chart.destroy(); chart = null; } // htmx replaced the block: the old canvas is gone
|
||||
if (!root || !root.dataset.trend || !window.Chart) return;
|
||||
try { data = JSON.parse(root.dataset.trend); } catch (e) { return; }
|
||||
draw(root);
|
||||
}
|
||||
|
||||
function setParam(k, v) {
|
||||
var u = new URL(location.href);
|
||||
if (v) u.searchParams.set(k, v); else u.searchParams.delete(k);
|
||||
history.replaceState(history.state, '', u);
|
||||
}
|
||||
|
||||
// the period changes the data: keep it in the URL and reload the block
|
||||
function reload() {
|
||||
var panel = document.getElementById('registry-trend-panel');
|
||||
if (!panel || !window.htmx) return;
|
||||
var f = document.getElementById('trend-from').value, t = document.getElementById('trend-to').value, qs = new URLSearchParams(panel.dataset.qs);
|
||||
qs.delete('trend_from'); qs.delete('trend_to');
|
||||
if (f) qs.set('trend_from', f);
|
||||
if (t) qs.set('trend_to', t);
|
||||
setParam('trend_from', f); setParam('trend_to', t);
|
||||
document.getElementById('trend-reset').hidden = !(f || t);
|
||||
window.htmx.ajax('GET', '/registry/trend?' + qs, { target: '#registry-trend', swap: 'outerHTML' });
|
||||
// the same period counts the always-pass tile
|
||||
var ap = new URLSearchParams(panel.dataset.apQs);
|
||||
ap.delete('trend_from'); ap.delete('trend_to');
|
||||
if (f) ap.set('trend_from', f);
|
||||
if (t) ap.set('trend_to', t);
|
||||
window.htmx.ajax('GET', '/registry/always-pass?' + ap, { target: '#registry-always-pass', swap: 'outerHTML' });
|
||||
}
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-trend-view]');
|
||||
if (b) {
|
||||
document.getElementById('registry-trend-view').value = b.dataset.trendView;
|
||||
setParam('trend_view', b.dataset.trendView);
|
||||
document.querySelectorAll('[data-trend-view]').forEach(function (x) { x.setAttribute('aria-pressed', x === b ? 'true' : 'false'); });
|
||||
if (chart) refresh();
|
||||
} else if (e.target.closest('#trend-reset')) {
|
||||
document.getElementById('trend-from').value = ''; document.getElementById('trend-to').value = '';
|
||||
reload();
|
||||
}
|
||||
});
|
||||
document.addEventListener('change', function (e) {
|
||||
if (e.target.id === 'trend-from' || e.target.id === 'trend-to') reload();
|
||||
});
|
||||
document.addEventListener('htmx:load', init);
|
||||
// the theme is switched by data-theme on <html> or by the system setting
|
||||
new MutationObserver(paint).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', paint);
|
||||
init();
|
||||
})();
|
||||
@@ -8,6 +8,8 @@
|
||||
window.registryBreakdownBound = true;
|
||||
|
||||
var HINTS = {
|
||||
'Подсеть': 'Подсеть из списка в настройках, в которую входит адрес. «вне списка подсетей» — ни в одну не входит.',
|
||||
'Метка подсети': 'Название подсети, которое задал администратор. Пусто, если метки нет.',
|
||||
'Результат': 'Итог именно этой проверки. Список начинается с проваленных.',
|
||||
'Тип проверки': 'https, icmp, ssh, tcp-22, tls-443 и т. д.',
|
||||
'Валидатор': 'Валидатор, с которого шла egress-проверка.',
|
||||
@@ -40,8 +42,39 @@
|
||||
});
|
||||
}
|
||||
|
||||
// the "always passed" tile above the trend chart: the same dialog, a different list
|
||||
var AP_HINTS = {
|
||||
'Подсеть': HINTS['Подсеть'],
|
||||
'Метка подсети': HINTS['Метка подсети'],
|
||||
'Запусков с проверками': 'В скольких запусках периода у адреса есть проверки этого направления и протокола.',
|
||||
'Запусков в периоде': 'Сколько завершённых запусков учтено для периода.',
|
||||
'Проверок (все успешны)': 'Все проверки адреса в этих запусках; ни одна не провалена.',
|
||||
'Первый запуск (UTC)': 'Первый запуск периода, в котором адрес проверялся.',
|
||||
'Последний запуск (UTC)': 'Последний запуск периода, в котором адрес проверялся.'
|
||||
};
|
||||
|
||||
function openAlwaysPass(btn) {
|
||||
var A = window.AnalyticsDialog;
|
||||
if (!A) return;
|
||||
var qs = btn.dataset.apQs, title = btn.dataset.apLabel;
|
||||
A.load('/registry/always-pass/list?' + qs, title).then(function (l) {
|
||||
if (!l) return;
|
||||
var hints = {};
|
||||
l.columns.forEach(function (c, i) { if (AP_HINTS[c]) hints[i] = AP_HINTS[c]; });
|
||||
A.fill({
|
||||
title: title,
|
||||
scope: 'Период',
|
||||
runLabel: btn.dataset.apSlice,
|
||||
note: 'Адреса, у которых в этих запусках есть проверки и ни одна не провалена. Фильтр запуска и статуса не применяется.',
|
||||
cols: l.columns, rows: l.rows, hints: hints,
|
||||
csvURL: '/registry/always-pass/csv?' + qs
|
||||
});
|
||||
if (!l.rows.length) document.getElementById('an-dlg-msg').textContent = 'Таких адресов нет.';
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-bd-key]');
|
||||
if (b) open(b);
|
||||
var b = e.target.closest('[data-bd-key]'), t = e.target.closest('[data-ap-qs].ap-tile');
|
||||
if (b) open(b); else if (t) openAlwaysPass(t);
|
||||
});
|
||||
})();
|
||||
+7
-1
@@ -9,6 +9,7 @@ commit, if a newer version is actually needed.
|
||||
|---|---|---|---|
|
||||
| `htmx.min.js` | https://unpkg.com/htmx.org@2.0.10/dist/htmx.min.js | 2.0.10 | 2026-08-23 |
|
||||
| `alpine.min.js` | https://unpkg.com/alpinejs@3.16.2/dist/cdn.min.js | 3.16.2 | 2026-08-23 |
|
||||
| `chart.umd.min.js` | https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js | 4.5.1 | 2026-10-08 |
|
||||
| `fonts.css` + `fonts/*.woff2` | Google Fonts CSS2 API (`family=JetBrains+Mono:wght@400;500;600;700;800\|family=IBM+Plex+Sans:wght@400;500;600;700`) | JetBrains Mono v24, IBM Plex Sans v23 | 2026-08-26 |
|
||||
|
||||
## Fonts
|
||||
@@ -41,5 +42,10 @@ doesn't use any component that requires JS beyond htmx/Alpine themselves
|
||||
(the mobile sidebar toggle is a pure-CSS checkbox trick, not JS;
|
||||
confirmations use the browser's native dialog via htmx's `hx-confirm`).
|
||||
|
||||
Licenses: htmx (BSD 2-Clause), Alpine.js (MIT), JetBrains Mono (OFL-1.1),
|
||||
Licenses: htmx (BSD 2-Clause), Alpine.js (MIT), Chart.js (MIT), JetBrains Mono (OFL-1.1),
|
||||
IBM Plex Sans (OFL-1.1) — all permit vendoring/redistribution unmodified.
|
||||
|
||||
## Chart.js
|
||||
|
||||
Used only by the trend chart of the registry page (`../registry-trend.js`);
|
||||
loaded only by `registry.html`, no plugins.
|
||||
@@ -0,0 +1,14 @@
|
||||
/*!
|
||||
* Chart.js v4.5.1
|
||||
* https://www.chartjs.org
|
||||
* (c) 2025 Chart.js Contributors
|
||||
* Released under the MIT License
|
||||
*/
|
||||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Na}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?x(n,a,s):e[t]=g(a)}function x(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function b(t,e){return x(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?b(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={"":t=>t,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((t,e)=>t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function J(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function Z(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return Z(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=["push","pop","shift","splice","unshift"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...eLine truncated
|
||||
/*!
|
||||
* @kurkle/color v0.3.2
|
||||
* https://github.com/kurkle/color#readme
|
||||
* (c) 2023 Jukka Kurkela
|
||||
* Released under the MIT License
|
||||
*/function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Nt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),Line truncated
|
||||
//# sourceMappingURL=chart.umd.min.js.map
|
||||
@@ -21,6 +21,8 @@
|
||||
<div class="an">{{template "analytics_dialog"}}</div>
|
||||
<script src="/static/analytics-dialog.js"></script>
|
||||
<script src="/static/registry.js"></script>
|
||||
<script src="/static/vendor/chart.umd.min.js"></script>
|
||||
<script src="/static/registry-trend.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -32,6 +34,8 @@
|
||||
Глубина хранимой истории на адрес настраивается на <a href="/settings">странице настроек</a>.</p>
|
||||
|
||||
<form id="registry-filter" class="panel" onsubmit="return false" style="margin-bottom:16px">
|
||||
{{/* The state of the trend chart rides along with every filter request, so it stays in the URL. */}}
|
||||
<input type="hidden" id="registry-trend-view" name="trend_view" value="{{.TrendView}}">
|
||||
<div class="panel-body field-row">
|
||||
<div class="field" style="flex:1 1 260px">
|
||||
<label for="registry-q">Поиск по IP</label>
|
||||
@@ -153,8 +157,61 @@ tls проверяется только на входе (Ingress).
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "registry_trend"}}
|
||||
<div class="an bd-wrap">
|
||||
<section class="an-panel" id="registry-trend-panel" aria-labelledby="registry-trend-h" data-qs="{{.QS}}" data-ap-qs="{{.APQS}}">
|
||||
<div class="an-head">
|
||||
<h2 id="registry-trend-h">Динамика по запускам · {{.Scope}}</h2>
|
||||
<div class="an-tabs" role="group" aria-label="Что показывает ось Y">
|
||||
<button type="button" data-trend-view="pct" aria-pressed="{{if eq .View "pct"}}true{{else}}false{{end}}">%</button>
|
||||
<button type="button" data-trend-view="count" aria-pressed="{{if eq .View "count"}}true{{else}}false{{end}}">кол-во</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="an-fields">
|
||||
<div class="an-field"><label for="trend-from">Период: с даты</label><input type="date" id="trend-from" name="trend_from" form="registry-filter" value="{{.From}}"></div>
|
||||
<div class="an-field"><label for="trend-to">по дату</label><input type="date" id="trend-to" name="trend_to" form="registry-filter" value="{{.To}}"></div>
|
||||
<button type="button" class="an-btn" id="trend-reset" {{if not (or .From .To)}}hidden{{end}}>Сбросить период</button>
|
||||
</div>
|
||||
<div id="registry-always-pass" hx-get="/registry/always-pass?{{.APQS}}" hx-trigger="load" hx-swap="outerHTML"><p class="an-note">Загрузка показателя…</p></div>
|
||||
<div id="registry-trend" hx-get="/registry/trend?{{.QS}}" hx-trigger="load" hx-swap="outerHTML"><p class="an-note">Загрузка графика…</p></div>
|
||||
<p class="an-note">Учтены направление, протокол, подсеть и период (даты по UTC, «по» включительно). Не учтены запуск, статус и поиск по IP: они описывают текущее состояние адресов. Считаются проверки, а не адреса: у tcp и tls на ingress у адреса может быть по проверке на каждую площадку и порт. Без периода — последние 30 запусков.</p>
|
||||
</section>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{define "registry_always_pass"}}
|
||||
<div id="registry-always-pass">
|
||||
{{if .Err}}<p class="an-note">{{.Err}}</p>
|
||||
{{else if .Hint}}<p class="an-note">{{.Hint}}</p>
|
||||
{{else}}
|
||||
<button type="button" class="ap-tile" data-ap-qs="{{.QS}}" data-ap-label="{{.Label}}" data-ap-slice="{{.Period}}" aria-haspopup="dialog" aria-label="{{.Aria}}">
|
||||
<span class="ap-main"><span class="ap-t">Всегда проходили</span><span class="ap-v">{{.N}}</span><span class="ap-of">из {{.M}} адресов · {{.Pct}} %</span></span>
|
||||
<span class="ap-sub">{{.Period}}</span>
|
||||
</button>
|
||||
<p class="an-note">{{.Slice}}</p>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{define "registry_trend_data"}}
|
||||
<div id="registry-trend"{{if .JSON}} data-trend="{{.JSON}}"{{end}}>
|
||||
{{if .Err}}<p class="an-note">{{.Err}}</p>
|
||||
{{else if .Empty}}<p class="an-note">За этот период завершённых запусков с такими проверками нет.</p>
|
||||
{{else}}
|
||||
<div class="tr-scroll"><div class="tr-plot"><canvas aria-hidden="true"></canvas></div></div>
|
||||
<div class="tr-sr"><table>
|
||||
<caption>Успешные проверки по запускам</caption>
|
||||
<thead><tr><th scope="col"></th>{{range .Runs}}<th scope="col">Запуск {{.ID}}, {{.Date}} UTC, адресов {{.Addresses}}</th>{{end}}</tr></thead>
|
||||
<tbody>{{range .Rows}}<tr><th scope="row">{{.Label}}</th>{{range .Cells}}<td>{{.}}</td>{{end}}</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
<p class="an-note">{{.Note}}</p>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{define "registry_table"}}
|
||||
{{with .Breakdown}}{{template "registry_breakdown" .}}{{end}}
|
||||
{{with .Trend}}{{template "registry_trend" .}}{{end}}
|
||||
{{if or .Items .Run}}<p class="muted" style="margin-bottom:8px">Найдено адресов: {{.Total}}{{if .Run}} · <a href="{{.AnalyticsURL}}">к аналитике запуска {{.Run}}</a>{{end}}</p>{{end}}
|
||||
{{if .Items}}
|
||||
<div class="panel">
|
||||
|
||||
@@ -131,7 +131,7 @@ inbound-проверки к нулю, не трогая список площа
|
||||
<p class="muted" style="margin-bottom:16px">Подсети для страницы <a href="/analytics">«Аналитика»</a>: по ним
|
||||
группируются адреса запуска. По одной в строке — <code>CIDR</code> и, через пробел, необязательная подпись
|
||||
(<code>83.166.248.0/21 москва</code>). Адрес относится к самой узкой подходящей подсети, остальные идут в строку
|
||||
«прочие». Пока список пуст, адреса группируются по /24.</p>
|
||||
«вне списка подсетей». Пока список пуст, адреса группируются по /24.</p>
|
||||
<form hx-put="/settings/subnets" hx-target="#settings-form-wrap" hx-swap="innerHTML">
|
||||
<div class="field">
|
||||
<label for="subnets_text">Подсети</label>
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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