- 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>
626 lines
22 KiB
Go
626 lines
22 KiB
Go
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
|
|
// db.RegistryFilter's Level and Family.
|
|
var (
|
|
registryDirections = []string{"egress", "ingress"}
|
|
registryProtocols = []string{"icmp", "tcp", "ssh", "https", "tls"}
|
|
)
|
|
|
|
type registryPageData struct {
|
|
PageData
|
|
Items []registryItem
|
|
Query string
|
|
StatusFilter string
|
|
Run int64 // data slice: the address's cycle in this run (also the drill-down from analytics)
|
|
Subnet string
|
|
Direction string
|
|
Protocol string
|
|
Protocols []string
|
|
Scoped bool // direction or protocol is set
|
|
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
|
|
Pager pagerData
|
|
PerPageOptions []int
|
|
}
|
|
|
|
type registryDetailData struct {
|
|
PageData
|
|
History registryHistoryResponse
|
|
}
|
|
|
|
// handleRegistryPage lists every address ever submitted to the check
|
|
// queue, with a summary of its accumulated check history — the durable
|
|
// record that survives an address being deleted from /ips and later
|
|
// re-added. See internal/db/migrations/0007_ip_registry.sql. Optional
|
|
// ?q=&status= query params narrow the list by address substring and by
|
|
// LastResult, ?run=&subnet=&direction=&protocol= by run, subnet and the
|
|
// direction/protocol of the checks, and ?page=&per_page= select a page — all
|
|
// applied server-side (control-api's ListRegistryPage), so only the visible
|
|
// rows are transferred. The run and subnet choices come from the analytics
|
|
// run list and the configured subnets; if either list is unavailable the
|
|
// filters still work, just without those choices.
|
|
func (s *Server) handleRegistryPage(w http.ResponseWriter, r *http.Request) {
|
|
query := parseRegistryQuery(r)
|
|
q, status, run, subnet, direction, protocol := query.Q, query.LastResult, query.Run, query.Subnet, query.Direction, query.Protocol
|
|
perPage := parsePerPage(r.URL.Query().Get("per_page"))
|
|
page := parsePage(r.URL.Query().Get("page"))
|
|
query.Limit, query.Offset = perPage, (page-1)*perPage
|
|
|
|
res, err := s.CA.ListRegistryPage(r.Context(), query)
|
|
if err == nil {
|
|
if clamped := clampPage(page, res.Total, perPage); clamped != page {
|
|
page = clamped
|
|
query.Offset = (page - 1) * perPage
|
|
res, err = s.CA.ListRegistryPage(r.Context(), query)
|
|
}
|
|
}
|
|
params := url.Values{}
|
|
if q != "" {
|
|
params.Set("q", q)
|
|
}
|
|
if status != "" {
|
|
params.Set("status", status)
|
|
}
|
|
if run > 0 {
|
|
params.Set("run", strconv.FormatInt(run, 10))
|
|
}
|
|
if subnet != "" {
|
|
params.Set("subnet", subnet)
|
|
}
|
|
if direction != "" {
|
|
params.Set("direction", direction)
|
|
}
|
|
if protocol != "" {
|
|
params.Set("protocol", protocol)
|
|
}
|
|
// A filter/pager request from htmx swaps only #registry-table-wrap
|
|
// (hx-select), so the run and subnet choices of the form are not needed.
|
|
// A history-restore fetch needs the full page.
|
|
var runs []analyticsRun
|
|
var subnets subnetList
|
|
var runsErr, subnetsErr error
|
|
if r.Header.Get("HX-Request") != "true" || r.Header.Get("HX-History-Restore-Request") == "true" {
|
|
runs, runsErr = s.CA.ListAnalyticsRuns(r.Context())
|
|
subnets, subnetsErr = s.CA.GetSubnets(r.Context())
|
|
}
|
|
data := registryPageData{
|
|
Run: run,
|
|
Subnet: subnet,
|
|
Direction: direction,
|
|
Protocol: protocol,
|
|
Protocols: registryProtocols,
|
|
Scoped: direction != "" || protocol != "",
|
|
Runs: registryRunOptions(runs, run),
|
|
SubnetOptions: registrySubnetOptions(subnets.Subnets, subnet),
|
|
Items: res.Items,
|
|
Query: q,
|
|
StatusFilter: status,
|
|
Page: page,
|
|
PerPage: perPage,
|
|
Total: res.Total,
|
|
Pager: newPager("/registry", "registry-table-wrap", params, page, perPage, res.Total),
|
|
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)
|
|
}
|
|
if err == nil {
|
|
data.Breakdown = s.registryBreakdown(r, query, params)
|
|
err = errors.Join(runsErr, subnetsErr)
|
|
}
|
|
data.Banner = bannerFor(err)
|
|
s.renderPage(w, r, "registry_page", data)
|
|
}
|
|
|
|
// parseRegistryQuery reads the filter of the registry page and of its chart
|
|
// requests (?q=&status=&run=&subnet=&direction=&protocol=); a value that is
|
|
// not valid is dropped.
|
|
func parseRegistryQuery(r *http.Request) registryQuery {
|
|
v := r.URL.Query()
|
|
q := parseSliceFilter(v)
|
|
q.Q, q.LastResult = strings.TrimSpace(v.Get("q")), v.Get("status")
|
|
if !containsStr(ipResults, q.LastResult) {
|
|
q.LastResult = ""
|
|
}
|
|
return q
|
|
}
|
|
|
|
// parseSliceFilter reads the part of the filter that the registry and the
|
|
// analytics page share (?run=&subnet=&direction=&protocol=): the data slice
|
|
// of a run, a subnet, and the direction and protocol of the checks. A value
|
|
// that is not valid is dropped.
|
|
func parseSliceFilter(v url.Values) registryQuery {
|
|
var q registryQuery
|
|
if q.Run, _ = strconv.ParseInt(v.Get("run"), 10, 64); q.Run < 0 {
|
|
q.Run = 0
|
|
}
|
|
if q.Subnet = strings.TrimSpace(v.Get("subnet")); q.Subnet != "" {
|
|
if _, err := netip.ParsePrefix(q.Subnet); err != nil {
|
|
q.Subnet = ""
|
|
}
|
|
}
|
|
if q.Direction = v.Get("direction"); !containsStr(registryDirections, q.Direction) {
|
|
q.Direction = ""
|
|
}
|
|
if q.Protocol = v.Get("protocol"); !containsStr(registryProtocols, q.Protocol) {
|
|
q.Protocol = ""
|
|
}
|
|
return q
|
|
}
|
|
|
|
// subnetOption is one entry of the "Подсеть" selector.
|
|
type subnetOption struct {
|
|
CIDR, Text string
|
|
Selected bool
|
|
}
|
|
|
|
// registrySubnetOptions lists the configured subnets for the selector as
|
|
// "CIDR — label". The chosen subnet is always present and selected: one that is
|
|
// not configured (a link from analytics, or the list is unavailable) is added
|
|
// as a separate entry.
|
|
func registrySubnetOptions(subnets []subnetEntry, chosen string) []subnetOption {
|
|
var out []subnetOption
|
|
found := false
|
|
for _, x := range subnets {
|
|
text := x.CIDR
|
|
if x.Label != "" {
|
|
text += " — " + x.Label
|
|
}
|
|
out = append(out, subnetOption{CIDR: x.CIDR, Text: text, Selected: x.CIDR == chosen})
|
|
found = found || x.CIDR == chosen
|
|
}
|
|
if chosen != "" && !found {
|
|
out = append(out, subnetOption{CIDR: chosen, Text: chosen + " (нет в списке)", Selected: true})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// breakdownView is the chart "successful checks per target / site" above the
|
|
// registry table. With Hint set, it is only a prompt to choose the missing
|
|
// filter; with Err set, the chart could not be loaded.
|
|
type breakdownView struct {
|
|
Title, Scope, Slice, QS string
|
|
Hint, Err string
|
|
Addresses int
|
|
Rows []breakdownRowView
|
|
}
|
|
|
|
type breakdownRowView struct {
|
|
Key, Label, Width, Text, Tip string
|
|
}
|
|
|
|
// registryBreakdown builds the chart for the page's filter: nothing without a
|
|
// direction and a protocol, then a hint for the missing one. params is the
|
|
// filter as the page's links carry it; the chart's dialog requests its lists
|
|
// with the same query string.
|
|
func (s *Server) registryBreakdown(r *http.Request, q registryQuery, params url.Values) *breakdownView {
|
|
switch {
|
|
case q.Direction == "" && q.Protocol == "":
|
|
return nil
|
|
case q.Protocol == "":
|
|
return &breakdownView{Hint: "Выберите протокол, чтобы увидеть распределение по " + breakdownGroupName(q.Direction) + "."}
|
|
case q.Direction == "":
|
|
return &breakdownView{Hint: "Выберите направление, чтобы увидеть распределение по целям или площадкам."}
|
|
}
|
|
v := &breakdownView{Scope: strings.ToUpper(q.Direction[:1]) + q.Direction[1:] + " " + q.Protocol, QS: params.Encode(), Slice: "последний цикл адреса"}
|
|
if q.Run > 0 {
|
|
v.Slice = "запуск " + strconv.FormatInt(q.Run, 10)
|
|
}
|
|
if q.Subnet != "" {
|
|
v.Slice += " · подсеть " + q.Subnet
|
|
}
|
|
v.Title = "Успешные проверки по " + breakdownGroupName(q.Direction)
|
|
b, err := s.CA.GetRegistryBreakdown(r.Context(), q)
|
|
if err != nil {
|
|
v.Err = "Не удалось получить распределение: " + err.Error()
|
|
return v
|
|
}
|
|
v.Addresses = b.Addresses
|
|
most := 0
|
|
for _, x := range b.Rows {
|
|
most = max(most, x.OK)
|
|
}
|
|
for _, x := range b.Rows { // control-api sorts them, most successful first
|
|
width := 0.0
|
|
if most > 0 {
|
|
width = float64(x.OK) * 100 / float64(most)
|
|
}
|
|
ok, total := groupThousands(x.OK), groupThousands(x.Total)
|
|
v.Rows = append(v.Rows, breakdownRowView{
|
|
Key: x.Key, Label: x.Label, Width: strconv.FormatFloat(width, 'f', 1, 64),
|
|
Text: ok + " из " + total + " · " + pct1(x.OK, x.Total) + "%",
|
|
Tip: x.Label + ": успешно " + ok + " из " + total + " проверок. Нажмите, чтобы открыть список адресов",
|
|
})
|
|
}
|
|
return v
|
|
}
|
|
|
|
// breakdownGroupName is what the chart groups the checks of a direction by.
|
|
func breakdownGroupName(direction string) string {
|
|
if direction == "ingress" {
|
|
return "площадкам"
|
|
}
|
|
return "целям"
|
|
}
|
|
|
|
// pct1 is a/b in percent with at most one decimal and a decimal comma: 98,7.
|
|
func pct1(a, b int) string {
|
|
if b == 0 {
|
|
return "0"
|
|
}
|
|
s := strconv.FormatFloat(float64(a)*100/float64(b), 'f', 1, 64)
|
|
return strings.Replace(strings.TrimSuffix(s, ".0"), ".", ",", 1)
|
|
}
|
|
|
|
// breakdownQuery reads the request of the chart's list proxies: the page's
|
|
// filter, with direction and protocol and the row's key required.
|
|
func breakdownQuery(w http.ResponseWriter, r *http.Request) (q registryQuery, key string, ok bool) {
|
|
q, key = parseRegistryQuery(r), r.URL.Query().Get("key")
|
|
if q.Direction == "" || q.Protocol == "" || key == "" {
|
|
http.Error(w, "direction, protocol and key are required", http.StatusBadRequest)
|
|
return q, key, false
|
|
}
|
|
return q, key, true
|
|
}
|
|
|
|
// handleRegistryBreakdownList proxies the checks behind one row of the chart as JSON.
|
|
func (s *Server) handleRegistryBreakdownList(w http.ResponseWriter, r *http.Request) {
|
|
q, key, ok := breakdownQuery(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
out, err := s.CA.GetRegistryBreakdownList(r.Context(), q, key)
|
|
if err != nil {
|
|
writeProxyError(w, err)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
_, _ = w.Write(out)
|
|
}
|
|
|
|
// handleRegistryBreakdownCSV proxies the same table as a CSV download.
|
|
func (s *Server) handleRegistryBreakdownCSV(w http.ResponseWriter, r *http.Request) {
|
|
q, key, ok := breakdownQuery(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
body, disposition, err := s.CA.GetRegistryBreakdownCSV(r.Context(), q, key)
|
|
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)
|
|
}
|
|
|
|
// registryRunOptions lists the runs for the "Запуск" selector, newest first as
|
|
// control-api returns them; a finished run without addresses is hidden. The
|
|
// chosen run is always present and selected, even if the list lacks it (the
|
|
// history was cleaned up, or the list is unavailable).
|
|
func registryRunOptions(runs []analyticsRun, chosen int64) []runOption {
|
|
var out []runOption
|
|
found := false
|
|
for _, x := range runs {
|
|
if x.State == "finalized" && x.Addresses == 0 && x.ID != chosen {
|
|
continue
|
|
}
|
|
out = append(out, runOption{ID: x.ID, Label: runLabel(x), Selected: x.ID == chosen})
|
|
found = found || x.ID == chosen
|
|
}
|
|
if chosen > 0 && !found {
|
|
out = append(out, runOption{ID: chosen, Label: "Запуск " + strconv.FormatInt(chosen, 10), Selected: true})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// handleRegistryDetail shows one address's full retained check history
|
|
// across every cycle it has ever run, not just the current attempt — see
|
|
// ip_detail_content in ip_detail.html for the attempt-scoped equivalent.
|
|
func (s *Server) handleRegistryDetail(w http.ResponseWriter, r *http.Request) {
|
|
ip := r.PathValue("ip")
|
|
history, err := s.CA.GetRegistryHistory(r.Context(), ip)
|
|
data := registryDetailData{History: history}
|
|
data.ActiveNav = "registry"
|
|
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)
|
|
}
|