New external site management. New external prober heartbeat feature.

This commit is contained in:
ayurishchev committed 2026-08-26 20:47:54 +03:00
1 parent 42f584dd3c
commit ef24cc9858
38 files changed
+1058 -158

No files matched your search

+15 -5
View File
@@ -26,6 +26,8 @@ type fakeControlAPI struct {
ips []ipQueueItem
validators []validatorDTO
sites map[int]string
siteState map[int]string
siteHostname map[int]string
groups map[string][]string
checkTypes map[string]checkTypeDTO
fipSettleSeconds int
@@ -36,9 +38,11 @@ type fakeControlAPI struct {
func newFakeControlAPI(t *testing.T) (*fakeControlAPI, string) {
t.Helper()
f := &fakeControlAPI{
sites: map[int]string{},
groups: map[string][]string{},
checkTypes: map[string]checkTypeDTO{},
sites: map[int]string{},
siteState: map[int]string{},
siteHostname: map[int]string{},
groups: map[string][]string{},
checkTypes: map[string]checkTypeDTO{},
}
ts := httptest.NewServer(f.handler())
t.Cleanup(ts.Close)
@@ -285,7 +289,7 @@ func (f *fakeControlAPI) handler() http.Handler {
defer f.mu.Unlock()
var out []siteDTO
for idx, id := range f.sites {
out = append(out, siteDTO{Index: idx, SiteID: id})
out = append(out, siteDTO{Index: idx, SiteID: id, Hostname: f.siteHostname[idx], State: f.siteState[idx]})
}
writeJSON(w, http.StatusOK, out)
})
@@ -305,7 +309,11 @@ func (f *fakeControlAPI) handler() http.Handler {
}
}
f.sites[idx] = req.SiteID
writeJSON(w, http.StatusOK, siteDTO{Index: idx, SiteID: req.SiteID})
// UpsertSite always resets connection status on write (see its
// control-api doc comment) — mirror that here.
f.siteState[idx] = "unregistered"
f.siteHostname[idx] = ""
writeJSON(w, http.StatusOK, siteDTO{Index: idx, SiteID: req.SiteID, State: "unregistered"})
})
mux.HandleFunc("DELETE /api/v1/admin/config/sites/{index}", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
@@ -313,6 +321,8 @@ func (f *fakeControlAPI) handler() http.Handler {
var idx int
fmt.Sscanf(r.PathValue("index"), "%d", &idx)
delete(f.sites, idx)
delete(f.siteState, idx)
delete(f.siteHostname, idx)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
})
+5 -5
View File
@@ -30,9 +30,6 @@ type ipQueueItem struct {
RetryCount int
LeaseExpiresAt *time.Time
EgressComplete bool
Site1Complete bool
Site2Complete bool
Site3Complete bool
OverallResult string
AssignedAt *time.Time
FIPAssociatedAt *time.Time
@@ -106,8 +103,11 @@ type validatorDTO struct {
}
type siteDTO struct {
Index int `json:"index"`
SiteID string `json:"site_id"`
Index int `json:"index"`
SiteID string `json:"site_id"`
Hostname string `json:"hostname"`
State string `json:"state"`
LastHeartbeatAt *time.Time `json:"last_heartbeat_at"`
}
type targetGroupDTO struct {
+22 -17
View File
@@ -8,26 +8,12 @@ import (
type sitesPageData struct {
PageData
Items []siteDTO // always exactly 3 entries, index 1..3, SiteID=="" for an empty slot
}
// fillSlots pads control-api's response (which only lists assigned slots)
// out to all three fixed slots, so the table always renders 3 rows.
func fillSlots(sites []siteDTO) []siteDTO {
byIndex := make(map[int]string, len(sites))
for _, s := range sites {
byIndex[s.Index] = s.SiteID
}
out := make([]siteDTO, 3)
for i := 0; i < 3; i++ {
out[i] = siteDTO{Index: i + 1, SiteID: byIndex[i+1]}
}
return out
Items []siteDTO // dynamic length — as many slots as configured, no fixed cap
}
func (s *Server) handleSitesPage(w http.ResponseWriter, r *http.Request) {
items, err := s.CA.ListSites(r.Context())
data := sitesPageData{Items: fillSlots(items)}
data := sitesPageData{Items: items}
data.ActiveNav = "sites"
data.Banner = bannerFor(err)
s.renderPage(w, "sites_page", data)
@@ -38,7 +24,26 @@ func (s *Server) renderSitesTable(w http.ResponseWriter, r *http.Request, action
if actionErr == nil {
actionErr = listErr
}
s.renderFragment(w, "sites_table", sitesPageData{Items: fillSlots(items)}, actionErr)
s.renderFragment(w, "sites_table", sitesPageData{Items: items}, actionErr)
}
// handleSiteCreate adds a brand-new slot via the "add site" form — same
// create-alongside-update pattern as /targets' handleTargetCreate, just
// backed by the same PutSite call the per-row form already uses (there's
// no separate "create" endpoint on control-api since PUT is already an
// upsert).
func (s *Server) handleSiteCreate(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderSitesTable(w, r, fmt.Errorf("invalid form: %w", err))
return
}
index, convErr := strconv.Atoi(r.PostFormValue("index"))
if convErr != nil {
s.renderSitesTable(w, r, &apiErr{Status: http.StatusBadRequest, Message: "index должен быть числом"})
return
}
err := s.CA.PutSite(r.Context(), index, r.PostFormValue("site_id"))
s.renderSitesTable(w, r, err)
}
func (s *Server) handleSitePut(w http.ResponseWriter, r *http.Request) {
+51 -4
View File
@@ -316,11 +316,11 @@ func TestSitesPutAndConflict(t *testing.T) {
t.Fatalf("expected site-1 assigned to slot 1, got:\n%s", body)
}
// Slot page always renders exactly 3 rows, including empty ones — count
// the per-slot PUT forms rather than raw <tr> (the thead row has one too).
// The table renders exactly as many rows as configured slots — no
// fixed cap, no padding to a fixed count.
page := get(t, ts, "/sites")
if strings.Count(page, `hx-put="/sites/`) != 3 {
t.Fatalf("expected exactly 3 site slot rows, got:\n%s", page)
if strings.Count(page, `hx-put="/sites/`) != 1 {
t.Fatalf("expected exactly 1 site slot row, got:\n%s", page)
}
body = postForm(t, ts, "PUT", "/sites/2", map[string][]string{"site_id": {"site-1"}})
@@ -329,6 +329,53 @@ func TestSitesPutAndConflict(t *testing.T) {
}
}
// TestSiteCreateAddsSlotBeyondThree proves there's no hardcoded cap on the
// number of prober slots — the "add site" form can create slot 4 and
// beyond.
func TestSiteCreateAddsSlotBeyondThree(t *testing.T) {
_, caURL := newFakeControlAPI(t)
ts := newTestServer(t, caURL)
postForm(t, ts, "PUT", "/sites/1", map[string][]string{"site_id": {"site-1"}})
postForm(t, ts, "PUT", "/sites/2", map[string][]string{"site_id": {"site-2"}})
postForm(t, ts, "PUT", "/sites/3", map[string][]string{"site_id": {"site-3"}})
body := postForm(t, ts, "POST", "/sites", map[string][]string{"index": {"4"}, "site_id": {"site-4"}})
if !strings.Contains(body, "site-4") {
t.Fatalf("expected slot 4 created, got:\n%s", body)
}
if strings.Count(body, `hx-put="/sites/`) != 4 {
t.Fatalf("expected exactly 4 site slot rows, got:\n%s", body)
}
// A malformed index is caught by the dashboard itself.
body = postForm(t, ts, "POST", "/sites", map[string][]string{"index": {"not-a-number"}, "site_id": {"site-5"}})
if !strings.Contains(body, "alert-warning") {
t.Fatalf("expected client error banner for non-numeric index, got:\n%s", body)
}
}
func TestSitesPageShowsProberBadge(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
fake.sites[1] = "site-1"
fake.siteState[1] = "idle"
fake.siteHostname[1] = "probe-host-1"
fake.sites[2] = "site-2"
fake.siteState[2] = "unreachable"
ts := newTestServer(t, caURL)
page := get(t, ts, "/sites")
if !strings.Contains(page, "probe-host-1") {
t.Fatalf("expected hostname shown, got:\n%s", page)
}
if !strings.Contains(page, "pill-success") || !strings.Contains(page, ">idle<") {
t.Fatalf("expected idle badge for site-1, got:\n%s", page)
}
if !strings.Contains(page, "pill-danger") || !strings.Contains(page, ">unreachable<") {
t.Fatalf("expected unreachable badge for site-2, got:\n%s", page)
}
}
func TestTargetsAndCheckTypesRoundTrip(t *testing.T) {
_, caURL := newFakeControlAPI(t)
ts := newTestServer(t, caURL)
+8 -4
View File
@@ -101,10 +101,14 @@ func joinInts(ints []int, sep string) string {
var funcMap = template.FuncMap{
"ipBadge": ipBadge,
"validatorBadge": validatorBadge,
"fmtTime": fmtTime,
"deref": derefStr,
"join": strings.Join,
"joinInts": joinInts,
// proberBadge reuses validatorBadge as-is: prober states
// (unregistered/idle/unreachable) are a subset of validator states
// with identical labels/styles, so no separate function is needed.
"proberBadge": validatorBadge,
"fmtTime": fmtTime,
"deref": derefStr,
"join": strings.Join,
"joinInts": joinInts,
}
func parseTemplates() (*template.Template, error) {
+1
View File
@@ -23,6 +23,7 @@ func (s *Server) routes(mux *http.ServeMux) {
mux.HandleFunc("DELETE /validators/{id}", s.handleValidatorDelete)
mux.HandleFunc("GET /sites", s.handleSitesPage)
mux.HandleFunc("POST /sites", s.handleSiteCreate)
mux.HandleFunc("PUT /sites/{index}", s.handleSitePut)
mux.HandleFunc("DELETE /sites/{index}", s.handleSiteDelete)
+28 -6
View File
@@ -20,8 +20,27 @@
{{define "sites_content"}}
<div class="topbar"><h1>Площадки</h1></div>
<p class="muted" style="margin-bottom:16px">Ровно три слота (1, 2, 3) — жёсткое ограничение схемы БД control-api.
Пустой слот — площадка не используется, входящие проверки для неё не ожидаются.</p>
<p class="muted" style="margin-bottom:16px">Внешние площадки (проберы), проверяющие адреса «снаружи». Число площадок
не ограничено — добавляйте столько слотов, сколько нужно. «Статус» показывает, подключён ли прямо сейчас
процесс prober на этой площадке (по heartbeat, аналогично валидаторам).</p>
<div class="panel">
<div class="panel-body">
<form hx-post="/sites" hx-target="#sites-table-wrap" hx-swap="innerHTML" hx-on::after-request="this.reset()">
<div class="field-row">
<div class="field" style="flex: 0 1 120px;">
<label>Слот (index)</label>
<input type="number" name="index" min="1" step="1" required>
</div>
<div class="field" style="flex: 1 1 240px;">
<label>site_id</label>
<input type="text" name="site_id" placeholder="site-4" required>
</div>
<button type="submit" class="btn btn-primary">Добавить</button>
</div>
</form>
</div>
</div>
<div id="sites-table-wrap">
{{template "sites_table" .}}
@@ -32,9 +51,10 @@
<div class="panel">
<div class="table-scroll">
<table>
<thead><tr><th>Слот</th><th>site_id</th><th></th></tr></thead>
<thead><tr><th>Слот</th><th>site_id</th><th>Хост</th><th>Статус</th><th>Heartbeat</th><th></th></tr></thead>
<tbody>
{{range .Items}}
{{$b := proberBadge .State}}
<tr>
<td class="num" data-label="Слот">{{.Index}}</td>
<td data-label="site_id">
@@ -43,17 +63,19 @@
<button type="submit" class="btn btn-ghost btn-sm">Сохранить</button>
</form>
</td>
<td class="mono" data-label="Хост">{{if .Hostname}}{{.Hostname}}{{else}}—{{end}}</td>
<td data-label="Статус"><span class="pill {{$b.Class}}">{{$b.Label}}</span></td>
<td data-label="Heartbeat">{{fmtTime .LastHeartbeatAt}}</td>
<td data-label="">
<div class="actions">
{{if .SiteID}}
<button class="btn btn-danger-ghost btn-sm" hx-delete="/sites/{{.Index}}" hx-target="#sites-table-wrap" hx-swap="innerHTML" hx-confirm="Освободить слот {{.Index}}?">Очистить</button>
{{end}}
<button class="btn btn-danger-ghost btn-sm" hx-delete="/sites/{{.Index}}" hx-target="#sites-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить слот {{.Index}} ({{.SiteID}})?">Удалить</button>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
{{if not .Items}}<p class="muted" style="padding:16px">Площадок пока нет — добавьте первую формой выше.</p>{{end}}
</div>
</div>
{{end}}