added FIP Cooldown before start

This commit is contained in:
ayurishchev committed 2026-08-24 10:29:08 +03:00
1 parent 291eea3eb8
commit f22ad569b6
36 files changed
+1182 -25

No files matched your search

+13
View File
@@ -200,3 +200,16 @@ func (c *client) PutCheckType(ctx context.Context, name string, enabled bool, ta
func (c *client) DeleteCheckType(ctx context.Context, name string) error {
return c.do(ctx, http.MethodDelete, "/api/v1/admin/config/check-types/"+url.PathEscape(name), nil, nil)
}
func (c *client) GetOrchestratorSettings(ctx context.Context) (orchestratorSettingsDTO, error) {
var out orchestratorSettingsDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/orchestrator", nil, &out)
return out, err
}
func (c *client) PutOrchestratorSettings(ctx context.Context, fipSettleSeconds int) (orchestratorSettingsDTO, error) {
var out orchestratorSettingsDTO
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/orchestrator",
orchestratorSettingsDTO{FIPSettleSeconds: fipSettleSeconds}, &out)
return out, err
}
+25 -6
View File
@@ -22,12 +22,13 @@ import (
// re-implementation of control-api's own business rules (that's already
// covered by internal/httpapi's own tests).
type fakeControlAPI struct {
mu sync.Mutex
ips []ipQueueItem
validators []validatorDTO
sites map[int]string
groups map[string][]string
checkTypes map[string]checkTypeDTO
mu sync.Mutex
ips []ipQueueItem
validators []validatorDTO
sites map[int]string
groups map[string][]string
checkTypes map[string]checkTypeDTO
fipSettleSeconds int
}
func newFakeControlAPI(t *testing.T) (*fakeControlAPI, string) {
@@ -187,6 +188,24 @@ func (f *fakeControlAPI) handler() http.Handler {
writeJSON(w, http.StatusOK, resp)
})
mux.HandleFunc("GET /api/v1/admin/config/orchestrator", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{FIPSettleSeconds: f.fipSettleSeconds})
})
mux.HandleFunc("PUT /api/v1/admin/config/orchestrator", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
var req orchestratorSettingsDTO
_ = json.NewDecoder(r.Body).Decode(&req)
if req.FIPSettleSeconds < 0 {
writeAPIErr(w, http.StatusBadRequest, "fip_settle_seconds must be >= 0")
return
}
f.fipSettleSeconds = req.FIPSettleSeconds
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{FIPSettleSeconds: f.fipSettleSeconds})
})
mux.HandleFunc("GET /api/v1/admin/config/validators", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
+5
View File
@@ -35,6 +35,7 @@ type ipQueueItem struct {
Site3Complete bool
OverallResult string
AssignedAt *time.Time
FIPAssociatedAt *time.Time
AggregatedAt *time.Time
FIPReleasedAt *time.Time
CreatedAt time.Time
@@ -123,3 +124,7 @@ type checkTypeDTO struct {
type errorResponse struct {
Error string `json:"error"`
}
type orchestratorSettingsDTO struct {
FIPSettleSeconds int `json:"fip_settle_seconds"`
}
+12 -3
View File
@@ -7,7 +7,8 @@ import (
type ipsPageData struct {
PageData
Items []ipQueueItem
Items []ipQueueItem
FIPSettleSeconds int
}
type ipDetailData struct {
@@ -17,7 +18,11 @@ type ipDetailData struct {
func (s *Server) handleIPsPage(w http.ResponseWriter, r *http.Request) {
items, err := s.CA.ListIPs(r.Context())
data := ipsPageData{Items: items}
settings, settingsErr := s.CA.GetOrchestratorSettings(r.Context())
if err == nil {
err = settingsErr
}
data := ipsPageData{Items: items, FIPSettleSeconds: settings.FIPSettleSeconds}
data.ActiveNav = "ips"
data.Banner = bannerFor(err)
s.renderPage(w, "ips_page", data)
@@ -41,7 +46,11 @@ func (s *Server) renderIPsTable(w http.ResponseWriter, r *http.Request, actionEr
if actionErr == nil {
actionErr = listErr
}
s.renderFragment(w, "ips_table", ipsPageData{Items: items}, actionErr)
settings, settingsErr := s.CA.GetOrchestratorSettings(r.Context())
if actionErr == nil {
actionErr = settingsErr
}
s.renderFragment(w, "ips_table", ipsPageData{Items: items, FIPSettleSeconds: settings.FIPSettleSeconds}, actionErr)
}
func (s *Server) handleIPsSubmit(w http.ResponseWriter, r *http.Request) {
+46
View File
@@ -0,0 +1,46 @@
package dashboard
import (
"fmt"
"net/http"
"strconv"
)
type settingsPageData struct {
PageData
Settings orchestratorSettingsDTO
}
func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
settings, err := s.CA.GetOrchestratorSettings(r.Context())
data := settingsPageData{Settings: settings}
data.ActiveNav = "settings"
data.Banner = bannerFor(err)
s.renderPage(w, "settings_page", data)
}
// renderSettingsForm re-fetches the current settings and renders the
// settings_form fragment, tagging actionErr (if any) on the shared error
// banner — same pattern as renderIPsTable: always reflect true current
// state regardless of whether the mutation itself succeeded.
func (s *Server) renderSettingsForm(w http.ResponseWriter, r *http.Request, actionErr error) {
settings, getErr := s.CA.GetOrchestratorSettings(r.Context())
if actionErr == nil {
actionErr = getErr
}
s.renderFragment(w, "settings_form", settingsPageData{Settings: settings}, actionErr)
}
func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderSettingsForm(w, r, fmt.Errorf("invalid form: %w", err))
return
}
seconds, err := strconv.Atoi(r.PostFormValue("fip_settle_seconds"))
if err != nil {
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "пауза должна быть целым числом секунд"})
return
}
_, err = s.CA.PutOrchestratorSettings(r.Context(), seconds)
s.renderSettingsForm(w, r, err)
}
+55
View File
@@ -175,6 +175,61 @@ func TestIPsClear(t *testing.T) {
}
}
func TestSettingsGetAndPut(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
ts := newTestServer(t, caURL)
page := get(t, ts, "/settings")
if !strings.Contains(page, `value="0"`) {
t.Fatalf("expected default 0 in the form, got:\n%s", page)
}
body := postForm(t, ts, "PUT", "/settings", map[string][]string{"fip_settle_seconds": {"15"}})
if !strings.Contains(body, `value="15"`) {
t.Fatalf("expected updated value 15 in re-rendered form, got:\n%s", body)
}
if fake.fipSettleSeconds != 15 {
t.Fatalf("expected fake control-api settings updated, got %d", fake.fipSettleSeconds)
}
// A control-api validation error (negative value here) surfaces via
// the banner, not a crash.
body = postForm(t, ts, "PUT", "/settings", map[string][]string{"fip_settle_seconds": {"-1"}})
if !strings.Contains(body, "alert-warning") {
t.Fatalf("expected client error banner for invalid value, got:\n%s", body)
}
// A non-numeric value is caught by the dashboard itself before it ever
// reaches control-api.
body = postForm(t, ts, "PUT", "/settings", map[string][]string{"fip_settle_seconds": {"not-a-number"}})
if !strings.Contains(body, "alert-warning") {
t.Fatalf("expected client error banner for non-numeric value, got:\n%s", body)
}
}
func TestIPsPageShowsSettleBadge(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
fake.fipSettleSeconds = 60
fake.ips = []ipQueueItem{
{IPAddress: "1.1.1.1", State: "awaiting_self_check", FIPAssociatedAt: &now, UpdatedAt: now, CreatedAt: now},
}
ts := newTestServer(t, caURL)
body := get(t, ts, "/ips")
if !strings.Contains(body, "прогрев FIP") {
t.Fatalf("expected settle badge for a freshly-associated ip within the pause, got:\n%s", body)
}
// Once fip_settle_seconds is 0, the same row falls back to the plain
// state pill.
fake.fipSettleSeconds = 0
body = get(t, ts, "/ips")
if strings.Contains(body, "прогрев FIP") {
t.Fatalf("expected no settle badge once fip_settle_seconds is 0, got:\n%s", body)
}
}
func TestValidatorsCRUD(t *testing.T) {
_, caURL := newFakeControlAPI(t)
ts := newTestServer(t, caURL)
+13 -1
View File
@@ -13,7 +13,14 @@ import (
// with "pill" in the template (e.g. `class="pill {{.Class}}"`).
type Badge struct{ Class, Label string }
func ipBadge(state, result string) Badge {
// ipBadge picks the status pill for a queue row. fipAssociatedAt/
// settleSeconds are only consulted for state=="awaiting_self_check": if
// the configured fip_settle_seconds pause (see docs/USAGE.md) hasn't
// elapsed since the floating IP was associated, the row gets a distinct
// "прогрев FIP" badge instead of looking identical to a row just waiting
// on the agent's next poll. The time math happens here, not in the
// template, same as fmtTime's existing precedent.
func ipBadge(state, result string, fipAssociatedAt *time.Time, settleSeconds int) Badge {
switch state {
case "done", "failed":
switch result {
@@ -28,6 +35,11 @@ func ipBadge(state, result string) Badge {
}
case "queued":
return Badge{"pill-neutral", "queued"}
case "awaiting_self_check":
if settleSeconds > 0 && fipAssociatedAt != nil && time.Now().Before(fipAssociatedAt.Add(time.Duration(settleSeconds)*time.Second)) {
return Badge{"pill-warning", "прогрев FIP"}
}
return Badge{"pill-info", state}
default:
return Badge{"pill-info", state}
}
+3
View File
@@ -36,6 +36,9 @@ func (s *Server) routes(mux *http.ServeMux) {
mux.HandleFunc("PUT /check-types/{name}", s.handleCheckTypeUpdate)
mux.HandleFunc("DELETE /check-types/{name}", s.handleCheckTypeDelete)
mux.HandleFunc("GET /settings", s.handleSettingsPage)
mux.HandleFunc("PUT /settings", s.handleSettingsPut)
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(staticSubFS())))
}
+1 -1
View File
@@ -20,7 +20,7 @@
{{define "ip_detail_content"}}
<p><a href="/ips">&larr; К очереди</a></p>
{{$b := ipBadge .Detail.IP.State .Detail.IP.OverallResult}}
{{$b := ipBadge .Detail.IP.State .Detail.IP.OverallResult .Detail.IP.FIPAssociatedAt 0}}
<div class="topbar">
<h1 class="mono" style="display:flex;align-items:center;gap:10px">{{.Detail.IP.IPAddress}} <span class="pill {{$b.Class}}">{{$b.Label}}</span></h1>
</div>
+1 -1
View File
@@ -54,7 +54,7 @@
<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>
<tbody>
{{range .Items}}
{{$b := ipBadge .State .OverallResult}}
{{$b := ipBadge .State .OverallResult .FIPAssociatedAt $.FIPSettleSeconds}}
{{$terminal := or (eq .State "done") (eq .State "failed")}}
<tr>
<td data-label=""><input type="checkbox" name="addresses" value="{{.IPAddress}}"></td>
+4
View File
@@ -52,6 +52,10 @@
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
Типы проверок
</a>
<a class="nav-link{{if eq .ActiveNav "settings"}} active{{end}}" {{if eq .ActiveNav "settings"}}aria-current="page"{{end}} href="/settings">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/></svg>
Настройки
</a>
</nav>
<div class="sidebar-foot">
@@ -15,7 +15,7 @@
<thead><tr><th>Адрес</th><th>Состояние</th><th>Валидатор</th><th>Попытка</th><th>Назначено</th></tr></thead>
<tbody>
{{range .CurrentItems}}
{{$b := ipBadge .State .OverallResult}}
{{$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>
@@ -46,7 +46,7 @@
<thead><tr><th>Адрес</th><th>Итог</th><th>Завершено</th></tr></thead>
<tbody>
{{range .LastCompleted}}
{{$b := ipBadge .State .OverallResult}}
{{$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>
@@ -0,0 +1,48 @@
{{define "settings_page"}}
<!doctype html>
<html lang="ru">
<head>{{template "html_head" .}}</head>
<body>
<input type="checkbox" id="nav-toggle" class="nav-toggle">
<div class="shell">
{{template "sidebar_nav" .}}
<div>
{{template "topbar_mobile" .}}
<main class="main">
<div id="error-banner">{{template "banner_inner" .Banner}}</div>
{{template "settings_content" .}}
</main>
</div>
</div>
</body>
</html>
{{end}}
{{define "settings_content"}}
<div class="topbar"><h1>Настройки</h1></div>
<div id="settings-form-wrap">
{{template "settings_form" .}}
</div>
{{end}}
{{define "settings_form"}}
<div class="panel">
<div class="panel-body">
<p class="muted" style="margin-bottom:16px">Пауза между привязкой Floating IP к валидатору и началом self-check —
даёт data plane OpenStack время начать пропускать трафик через только что привязанный адрес, прежде чем
проверять его. <code>0</code> — без паузы (поведение по умолчанию). Значение должно оставлять запас внутри лизинга
адреса: <code>fip_settle_seconds + self_check_timeout_seconds &lt; lease_ttl_seconds</code> — иначе адрес не успеет
пройти self-check до истечения лизинга и будет возвращён в очередь.</p>
<form hx-put="/settings" hx-target="#settings-form-wrap" hx-swap="innerHTML">
<div class="field-row">
<div class="field">
<label for="fip_settle_seconds">Пауза перед self-check (сек)</label>
<input type="number" id="fip_settle_seconds" name="fip_settle_seconds" min="0" step="1" value="{{.Settings.FIPSettleSeconds}}" required>
</div>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
{{end}}