Add optional automatic check cycle (clear queue -> scan FIPs -> wait -> repeat)
An admin-controlled scenario that repeats what the operator does by hand: clear the IP queue, scan and enqueue all free Floating IPs, wait until every queued address reaches a terminal state (so results are in the Registry), then wait a configurable interval and start over. - control-api: new auto_cycle singleton table (migration 0008) holding enabled/interval/max-run settings and persisted phase state, so the cycle survives restarts; engine in orchestrator/autocycle.go driven from the existing loop tick with an injectable "now" for deterministic tests. - Interval (default 1h, min 60s) and max wait (default unlimited, timeout outcome) are runtime settings, never hardcoded. - The periodic fip_scan_interval_seconds scan is skipped while the cycle is enabled. An emptied queue mid-cycle counts as finished; stopping during the pause keeps the last cycle's outcome. - API: GET/PUT /api/v1/admin/auto-cycle, POST .../start, POST .../stop. - admin-dashboard: "Автоматический цикл" panel on /settings and an "Автоцикл активен" indicator on /overview. - Tests for db, orchestrator, httpapi and dashboard; run-local-e2e.sh now exercises a full auto cycle; docs updated; bin/ rebuilt with refreshed SHA256SUMS. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
008ae1b0db
commit
cd37b10f3b
35 files changed
+2205
-16
No files matched your search
@@ -252,3 +252,28 @@ func (c *client) PutInboundChecks(ctx context.Context, ports []int, icmp bool) (
|
||||
inboundChecksDTO{Ports: ports, ICMP: icmp}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) GetAutoCycle(ctx context.Context) (autoCycleDTO, error) {
|
||||
var out autoCycleDTO
|
||||
err := c.do(ctx, http.MethodGet, "/api/v1/admin/auto-cycle", nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) PutAutoCycle(ctx context.Context, intervalSeconds, maxRunSeconds int) (autoCycleDTO, error) {
|
||||
var out autoCycleDTO
|
||||
err := c.do(ctx, http.MethodPut, "/api/v1/admin/auto-cycle",
|
||||
map[string]int{"interval_seconds": intervalSeconds, "max_run_seconds": maxRunSeconds}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) StartAutoCycle(ctx context.Context) (autoCycleDTO, error) {
|
||||
var out autoCycleDTO
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/admin/auto-cycle/start", nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) StopAutoCycle(ctx context.Context) (autoCycleDTO, error) {
|
||||
var out autoCycleDTO
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/admin/auto-cycle/stop", nil, &out)
|
||||
return out, err
|
||||
}
|
||||
@@ -41,6 +41,11 @@ type fakeControlAPI struct {
|
||||
scanFreeAddresses []string
|
||||
registry map[string]registryItem
|
||||
registryChecks map[string][]check
|
||||
|
||||
// autoCycle is the state served by /api/v1/admin/auto-cycle*;
|
||||
// autoCycleDown makes all four endpoints answer 500 (unavailable API).
|
||||
autoCycle autoCycleDTO
|
||||
autoCycleDown bool
|
||||
}
|
||||
|
||||
func newFakeControlAPI(t *testing.T) (*fakeControlAPI, string) {
|
||||
@@ -53,6 +58,7 @@ func newFakeControlAPI(t *testing.T) (*fakeControlAPI, string) {
|
||||
checkTypes: map[string]checkTypeDTO{},
|
||||
registry: map[string]registryItem{},
|
||||
registryChecks: map[string][]check{},
|
||||
autoCycle: autoCycleDTO{IntervalSeconds: 3600, Phase: "idle"},
|
||||
}
|
||||
ts := httptest.NewServer(f.handler())
|
||||
t.Cleanup(ts.Close)
|
||||
@@ -250,6 +256,72 @@ func (f *fakeControlAPI) handler() http.Handler {
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /api/v1/admin/auto-cycle", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.autoCycleDown {
|
||||
writeAPIErr(w, http.StatusInternalServerError, "auto-cycle unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, f.autoCycle)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/admin/auto-cycle", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.autoCycleDown {
|
||||
writeAPIErr(w, http.StatusInternalServerError, "auto-cycle unavailable")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
IntervalSeconds *int `json:"interval_seconds"`
|
||||
MaxRunSeconds *int `json:"max_run_seconds"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
if req.IntervalSeconds != nil && *req.IntervalSeconds < 60 {
|
||||
writeAPIErr(w, http.StatusBadRequest, "interval_seconds must be >= 60: validation failed")
|
||||
return
|
||||
}
|
||||
if req.MaxRunSeconds != nil && *req.MaxRunSeconds < 0 {
|
||||
writeAPIErr(w, http.StatusBadRequest, "max_run_seconds must be >= 0: validation failed")
|
||||
return
|
||||
}
|
||||
if req.IntervalSeconds != nil {
|
||||
f.autoCycle.IntervalSeconds = *req.IntervalSeconds
|
||||
}
|
||||
if req.MaxRunSeconds != nil {
|
||||
f.autoCycle.MaxRunSeconds = *req.MaxRunSeconds
|
||||
}
|
||||
writeJSON(w, http.StatusOK, f.autoCycle)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/admin/auto-cycle/start", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.autoCycleDown {
|
||||
writeAPIErr(w, http.StatusInternalServerError, "auto-cycle unavailable")
|
||||
return
|
||||
}
|
||||
if !f.autoCycle.Enabled {
|
||||
now := time.Now()
|
||||
f.autoCycle.Enabled = true
|
||||
f.autoCycle.Phase = "idle"
|
||||
f.autoCycle.NextRunAt = &now
|
||||
}
|
||||
writeJSON(w, http.StatusOK, f.autoCycle)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/admin/auto-cycle/stop", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.autoCycleDown {
|
||||
writeAPIErr(w, http.StatusInternalServerError, "auto-cycle unavailable")
|
||||
return
|
||||
}
|
||||
f.autoCycle.Enabled = false
|
||||
f.autoCycle.Phase = "idle"
|
||||
f.autoCycle.NextRunAt = nil
|
||||
f.autoCycle.LastOutcome = "stopped"
|
||||
writeJSON(w, http.StatusOK, f.autoCycle)
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /api/v1/admin/registry", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package dashboard
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Wire shapes for control-api's /api/v1/admin/* surface, defined locally
|
||||
// rather than importing internal/httpapi's (unexported) DTOs or
|
||||
@@ -165,3 +168,79 @@ type inboundChecksDTO struct {
|
||||
Ports []int `json:"ports"`
|
||||
ICMP bool `json:"icmp"`
|
||||
}
|
||||
|
||||
// autoCycleDTO mirrors internal/httpapi's autoCycleDTO — the status and
|
||||
// parameters of the automatic check cycle (/api/v1/admin/auto-cycle).
|
||||
type autoCycleDTO struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
IntervalSeconds int `json:"interval_seconds"`
|
||||
MaxRunSeconds int `json:"max_run_seconds"`
|
||||
Phase string `json:"phase"`
|
||||
RunStartedAt *time.Time `json:"run_started_at"`
|
||||
NextRunAt *time.Time `json:"next_run_at"`
|
||||
LastRunStartedAt *time.Time `json:"last_run_started_at"`
|
||||
LastRunFinishedAt *time.Time `json:"last_run_finished_at"`
|
||||
LastOutcome string `json:"last_outcome"`
|
||||
LastError string `json:"last_error"`
|
||||
LastScannedFree int `json:"last_scanned_free"`
|
||||
RunsTotal int `json:"runs_total"`
|
||||
}
|
||||
|
||||
// secondsToMinutes renders seconds as minutes for the settings form: a
|
||||
// whole number when divisible by 60, otherwise a decimal ("1.5").
|
||||
func secondsToMinutes(sec int) string {
|
||||
return strconv.FormatFloat(float64(sec)/60, 'f', -1, 64)
|
||||
}
|
||||
|
||||
// IntervalMinutes and MaxRunMinutes are used by the settings template: the
|
||||
// UI works in minutes, the API in seconds.
|
||||
func (a autoCycleDTO) IntervalMinutes() string { return secondsToMinutes(a.IntervalSeconds) }
|
||||
func (a autoCycleDTO) MaxRunMinutes() string { return secondsToMinutes(a.MaxRunSeconds) }
|
||||
|
||||
// PhaseLabel is the Russian description of the current phase.
|
||||
func (a autoCycleDTO) PhaseLabel() string {
|
||||
switch a.Phase {
|
||||
case "running":
|
||||
return "идёт проверка"
|
||||
case "waiting":
|
||||
return "пауза между циклами"
|
||||
case "idle":
|
||||
return "ожидает запуска"
|
||||
default:
|
||||
return a.Phase
|
||||
}
|
||||
}
|
||||
|
||||
// OutcomeLabel is the Russian description of the last cycle's outcome.
|
||||
func (a autoCycleDTO) OutcomeLabel() string {
|
||||
switch a.LastOutcome {
|
||||
case "completed":
|
||||
return "завершён"
|
||||
case "no_free_ips":
|
||||
return "нет свободных IP"
|
||||
case "timeout":
|
||||
return "превышено время ожидания"
|
||||
case "error":
|
||||
return "ошибка"
|
||||
case "stopped":
|
||||
return "остановлен"
|
||||
case "":
|
||||
return "—"
|
||||
default:
|
||||
return a.LastOutcome
|
||||
}
|
||||
}
|
||||
|
||||
// OutcomePillClass picks the pill style for the last outcome.
|
||||
func (a autoCycleDTO) OutcomePillClass() string {
|
||||
switch a.LastOutcome {
|
||||
case "completed":
|
||||
return "pill-success"
|
||||
case "no_free_ips", "timeout", "stopped":
|
||||
return "pill-warning"
|
||||
case "error":
|
||||
return "pill-danger"
|
||||
default:
|
||||
return "pill-neutral"
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@ type overviewData struct {
|
||||
PollSeconds int
|
||||
Query string
|
||||
StatusFilter string
|
||||
// AutoCycle is nil when the auto-cycle status could not be fetched; the
|
||||
// indicator is then simply hidden (a non-fatal failure).
|
||||
AutoCycle *autoCycleDTO
|
||||
}
|
||||
|
||||
func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
|
||||
@@ -28,6 +31,12 @@ func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
|
||||
if err != nil {
|
||||
return overviewData{}, err
|
||||
}
|
||||
var autoCycle *autoCycleDTO
|
||||
if ac, acErr := s.CA.GetAutoCycle(ctx); acErr != nil {
|
||||
s.Log.Warn("overview: auto-cycle status unavailable", "err", acErr)
|
||||
} else {
|
||||
autoCycle = &ac
|
||||
}
|
||||
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
resultFilter := r.URL.Query().Get("status")
|
||||
last := lastCompleted(ips, s.Cfg.LastCompletedCount)
|
||||
@@ -40,6 +49,7 @@ func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
|
||||
PollSeconds: s.Cfg.OverviewPollIntervalS,
|
||||
Query: q,
|
||||
StatusFilter: resultFilter,
|
||||
AutoCycle: autoCycle,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package dashboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -11,6 +12,8 @@ type settingsPageData struct {
|
||||
PageData
|
||||
Settings orchestratorSettingsDTO
|
||||
Inbound inboundChecksDTO
|
||||
// AutoCycle is the automatic-check-cycle panel's status/parameters.
|
||||
AutoCycle autoCycleDTO
|
||||
}
|
||||
|
||||
func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -19,7 +22,11 @@ func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
|
||||
if err == nil {
|
||||
err = inboundErr
|
||||
}
|
||||
data := settingsPageData{Settings: settings, Inbound: inbound}
|
||||
autoCycle, autoCycleErr := s.CA.GetAutoCycle(r.Context())
|
||||
if err == nil {
|
||||
err = autoCycleErr
|
||||
}
|
||||
data := settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle}
|
||||
data.ActiveNav = "settings"
|
||||
data.Banner = bannerFor(err)
|
||||
s.renderPage(w, "settings_page", data)
|
||||
@@ -38,7 +45,11 @@ func (s *Server) renderSettingsForm(w http.ResponseWriter, r *http.Request, acti
|
||||
if actionErr == nil {
|
||||
actionErr = inboundErr
|
||||
}
|
||||
s.renderFragment(w, "settings_form", settingsPageData{Settings: settings, Inbound: inbound}, actionErr)
|
||||
autoCycle, autoCycleErr := s.CA.GetAutoCycle(r.Context())
|
||||
if actionErr == nil {
|
||||
actionErr = autoCycleErr
|
||||
}
|
||||
s.renderFragment(w, "settings_form", settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle}, actionErr)
|
||||
}
|
||||
|
||||
func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -90,3 +101,45 @@ func (s *Server) handleInboundChecksPut(w http.ResponseWriter, r *http.Request)
|
||||
_, err := s.CA.PutInboundChecks(r.Context(), ports, icmp)
|
||||
s.renderSettingsForm(w, r, err)
|
||||
}
|
||||
|
||||
// parseMinutes converts a form field holding a (possibly fractional) number
|
||||
// of minutes into whole seconds.
|
||||
func parseMinutes(raw string) (int, error) {
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(strings.ReplaceAll(raw, ",", ".")), 64)
|
||||
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || math.Abs(f) > 1e6 {
|
||||
return 0, fmt.Errorf("not a number of minutes: %q", raw)
|
||||
}
|
||||
return int(math.Round(f * 60)), nil
|
||||
}
|
||||
|
||||
// handleAutoCyclePut saves the auto-cycle interval and maximum run duration
|
||||
// (entered in minutes, sent to control-api in seconds). It does not touch
|
||||
// the enabled flag — that's what the start/stop buttons are for.
|
||||
func (s *Server) handleAutoCyclePut(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
s.renderSettingsForm(w, r, fmt.Errorf("invalid form: %w", err))
|
||||
return
|
||||
}
|
||||
intervalSec, err := parseMinutes(r.PostFormValue("interval_minutes"))
|
||||
if err != nil {
|
||||
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "интервал должен быть числом минут"})
|
||||
return
|
||||
}
|
||||
maxRunSec, err := parseMinutes(r.PostFormValue("max_run_minutes"))
|
||||
if err != nil {
|
||||
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "максимальная длительность должна быть числом минут (0 — без лимита)"})
|
||||
return
|
||||
}
|
||||
_, err = s.CA.PutAutoCycle(r.Context(), intervalSec, maxRunSec)
|
||||
s.renderSettingsForm(w, r, err)
|
||||
}
|
||||
|
||||
func (s *Server) handleAutoCycleStart(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := s.CA.StartAutoCycle(r.Context())
|
||||
s.renderSettingsForm(w, r, err)
|
||||
}
|
||||
|
||||
func (s *Server) handleAutoCycleStop(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := s.CA.StopAutoCycle(r.Context())
|
||||
s.renderSettingsForm(w, r, err)
|
||||
}
|
||||
@@ -724,3 +724,186 @@ func TestFilterRegistryItems(t *testing.T) {
|
||||
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)
|
||||
fake.autoCycle = autoCycleDTO{
|
||||
IntervalSeconds: 5400, MaxRunSeconds: 1800, Phase: "waiting",
|
||||
LastRunFinishedAt: &finished, LastOutcome: "timeout", LastError: "checks did not finish", RunsTotal: 4,
|
||||
}
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
page := get(t, ts, "/settings")
|
||||
for _, want := range []string{
|
||||
"Автоматический цикл",
|
||||
"Интервал между циклами (мин)",
|
||||
"Максимальная длительность проверки (мин, 0 = без лимита)",
|
||||
`name="interval_minutes" min="1" step="any" value="90"`,
|
||||
`name="max_run_minutes" min="0" step="any" value="30"`,
|
||||
"Автоцикл выключен",
|
||||
"пауза между циклами",
|
||||
"превышено время ожидания",
|
||||
"checks did not finish",
|
||||
`hx-put="/settings/auto-cycle"`,
|
||||
`hx-post="/settings/auto-cycle/start"`,
|
||||
"Включить",
|
||||
"Сохранить",
|
||||
} {
|
||||
if !strings.Contains(page, want) {
|
||||
t.Fatalf("expected %q on the settings page, got:\n%s", want, page)
|
||||
}
|
||||
}
|
||||
if strings.Contains(page, "Выключить") {
|
||||
t.Fatalf("stop button must be hidden while the auto-cycle is disabled, got:\n%s", page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCycleStartAndStopButtons(t *testing.T) {
|
||||
fake, caURL := newFakeControlAPI(t)
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
body := postForm(t, ts, "POST", "/settings/auto-cycle/start", nil)
|
||||
if !fake.autoCycle.Enabled {
|
||||
t.Fatalf("expected the fake control-api auto-cycle enabled after start")
|
||||
}
|
||||
if !strings.Contains(body, "Автоцикл включён") || !strings.Contains(body, "Выключить") ||
|
||||
!strings.Contains(body, `hx-post="/settings/auto-cycle/stop"`) {
|
||||
t.Fatalf("expected the re-rendered panel to show the enabled state with a stop button, got:\n%s", body)
|
||||
}
|
||||
if strings.Contains(body, "alert-") {
|
||||
t.Fatalf("expected no error banner after a successful start, got:\n%s", body)
|
||||
}
|
||||
|
||||
body = postForm(t, ts, "POST", "/settings/auto-cycle/stop", nil)
|
||||
if fake.autoCycle.Enabled {
|
||||
t.Fatalf("expected the fake control-api auto-cycle disabled after stop")
|
||||
}
|
||||
if !strings.Contains(body, "Автоцикл выключен") || !strings.Contains(body, "Включить") ||
|
||||
!strings.Contains(body, "остановлен") {
|
||||
t.Fatalf("expected the re-rendered panel to show the stopped state, got:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCyclePutConvertsMinutesToSeconds(t *testing.T) {
|
||||
fake, caURL := newFakeControlAPI(t)
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
body := postForm(t, ts, "PUT", "/settings/auto-cycle", map[string][]string{
|
||||
"interval_minutes": {"30"}, "max_run_minutes": {"10"},
|
||||
})
|
||||
if fake.autoCycle.IntervalSeconds != 1800 || fake.autoCycle.MaxRunSeconds != 600 {
|
||||
t.Fatalf("expected 1800/600 seconds at control-api, got %d/%d",
|
||||
fake.autoCycle.IntervalSeconds, fake.autoCycle.MaxRunSeconds)
|
||||
}
|
||||
if !strings.Contains(body, `name="interval_minutes" min="1" step="any" value="30"`) ||
|
||||
!strings.Contains(body, `name="max_run_minutes" min="0" step="any" value="10"`) {
|
||||
t.Fatalf("expected updated minutes in the re-rendered form, got:\n%s", body)
|
||||
}
|
||||
if fake.autoCycle.Enabled {
|
||||
t.Fatalf("saving parameters must not toggle the auto-cycle")
|
||||
}
|
||||
|
||||
// 0 = no limit.
|
||||
postForm(t, ts, "PUT", "/settings/auto-cycle", map[string][]string{
|
||||
"interval_minutes": {"30"}, "max_run_minutes": {"0"},
|
||||
})
|
||||
if fake.autoCycle.MaxRunSeconds != 0 {
|
||||
t.Fatalf("expected max_run_seconds 0, got %d", fake.autoCycle.MaxRunSeconds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCyclePutValidationErrors(t *testing.T) {
|
||||
fake, caURL := newFakeControlAPI(t)
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
// Below the control-api minimum (60 s): rejected by control-api with
|
||||
// 400, surfaced as a warning banner; stored value is untouched.
|
||||
body := postForm(t, ts, "PUT", "/settings/auto-cycle", map[string][]string{
|
||||
"interval_minutes": {"0.5"}, "max_run_minutes": {"0"},
|
||||
})
|
||||
if !strings.Contains(body, "alert-warning") {
|
||||
t.Fatalf("expected client error banner for a too-short interval, got:\n%s", body)
|
||||
}
|
||||
if fake.autoCycle.IntervalSeconds != 3600 {
|
||||
t.Fatalf("expected interval unchanged, got %d", fake.autoCycle.IntervalSeconds)
|
||||
}
|
||||
|
||||
// Negative max run.
|
||||
body = postForm(t, ts, "PUT", "/settings/auto-cycle", map[string][]string{
|
||||
"interval_minutes": {"10"}, "max_run_minutes": {"-5"},
|
||||
})
|
||||
if !strings.Contains(body, "alert-warning") {
|
||||
t.Fatalf("expected client error banner for a negative max run, got:\n%s", body)
|
||||
}
|
||||
|
||||
// Non-numeric input is caught by the dashboard itself.
|
||||
body = postForm(t, ts, "PUT", "/settings/auto-cycle", map[string][]string{
|
||||
"interval_minutes": {"abc"}, "max_run_minutes": {"0"},
|
||||
})
|
||||
if !strings.Contains(body, "alert-warning") || !strings.Contains(body, "интервал должен быть числом минут") {
|
||||
t.Fatalf("expected a Russian banner for a non-numeric interval, got:\n%s", body)
|
||||
}
|
||||
body = postForm(t, ts, "PUT", "/settings/auto-cycle", map[string][]string{
|
||||
"interval_minutes": {"10"}, "max_run_minutes": {"abc"},
|
||||
})
|
||||
if !strings.Contains(body, "alert-warning") || !strings.Contains(body, "максимальная длительность") {
|
||||
t.Fatalf("expected a Russian banner for a non-numeric max run, got:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverviewShowsAutoCycleIndicatorWhenEnabled(t *testing.T) {
|
||||
fake, caURL := newFakeControlAPI(t)
|
||||
next := time.Now().Add(30 * time.Minute)
|
||||
fake.autoCycle = autoCycleDTO{Enabled: true, IntervalSeconds: 3600, Phase: "waiting", NextRunAt: &next}
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
page := get(t, ts, "/overview")
|
||||
for _, want := range []string{"Автоцикл активен", "пауза между циклами", "следующий запуск"} {
|
||||
if !strings.Contains(page, want) {
|
||||
t.Fatalf("expected %q in the overview indicator, got:\n%s", want, page)
|
||||
}
|
||||
}
|
||||
// The indicator sits inside the stats block, so the DOM order
|
||||
// stats -> filter -> tables is preserved.
|
||||
indIdx := strings.Index(page, "Автоцикл активен")
|
||||
filterIdx := strings.Index(page, `id="overview-filter"`)
|
||||
tablesIdx := strings.Index(page, `id="overview-tables"`)
|
||||
if !(indIdx < filterIdx && filterIdx < tablesIdx) {
|
||||
t.Fatalf("expected indicator -> filter -> tables order, got %d/%d/%d", indIdx, filterIdx, tablesIdx)
|
||||
}
|
||||
|
||||
// The polled fragment refreshes it through the stats OOB block.
|
||||
frag := get(t, ts, "/overview/fragment")
|
||||
oobIdx := strings.Index(frag, `id="overview-stats" hx-swap-oob="true"`)
|
||||
if oobIdx < 0 || !strings.Contains(frag[oobIdx:], "Автоцикл активен") {
|
||||
t.Fatalf("expected the indicator inside the OOB stats block, got:\n%s", frag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverviewHidesAutoCycleIndicatorWhenDisabledOrUnavailable(t *testing.T) {
|
||||
fake, caURL := newFakeControlAPI(t)
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
// Disabled: no indicator.
|
||||
if page := get(t, ts, "/overview"); strings.Contains(page, "Автоцикл активен") {
|
||||
t.Fatalf("indicator must be hidden while the auto-cycle is disabled, got:\n%s", page)
|
||||
}
|
||||
|
||||
// Enabled but the auto-cycle API fails: the overview still renders
|
||||
// (non-fatal), without the indicator and without an error banner.
|
||||
fake.mu.Lock()
|
||||
fake.autoCycle.Enabled = true
|
||||
fake.autoCycleDown = true
|
||||
fake.mu.Unlock()
|
||||
page := get(t, ts, "/overview")
|
||||
if strings.Contains(page, "Автоцикл активен") {
|
||||
t.Fatalf("indicator must be hidden when the auto-cycle API fails, got:\n%s", page)
|
||||
}
|
||||
if strings.Contains(page, "alert-") {
|
||||
t.Fatalf("an auto-cycle failure must not raise an error banner on the overview, got:\n%s", page)
|
||||
}
|
||||
if !strings.Contains(page, "всего IP") {
|
||||
t.Fatalf("expected the overview to still render its stats, got:\n%s", page)
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@ func (s *Server) routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /settings", s.handleSettingsPage)
|
||||
mux.HandleFunc("PUT /settings", s.handleSettingsPut)
|
||||
mux.HandleFunc("PUT /settings/inbound-checks", s.handleInboundChecksPut)
|
||||
mux.HandleFunc("PUT /settings/auto-cycle", s.handleAutoCyclePut)
|
||||
mux.HandleFunc("POST /settings/auto-cycle/start", s.handleAutoCycleStart)
|
||||
mux.HandleFunc("POST /settings/auto-cycle/stop", s.handleAutoCycleStop)
|
||||
|
||||
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(staticSubFS())))
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
<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>
|
||||
{{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}}
|
||||
{{end}}
|
||||
|
||||
{{/* Out-of-band counterpart of overview_stats, appended to every
|
||||
|
||||
@@ -28,6 +28,47 @@
|
||||
{{end}}
|
||||
|
||||
{{define "settings_form"}}
|
||||
<div class="panel" id="auto-cycle-panel">
|
||||
<div class="panel-body">
|
||||
<h2 class="section-title" style="margin-top:0">Автоматический цикл</h2>
|
||||
<p class="muted" style="margin-bottom:16px">Повторяет сценарий оператора: «Очистить всё» → «Сканировать Floating IP» →
|
||||
ожидание, пока все адреса очереди пройдут проверку → пауза и новый цикл. Интервал отсчитывается от завершения
|
||||
предыдущего цикла. Пока автоцикл включён, периодическое сканирование по <code>fip_scan_interval_seconds</code>
|
||||
не выполняется. Выключение не прерывает проверки, которые уже идут.</p>
|
||||
<p style="margin-bottom:16px">
|
||||
<span class="pill {{if .AutoCycle.Enabled}}pill-success{{else}}pill-neutral{{end}}">{{if .AutoCycle.Enabled}}Автоцикл включён{{else}}Автоцикл выключен{{end}}</span>
|
||||
· фаза: {{.AutoCycle.PhaseLabel}}
|
||||
</p>
|
||||
<div class="muted" style="margin-bottom:16px">
|
||||
<div>Последний запуск: {{fmtTime .AutoCycle.LastRunStartedAt}}</div>
|
||||
<div>Завершён: {{fmtTime .AutoCycle.LastRunFinishedAt}}</div>
|
||||
<div>Следующий запуск: {{fmtTime .AutoCycle.NextRunAt}}</div>
|
||||
<div>Результат последнего цикла: <span class="pill {{.AutoCycle.OutcomePillClass}}">{{.AutoCycle.OutcomeLabel}}</span>{{if .AutoCycle.LastError}} — {{.AutoCycle.LastError}}{{end}}</div>
|
||||
<div>Свободных адресов в последнем скане: {{.AutoCycle.LastScannedFree}} · завершённых циклов: {{.AutoCycle.RunsTotal}}</div>
|
||||
</div>
|
||||
<form hx-put="/settings/auto-cycle" hx-target="#settings-form-wrap" hx-swap="innerHTML">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="auto_cycle_interval">Интервал между циклами (мин)</label>
|
||||
<input type="number" id="auto_cycle_interval" name="interval_minutes" min="1" step="any" value="{{.AutoCycle.IntervalMinutes}}" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="auto_cycle_max_run">Максимальная длительность проверки (мин, 0 = без лимита)</label>
|
||||
<input type="number" id="auto_cycle_max_run" name="max_run_minutes" min="0" step="any" value="{{.AutoCycle.MaxRunMinutes}}" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||
</div>
|
||||
</form>
|
||||
<div style="margin-top:16px">
|
||||
{{if .AutoCycle.Enabled}}
|
||||
<button type="button" class="btn btn-primary" hx-post="/settings/auto-cycle/stop" hx-target="#settings-form-wrap" hx-swap="innerHTML">Выключить</button>
|
||||
{{else}}
|
||||
<button type="button" class="btn btn-primary" hx-post="/settings/auto-cycle/start" hx-target="#settings-form-wrap" hx-swap="innerHTML">Включить</button>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel-body">
|
||||
<p class="muted" style="margin-bottom:16px">Пауза между привязкой Floating IP к валидатору и началом self-check —
|
||||
|
||||
Reference in new issue
Block a user