Scan floating IPs in the background, page by page, so thousands of addresses work

The "Scan Floating IP" button failed with a client timeout: the project now
holds ~6.4k floating IPs and the scan listed them all in one unpaginated,
timeout-less Neutron request on the HTTP request context.

openstack: ListFreeFloatingIPs reads marker-based pages (fields= keeps them
small) with per-page retry/backoff on transport errors, 5xx and 429, and every
request now has a timeout (also ends hangs inside the orchestrator tick).

orchestrator: the scan is a single-flight background job on the process
context with progress (clearing/listing/enqueuing/done/error), dry_run, full
discovery before anything is enqueued, then SubmitIPs in chunks of 500 in
ascending IP order; a failed read leaves the queue untouched. The auto-cycle
gets a "scanning" phase that polls the job, so the control loop and
autoCycleMu are never held across OpenStack/DB work; it recovers after a
restart and waits for (instead of adopting) a scan started by someone else.

db: migration 0009 (indexes), paged ListIPsPage/ListRegistryPage, GROUP BY
counters, EXISTS completion check, set-based ClearAllIPs.

API: POST /admin/ips/scan -> 202 (dry_run, wait), GET /admin/ips/scan, paging
and filters on /admin/ips and /admin/registry (bare arrays without limit),
results_by_overall in /admin/status.

dashboard: scan progress panel and dry-run button, paginated /ips and
/registry with server-side filters, Overview on counters and capped lists
with progress/ETA, "select all N by filter", hx-params fix for per-row
buttons, real counts in confirmations.

Also: docs (API, USAGE, DASHBOARD, README), plan and review under
docs/changes/, bin/ rebuilt with new SHA256SUMS.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-01 19:31:11 +03:00
1 parent debf2afed2
commit aff8fe38b5
61 files changed
+5833 -536

No files matched your search

+130 -20
View File
@@ -8,6 +8,8 @@ import (
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
@@ -39,15 +41,44 @@ func (e *apiErr) Error() string {
type client struct {
baseURL string
http *http.Client
// long is used for clear / bulk operations, which legitimately take far
// longer than a plain read (thousands of rows in one transaction): same
// transport, but a longer whole-call timeout.
long *http.Client
// token, when non-empty, is sent to control-api as a Bearer credential.
token string
}
// longCallTimeout is the minimum whole-call timeout for clear and bulk
// operations (ClearQueue, DeleteIPs, SubmitIPs).
const longCallTimeout = 120 * time.Second
func newClient(baseURL string, timeout time.Duration) *client {
return &client{baseURL: baseURL, http: &http.Client{Timeout: timeout}}
longT := longCallTimeout
if timeout > longT {
longT = timeout
}
return &client{
baseURL: baseURL,
http: &http.Client{Timeout: timeout},
long: &http.Client{Timeout: longT},
}
}
func (c *client) do(ctx context.Context, method, path string, body, out interface{}) error {
return c.doWith(ctx, c.http, method, path, body, out)
}
// doLong is do with the long (clear/bulk) timeout.
func (c *client) doLong(ctx context.Context, method, path string, body, out interface{}) error {
hc := c.long
if hc == nil {
hc = c.http
}
return c.doWith(ctx, hc, method, path, body, out)
}
func (c *client) doWith(ctx context.Context, hc *http.Client, method, path string, body, out interface{}) error {
var reader io.Reader
if body != nil {
b, err := json.Marshal(body)
@@ -67,7 +98,7 @@ func (c *client) do(ctx context.Context, method, path string, body, out interfac
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.http.Do(req)
resp, err := hc.Do(req)
if err != nil {
return &apiErr{Status: 0, Message: err.Error()}
}
@@ -96,9 +127,58 @@ func (c *client) Status(ctx context.Context) (statusResponse, error) {
return out, err
}
func (c *client) ListIPs(ctx context.Context) ([]ipQueueItem, error) {
var out []ipQueueItem
err := c.do(ctx, http.MethodGet, "/api/v1/admin/ips", nil, &out)
// maxPageLimit is control-api's cap on `limit`.
const maxPageLimit = 1000
// clampLimit keeps limit within 1..maxPageLimit: a request without `limit`
// would make control-api answer with the legacy unbounded bare array.
func clampLimit(limit int) int {
if limit < 1 {
return 1
}
if limit > maxPageLimit {
return maxPageLimit
}
return limit
}
// ipsQuery selects one page of GET /admin/ips: server-side filters plus
// limit/offset. Order is "sequence" (default) or "aggregated_at_desc".
type ipsQuery struct {
States []string
Q string
Result string
Order string
Limit int
Offset int
}
func (q ipsQuery) values() url.Values {
v := url.Values{}
v.Set("limit", strconv.Itoa(clampLimit(q.Limit)))
if q.Offset > 0 {
v.Set("offset", strconv.Itoa(q.Offset))
}
if len(q.States) > 0 {
v.Set("state", strings.Join(q.States, ","))
}
if q.Q != "" {
v.Set("q", q.Q)
}
if q.Result != "" {
v.Set("result", q.Result)
}
if q.Order != "" {
v.Set("order", q.Order)
}
return v
}
// ListIPsPage returns one page of the check queue plus the total number of
// rows matching the filter. Never loads the whole queue.
func (c *client) ListIPsPage(ctx context.Context, q ipsQuery) (ipsPage, error) {
var out ipsPage
err := c.do(ctx, http.MethodGet, "/api/v1/admin/ips?"+q.values().Encode(), nil, &out)
return out, err
}
@@ -112,7 +192,7 @@ func (c *client) GetIP(ctx context.Context, ip string) (ipDetailResponse, error)
// forcing a recheck of already-finished ones — see docs/API.md.
func (c *client) SubmitIPs(ctx context.Context, addresses []string) (submitIPsResponse, error) {
var out submitIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips", map[string][]string{"addresses": addresses}, &out)
err := c.doLong(ctx, http.MethodPost, "/api/v1/admin/ips", map[string][]string{"addresses": addresses}, &out)
return out, err
}
@@ -129,7 +209,7 @@ func (c *client) DeleteIP(ctx context.Context, ip string) error {
// DeleteIPs permanently removes a specific list of addresses in one call.
func (c *client) DeleteIPs(ctx context.Context, addresses []string) (deleteIPsResponse, error) {
var out deleteIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/delete", map[string][]string{"addresses": addresses}, &out)
err := c.doLong(ctx, http.MethodPost, "/api/v1/admin/ips/delete", map[string][]string{"addresses": addresses}, &out)
return out, err
}
@@ -137,25 +217,55 @@ func (c *client) DeleteIPs(ctx context.Context, addresses []string) (deleteIPsRe
// including those actively being checked.
func (c *client) ClearQueue(ctx context.Context) (clearQueueResponse, error) {
var out clearQueueResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/clear", nil, &out)
err := c.doLong(ctx, http.MethodPost, "/api/v1/admin/ips/clear", nil, &out)
return out, err
}
// ScanFloatingIPs lists the OpenStack project's free (unassociated)
// floating IPs and submits them to the check queue — see
// orchestrator.ScanFloatingIPs.
func (c *client) ScanFloatingIPs(ctx context.Context) (scanIPsResponse, error) {
var out scanIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/scan", nil, &out)
// StartScan starts control-api's background floating-IP scan (or joins the
// one already running) and returns immediately with its current status.
func (c *client) StartScan(ctx context.Context, dryRun bool) (scanStatusDTO, error) {
var out scanStatusDTO
path := "/api/v1/admin/ips/scan"
if dryRun {
path += "?dry_run=true"
}
err := c.do(ctx, http.MethodPost, path, nil, &out)
return out, err
}
// ListRegistry returns every address ever submitted to the check queue,
// each with a summary of its accumulated check history — survives an
// address being deleted from the queue and later re-added.
func (c *client) ListRegistry(ctx context.Context) ([]registryItem, error) {
var out []registryItem
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry", nil, &out)
// ScanStatus returns the progress of the background scan job.
func (c *client) ScanStatus(ctx context.Context) (scanStatusDTO, error) {
var out scanStatusDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/ips/scan", nil, &out)
return out, err
}
// registryQuery selects one page of GET /admin/registry.
type registryQuery struct {
Q string
LastResult string
Limit int
Offset int
}
// ListRegistryPage returns one page of the registry (every address ever
// submitted to the check queue, each with a summary of its accumulated check
// history — survives an address being deleted from the queue and later
// re-added) plus the total number of rows matching the filter.
func (c *client) ListRegistryPage(ctx context.Context, q registryQuery) (registryPage, error) {
v := url.Values{}
v.Set("limit", strconv.Itoa(clampLimit(q.Limit)))
if q.Offset > 0 {
v.Set("offset", strconv.Itoa(q.Offset))
}
if q.Q != "" {
v.Set("q", q.Q)
}
if q.LastResult != "" {
v.Set("last_result", q.LastResult)
}
var out registryPage
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry?"+v.Encode(), nil, &out)
return out, err
}
+194 -16
View File
@@ -9,6 +9,8 @@ import (
"net/http/httptest"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync"
"testing"
@@ -42,6 +44,27 @@ type fakeControlAPI struct {
registry map[string]registryItem
registryChecks map[string][]check
// Scan job state machine (see the scan handlers): POST starts a job that
// stays "running" for scanRunPolls GET polls (0 = finishes at once), then
// ends as done — or as error when scanFinalError is set. scan is the status
// served by GET; tests may also set it directly (with scanPollsLeft == 0 it
// stays as is). scanStartStatus != 0 makes POST fail with that HTTP status.
scan scanStatusDTO
scanRunPolls int
scanPollsLeft int
scanFinalError string
scanStartStatus int
// Requests seen on the list endpoints, for "never loads everything" checks:
// the raw query of every GET /ips (ipsQueries) and the number of GET
// /registry calls without `limit` (bare), plus the sizes of the DeleteIPs /
// SubmitIPs bulk calls.
ipsQueries []string
registryQueries []string
bareIPsCalls int
deleteChunks []int
submitChunks []int
// autoCycle is the state served by /api/v1/admin/auto-cycle*;
// autoCycleDown makes all four endpoints answer 500 (unavailable API).
autoCycle autoCycleDTO
@@ -86,16 +109,72 @@ func (f *fakeControlAPI) handler() http.Handler {
f.mu.Lock()
defer f.mu.Unlock()
byState := map[string]int{}
results := map[string]int{"pass": 0, "partial": 0, "fail": 0, "cancelled": 0}
for _, ip := range f.ips {
byState[ip.State]++
if ip.OverallResult != "" {
results[ip.OverallResult]++
}
}
writeJSON(w, http.StatusOK, statusResponse{TotalIPs: len(f.ips), IPsByState: byState, TotalValidators: len(f.validators)})
writeJSON(w, http.StatusOK, statusResponse{TotalIPs: len(f.ips), IPsByState: byState, TotalValidators: len(f.validators), ResultsByOverall: results})
})
mux.HandleFunc("GET /api/v1/admin/ips", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
writeJSON(w, http.StatusOK, f.ips)
f.ipsQueries = append(f.ipsQueries, r.URL.RawQuery)
qv := r.URL.Query()
if qv.Get("limit") == "" {
// Legacy shape: the whole queue as a bare array.
f.bareIPsCalls++
writeJSON(w, http.StatusOK, f.ips)
return
}
limit, err := strconv.Atoi(qv.Get("limit"))
if err != nil || limit < 1 || limit > 1000 {
writeAPIErr(w, http.StatusBadRequest, "limit must be 1..1000")
return
}
offset, _ := strconv.Atoi(qv.Get("offset"))
var states map[string]bool
if st := qv.Get("state"); st != "" {
states = map[string]bool{}
for _, x := range strings.Split(st, ",") {
states[x] = true
}
}
var matched []ipQueueItem
for _, ip := range f.ips {
if states != nil && !states[ip.State] {
continue
}
if q := qv.Get("q"); q != "" && !strings.Contains(strings.ToLower(ip.IPAddress), strings.ToLower(q)) {
continue
}
if res := qv.Get("result"); res != "" && ip.OverallResult != res {
continue
}
matched = append(matched, ip)
}
if qv.Get("order") == "aggregated_at_desc" {
sort.SliceStable(matched, func(i, j int) bool {
a, b := matched[i].AggregatedAt, matched[j].AggregatedAt
if a == nil || b == nil {
return a != nil && b == nil
}
return a.After(*b)
})
} else {
sort.SliceStable(matched, func(i, j int) bool { return matched[i].Sequence < matched[j].Sequence })
}
page := []ipQueueItem{}
if offset < len(matched) {
page = matched[offset:]
if len(page) > limit {
page = page[:limit]
}
}
writeJSON(w, http.StatusOK, ipsPage{Items: page, Total: len(matched), Limit: limit, Offset: offset})
})
mux.HandleFunc("GET /api/v1/admin/ips/{ip}", func(w http.ResponseWriter, r *http.Request) {
@@ -122,6 +201,7 @@ func (f *fakeControlAPI) handler() http.Handler {
writeAPIErr(w, http.StatusBadRequest, "addresses must not be empty")
return
}
f.submitChunks = append(f.submitChunks, len(req.Addresses))
resp := submitIPsResponse{}
for _, addr := range req.Addresses {
idx := f.findIP(addr)
@@ -190,6 +270,7 @@ func (f *fakeControlAPI) handler() http.Handler {
writeAPIErr(w, http.StatusBadRequest, "addresses must not be empty")
return
}
f.deleteChunks = append(f.deleteChunks, len(req.Addresses))
resp := deleteIPsResponse{}
for _, addr := range req.Addresses {
idx := f.findIP(addr)
@@ -210,6 +291,7 @@ func (f *fakeControlAPI) handler() http.Handler {
for _, ip := range f.ips {
resp.Deleted = append(resp.Deleted, ip.IPAddress)
}
resp.Count = len(resp.Deleted)
f.ips = nil
writeJSON(w, http.StatusOK, resp)
})
@@ -246,18 +328,32 @@ func (f *fakeControlAPI) handler() http.Handler {
mux.HandleFunc("POST /api/v1/admin/ips/scan", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
resp := scanIPsResponse{ScannedFree: len(f.scanFreeAddresses)}
for _, addr := range f.scanFreeAddresses {
idx := f.findIP(addr)
if idx < 0 {
now := time.Now()
f.ips = append(f.ips, ipQueueItem{IPAddress: addr, State: "queued", CreatedAt: now, UpdatedAt: now})
resp.Added = append(resp.Added, addr)
continue
}
resp.Reordered = append(resp.Reordered, addr)
if f.scanStartStatus != 0 {
writeAPIErr(w, f.scanStartStatus, "scan refused")
return
}
writeJSON(w, http.StatusOK, resp)
if !f.scan.Running {
now := time.Now()
f.scan = scanStatusDTO{State: "listing", Running: true, DryRun: r.URL.Query().Get("dry_run") == "true", StartedAt: &now}
f.scanPollsLeft = f.scanRunPolls
if f.scanPollsLeft == 0 {
f.finishScan()
}
}
writeJSON(w, http.StatusAccepted, f.scan)
})
mux.HandleFunc("GET /api/v1/admin/ips/scan", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
if f.scan.Running && f.scanPollsLeft > 0 {
f.scanPollsLeft--
if f.scanPollsLeft == 0 {
f.finishScan()
} else {
f.scan.Pages++
}
}
writeJSON(w, http.StatusOK, f.scan)
})
mux.HandleFunc("GET /api/v1/admin/auto-cycle", func(w http.ResponseWriter, r *http.Request) {
@@ -329,11 +425,37 @@ func (f *fakeControlAPI) handler() http.Handler {
mux.HandleFunc("GET /api/v1/admin/registry", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
out := make([]registryItem, 0, len(f.registry))
qv := r.URL.Query()
f.registryQueries = append(f.registryQueries, r.URL.RawQuery)
matched := make([]registryItem, 0, len(f.registry))
for _, item := range f.registry {
out = append(out, item)
if q := qv.Get("q"); q != "" && !strings.Contains(strings.ToLower(item.IPAddress), strings.ToLower(q)) {
continue
}
if lr := qv.Get("last_result"); lr != "" && item.LastResult != lr {
continue
}
matched = append(matched, item)
}
writeJSON(w, http.StatusOK, out)
sort.Slice(matched, func(i, j int) bool { return matched[i].IPAddress < matched[j].IPAddress })
if qv.Get("limit") == "" {
writeJSON(w, http.StatusOK, matched)
return
}
limit, err := strconv.Atoi(qv.Get("limit"))
if err != nil || limit < 1 || limit > 1000 {
writeAPIErr(w, http.StatusBadRequest, "limit must be 1..1000")
return
}
offset, _ := strconv.Atoi(qv.Get("offset"))
page := []registryItem{}
if offset < len(matched) {
page = matched[offset:]
if len(page) > limit {
page = page[:limit]
}
}
writeJSON(w, http.StatusOK, registryPage{Items: page, Total: len(matched), Limit: limit, Offset: offset})
})
mux.HandleFunc("GET /api/v1/admin/registry/{ip}", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
@@ -544,6 +666,51 @@ func (f *fakeControlAPI) handler() http.Handler {
})
}
// finishScan ends the running scan job (caller holds f.mu): the discovered
// free addresses are queued unless it was a dry run, or the job fails with
// scanFinalError.
func (f *fakeControlAPI) finishScan() {
now := time.Now()
f.scan.Running = false
f.scan.FinishedAt = &now
f.scan.Discovered = len(f.scanFreeAddresses)
f.scan.Free = len(f.scanFreeAddresses)
if f.scanFinalError != "" {
f.scan.State = "error"
f.scan.Error = f.scanFinalError
return
}
f.scan.State = "done"
if f.scan.DryRun {
return
}
for _, addr := range f.scanFreeAddresses {
if f.findIP(addr) < 0 {
f.ips = append(f.ips, ipQueueItem{IPAddress: addr, State: "queued", Sequence: len(f.ips) + 1, CreatedAt: now, UpdatedAt: now})
f.scan.Added++
} else {
f.scan.Reordered++
}
}
}
// seedIPs appends n queued addresses 10.x.y.z (distinct, in sequence order)
// and returns them. Use it for tests that need pages' worth of rows.
func (f *fakeControlAPI) seedIPs(n int) []string {
f.mu.Lock()
defer f.mu.Unlock()
now := time.Now()
out := make([]string, 0, n)
base := len(f.ips)
for i := 0; i < n; i++ {
k := base + i + 1
addr := fmt.Sprintf("10.%d.%d.%d", k/65536, (k/256)%256, k%256)
f.ips = append(f.ips, ipQueueItem{IPAddress: addr, State: "queued", Sequence: k, CreatedAt: now, UpdatedAt: now})
out = append(out, addr)
}
return out
}
func (f *fakeControlAPI) findIP(addr string) int {
for i, ip := range f.ips {
if ip.IPAddress == addr {
@@ -596,3 +763,14 @@ func postForm(t *testing.T, ts *httptest.Server, method, path string, form url.V
body, _ := io.ReadAll(resp.Body)
return string(body)
}
// newSlowAPI serves an empty JSON object for every request after delay.
func newSlowAPI(t *testing.T, delay time.Duration) string {
t.Helper()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(delay)
writeJSON(w, http.StatusOK, map[string]interface{}{})
}))
t.Cleanup(ts.Close)
return ts.URL
}
+151 -6
View File
@@ -1,6 +1,7 @@
package dashboard
import (
"fmt"
"strconv"
"time"
)
@@ -20,6 +21,27 @@ type statusResponse struct {
TotalIPs int `json:"total_ips"`
IPsByState map[string]int `json:"ips_by_state"`
TotalValidators int `json:"total_validators"`
// ResultsByOverall counts finished addresses by overall result
// (pass/partial/fail/cancelled).
ResultsByOverall map[string]int `json:"results_by_overall"`
}
// Terminal queue states: the address needs no further processing. Shared by
// the overview progress indicator; "occupied" counts as terminal too (the
// check cycle never ran because the floating IP was already bound).
var terminalStates = []string{"done", "failed", "occupied"}
// activeStates are the states of an address that is being worked on right
// now (everything between "queued" and a terminal state).
var activeStates = []string{"assigning_fip", "awaiting_self_check", "checking", "aggregating"}
// sumStates adds up the counts of the given states in a status breakdown.
func sumStates(byState map[string]int, states []string) int {
n := 0
for _, s := range states {
n += byState[s]
}
return n
}
type ipQueueItem struct {
@@ -99,14 +121,135 @@ type deleteIPsResponse struct {
type clearQueueResponse struct {
Deleted []string `json:"deleted"`
Count int `json:"count"`
}
type scanIPsResponse struct {
ScannedFree int `json:"scanned_free"`
Added []string `json:"added"`
Requeued []string `json:"requeued"`
Reordered []string `json:"reordered"`
SkippedInProgress []string `json:"skipped_in_progress"`
// ipsPage is the paginated envelope of GET /admin/ips (sent when the request
// carries `limit`).
type ipsPage struct {
Items []ipQueueItem `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
// registryPage is the paginated envelope of GET /admin/registry.
type registryPage struct {
Items []registryItem `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
// scanStatusDTO is the state of control-api's background floating-IP scan job
// (POST/GET /api/v1/admin/ips/scan).
type scanStatusDTO struct {
State string `json:"state"`
Running bool `json:"running"`
DryRun bool `json:"dry_run"`
Pages int `json:"pages"`
Discovered int `json:"discovered"`
Free int `json:"free"`
Added int `json:"added"`
Requeued int `json:"requeued"`
Reordered int `json:"reordered"`
SkippedInProgress int `json:"skipped_in_progress"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
Error string `json:"error"`
}
// Finished reports a job that has run to a terminal state (as opposed to
// "idle" = never started, or still running).
func (s scanStatusDTO) Finished() bool {
if s.Running {
return false
}
switch s.State {
case "done", "error", "cancelled":
return true
}
return false
}
// StateLabel is the Russian description of the job's state.
func (s scanStatusDTO) StateLabel() string {
switch s.State {
case "clearing":
return "очистка"
case "listing":
return "читаются страницы"
case "enqueuing":
return "ставятся в очередь"
case "done":
return "готово"
case "error":
return "ошибка"
case "cancelled":
return "отменено"
case "idle", "":
return "нет активного сканирования"
default:
return s.State
}
}
// PillClass picks the pill style for the state.
func (s scanStatusDTO) PillClass() string {
switch s.State {
case "done":
return "pill-success"
case "error":
return "pill-danger"
case "cancelled":
return "pill-cancel"
case "clearing", "listing", "enqueuing":
return "pill-info"
default:
return "pill-neutral"
}
}
// Handled is how many of the free addresses the enqueuing phase has already
// processed.
func (s scanStatusDTO) Handled() int {
return s.Added + s.Requeued + s.Reordered + s.SkippedInProgress
}
// Indeterminate is true while the amount of work is not known yet.
func (s scanStatusDTO) Indeterminate() bool {
return s.State == "clearing" || s.State == "listing" || (s.State == "enqueuing" && s.Free <= 0)
}
// Elapsed is the human-readable run time: until now while running, until
// finished_at afterwards; empty when the job never started.
func (s scanStatusDTO) Elapsed() string {
if s.StartedAt == nil {
return ""
}
end := time.Now()
if !s.Running && s.FinishedAt != nil {
end = *s.FinishedAt
}
return fmtDuration(end.Sub(*s.StartedAt))
}
// fmtDuration renders a duration in Russian as "2 ч 05 мин", "3 мин 07 с" or
// "42 с" — coarse on purpose (progress/ETA display).
func fmtDuration(d time.Duration) string {
if d < 0 {
d = 0
}
sec := int(d.Round(time.Second) / time.Second)
h, m, sc := sec/3600, (sec%3600)/60, sec%60
switch {
case h > 0:
return fmt.Sprintf("%d ч %02d мин", h, m)
case m > 0:
return fmt.Sprintf("%d мин %02d с", m, sc)
default:
return fmt.Sprintf("%d с", sc)
}
}
// registryItem is one row of the durable per-address registry — see
@@ -200,6 +343,8 @@ func (a autoCycleDTO) MaxRunMinutes() string { return secondsToMinutes(a.MaxRu
// PhaseLabel is the Russian description of the current phase.
func (a autoCycleDTO) PhaseLabel() string {
switch a.Phase {
case "scanning":
return "сканирование Floating IP"
case "running":
return "идёт проверка"
case "waiting":
+279 -38
View File
@@ -1,14 +1,122 @@
package dashboard
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
)
// bulkChunk is how many addresses go into one DeleteIPs/SubmitIPs call when
// an operation spans a whole filter ("scope=all").
const bulkChunk = 500
// ipStates are the queue states control-api accepts in the `state` filter.
var ipStates = []string{"queued", "assigning_fip", "awaiting_self_check", "checking", "aggregating", "done", "failed", "occupied"}
var ipResults = []string{"pass", "partial", "fail", "cancelled"}
func containsStr(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
// ipsFilter is the server-side filter of the /ips list. State is a filter
// token: one of "", "queued", "active" (every in-progress state), "done",
// "failed", "occupied", or a comma-separated list of raw queue states; the
// result filter is separate (Result) and may be combined with it.
type ipsFilter struct {
Q string
State string
Result string
}
// parseIPsFilter reads q/state/result from the request (query or form body).
// The state <select> posts a single `state` value, so "result:pass" selects a
// result filter; anything unrecognised is dropped rather than forwarded.
func parseIPsFilter(r *http.Request) ipsFilter {
f := ipsFilter{
Q: strings.TrimSpace(r.FormValue("q")),
State: strings.TrimSpace(r.FormValue("state")),
Result: strings.TrimSpace(r.FormValue("result")),
}
if res, ok := strings.CutPrefix(f.State, "result:"); ok {
f.State, f.Result = "", res
}
if !containsStr(ipResults, f.Result) {
f.Result = ""
}
switch f.State {
case "", "active":
default:
for _, st := range strings.Split(f.State, ",") {
if !containsStr(ipStates, st) {
f.State = ""
break
}
}
}
return f
}
// States expands the state token into the list sent to control-api.
func (f ipsFilter) States() []string {
switch f.State {
case "":
return nil
case "active":
return activeStates
default:
return strings.Split(f.State, ",")
}
}
// Active reports whether any filter is applied.
func (f ipsFilter) Active() bool { return f.Q != "" || f.State != "" || f.Result != "" }
// Token is the value of the state <select> option matching the filter.
func (f ipsFilter) Token() string {
if f.State == "" && f.Result != "" {
return "result:" + f.Result
}
return f.State
}
func (f ipsFilter) values() url.Values {
v := url.Values{}
if f.Q != "" {
v.Set("q", f.Q)
}
if f.State != "" {
v.Set("state", f.State)
}
if f.Result != "" {
v.Set("result", f.Result)
}
return v
}
type ipsPageData struct {
PageData
Items []ipQueueItem
FIPSettleSeconds int
Filter ipsFilter
Page, PerPage int
// Total is the number of rows matching the filter; QueueTotal is the whole
// queue (what "Очистить всё" would remove).
Total, QueueTotal int
Pager pagerData
// SelfURL is this page's own URL (filter + page), re-requested to reload
// the table when a scan finishes.
SelfURL string
PerPageOptions []int
Scan scanProgressData
}
type ipDetailData struct {
@@ -16,13 +124,67 @@ type ipDetailData struct {
Detail ipDetailResponse
}
func (s *Server) handleIPsPage(w http.ResponseWriter, r *http.Request) {
items, err := s.CA.ListIPs(r.Context())
settings, settingsErr := s.CA.GetOrchestratorSettings(r.Context())
// loadIPsData fetches the page of the queue selected by the request's
// page/per_page/q/state/result params. A page that became empty (e.g. after
// deleting its last rows) is clamped to the last non-empty page.
func (s *Server) loadIPsData(r *http.Request) (ipsPageData, error) {
ctx := r.Context()
f := parseIPsFilter(r)
perPage := parsePerPage(r.FormValue("per_page"))
page := parsePage(r.FormValue("page"))
q := ipsQuery{States: f.States(), Q: f.Q, Result: f.Result, Order: "sequence", Limit: perPage, Offset: (page - 1) * perPage}
res, err := s.CA.ListIPsPage(ctx, q)
if err == nil {
err = settingsErr
if clamped := clampPage(page, res.Total, perPage); clamped != page {
page = clamped
q.Offset = (page - 1) * perPage
res, err = s.CA.ListIPsPage(ctx, q)
}
}
data := ipsPageData{
Items: res.Items,
Filter: f,
Page: page,
PerPage: perPage,
Total: res.Total,
QueueTotal: res.Total,
PerPageOptions: perPageOptions,
}
data.Pager = newPager("/ips", "ips-table-wrap", f.values(), page, perPage, res.Total)
data.SelfURL = pageURL("/ips", f.values(), page, perPage)
if settings, settingsErr := s.CA.GetOrchestratorSettings(ctx); settingsErr != nil {
if err == nil {
err = settingsErr
}
} else {
data.FIPSettleSeconds = settings.FIPSettleSeconds
}
if err == nil && f.Active() {
// "Очистить всё" ignores the filter: show the real queue size in its
// confirmation. Non-fatal — the label just falls back to the filtered total.
if st, stErr := s.CA.Status(ctx); stErr == nil {
data.QueueTotal = st.TotalIPs
}
}
return data, err
}
func (s *Server) handleIPsPage(w http.ResponseWriter, r *http.Request) {
data, err := s.loadIPsData(r)
// A filter/pager request from htmx swaps only #ips-table-wrap (hx-select),
// so there is no need to re-render the whole page (and re-query the scan
// status). A history-restore fetch needs the full page.
if r.Header.Get("HX-Request") == "true" && r.Header.Get("HX-History-Restore-Request") != "true" {
s.renderFragment(w, "ips_table_wrap", data, err)
return
}
if st, scanErr := s.CA.ScanStatus(r.Context()); scanErr != nil {
s.Log.Warn("ips: scan status unavailable", "err", scanErr)
} else {
data.Scan = newScanProgress(st)
}
data := ipsPageData{Items: items, FIPSettleSeconds: settings.FIPSettleSeconds}
data.ActiveNav = "ips"
data.Banner = bannerFor(err)
s.renderPage(w, r, "ips_page", data)
@@ -37,20 +199,18 @@ func (s *Server) handleIPDetail(w http.ResponseWriter, r *http.Request) {
s.renderPage(w, r, "ip_detail_page", data)
}
// renderIPsTable re-fetches the current queue and renders the ips_table
// fragment, tagging actionErr (if any) on the shared error banner. Called
// after every mutating /ips/* request so the table always reflects true
// current state regardless of whether the mutation itself succeeded.
// renderIPsTable re-fetches the current page of the queue (same page/filter as
// the request, carried in hidden #ips-form inputs) and renders the
// ips_table_wrap fragment, tagging actionErr (if any) on the shared error
// banner. Called after every mutating /ips/* request so the table always
// reflects true current state regardless of whether the mutation itself
// succeeded.
func (s *Server) renderIPsTable(w http.ResponseWriter, r *http.Request, actionErr error) {
items, listErr := s.CA.ListIPs(r.Context())
data, err := s.loadIPsData(r)
if actionErr == nil {
actionErr = listErr
actionErr = err
}
settings, settingsErr := s.CA.GetOrchestratorSettings(r.Context())
if actionErr == nil {
actionErr = settingsErr
}
s.renderFragment(w, "ips_table", ipsPageData{Items: items, FIPSettleSeconds: settings.FIPSettleSeconds}, actionErr)
s.renderFragment(w, "ips_table_wrap", data, actionErr)
}
func (s *Server) handleIPsSubmit(w http.ResponseWriter, r *http.Request) {
@@ -63,7 +223,7 @@ func (s *Server) handleIPsSubmit(w http.ResponseWriter, r *http.Request) {
s.renderIPsTable(w, r, &apiErr{Status: http.StatusBadRequest, Message: "укажите хотя бы один адрес"})
return
}
_, err := s.CA.SubmitIPs(r.Context(), addresses)
err := s.submitChunked(r.Context(), addresses)
s.renderIPsTable(w, r, err)
}
@@ -85,31 +245,76 @@ func (s *Server) handleIPDelete(w http.ResponseWriter, r *http.Request) {
s.renderIPsTable(w, r, err)
}
func (s *Server) handleIPsDeleteSelected(w http.ResponseWriter, r *http.Request) {
// submitChunked feeds addresses to SubmitIPs in chunks of bulkChunk so one
// huge list never becomes one huge request/transaction.
func (s *Server) submitChunked(ctx context.Context, addresses []string) error {
for _, part := range chunk(addresses, bulkChunk) {
if _, err := s.CA.SubmitIPs(ctx, part); err != nil {
return err
}
}
return nil
}
// resolveFilterAddresses lists every address matching filter by paging
// ListIPsPage (≤ maxPageLimit rows per call), for "select all N by filter".
func (s *Server) resolveFilterAddresses(ctx context.Context, f ipsFilter) ([]string, error) {
var out []string
for offset := 0; ; {
page, err := s.CA.ListIPsPage(ctx, ipsQuery{States: f.States(), Q: f.Q, Result: f.Result, Order: "sequence", Limit: maxPageLimit, Offset: offset})
if err != nil {
return nil, err
}
for _, it := range page.Items {
out = append(out, it.IPAddress)
}
offset += len(page.Items)
if len(page.Items) == 0 || offset >= page.Total {
return out, nil
}
}
}
// bulkAddresses returns the addresses a bulk delete/recheck acts on: the
// checked rows of the current page, or — with scope=all — everything that
// matches the current filter, resolved server-side.
func (s *Server) bulkAddresses(r *http.Request) ([]string, error) {
if err := r.ParseForm(); err != nil {
s.renderIPsTable(w, r, fmt.Errorf("invalid form: %w", err))
return
return nil, fmt.Errorf("invalid form: %w", err)
}
var addresses []string
if r.FormValue("scope") == "all" {
var err error
addresses, err = s.resolveFilterAddresses(r.Context(), parseIPsFilter(r))
if err != nil {
return nil, err
}
} else {
addresses = r.Form["addresses"]
}
addresses := r.Form["addresses"]
if len(addresses) == 0 {
s.renderIPsTable(w, r, &apiErr{Status: http.StatusBadRequest, Message: "ничего не выбрано"})
return
return nil, &apiErr{Status: http.StatusBadRequest, Message: "ничего не выбрано"}
}
return addresses, nil
}
func (s *Server) handleIPsDeleteSelected(w http.ResponseWriter, r *http.Request) {
addresses, err := s.bulkAddresses(r)
if err == nil {
for _, part := range chunk(addresses, bulkChunk) {
if _, err = s.CA.DeleteIPs(r.Context(), part); err != nil {
break
}
}
}
_, err := s.CA.DeleteIPs(r.Context(), addresses)
s.renderIPsTable(w, r, err)
}
func (s *Server) handleIPsRecheckSelected(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderIPsTable(w, r, fmt.Errorf("invalid form: %w", err))
return
addresses, err := s.bulkAddresses(r)
if err == nil {
err = s.submitChunked(r.Context(), addresses)
}
addresses := r.Form["addresses"]
if len(addresses) == 0 {
s.renderIPsTable(w, r, &apiErr{Status: http.StatusBadRequest, Message: "ничего не выбрано"})
return
}
_, err := s.CA.SubmitIPs(r.Context(), addresses)
s.renderIPsTable(w, r, err)
}
@@ -118,10 +323,46 @@ func (s *Server) handleIPsClear(w http.ResponseWriter, r *http.Request) {
s.renderIPsTable(w, r, err)
}
// handleIPsScan lists the OpenStack project's free (unassociated) floating
// IPs and submits them to the check queue in one step — see
// client.ScanFloatingIPs.
// scanProgressData drives the scan_progress partial. Poll keeps the partial's
// own hx-trigger="every 2s" alive: while the job runs, or while control-api is
// transiently unreachable (so one failed poll doesn't freeze the panel).
type scanProgressData struct {
Status scanStatusDTO
Poll bool
}
func newScanProgress(st scanStatusDTO) scanProgressData {
return scanProgressData{Status: st, Poll: st.Running}
}
// renderScanProgress renders the scan panel fragment. A finished job also
// sends `HX-Trigger: scan-finished`, which makes #ips-table-wrap reload.
// Errors go to the shared banner; only transient ones (transport/5xx) keep
// polling when keepPolling is set.
func (s *Server) renderScanProgress(w http.ResponseWriter, st scanStatusDTO, err error, keepPolling bool) {
data := newScanProgress(st)
if err != nil {
data = scanProgressData{}
var ae *apiErr
if keepPolling && errors.As(err, &ae) && (ae.Status == 0 || ae.Status >= 500) {
data.Poll = true
}
} else if st.Finished() {
w.Header().Set("HX-Trigger", "scan-finished")
}
s.renderFragment(w, "scan_progress", data, err)
}
// handleIPsScan starts the background floating-IP scan (or joins the running
// one) and returns the progress panel at once — the job itself runs in
// control-api, so this never waits for OpenStack. ?dry_run=true only counts.
func (s *Server) handleIPsScan(w http.ResponseWriter, r *http.Request) {
_, err := s.CA.ScanFloatingIPs(r.Context())
s.renderIPsTable(w, r, err)
st, err := s.CA.StartScan(r.Context(), r.URL.Query().Get("dry_run") == "true")
s.renderScanProgress(w, st, err, false)
}
// handleIPsScanStatus is the progress panel's poll target.
func (s *Server) handleIPsScanStatus(w http.ResponseWriter, r *http.Request) {
st, err := s.CA.ScanStatus(r.Context())
s.renderScanProgress(w, st, err, true)
}
+109 -71
View File
@@ -2,23 +2,51 @@ package dashboard
import (
"net/http"
"sort"
"strings"
"time"
)
const (
// overviewActiveLimit caps the "В работе" table; overviewQueueLimit caps
// the compact list of the next queued addresses. The queue itself can hold
// thousands of rows, so the overview never lists more than these.
overviewActiveLimit = 100
overviewQueueLimit = 10
// etaMinSamples is how many completed rows (with AggregatedAt) the ETA
// needs to derive a rate from.
etaMinSamples = 5
)
// overviewProgress is the "Готово D из T" indicator of the stats block.
type overviewProgress struct {
Total, Done, Active, Queued, Percent int
// ETA is a rough time-to-finish estimate ("" when not enough data).
ETA string
}
type overviewData struct {
PageData
Status statusResponse
CurrentItems []ipQueueItem
Status statusResponse
// ActiveItems are the addresses being checked right now (≤ overviewActiveLimit
// of ActiveTotal); QueuedItems are the next few waiting ones (QueuedTotal
// in total). Both stay empty under a result filter: an address without a
// verdict can't match one.
ActiveItems []ipQueueItem
ActiveTotal int
QueuedItems []ipQueueItem
QueuedTotal int
LastCompleted []ipQueueItem
Breakdown map[string]int
LastN int
PollSeconds int
Query string
StatusFilter string
Progress overviewProgress
// AutoCycle is nil when the auto-cycle status could not be fetched; the
// indicator is then simply hidden (a non-fatal failure).
// indicator is then simply hidden (a non-fatal failure). Scan is likewise
// nil when the scan status is unavailable.
AutoCycle *autoCycleDTO
Scan *scanStatusDTO
}
func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
@@ -27,30 +55,58 @@ func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
if err != nil {
return overviewData{}, err
}
ips, err := s.CA.ListIPs(ctx)
q := strings.TrimSpace(r.URL.Query().Get("q"))
resultFilter := r.URL.Query().Get("status")
if !containsStr(ipResults, resultFilter) {
resultFilter = ""
}
lastN := s.Cfg.LastCompletedCount
if lastN < 1 {
lastN = 20
}
data := overviewData{
Status: status,
LastN: lastN,
PollSeconds: s.Cfg.OverviewPollIntervalS,
Query: q,
StatusFilter: resultFilter,
}
if resultFilter == "" {
active, err := s.CA.ListIPsPage(ctx, ipsQuery{States: activeStates, Q: q, Order: "sequence", Limit: overviewActiveLimit})
if err != nil {
return overviewData{}, err
}
queued, err := s.CA.ListIPsPage(ctx, ipsQuery{States: []string{"queued"}, Q: q, Order: "sequence", Limit: overviewQueueLimit})
if err != nil {
return overviewData{}, err
}
data.ActiveItems, data.ActiveTotal = active.Items, active.Total
data.QueuedItems, data.QueuedTotal = queued.Items, queued.Total
}
completed, err := s.CA.ListIPsPage(ctx, ipsQuery{States: []string{"done", "failed"}, Q: q, Result: resultFilter, Order: "aggregated_at_desc", Limit: lastN})
if err != nil {
return overviewData{}, err
}
var autoCycle *autoCycleDTO
data.LastCompleted = completed.Items
data.Breakdown = resultBreakdown(completed.Items)
// ETA from the unfiltered window only: a filtered list is not a sample of
// the checks' real throughput.
data.Progress = computeProgress(status, completed.Items, q == "" && resultFilter == "")
if ac, acErr := s.CA.GetAutoCycle(ctx); acErr != nil {
s.Log.Warn("overview: auto-cycle status unavailable", "err", acErr)
} else {
autoCycle = &ac
data.AutoCycle = &ac
}
q := strings.TrimSpace(r.URL.Query().Get("q"))
resultFilter := r.URL.Query().Get("status")
last := lastCompleted(ips, s.Cfg.LastCompletedCount)
return overviewData{
Status: status,
CurrentItems: filterQueueItems(currentlyChecking(ips), q, resultFilter),
LastCompleted: filterQueueItems(last, q, resultFilter),
Breakdown: resultBreakdown(last),
LastN: s.Cfg.LastCompletedCount,
PollSeconds: s.Cfg.OverviewPollIntervalS,
Query: q,
StatusFilter: resultFilter,
AutoCycle: autoCycle,
}, nil
if sc, scErr := s.CA.ScanStatus(ctx); scErr != nil {
s.Log.Warn("overview: scan status unavailable", "err", scErr)
} else if sc.Running {
data.Scan = &sc
}
return data, nil
}
func (s *Server) handleOverview(w http.ResponseWriter, r *http.Request) {
@@ -75,40 +131,45 @@ func (s *Server) handleOverviewFragment(w http.ResponseWriter, r *http.Request)
}
}
// currentlyChecking is every IP not yet in a terminal state, ordered by
// queue position — the "текущая проверка" live snapshot. No backend
// concept of a "run" exists; this is computed fresh on every request.
func currentlyChecking(ips []ipQueueItem) []ipQueueItem {
var out []ipQueueItem
for _, ip := range ips {
if ip.State != "done" && ip.State != "failed" {
out = append(out, ip)
// computeProgress derives the done/active/queued counters from the status
// breakdown (done = every terminal state, "occupied" included) and, when
// useETA is set and the newest-first list of completed rows has at least
// etaMinSamples with AggregatedAt, a rough ETA from their completion rate.
func computeProgress(st statusResponse, completed []ipQueueItem, useETA bool) overviewProgress {
p := overviewProgress{
Total: st.TotalIPs,
Done: sumStates(st.IPsByState, terminalStates),
Active: sumStates(st.IPsByState, activeStates),
Queued: st.IPsByState["queued"],
}
if p.Total > 0 {
p.Percent = p.Done * 100 / p.Total
}
remaining := p.Active + p.Queued
if !useETA || remaining == 0 {
return p
}
var stamps []time.Time
for _, ip := range completed {
if ip.AggregatedAt != nil {
stamps = append(stamps, *ip.AggregatedAt)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Sequence < out[j].Sequence })
return out
}
// lastCompleted returns the n most recently completed (done/failed) IPs by
// AggregatedAt descending — the "последняя завершённая проверка" summary
// window. This is an operational definition, not a real "batch": resubmit
// n if the window size needs tuning (overview.last_completed_count).
func lastCompleted(ips []ipQueueItem, n int) []ipQueueItem {
var done []ipQueueItem
for _, ip := range ips {
if (ip.State == "done" || ip.State == "failed") && ip.AggregatedAt != nil {
done = append(done, ip)
}
if len(stamps) < etaMinSamples {
return p
}
sort.Slice(done, func(i, j int) bool { return done[i].AggregatedAt.After(*done[j].AggregatedAt) })
if len(done) > n {
done = done[:n]
// completed is newest-first: stamps[0] is the newest, the last the oldest.
span := stamps[0].Sub(stamps[len(stamps)-1])
if span <= 0 {
return p
}
return done
perItem := span / time.Duration(len(stamps)-1)
p.ETA = fmtDuration(perItem * time.Duration(remaining))
return p
}
// resultBreakdown counts OverallResult values across exactly the given
// items (normally the output of lastCompleted) — pass/partial/fail/cancelled.
// items (the "последние N завершённых" window) — pass/partial/fail/cancelled.
func resultBreakdown(items []ipQueueItem) map[string]int {
out := map[string]int{"pass": 0, "partial": 0, "fail": 0, "cancelled": 0}
for _, ip := range items {
@@ -116,26 +177,3 @@ func resultBreakdown(items []ipQueueItem) map[string]int {
}
return out
}
// filterQueueItems narrows items to those whose address contains q
// (case-insensitive substring) and, if status is set, whose OverallResult
// matches it exactly. A still-in-progress item always has an empty
// OverallResult, so picking any specific status hides it — the intended
// behavior for "Текущая проверка", which has no verdict yet.
func filterQueueItems(items []ipQueueItem, q, status string) []ipQueueItem {
if q == "" && status == "" {
return items
}
q = strings.ToLower(q)
out := make([]ipQueueItem, 0, len(items))
for _, ip := range items {
if q != "" && !strings.Contains(strings.ToLower(ip.IPAddress), q) {
continue
}
if status != "" && ip.OverallResult != status {
continue
}
out = append(out, ip)
}
return out
}
+40 -30
View File
@@ -2,14 +2,19 @@ package dashboard
import (
"net/http"
"net/url"
"strings"
)
type registryPageData struct {
PageData
Items []registryItem
Query string
StatusFilter string
Items []registryItem
Query string
StatusFilter string
Page, PerPage int
Total int
Pager pagerData
PerPageOptions []int
}
type registryDetailData struct {
@@ -22,43 +27,48 @@ type registryDetailData struct {
// 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 — see filterRegistryItems.
// LastResult, and ?page=&per_page= select a page — all applied server-side
// (control-api's ListRegistryPage), so only the visible rows are transferred.
func (s *Server) handleRegistryPage(w http.ResponseWriter, r *http.Request) {
items, err := s.CA.ListRegistry(r.Context())
q := strings.TrimSpace(r.URL.Query().Get("q"))
status := r.URL.Query().Get("status")
if !containsStr(ipResults, status) {
status = ""
}
perPage := parsePerPage(r.URL.Query().Get("per_page"))
page := parsePage(r.URL.Query().Get("page"))
query := registryQuery{Q: q, LastResult: status, Limit: perPage, Offset: (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)
}
data := registryPageData{
Items: filterRegistryItems(items, q, status),
Query: q,
StatusFilter: status,
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.Banner = bannerFor(err)
s.renderPage(w, r, "registry_page", data)
}
// filterRegistryItems narrows items to those whose address contains q
// (case-insensitive substring) and, if status is set, whose LastResult
// matches it exactly — the registry list's search-by-IP and
// filter-by-status, mirroring filterQueueItems in handlers_overview.go.
func filterRegistryItems(items []registryItem, q, status string) []registryItem {
if q == "" && status == "" {
return items
}
q = strings.ToLower(q)
out := make([]registryItem, 0, len(items))
for _, it := range items {
if q != "" && !strings.Contains(strings.ToLower(it.IPAddress), q) {
continue
}
if status != "" && it.LastResult != status {
continue
}
out = append(out, it)
}
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.
-72
View File
@@ -558,20 +558,6 @@ func TestTargetsAndCheckTypesRoundTrip(t *testing.T) {
}
}
func TestIPsScan(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.scanFreeAddresses = []string{"5.5.5.5"}
ts := newTestServer(t, caURL)
body := postForm(t, ts, "POST", "/ips/scan", nil)
if !strings.Contains(body, "5.5.5.5") {
t.Fatalf("expected scanned address in re-rendered table, got:\n%s", body)
}
if len(fake.ips) != 1 || fake.ips[0].IPAddress != "5.5.5.5" {
t.Fatalf("expected fake control-api queue to contain the scanned address, got %+v", fake.ips)
}
}
func TestRegistryPageAndDetail(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
@@ -667,64 +653,6 @@ func TestControlAPIUnreachable(t *testing.T) {
}
}
func TestFilterQueueItems(t *testing.T) {
items := []ipQueueItem{
{IPAddress: "1.1.1.1", OverallResult: "pass"},
{IPAddress: "1.1.1.2", OverallResult: "fail"},
{IPAddress: "2.2.2.2", OverallResult: "pass"},
}
if got := filterQueueItems(items, "", ""); len(got) != 3 {
t.Fatalf("expected no-op with empty q/status, got %+v", got)
}
if got := filterQueueItems(items, "1.1.1", ""); len(got) != 2 {
t.Fatalf("expected 2 matches for q=1.1.1, got %+v", got)
}
if got := filterQueueItems(items, "1.1.1.1", ""); len(got) != 1 || got[0].IPAddress != "1.1.1.1" {
t.Fatalf("expected exact-substring match, got %+v", got)
}
if got := filterQueueItems(items, "1.1.1.1", ""); len(got) != 1 {
t.Fatalf("expected search to be case/substring based, got %+v", got)
}
if got := filterQueueItems(items, "", "pass"); len(got) != 2 {
t.Fatalf("expected 2 matches for status=pass, got %+v", got)
}
if got := filterQueueItems(items, "1.1.1", "pass"); len(got) != 1 || got[0].IPAddress != "1.1.1.1" {
t.Fatalf("expected q+status combined with AND, got %+v", got)
}
if got := filterQueueItems(items, "9.9.9.9", ""); len(got) != 0 {
t.Fatalf("expected no matches, got %+v", got)
}
// Case-insensitivity, via a query with mixed-case letters (IP octets
// are numeric, so exercise it through IPv6-shaped input instead).
mixed := []ipQueueItem{{IPAddress: "fe80::AbCd"}}
if got := filterQueueItems(mixed, "abcd", ""); len(got) != 1 {
t.Fatalf("expected case-insensitive search to match, got %+v", got)
}
}
func TestFilterRegistryItems(t *testing.T) {
items := []registryItem{
{IPAddress: "1.1.1.1", LastResult: "pass"},
{IPAddress: "1.1.1.2", LastResult: "partial"},
{IPAddress: "2.2.2.2", LastResult: ""},
}
if got := filterRegistryItems(items, "", ""); len(got) != 3 {
t.Fatalf("expected no-op with empty q/status, got %+v", got)
}
if got := filterRegistryItems(items, "1.1.1", ""); len(got) != 2 {
t.Fatalf("expected 2 matches for q=1.1.1, got %+v", got)
}
if got := filterRegistryItems(items, "", "partial"); len(got) != 1 || got[0].IPAddress != "1.1.1.2" {
t.Fatalf("expected exactly the partial-result address, got %+v", got)
}
if got := filterRegistryItems(items, "2.2.2", "partial"); len(got) != 0 {
t.Fatalf("expected q+status combined with AND to exclude non-matching, got %+v", got)
}
}
func TestAutoCyclePanelRenders(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
finished := time.Now().Add(-time.Hour)
+118
View File
@@ -0,0 +1,118 @@
package dashboard
import (
"net/url"
"strconv"
"strings"
)
// Server-side pagination shared by /ips and /registry: `page` (1-based,
// clamped to the last page) and `per_page` (one of perPageOptions, else
// defaultPerPage).
const defaultPerPage = 50
var perPageOptions = []int{25, 50, 100, 200}
// parsePerPage accepts only the whitelisted page sizes.
func parsePerPage(raw string) int {
n, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return defaultPerPage
}
for _, o := range perPageOptions {
if n == o {
return n
}
}
return defaultPerPage
}
// parsePage returns the 1-based page number; anything invalid is page 1.
func parsePage(raw string) int {
n, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil || n < 1 {
return 1
}
return n
}
func pageCount(total, perPage int) int {
if total <= 0 || perPage <= 0 {
return 1
}
return (total + perPage - 1) / perPage
}
// clampPage limits page to the last non-empty page for the given total.
func clampPage(page, total, perPage int) int {
if last := pageCount(total, perPage); page > last {
page = last
}
if page < 1 {
page = 1
}
return page
}
// pagerData drives the shared "pager" template partial.
type pagerData struct {
// Wrap is the id of the swap-target element holding the table (the
// ‹ › links replace it via hx-select + hx-target).
Wrap string
Page, PerPage, Total, Pages, From, To int
PrevURL, NextURL string
}
// newPager builds the pager for page (already clamped) of total rows. base is
// the page path; params are the filters to preserve in the links (without
// page/per_page, which the pager sets itself).
func newPager(base, wrap string, params url.Values, page, perPage, total int) pagerData {
p := pagerData{Wrap: wrap, Page: page, PerPage: perPage, Total: total, Pages: pageCount(total, perPage)}
if total > 0 {
p.From = (page-1)*perPage + 1
p.To = page * perPage
if p.To > total {
p.To = total
}
}
if page > 1 {
p.PrevURL = pageURL(base, params, page-1, perPage)
}
if page < p.Pages {
p.NextURL = pageURL(base, params, page+1, perPage)
}
return p
}
// pageURL builds base?...&page=N&per_page=M with every value escaped by
// url.Values (so a search string like "a&b" can't smuggle in a parameter).
// Page 1 omits `page`.
func pageURL(base string, params url.Values, page, perPage int) string {
v := url.Values{}
for k, vals := range params {
for _, val := range vals {
if val != "" {
v.Add(k, val)
}
}
}
v.Set("per_page", strconv.Itoa(perPage))
if page > 1 {
v.Set("page", strconv.Itoa(page))
}
return base + "?" + v.Encode()
}
// chunk splits list into slices of at most size elements.
func chunk(list []string, size int) [][]string {
var out [][]string
for len(list) > size {
out = append(out, list[:size])
list = list[size:]
}
if len(list) > 0 {
out = append(out, list)
}
return out
}
+1
View File
@@ -18,6 +18,7 @@ func (s *Server) routes(mux *http.ServeMux) {
mux.HandleFunc("GET /ips/{ip}", s.handleIPDetail)
mux.HandleFunc("POST /ips", s.handleIPsSubmit)
mux.HandleFunc("POST /ips/scan", s.handleIPsScan)
mux.HandleFunc("GET /ips/scan/status", s.handleIPsScanStatus)
mux.HandleFunc("POST /ips/{ip}/recheck", s.handleIPRecheck)
mux.HandleFunc("POST /ips/{ip}/cancel", s.handleIPCancel)
mux.HandleFunc("DELETE /ips/{ip}", s.handleIPDelete)
+685
View File
@@ -0,0 +1,685 @@
package dashboard
import (
"fmt"
"html"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"time"
)
// Tests for the scale features: background scan panel, server-side
// pagination/filters on /ips and /registry, bulk selection by filter, and the
// bounded overview.
func ipRowLink(ip string) string { return `href="/ips/` + ip + `"` }
func countRows(body string) int { return strings.Count(body, `name="addresses" value="`) }
func hasHXTriggerEvery(body string) bool { return strings.Contains(body, `hx-trigger="every 2s"`) }
var hrefRe = regexp.MustCompile(`href="([^"]*)"[^>]*rel="(prev|next)"`)
// pagerLink extracts the (unescaped, parsed) prev/next link of the pager.
func pagerLink(t *testing.T, body, rel string) *url.URL {
t.Helper()
for _, m := range hrefRe.FindAllStringSubmatch(body, -1) {
if m[2] == rel {
u, err := url.Parse(html.UnescapeString(m[1]))
if err != nil {
t.Fatalf("parse pager link %q: %v", m[1], err)
}
return u
}
}
return nil
}
func TestIPsScan(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.scanFreeAddresses = []string{"5.5.5.5", "5.5.5.6"}
fake.scanRunPolls = 2
ts := newTestServer(t, caURL)
// Start: answers at once with the panel; it polls itself, the scan
// buttons are disabled and nothing is queued yet.
resp, body := doReq(t, ts, reqOpts{method: http.MethodPost, path: "/ips/scan"})
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200", resp.StatusCode)
}
for _, want := range []string{
`id="scan-progress"`, `hx-get="/ips/scan/status"`, `hx-trigger="every 2s"`, "читаются страницы",
`<progress aria-label="Сканирование"></progress>`, ` disabled`,
} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the running panel, got:\n%s", want, body)
}
}
if resp.Header.Get("HX-Trigger") != "" {
t.Fatalf("a running scan must not fire scan-finished, got %q", resp.Header.Get("HX-Trigger"))
}
if len(fake.ips) != 0 {
t.Fatalf("nothing should be queued before the job finishes, got %+v", fake.ips)
}
// First poll: still running, keeps polling.
resp, body = doReq(t, ts, reqOpts{path: "/ips/scan/status"})
if !hasHXTriggerEvery(body) || resp.Header.Get("HX-Trigger") != "" {
t.Fatalf("expected a still-polling panel without HX-Trigger, got %q:\n%s", resp.Header.Get("HX-Trigger"), body)
}
// Second poll: finished — no polling trigger, HX-Trigger tells the table to reload.
resp, body = doReq(t, ts, reqOpts{path: "/ips/scan/status"})
if hasHXTriggerEvery(body) || strings.Contains(body, `hx-get="/ips/scan/status"`) {
t.Fatalf("a finished panel must stop polling, got:\n%s", body)
}
if got := resp.Header.Get("HX-Trigger"); got != "scan-finished" {
t.Fatalf("HX-Trigger = %q, want scan-finished", got)
}
for _, want := range []string{"готово", "<dt>добавлено</dt><dd>2</dd>", `<progress max="1" value="1"`} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the finished panel, got:\n%s", want, body)
}
}
if strings.Contains(body, " disabled") {
t.Fatalf("buttons must be enabled again once finished, got:\n%s", body)
}
if len(fake.ips) != 2 {
t.Fatalf("expected both scanned addresses queued, got %+v", fake.ips)
}
// The table reload target: #ips-table-wrap listens for scan-finished and
// re-fetches the current /ips URL.
page := get(t, ts, "/ips")
if !strings.Contains(page, `hx-trigger="scan-finished from:body"`) || !strings.Contains(page, `hx-select="#ips-table-wrap"`) {
t.Fatalf("expected #ips-table-wrap to reload on scan-finished, got:\n%s", page)
}
if !strings.Contains(page, ipRowLink("5.5.5.5")) {
t.Fatalf("expected the scanned address in the table, got:\n%s", page)
}
}
func TestIPsScanErrorAndDryRunAndRefusal(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.scanFreeAddresses = []string{"5.5.5.5"}
fake.scanFinalError = "openstack: list floating ips: boom"
ts := newTestServer(t, caURL)
// A job that fails: the panel shows the error and stops polling.
resp, body := doReq(t, ts, reqOpts{method: http.MethodPost, path: "/ips/scan"})
for _, want := range []string{"ошибка", "openstack: list floating ips: boom", `class="scan-error"`} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the error panel, got:\n%s", want, body)
}
}
if hasHXTriggerEvery(body) || resp.Header.Get("HX-Trigger") != "scan-finished" {
t.Fatalf("an errored job must stop polling and signal scan-finished, got %q:\n%s", resp.Header.Get("HX-Trigger"), body)
}
if len(fake.ips) != 0 {
t.Fatalf("a failed scan must not queue anything, got %+v", fake.ips)
}
// Dry run: the flag reaches control-api, the queue stays untouched.
fake.mu.Lock()
fake.scanFinalError = ""
fake.scan = scanStatusDTO{}
fake.scanRunPolls = 1
fake.mu.Unlock()
_, body = doReq(t, ts, reqOpts{method: http.MethodPost, path: "/ips/scan?dry_run=true"})
if !strings.Contains(body, "пробный запуск") {
t.Fatalf("expected the dry-run marker, got:\n%s", body)
}
_, body = doReq(t, ts, reqOpts{path: "/ips/scan/status"})
if !strings.Contains(body, "готово") || len(fake.ips) != 0 {
t.Fatalf("dry run must finish without queueing, queue=%+v body:\n%s", fake.ips, body)
}
// control-api refuses to start: banner, no polling.
fake.mu.Lock()
fake.scanStartStatus = http.StatusConflict
fake.mu.Unlock()
_, body = doReq(t, ts, reqOpts{method: http.MethodPost, path: "/ips/scan"})
if !strings.Contains(body, "alert-warning") || hasHXTriggerEvery(body) {
t.Fatalf("expected a client-error banner and no polling, got:\n%s", body)
}
}
func TestIPsPageRendersRunningScanPanelOutsideForm(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
fake.scan = scanStatusDTO{State: "enqueuing", Running: true, Pages: 33, Discovered: 6440, Free: 6440, Added: 1200, StartedAt: &now}
ts := newTestServer(t, caURL)
page := get(t, ts, "/ips")
for _, want := range []string{`hx-get="/ips/scan/status"`, "ставятся в очередь", `<progress max="6440" value="1200"`, "<dt>прочитано страниц</dt><dd>33</dd>"} {
if !strings.Contains(page, want) {
t.Fatalf("expected %q in the page, got:\n%s", want, page)
}
}
if strings.Index(page, `id="scan-progress"`) > strings.Index(page, `<form id="ips-form"`) {
t.Fatalf("the scan panel must sit above (outside) #ips-form")
}
}
func TestPageURLEscapesQuery(t *testing.T) {
got := pageURL("/ips", url.Values{"q": {"a b&c=d"}, "state": {"queued"}}, 3, 100)
u, err := url.Parse(got)
if err != nil {
t.Fatal(err)
}
q := u.Query()
if u.Path != "/ips" || q.Get("q") != "a b&c=d" || q.Get("state") != "queued" || q.Get("page") != "3" || q.Get("per_page") != "100" || len(q) != 4 {
t.Fatalf("unexpected URL %q (query %v)", got, q)
}
if first := pageURL("/ips", nil, 1, 50); strings.Contains(first, "page=") && !strings.Contains(first, "per_page=") {
t.Fatalf("page 1 must not carry page=, got %q", first)
}
}
func TestIPsPagination(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(120)
ts := newTestServer(t, caURL)
body := get(t, ts, "/ips")
if !strings.Contains(body, "Показано 1–50 из 120") || countRows(body) != 50 {
t.Fatalf("page 1: want «Показано 1–50 из 120» and 50 rows, got %d rows:\n%s", countRows(body), body)
}
if next := pagerLink(t, body, "next"); next == nil || next.Query().Get("page") != "2" {
t.Fatalf("expected a next link to page 2, got %v", next)
}
if pagerLink(t, body, "prev") != nil {
t.Fatalf("page 1 must have no prev link")
}
body = get(t, ts, "/ips?page=2")
if !strings.Contains(body, "Показано 51–100 из 120") || countRows(body) != 50 {
t.Fatalf("page 2: got:\n%s", body)
}
if prev := pagerLink(t, body, "prev"); prev == nil || prev.Query().Get("page") != "" {
t.Fatalf("page 2 must link back to page 1 (no page param), got %v", prev)
}
// Last page, and a page past the end clamps to it; junk is page 1.
for _, p := range []string{"3", "99"} {
body = get(t, ts, "/ips?page="+p)
if !strings.Contains(body, "Показано 101–120 из 120") || countRows(body) != 20 || pagerLink(t, body, "next") != nil {
t.Fatalf("page=%s: want the last page, got:\n%s", p, body)
}
}
for _, p := range []string{"0", "-4", "abc"} {
if body = get(t, ts, "/ips?page="+p); !strings.Contains(body, "Показано 1–50 из 120") {
t.Fatalf("page=%s: want page 1, got:\n%s", p, body)
}
}
// per_page: only 25/50/100/200 are accepted, anything else is the default.
for per, want := range map[string]int{"25": 25, "100": 100, "200": 120, "77": 50, "": 50, "x": 50} {
if body = get(t, ts, "/ips?per_page="+per); countRows(body) != want {
t.Fatalf("per_page=%q: want %d rows, got %d", per, want, countRows(body))
}
}
}
func TestIPsPaginationKeepsFilterInLinks(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(120)
ts := newTestServer(t, caURL)
// 10.0.0.1 matches .1, .10-.19, .100-.120: 32 rows.
body := get(t, ts, "/ips?q=10.0.0.1&state=queued&per_page=25")
if !strings.Contains(body, "Показано 1–25 из 32") {
t.Fatalf("expected the filtered total, got:\n%s", body)
}
next := pagerLink(t, body, "next")
if next == nil {
t.Fatalf("expected a next link")
}
q := next.Query()
if q.Get("q") != "10.0.0.1" || q.Get("state") != "queued" || q.Get("per_page") != "25" || q.Get("page") != "2" {
t.Fatalf("next link lost the filter: %v", next)
}
// The same filter is carried by the hidden inputs of #ips-form and by the
// wrapper's own reload URL.
for _, want := range []string{
`name="q" value="10.0.0.1"`, `name="state" value="queued"`, `name="per_page" value="25"`, `name="page" value="1"`,
`hx-get="/ips?per_page=25&amp;q=10.0.0.1&amp;state=queued"`,
} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the page, got:\n%s", want, body)
}
}
}
func TestIPsFilters(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
mk := func(ip, state, result string, seq int) ipQueueItem {
return ipQueueItem{IPAddress: ip, State: state, OverallResult: result, Sequence: seq, AggregatedAt: &now, CreatedAt: now, UpdatedAt: now}
}
fake.ips = []ipQueueItem{
mk("1.1.1.1", "queued", "", 1), mk("1.1.1.2", "checking", "", 2), mk("1.1.1.3", "awaiting_self_check", "", 3),
mk("2.2.2.1", "done", "pass", 4), mk("2.2.2.2", "failed", "fail", 5), mk("2.2.2.3", "failed", "cancelled", 6),
mk("3.3.3.3", "occupied", "", 7),
}
ts := newTestServer(t, caURL)
cases := []struct {
query string
want []string
}{
{"", []string{"1.1.1.1", "1.1.1.2", "1.1.1.3", "2.2.2.1", "2.2.2.2", "2.2.2.3", "3.3.3.3"}},
{"state=queued", []string{"1.1.1.1"}},
{"state=active", []string{"1.1.1.2", "1.1.1.3"}},
{"state=done", []string{"2.2.2.1"}},
{"state=failed", []string{"2.2.2.2", "2.2.2.3"}},
{"state=occupied", []string{"3.3.3.3"}},
{"state=result:fail", []string{"2.2.2.2"}},
{"result=cancelled", []string{"2.2.2.3"}},
{"state=failed&result=cancelled", []string{"2.2.2.3"}},
{"q=1.1.1&state=active", []string{"1.1.1.2", "1.1.1.3"}},
{"state=bogus", []string{"1.1.1.1", "1.1.1.2", "1.1.1.3", "2.2.2.1", "2.2.2.2", "2.2.2.3", "3.3.3.3"}},
}
for _, c := range cases {
body := get(t, ts, "/ips?"+c.query)
got := map[string]bool{}
for _, ip := range []string{"1.1.1.1", "1.1.1.2", "1.1.1.3", "2.2.2.1", "2.2.2.2", "2.2.2.3", "3.3.3.3"} {
got[ip] = strings.Contains(body, ipRowLink(ip))
}
for ip, in := range got {
if want := containsStr(c.want, ip); in != want {
t.Fatalf("?%s: row %s present=%v, want %v", c.query, ip, in, want)
}
}
}
// The select echoes the active filter; an empty filtered result says so.
if body := get(t, ts, "/ips?state=result:fail"); !strings.Contains(body, `value="result:fail" selected`) {
t.Fatalf("expected the result option to be selected, got:\n%s", body)
}
if body := get(t, ts, "/ips?q=zzz"); !strings.Contains(body, "Ничего не найдено по текущему фильтру") {
t.Fatalf("expected the filtered-empty message, got:\n%s", body)
}
// An htmx filter request gets just the swappable wrapper, not the page.
_, frag := doReq(t, ts, reqOpts{path: "/ips?state=queued", headers: map[string]string{"HX-Request": "true"}})
if strings.Contains(frag, "<html") || !strings.Contains(frag, `id="ips-table-wrap"`) || !strings.Contains(frag, ipRowLink("1.1.1.1")) {
t.Fatalf("expected the table wrapper fragment, got:\n%s", frag)
}
// Filters are applied server-side: control-api got them as parameters.
fake.mu.Lock()
defer fake.mu.Unlock()
var sawState bool
for _, q := range fake.ipsQueries {
if strings.Contains(q, "state=queued") && strings.Contains(q, "limit=50") {
sawState = true
}
}
if !sawState || fake.bareIPsCalls != 0 {
t.Fatalf("expected paginated filtered requests only (bare=%d), got %v", fake.bareIPsCalls, fake.ipsQueries)
}
}
func TestIPsMutationsKeepPageAndFilter(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
addrs := fake.seedIPs(120)
ts := newTestServer(t, caURL)
// Per-row delete on page 2 (the URL carries only the context params).
_, body := doReq(t, ts, reqOpts{method: http.MethodDelete, path: "/ips/" + addrs[60] + "?page=2&per_page=50&state=queued"})
if !strings.Contains(body, "Показано 51–100 из 119") || strings.Contains(body, ipRowLink(addrs[60])) {
t.Fatalf("delete must re-render page 2 of the same filter, got:\n%s", body)
}
for _, want := range []string{`name="page" value="2"`, `name="state" value="queued"`} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the re-rendered form, got:\n%s", want, body)
}
}
// Per-row recheck keeps the page too.
body = postForm(t, ts, "POST", "/ips/"+addrs[70]+"/recheck", url.Values{"page": {"2"}, "per_page": {"50"}})
if !strings.Contains(body, "Показано 51–100 из 119") {
t.Fatalf("recheck must stay on page 2, got:\n%s", body)
}
// Deleting every row of the last page clamps to the last non-empty page.
fake.mu.Lock()
var last []string
for _, ip := range fake.ips[100:] {
last = append(last, ip.IPAddress)
}
fake.mu.Unlock()
body = postForm(t, ts, "POST", "/ips/delete", url.Values{"page": {"3"}, "per_page": {"50"}, "addresses": last})
if !strings.Contains(body, "Показано 51–100 из 100") || !strings.Contains(body, `name="page" value="2"`) {
t.Fatalf("expected a clamp to page 2 after the last page emptied, got:\n%s", body)
}
// Adding addresses through the top form keeps the context hidden inputs' page too.
body = postForm(t, ts, "POST", "/ips", url.Values{"addresses": {"9.9.9.9"}, "page": {"2"}, "per_page": {"50"}})
if !strings.Contains(body, "Показано 51–100 из 101") {
t.Fatalf("expected page 2 of 101 after adding, got:\n%s", body)
}
}
func TestIPsBulkScopeAllResolvesByFilterInChunks(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(1300)
now := time.Now()
fake.mu.Lock()
for _, a := range []string{"2.2.2.1", "2.2.2.2", "2.2.2.3"} {
fake.ips = append(fake.ips, ipQueueItem{IPAddress: a, State: "done", OverallResult: "pass", AggregatedAt: &now, CreatedAt: now, UpdatedAt: now})
}
fake.mu.Unlock()
ts := newTestServer(t, caURL)
// Recheck everything in state=done: three addresses, one chunk.
postForm(t, ts, "POST", "/ips/recheck", url.Values{"scope": {"all"}, "state": {"done"}})
if len(fake.submitChunks) != 1 || fake.submitChunks[0] != 3 {
t.Fatalf("submit chunks = %v, want [3]", fake.submitChunks)
}
// Delete all 1300 queued+rechecked rows matching q=10. (the checked
// boxes of the page are ignored under scope=all): chunks of ≤500.
body := postForm(t, ts, "POST", "/ips/delete", url.Values{
"scope": {"all"}, "q": {"10."}, "state": {"queued"}, "per_page": {"50"}, "addresses": {"2.2.2.1"},
})
if got := fmt.Sprint(fake.deleteChunks); got != "[500 500 300]" {
t.Fatalf("delete chunks = %s, want [500 500 300]", got)
}
fake.mu.Lock()
left := len(fake.ips)
var big bool
for _, q := range fake.ipsQueries {
v, _ := url.ParseQuery(q)
if n, _ := strconv.Atoi(v.Get("limit")); n > 1000 || n == 0 {
big = true
}
}
bare := fake.bareIPsCalls
fake.mu.Unlock()
if left != 3 {
t.Fatalf("expected only the 3 non-matching rows left, got %d", left)
}
if big || bare != 0 {
t.Fatalf("every list call must be paginated with limit ≤ 1000, got %v (bare=%d)", fake.ipsQueries, bare)
}
if !strings.Contains(body, "Ничего не найдено по текущему фильтру") {
t.Fatalf("expected the emptied filter view, got:\n%s", body)
}
// scope=all with nothing matching is a client error, not a silent no-op.
body = postForm(t, ts, "POST", "/ips/delete", url.Values{"scope": {"all"}, "q": {"nothing"}})
if !strings.Contains(body, "alert-warning") {
t.Fatalf("expected a banner for an empty scope=all, got:\n%s", body)
}
}
func TestIPsTableControls(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(120)
now := time.Now()
fake.mu.Lock()
fake.ips[0].State = "checking"
fake.ips[1].State = "done"
fake.ips[1].OverallResult = "pass"
fake.ips[1].AggregatedAt = &now
fake.mu.Unlock()
ts := newTestServer(t, caURL)
body := get(t, ts, "/ips")
const params = `hx-params="page,per_page,q,state,result"`
// Every per-row button and the clear/scan buttons restrict the request
// params (htmx would otherwise put every checked checkbox into the URL).
var rowButtons int
for _, b := range strings.Split(body, "<button")[1:] {
tag := b[:strings.Index(b, ">")]
perRow := strings.Contains(tag, `hx-delete="/ips/`) ||
(strings.Contains(tag, `hx-post="/ips/1`) && (strings.Contains(tag, "/recheck") || strings.Contains(tag, "/cancel")))
if perRow {
rowButtons++
}
if perRow || strings.Contains(tag, `hx-post="/ips/clear"`) || strings.Contains(tag, `hx-post="/ips/scan`) {
if !strings.Contains(tag, params) {
t.Fatalf("button without hx-params: <button%s>", tag)
}
}
}
if rowButtons != 100 { // delete + recheck/cancel on each of the 50 rows
t.Fatalf("expected 100 per-row buttons, found %d", rowButtons)
}
// Bulk delete/recheck submit the whole form (checked boxes + scope), so no whitelist there.
for _, b := range strings.Split(body, "<button")[1:] {
tag := b[:strings.Index(b, ">")]
if (strings.Contains(tag, `hx-post="/ips/delete"`) || strings.Contains(tag, `hx-post="/ips/recheck"`)) && strings.Contains(tag, "hx-params") {
t.Fatalf("bulk buttons must submit the whole form: <button%s>", tag)
}
}
// Bulk selection UI with real counts.
for _, want := range []string{
"Выбрано на странице: <b data-sel-count>0</b> из 50",
"Выбрать все 120 по фильтру",
"Удалить ВСЕ 120 адресов, включая идущие проверки? Действие необратимо.",
"Удалить ВСЕ 120 адресов из очереди, включая идущие проверки? Действие необратимо.",
`<input type="hidden" name="scope" value="">`,
} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the page, got:\n%s", want, body)
}
}
// Under a filter the clear confirmation shows the whole queue, the
// delete-all one the filtered count.
body = get(t, ts, "/ips?q=10.0.0.1")
for _, want := range []string{"Удалить ВСЕ 32 адреса по текущему фильтру, включая", "Удалить ВСЕ 120 адресов из очереди"} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q under a filter, got:\n%s", want, body)
}
}
// Everything on one page: no "select all by filter" offer.
body = get(t, ts, "/ips?q=10.0.0.119")
if strings.Contains(body, `class="select-all-link"`) {
t.Fatalf("no select-all link when the filter fits on the page, got:\n%s", body)
}
}
func TestOverviewBoundedWithThousandsQueued(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(5000)
now := time.Now()
fake.mu.Lock()
for i := 0; i < 3; i++ {
fake.ips[i].State = "checking"
}
for i := 0; i < 30; i++ {
at := now.Add(-time.Duration(i) * time.Minute)
fake.ips = append(fake.ips, ipQueueItem{IPAddress: fmt.Sprintf("2.2.2.%d", i), State: "done", OverallResult: "pass", AggregatedAt: &at, CreatedAt: now, UpdatedAt: now})
}
fake.mu.Unlock()
ts := newTestServer(t, caURL)
for _, path := range []string{"/overview", "/overview/fragment"} {
body := get(t, ts, path)
// 3 active + the next 10 queued + the last 20 completed.
if n := strings.Count(body, `href="/ips/`); n != 33 {
t.Fatalf("%s: expected 33 address rows (3+10+20), got %d", path, n)
}
for _, want := range []string{"В очереди: <b>4997</b>", `href="/ips?state=queued"`, "Последние 20 завершённых", "Ближайшие в очереди"} {
if !strings.Contains(body, want) {
t.Fatalf("%s: expected %q, got:\n%s", path, want, body)
}
}
if !strings.Contains(body, ipRowLink("2.2.2.0")) || strings.Contains(body, ipRowLink("2.2.2.25")) {
t.Fatalf("%s: expected only the 20 newest completed rows", path)
}
}
fake.mu.Lock()
defer fake.mu.Unlock()
if fake.bareIPsCalls != 0 {
t.Fatalf("the overview must never load the whole queue, bare calls = %d", fake.bareIPsCalls)
}
if len(fake.ipsQueries) == 0 {
t.Fatalf("expected paginated list requests")
}
for _, q := range fake.ipsQueries {
v, _ := url.ParseQuery(q)
if n, _ := strconv.Atoi(v.Get("limit")); n < 1 || n > 100 {
t.Fatalf("overview list request without a small limit: %q", q)
}
}
}
func TestOverviewProgressIndicatorAndETA(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(100)
now := time.Now()
fake.mu.Lock()
// 6 completed rows, one every 10 s (span 50 s): 10 s per address.
for i := 0; i < 6; i++ {
at := now.Add(-time.Duration(i) * 10 * time.Second)
fake.ips = append(fake.ips, ipQueueItem{IPAddress: fmt.Sprintf("2.2.2.%d", i), State: "done", OverallResult: "pass", AggregatedAt: &at, CreatedAt: now, UpdatedAt: now})
}
// "occupied" counts as finished work too.
for i := 0; i < 2; i++ {
fake.ips = append(fake.ips, ipQueueItem{IPAddress: fmt.Sprintf("3.3.3.%d", i), State: "occupied", CreatedAt: now, UpdatedAt: now})
}
fake.mu.Unlock()
ts := newTestServer(t, caURL)
body := get(t, ts, "/overview")
for _, want := range []string{
"Готово 8 из 108 (7%) · в работе 0 · в очереди 100",
`<progress max="108" value="8"`,
"осталось ≈ 16 мин 40 с", // 100 queued × 10 s
"Итоги проверок: pass 6",
} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q in the stats block, got:\n%s", want, body)
}
}
// The ETA is not derived from a filtered window.
if body = get(t, ts, "/overview?q=2.2.2"); strings.Contains(body, "осталось") {
t.Fatalf("no ETA under a filter, got:\n%s", body)
}
// Too few samples: no ETA.
fake.mu.Lock()
fake.ips = append(fake.ips[:100], fake.ips[100:103]...)
fake.mu.Unlock()
if body = get(t, ts, "/overview"); strings.Contains(body, "осталось") || !strings.Contains(body, "Готово 3 из 103") {
t.Fatalf("expected progress without ETA for <5 samples, got:\n%s", body)
}
}
func TestOverviewScanLineAndScanningPhase(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.seedIPs(2)
now := time.Now()
fake.autoCycle = autoCycleDTO{Enabled: true, IntervalSeconds: 3600, Phase: "scanning", NextRunAt: &now}
ts := newTestServer(t, caURL)
// No running scan: no scan line.
if body := get(t, ts, "/overview"); strings.Contains(body, "Сканирование:") {
t.Fatalf("no scan line while idle, got:\n%s", body)
}
fake.mu.Lock()
fake.scan = scanStatusDTO{State: "enqueuing", Running: true, Pages: 33, Discovered: 6440, Free: 6439, Added: 500, StartedAt: &now}
fake.mu.Unlock()
body := get(t, ts, "/overview")
for _, want := range []string{"Сканирование: ставятся в очередь", "прочитано страниц 33", "найдено адресов 6440", "свободных 6439", "сканирование Floating IP", "Автоцикл активен"} {
if !strings.Contains(body, want) {
t.Fatalf("expected %q, got:\n%s", want, body)
}
}
// The polled fragment refreshes the line via the OOB stats block.
frag := get(t, ts, "/overview/fragment")
oob := strings.Index(frag, `id="overview-stats" hx-swap-oob="true"`)
if oob < 0 || !strings.Contains(frag[oob:], "Сканирование: ставятся в очередь") {
t.Fatalf("expected the scan line inside the OOB stats block, got:\n%s", frag)
}
}
func TestRegistryPaginationAndServerSideFilter(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
results := []string{"pass", "fail", "partial"}
for i := 0; i < 120; i++ {
ip := fmt.Sprintf("10.0.0.%d", i+1)
fake.registry[ip] = registryItem{IPAddress: ip, FirstSeenAt: now, LastSeenAt: now, TotalCycles: 1, LastResult: results[i%3]}
}
ts := newTestServer(t, caURL)
body := get(t, ts, "/registry?page=2")
if !strings.Contains(body, "Показано 51–100 из 120") || strings.Count(body, `href="/registry/10.`) != 50 {
t.Fatalf("expected page 2 with 50 rows, got:\n%s", body)
}
if body = get(t, ts, "/registry?page=99"); !strings.Contains(body, "Показано 101–120 из 120") {
t.Fatalf("expected a clamp to the last page, got:\n%s", body)
}
// 40 of the 120 are "fail"; q and status survive in the pager links and
// reach control-api as parameters (no client-side filtering).
body = get(t, ts, "/registry?status=fail&q=10.0.0&per_page=25")
if !strings.Contains(body, "Показано 1–25 из 40") {
t.Fatalf("expected the server-side filtered total, got:\n%s", body)
}
next := pagerLink(t, body, "next")
if next == nil || next.Path != "/registry" || next.Query().Get("status") != "fail" || next.Query().Get("q") != "10.0.0" ||
next.Query().Get("per_page") != "25" || next.Query().Get("page") != "2" {
t.Fatalf("pager link lost the filter: %v", next)
}
fake.mu.Lock()
defer fake.mu.Unlock()
last := fake.registryQueries[len(fake.registryQueries)-1]
for _, want := range []string{"last_result=fail", "q=10.0.0", "limit=25"} {
if !strings.Contains(last, want) {
t.Fatalf("control-api request %q lacks %s", last, want)
}
}
}
func TestLongTimeoutForClearAndBulkCalls(t *testing.T) {
// A short per-call timeout (50 ms) breaks plain reads of a slow control-api
// but not clear/bulk operations, which use the long client.
slow := newSlowAPI(t, 200*time.Millisecond)
c := newClient(slow, 50*time.Millisecond)
if _, err := c.Status(t.Context()); err == nil {
t.Fatalf("expected the short timeout to fail a plain read")
}
if _, err := c.ClearQueue(t.Context()); err != nil {
t.Fatalf("ClearQueue must use the long timeout: %v", err)
}
if _, err := c.DeleteIPs(t.Context(), []string{"1.1.1.1"}); err != nil {
t.Fatalf("DeleteIPs must use the long timeout: %v", err)
}
if _, err := c.SubmitIPs(t.Context(), []string{"1.1.1.1"}); err != nil {
t.Fatalf("SubmitIPs must use the long timeout: %v", err)
}
}
func TestScanRoutesPassOriginCheckWhenAuthEnabled(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.scanRunPolls = 1
_, ts := newAuthTestServer(t, caURL, nil)
cookie := login(t, ts)
resp, body := doReq(t, ts, reqOpts{method: http.MethodPost, path: "/ips/scan", cookie: cookie})
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("scan without Origin: status=%d, want 403", resp.StatusCode)
}
resp, body = doReq(t, ts, reqOpts{method: http.MethodPost, path: "/ips/scan", cookie: cookie, headers: map[string]string{"Origin": ts.URL}})
if resp.StatusCode != http.StatusOK || !strings.Contains(body, `id="scan-progress"`) {
t.Fatalf("scan with Origin: status=%d body:\n%s", resp.StatusCode, body)
}
resp, body = doReq(t, ts, reqOpts{path: "/ips/scan/status", cookie: cookie})
if resp.StatusCode != http.StatusOK || resp.Header.Get("HX-Trigger") != "scan-finished" {
t.Fatalf("status poll: status=%d trigger=%q body:\n%s", resp.StatusCode, resp.Header.Get("HX-Trigger"), body)
}
}
+50
View File
@@ -559,3 +559,53 @@ textarea.autosize { overflow-y: hidden; resize: none; }
}
.sidebar-user-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sidebar-user + .sidebar-foot { margin-top: 0; }
/* ---------- scan progress, progress bars, pager, bulk selection ---------- */
progress {
appearance: none; -webkit-appearance: none;
display: block; width: 100%; height: 8px;
border: 0; border-radius: var(--radius-sm);
background: var(--surface-alt); color: var(--accent);
overflow: hidden;
}
progress::-webkit-progress-bar { background: var(--surface-alt); border-radius: var(--radius-sm); }
progress::-webkit-progress-value { background: var(--accent); border-radius: var(--radius-sm); }
progress::-moz-progress-bar { background: var(--accent); border-radius: var(--radius-sm); }
/* Indeterminate (no value attribute): a sliding stripe, Firefox/Chromium. */
progress:indeterminate { background: linear-gradient(90deg, var(--surface-alt) 0, var(--accent-soft) 40%, var(--surface-alt) 80%); background-size: 200% 100%; animation: progress-slide 1.4s linear infinite; }
progress:indeterminate::-webkit-progress-value { background: transparent; }
progress:indeterminate::-moz-progress-bar { background: transparent; }
@keyframes progress-slide { from { background-position: 200% 0; } to { background-position: -200% 0; } }
@media (prefers-reduced-motion: reduce) { progress:indeterminate { animation: none; } }
.overall-progress { margin-top: 12px; font-size: 12.5px; color: var(--text-muted); }
.overall-progress p { margin-bottom: 6px; }
.scan-progress { margin-top: 16px; }
.scan-actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 10px; }
.scan-progress progress { margin-bottom: 10px; }
.scan-counters { display: flex; flex-wrap: wrap; gap: 6px 22px; font-size: 12.5px; color: var(--text-muted); }
.scan-counters dt { display: inline; }
.scan-counters dd { display: inline; margin: 0 0 0 4px; color: var(--text); font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.scan-error { margin-top: 8px; padding: 8px 10px; border: 1px solid var(--danger-border); border-radius: var(--radius-xs); background: var(--danger-soft); color: var(--danger); font-size: 12.5px; }
.btn[disabled] { opacity: .5; cursor: not-allowed; }
.pager { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 12px; font-size: 12.5px; color: var(--text-muted); }
.pager-nav { display: inline-flex; align-items: center; gap: 8px; }
.pager-page { font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
.btn.is-disabled { opacity: .4; pointer-events: none; }
.panel > .pager { margin: 0; padding: 10px 16px; border-top: 1px solid var(--border-soft); }
.bulk-bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.bulk-hint { padding: 8px 16px; font-size: 12.5px; color: var(--text-muted); border-top: 1px solid var(--border-soft); border-bottom: 1px solid var(--border-soft); background: var(--surface-alt); }
.bulk-hint b { color: var(--text); font-family: var(--font-mono); font-weight: 500; }
.select-all-link, .scope-all-msg, .btn-del-all { display: none; }
#ips-form.sel-all .select-all-link { display: inline; margin-left: 10px; }
#ips-form.scope-all .select-all-link { display: none; }
#ips-form.scope-all .scope-all-msg { display: inline; margin-left: 10px; color: var(--warning); }
#ips-form.scope-all .btn-del-all { display: inline-flex; }
#ips-form.scope-all .btn-del-sel { display: none; }
.queue-line { margin: 14px 0 8px; font-size: 13px; color: var(--text-muted); }
.queue-line b { color: var(--text); font-family: var(--font-mono); font-weight: 500; }
table.compact td, table.compact th { padding-top: 6px; padding-bottom: 6px; }
+126 -15
View File
@@ -24,7 +24,7 @@
<div class="panel">
<div class="panel-body">
<form hx-post="/ips" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last" hx-on::after-request="this.reset()">
<form hx-post="/ips" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-include=".ips-ctx" hx-sync="#ips-table-wrap:queue last" hx-on::after-request="this.reset()">
<div class="field-row">
<div class="field" style="flex: 1 1 420px;">
<label for="addresses">Адреса (по одному на строку или через запятую)</label>
@@ -36,28 +36,127 @@
<p class="muted" style="margin-top:8px">Новый адрес встаёт в очередь; уже завершённый (done/failed) запускается заново
(тот же вызов); тот, что сейчас проверяется, не трогается. Кнопка «Сканировать Floating IP» ниже делает то же самое
автоматически: находит в проекте OpenStack все свободные (не привязанные к порту) Floating IP и сразу передаёт их
в очередь на проверку. Полная история проверок по каждому адресу — включая уже удалённые из очереди — доступна в
<a href="/registry">реестре</a>.</p>
в очередь на проверку — сканирование идёт в фоне, прогресс виден в панели под кнопкой. Полная история проверок по
каждому адресу — включая уже удалённые из очереди — доступна в <a href="/registry">реестре</a>.</p>
</div>
</div>
<div id="ips-table-wrap">
{{template "scan_progress" .Scan}}
<form id="ips-filter" class="panel" onsubmit="return false" style="margin-top:16px">
<div class="panel-body field-row">
<div class="field" style="flex:1 1 260px">
<label for="ips-q">Поиск по IP</label>
<input type="search" id="ips-q" name="q" value="{{.Filter.Q}}" placeholder="203.0.113.10"
hx-get="/ips" hx-select="#ips-table-wrap" hx-target="#ips-table-wrap" hx-swap="outerHTML"
hx-include="#ips-filter" hx-trigger="input changed delay:300ms"
hx-replace-url="true" hx-sync="#ips-table-wrap:queue last">
</div>
<div class="field">
<label for="ips-state">Состояние</label>
<select id="ips-state" name="state"
hx-get="/ips" hx-select="#ips-table-wrap" hx-target="#ips-table-wrap" hx-swap="outerHTML"
hx-include="#ips-filter" hx-trigger="change"
hx-replace-url="true" hx-sync="#ips-table-wrap:queue last">
{{$tok := .Filter.Token}}
<option value="">Все</option>
<option value="queued" {{if eq $tok "queued"}}selected{{end}}>в очереди (queued)</option>
<option value="active" {{if eq $tok "active"}}selected{{end}}>в работе (assigning_fip, awaiting_self_check, checking, aggregating)</option>
<option value="done" {{if eq $tok "done"}}selected{{end}}>done</option>
<option value="failed" {{if eq $tok "failed"}}selected{{end}}>failed</option>
<option value="occupied" {{if eq $tok "occupied"}}selected{{end}}>occupied</option>
<option value="result:pass" {{if eq $tok "result:pass"}}selected{{end}}>результат: pass</option>
<option value="result:partial" {{if eq $tok "result:partial"}}selected{{end}}>результат: partial</option>
<option value="result:fail" {{if eq $tok "result:fail"}}selected{{end}}>результат: fail</option>
<option value="result:cancelled" {{if eq $tok "result:cancelled"}}selected{{end}}>результат: cancelled</option>
</select>
</div>
<div class="field" style="flex:0 0 120px">
<label for="ips-per-page">На странице</label>
<select id="ips-per-page" name="per_page"
hx-get="/ips" hx-select="#ips-table-wrap" hx-target="#ips-table-wrap" hx-swap="outerHTML"
hx-include="#ips-filter" hx-trigger="change"
hx-replace-url="true" hx-sync="#ips-table-wrap:queue last">
{{$pp := .PerPage}}
{{range .PerPageOptions}}<option value="{{.}}" {{if eq . $pp}}selected{{end}}>{{.}}</option>
{{end}}
</select>
</div>
</div>
</form>
{{template "ips_table_wrap" .}}
{{end}}
{{/* #ips-table-wrap is the swap target of every table mutation, the filter form
and the pager (all hx-swap="outerHTML", so the wrapper's own hx-get always
points at the page/filter it currently shows). It listens for the
scan-finished event (HX-Trigger from the scan progress panel) and reloads
itself. hx-disinherit="*": its attributes must not leak into the buttons
inside. */}}
{{define "ips_table_wrap"}}
<div id="ips-table-wrap" hx-get="{{.SelfURL}}" hx-trigger="scan-finished from:body" hx-select="#ips-table-wrap" hx-target="this" hx-swap="outerHTML" hx-disinherit="*">
{{template "ips_table" .}}
</div>
{{end}}
{{/* Scan progress panel. Lives outside #ips-form (no checkbox payload, survives
table swaps). While the job runs it polls itself; the response that finds
it finished has no hx-trigger and carries HX-Trigger: scan-finished. */}}
{{define "scan_progress"}}
{{$s := .Status}}
<div id="scan-progress" class="panel scan-progress"{{if .Poll}} hx-get="/ips/scan/status" hx-trigger="every 2s" hx-swap="outerHTML"{{end}}>
<div class="panel-body">
<div class="scan-actions">
<button type="button" class="btn btn-ghost btn-sm" hx-post="/ips/scan" hx-target="#scan-progress" hx-swap="outerHTML" hx-params="page,per_page,q,state,result"{{if $s.Running}} disabled{{end}}>Сканировать Floating IP</button>
<button type="button" class="btn btn-ghost btn-sm" hx-post="/ips/scan?dry_run=true" hx-target="#scan-progress" hx-swap="outerHTML" hx-params="page,per_page,q,state,result"{{if $s.Running}} disabled{{end}} title="Только найти и посчитать свободные адреса, очередь не меняется">Пробное сканирование</button>
{{if and $s.State (ne $s.State "idle")}}<span class="pill {{$s.PillClass}}">{{$s.StateLabel}}</span>{{if $s.DryRun}} <span class="muted">пробный запуск: очередь не меняется</span>{{end}}{{else}}<span class="muted">Найти все свободные Floating IP проекта и поставить их в очередь.</span>{{end}}
</div>
{{if and $s.State (ne $s.State "idle")}}
{{if or $s.Running (eq $s.State "done")}}
{{if $s.Indeterminate}}<progress aria-label="Сканирование"></progress>
{{else if eq $s.State "done"}}<progress max="1" value="1" aria-label="Сканирование"></progress>
{{else}}<progress max="{{$s.Free}}" value="{{$s.Handled}}" aria-label="Сканирование"></progress>{{end}}
{{end}}
<dl class="scan-counters">
<div><dt>прочитано страниц</dt><dd>{{$s.Pages}}</dd></div>
<div><dt>найдено адресов</dt><dd>{{$s.Discovered}}</dd></div>
<div><dt>свободных</dt><dd>{{$s.Free}}</dd></div>
<div><dt>добавлено</dt><dd>{{$s.Added}}</dd></div>
<div><dt>повторно</dt><dd>{{$s.Requeued}}</dd></div>
<div><dt>переупорядочено</dt><dd>{{$s.Reordered}}</dd></div>
{{if $s.SkippedInProgress}}<div><dt>уже в работе</dt><dd>{{$s.SkippedInProgress}}</dd></div>{{end}}
{{with $s.Elapsed}}<div><dt>время</dt><dd>{{.}}</dd></div>{{end}}
</dl>
{{if $s.Error}}<p class="scan-error">{{$s.Error}}</p>{{end}}
{{end}}
</div>
</div>
{{end}}
{{define "ips_table"}}
<form id="ips-form">
<form id="ips-form" onchange="var f=this,k=f.querySelectorAll('input[name=addresses]:checked').length,n=f.querySelectorAll('input[name=addresses]').length;f.querySelector('[data-sel-count]').textContent=k;f.classList.toggle('sel-all',n>0&&k===n);if(k!==n){f.elements.scope.value='';f.classList.remove('scope-all')}">
<input type="hidden" class="ips-ctx" name="page" value="{{.Page}}">
<input type="hidden" class="ips-ctx" name="per_page" value="{{.PerPage}}">
<input type="hidden" class="ips-ctx" name="q" value="{{.Filter.Q}}">
<input type="hidden" class="ips-ctx" name="state" value="{{.Filter.State}}">
<input type="hidden" class="ips-ctx" name="result" value="{{.Filter.Result}}">
<input type="hidden" name="scope" value="">
<div class="panel">
<div class="panel-body" style="display:flex; gap:8px; align-items:center;">
<button type="button" class="btn btn-ghost btn-sm" hx-post="/ips/scan" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last">Сканировать Floating IP</button>
<button type="button" class="btn btn-ghost btn-sm" hx-post="/ips/recheck" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last">Перепроверить выбранные</button>
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/ips/delete" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить выбранные адреса без возможности восстановления?">Удалить выбранные</button>
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/ips/clear" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить ВСЕ адреса из очереди, включая те, что сейчас проверяются? Действие необратимо.">Очистить всё</button>
<div class="panel-body bulk-bar">
<button type="button" class="btn btn-ghost btn-sm" hx-post="/ips/recheck" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-sync="#ips-table-wrap:queue last">Перепроверить выбранные</button>
<button type="button" class="btn btn-danger-ghost btn-sm btn-del-sel" hx-post="/ips/delete" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить выбранные адреса без возможности восстановления?">Удалить выбранные</button>
<button type="button" class="btn btn-danger-ghost btn-sm btn-del-all" hx-post="/ips/delete" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить ВСЕ {{.Total}} {{pluralAddr .Total}}{{if .Filter.Active}} по текущему фильтру{{end}}, включая идущие проверки? Действие необратимо.">Удалить все {{.Total}} по фильтру</button>
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/ips/clear" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-params="page,per_page,q,state,result" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить ВСЕ {{.QueueTotal}} {{pluralAddr .QueueTotal}} из очереди, включая идущие проверки? Действие необратимо.">Очистить всё</button>
</div>
<div class="bulk-hint">
Выбрано на странице: <b data-sel-count>0</b> из {{len .Items}}
{{if gt .Total (len .Items)}}<a href="#" class="select-all-link" onclick="var f=this.closest('form');f.elements.scope.value='all';f.classList.add('scope-all');return false">Выбрать все {{.Total}} по фильтру</a>
<span class="scope-all-msg">Выбраны все {{.Total}} {{pluralAddr .Total}} по фильтру (не только на этой странице).</span>{{end}}
</div>
<div class="table-scroll">
<table>
<thead><tr><th><input type="checkbox" onclick="this.closest('table').querySelectorAll('input[name=addresses]').forEach(cb => cb.checked = this.checked)"></th><th>Адрес</th><th>Состояние</th><th>Валидатор</th><th>Попытка</th><th>Обновлено</th><th></th></tr></thead>
<thead><tr><th><input type="checkbox" aria-label="Выбрать все на странице" onclick="this.closest('table').querySelectorAll('input[name=addresses]').forEach(cb => cb.checked = this.checked)"></th><th>Адрес</th><th>Состояние</th><th>Валидатор</th><th>Попытка</th><th>Обновлено</th><th></th></tr></thead>
<tbody>
{{range .Items}}
{{$b := ipBadge .State .OverallResult .FIPAssociatedAt $.FIPSettleSeconds}}
@@ -72,11 +171,11 @@
<td data-label="">
<div class="actions">
{{if $terminal}}
<button class="btn btn-ghost btn-sm" hx-post="/ips/{{.IPAddress}}/recheck" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last">Перепроверить</button>
<button class="btn btn-ghost btn-sm" hx-post="/ips/{{.IPAddress}}/recheck" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-params="page,per_page,q,state,result" hx-sync="#ips-table-wrap:queue last">Перепроверить</button>
{{else}}
<button class="btn btn-danger-ghost btn-sm" hx-post="/ips/{{.IPAddress}}/cancel" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last" hx-confirm="Остановить проверку {{.IPAddress}}?">Отменить</button>
<button class="btn btn-danger-ghost btn-sm" hx-post="/ips/{{.IPAddress}}/cancel" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-params="page,per_page,q,state,result" hx-sync="#ips-table-wrap:queue last" hx-confirm="Остановить проверку {{.IPAddress}}?">Отменить</button>
{{end}}
<button class="btn btn-danger-ghost btn-sm" hx-delete="/ips/{{.IPAddress}}" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить {{.IPAddress}} без возможности восстановления?">Удалить</button>
<button class="btn btn-danger-ghost btn-sm" hx-delete="/ips/{{.IPAddress}}" hx-target="#ips-table-wrap" hx-swap="outerHTML" hx-params="page,per_page,q,state,result" hx-sync="#ips-table-wrap:queue last" hx-confirm="Удалить {{.IPAddress}} без возможности восстановления?">Удалить</button>
</div>
</td>
</tr>
@@ -85,6 +184,18 @@
</table>
</div>
</div>
{{template "pager" .Pager}}
</form>
{{if not .Items}}<p class="muted">Очередь пуста.</p>{{end}}
{{if not .Items}}<p class="muted">{{if .Filter.Active}}Ничего не найдено по текущему фильтру.{{else}}Очередь пуста.{{end}}</p>{{end}}
{{end}}
{{define "pager"}}{{if .Total}}
<div class="pager">
<span class="pager-info">Показано {{.From}}–{{.To}} из {{.Total}}</span>
<span class="pager-nav">
{{if .PrevURL}}<a class="btn btn-ghost btn-sm" href="{{.PrevURL}}" hx-get="{{.PrevURL}}" hx-select="#{{.Wrap}}" hx-target="#{{.Wrap}}" hx-swap="outerHTML" hx-push-url="true" rel="prev" aria-label="Предыдущая страница">‹</a>{{else}}<span class="btn btn-ghost btn-sm is-disabled" aria-disabled="true">‹</span>{{end}}
<span class="pager-page">{{.Page}} / {{.Pages}}</span>
{{if .NextURL}}<a class="btn btn-ghost btn-sm" href="{{.NextURL}}" hx-get="{{.NextURL}}" hx-select="#{{.Wrap}}" hx-target="#{{.Wrap}}" hx-swap="outerHTML" hx-push-url="true" rel="next" aria-label="Следующая страница">›</a>{{else}}<span class="btn btn-ghost btn-sm is-disabled" aria-disabled="true">›</span>{{end}}
</span>
</div>
{{end}}{{end}}
+2 -2
View File
@@ -50,8 +50,8 @@
</select>
</div>
</div>
<p class="muted" style="padding:0 16px 12px">Действует на обе таблицы ниже. Фильтр по статусу — это фильтр по
итоговому результату, поэтому при выборе конкретного статуса строки «Текущей проверки» (у неё ещё нет результата)
<p class="muted" style="padding:0 16px 12px">Действует на все списки ниже. Фильтр по статусу — это фильтр по
итоговому результату, поэтому при выборе конкретного статуса строки «В работе» и «В очереди» (у них ещё нет результата)
не показываются.</p>
</form>
@@ -6,6 +6,18 @@
<div class="stat-card{{if eq $state "failed"}} bad{{else if eq $state "checking"}} accented{{end}}"><span class="value">{{$count}}</span><span class="label">{{$state}}</span></div>
{{end}}
</div>
{{if .Progress.Total}}
<div class="overall-progress" id="overview-progress">
<p>Готово {{.Progress.Done}} из {{.Progress.Total}} ({{.Progress.Percent}}%) · в работе {{.Progress.Active}} · в очереди {{.Progress.Queued}}{{if .Progress.ETA}} · осталось ≈ {{.Progress.ETA}}{{end}}</p>
<progress max="{{.Progress.Total}}" value="{{.Progress.Done}}" aria-label="Готово"></progress>
</div>
{{end}}
{{with .Status.ResultsByOverall}}{{if or (index . "pass") (index . "partial") (index . "fail") (index . "cancelled")}}
<p class="muted" id="overview-results" style="margin-top:8px">Итоги проверок: pass {{index . "pass"}} · partial {{index . "partial"}} · fail {{index . "fail"}} · cancelled {{index . "cancelled"}}</p>
{{end}}{{end}}
{{with .Scan}}
<p class="muted" id="overview-scan" style="margin-top:8px">Сканирование: {{.StateLabel}}{{if .DryRun}} (пробное){{end}} · прочитано страниц {{.Pages}}, найдено адресов {{.Discovered}}, свободных {{.Free}}{{if .Handled}}, обработано {{.Handled}}{{end}} · <a href="/ips">подробнее</a></p>
{{end}}
{{with .AutoCycle}}{{if .Enabled}}
<p class="muted" id="overview-auto-cycle" style="margin-top:12px"><span class="pill pill-info">Автоцикл активен</span> · {{.PhaseLabel}} · следующий запуск: {{fmtTime .NextRunAt}}</p>
{{end}}{{end}}
@@ -20,14 +32,14 @@
{{define "overview_stats_oob"}}<div id="overview-stats" hx-swap-oob="true">{{template "overview_stats" .}}</div>{{end}}
{{define "overview_tables"}}
<h2 class="section-title">Текущая проверка</h2>
{{if .CurrentItems}}
<h2 class="section-title">В работе</h2>
{{if .ActiveItems}}
<div class="panel">
<div class="table-scroll">
<table>
<thead><tr><th>Адрес</th><th>Состояние</th><th>Валидатор</th><th>Попытка</th><th>Назначено</th></tr></thead>
<tbody>
{{range .CurrentItems}}
{{range .ActiveItems}}
{{$b := ipBadge .State .OverallResult .FIPAssociatedAt 0}}
<tr>
<td class="addr" data-label="Адрес"><a href="/ips/{{.IPAddress}}">{{.IPAddress}}</a></td>
@@ -41,11 +53,35 @@
</table>
</div>
</div>
{{if gt .ActiveTotal (len .ActiveItems)}}<p class="muted">Показано {{len .ActiveItems}} из {{.ActiveTotal}} · <a href="/ips?state=active{{if .Query}}&amp;q={{.Query}}{{end}}">все в работе</a></p>{{end}}
{{else}}
{{if or .Query .StatusFilter}}<p class="muted">Ничего не найдено по текущему фильтру.</p>
{{else}}<p class="muted">Сейчас нет адресов в обработке.</p>{{end}}
{{end}}
{{if not .StatusFilter}}
<p class="queue-line">В очереди: <b>{{.QueuedTotal}}</b> · <a href="/ips?state=queued{{if .Query}}&amp;q={{.Query}}{{end}}">открыть весь список</a></p>
{{if .QueuedItems}}
<div class="panel">
<div class="table-scroll">
<table class="compact">
<thead><tr><th>Ближайшие в очереди</th><th>Состояние</th></tr></thead>
<tbody>
{{range .QueuedItems}}
{{$b := ipBadge .State .OverallResult .FIPAssociatedAt 0}}
<tr>
<td class="addr" data-label="Адрес"><a href="/ips/{{.IPAddress}}">{{.IPAddress}}</a></td>
<td data-label="Состояние"><span class="pill {{$b.Class}}">{{$b.Label}}</span></td>
</tr>
{{end}}
</tbody>
</table>
</div>
</div>
{{if gt .QueuedTotal (len .QueuedItems)}}<p class="muted">Показаны ближайшие {{len .QueuedItems}} из {{.QueuedTotal}}.</p>{{end}}
{{end}}
{{end}}
<h2 class="section-title">Последние {{.LastN}} завершённых</h2>
<div class="breakdown">
<span>pass <b>{{index .Breakdown "pass"}}</b></span>
@@ -47,6 +47,17 @@
<option value="cancelled" {{if eq .StatusFilter "cancelled"}}selected{{end}}>cancelled</option>
</select>
</div>
<div class="field" style="flex:0 0 120px">
<label for="registry-per-page">На странице</label>
<select id="registry-per-page" name="per_page"
hx-get="/registry" hx-select="#registry-table-wrap" hx-target="#registry-table-wrap" hx-swap="outerHTML"
hx-include="#registry-filter" hx-trigger="change"
hx-replace-url="true" hx-sync="#registry-table-wrap:queue last">
{{$pp := .PerPage}}
{{range .PerPageOptions}}<option value="{{.}}" {{if eq . $pp}}selected{{end}}>{{.}}</option>
{{end}}
</select>
</div>
</div>
</form>
@@ -83,6 +94,7 @@
</tbody>
</table>
</div>
{{template "pager" .Pager}}
</div>
{{else if or .Query .StatusFilter}}<p class="muted">Ничего не найдено по текущему фильтру.</p>
{{else}}<p class="muted">Реестр пуст — ни один адрес ещё не ставился на проверку.</p>{{end}}