Run manual diagnostic attachments in the background
This commit is contained in:
1 parent
d845a5e4b6
commit
89ac4d5bcd
40 files changed
+1560
-58
No files matched your search
@@ -684,3 +684,43 @@ func (c *client) PutSubnets(ctx context.Context, in subnetList) (subnetList, err
|
||||
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/subnets", in, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) ListDiagnostics(ctx context.Context) ([]diagnosticDTO, error) {
|
||||
var out []diagnosticDTO
|
||||
err := c.do(ctx, http.MethodGet, "/api/v1/admin/diagnostics", nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) DiagnosticAttach(ctx context.Context, items []diagnosticAttachItem, note string) ([]diagnosticResult, error) {
|
||||
body := map[string]interface{}{"items": items, "note": note}
|
||||
var out struct {
|
||||
Results []diagnosticResult `json:"results"`
|
||||
}
|
||||
err := c.doLong(ctx, http.MethodPost, "/api/v1/admin/diagnostics/attach", body, &out)
|
||||
return out.Results, err
|
||||
}
|
||||
|
||||
func (c *client) StartDiagnosticOperation(ctx context.Context, id string, items []diagnosticAttachItem, note string) error {
|
||||
body := map[string]interface{}{"id": id, "items": items, "note": note}
|
||||
return c.do(ctx, http.MethodPost, "/api/v1/admin/diagnostics/operations", body, nil)
|
||||
}
|
||||
|
||||
func (c *client) GetDiagnosticOperation(ctx context.Context, id string) (diagnosticOperation, error) {
|
||||
out := diagnosticOperation{ID: id}
|
||||
err := c.do(ctx, http.MethodGet, "/api/v1/admin/diagnostics/operations/"+url.PathEscape(id), nil, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (c *client) DiagnosticDetach(ctx context.Context, addresses []string, all bool) ([]diagnosticResult, error) {
|
||||
var body map[string]interface{}
|
||||
if all {
|
||||
body = map[string]interface{}{"all": true}
|
||||
} else {
|
||||
body = map[string]interface{}{"addresses": addresses}
|
||||
}
|
||||
var out struct {
|
||||
Results []diagnosticResult `json:"results"`
|
||||
}
|
||||
err := c.doLong(ctx, http.MethodPost, "/api/v1/admin/diagnostics/detach", body, &out)
|
||||
return out.Results, err
|
||||
}
|
||||
@@ -506,3 +506,26 @@ func (a autoCycleDTO) OutcomePillClass() string {
|
||||
return "pill-neutral"
|
||||
}
|
||||
}
|
||||
|
||||
// diagnosticDTO is one address held in diagnostic mode.
|
||||
type diagnosticDTO struct {
|
||||
Address string `json:"address"`
|
||||
ValidatorID string `json:"validator_id"`
|
||||
FIPID string `json:"fip_id"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// diagnosticResult is the per-address outcome of an attach/detach call.
|
||||
type diagnosticResult struct {
|
||||
Address string `json:"address"`
|
||||
Status string `json:"status"`
|
||||
ValidatorID string `json:"validator_id"`
|
||||
FIPID string `json:"fip_id"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type diagnosticAttachItem struct {
|
||||
Address string `json:"address"`
|
||||
ValidatorID string `json:"validator_id,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
type diagRow struct {
|
||||
diagnosticDTO
|
||||
Duration string
|
||||
}
|
||||
|
||||
type diagnosticOperation struct {
|
||||
ID string `json:"id"`
|
||||
Items []diagnosticResult `json:"items"`
|
||||
Poll bool `json:"-"`
|
||||
Immediate bool `json:"-"`
|
||||
Message string `json:"-"`
|
||||
RetryID string `json:"-"`
|
||||
NextKey string `json:"-"`
|
||||
}
|
||||
|
||||
type diagnosticsPageData struct {
|
||||
PageData
|
||||
Rows []diagRow
|
||||
FreeValidators []validatorDTO
|
||||
Operation diagnosticOperation
|
||||
OperationKey string
|
||||
}
|
||||
|
||||
func (s *Server) diagnosticRows(r *http.Request) ([]diagRow, error) {
|
||||
start := time.Now()
|
||||
items, err := s.CA.ListDiagnostics(r.Context())
|
||||
s.logDiagnosticRequest(r.URL.Query().Get("operation"), "list_holds", start, err)
|
||||
now := time.Now()
|
||||
var rows []diagRow
|
||||
for _, it := range items {
|
||||
rows = append(rows, diagRow{diagnosticDTO: it, Duration: fmtDuration(now.Sub(it.CreatedAt))})
|
||||
}
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (s *Server) diagnosticValidators(r *http.Request) ([]validatorDTO, error) {
|
||||
start := time.Now()
|
||||
items, err := s.CA.ListValidators(r.Context())
|
||||
s.logDiagnosticRequest(r.URL.Query().Get("operation"), "list_validators", start, err)
|
||||
var validators []validatorDTO
|
||||
for _, v := range items {
|
||||
if v.State == "idle" && v.OSPortID != "" {
|
||||
validators = append(validators, v)
|
||||
}
|
||||
}
|
||||
return validators, err
|
||||
}
|
||||
|
||||
func (s *Server) logDiagnosticRequest(id, stage string, start time.Time, err error) {
|
||||
s.Log.Info("diagnostic dashboard request", "operation_id", id, "stage", stage, "duration_ms", time.Since(start).Milliseconds(), "err", err)
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsPage(w http.ResponseWriter, r *http.Request) {
|
||||
var data diagnosticsPageData
|
||||
rows, rowsErr := s.diagnosticRows(r)
|
||||
vals, valsErr := s.diagnosticValidators(r)
|
||||
data.Rows, data.FreeValidators = rows, vals
|
||||
data.ActiveNav = "diagnostics"
|
||||
data.Banner = bannerFor(errors.Join(rowsErr, valsErr))
|
||||
data.OperationKey = rand.Text()
|
||||
if id := r.URL.Query().Get("operation"); id != "" {
|
||||
data.Operation = diagnosticOperation{ID: id, Poll: true, Immediate: true}
|
||||
}
|
||||
s.renderPage(w, r, "diagnostics_page", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsHolds(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := s.diagnosticRows(r)
|
||||
if err != nil {
|
||||
w.Header().Set("HX-Reswap", "none")
|
||||
s.renderDiagnosticsTemplate(w, "error_banner", bannerFor(err))
|
||||
return
|
||||
}
|
||||
s.renderDiagnosticsTemplate(w, "diagnostics_holds", diagnosticsPageData{Rows: rows})
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsValidators(w http.ResponseWriter, r *http.Request) {
|
||||
validators, err := s.diagnosticValidators(r)
|
||||
if err != nil {
|
||||
w.Header().Set("HX-Reswap", "none")
|
||||
s.renderDiagnosticsTemplate(w, "error_banner", bannerFor(err))
|
||||
return
|
||||
}
|
||||
s.renderDiagnosticsTemplate(w, "diagnostics_validators", diagnosticsPageData{FreeValidators: validators})
|
||||
}
|
||||
|
||||
func diagnosticForm(r *http.Request) ([]diagnosticAttachItem, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, fmt.Errorf("invalid form: %w", err)
|
||||
}
|
||||
addrs := splitList(r.PostFormValue("addresses"))
|
||||
if len(addrs) == 0 {
|
||||
return nil, &apiErr{Status: http.StatusBadRequest, Message: "укажите хотя бы один адрес"}
|
||||
}
|
||||
items := make([]diagnosticAttachItem, len(addrs))
|
||||
for i, addr := range addrs {
|
||||
items[i].Address = addr
|
||||
}
|
||||
// A chosen validator goes to the first address only.
|
||||
items[0].ValidatorID = r.PostFormValue("validator_id")
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (s *Server) renderDiagnosticsTemplate(w http.ResponseWriter, name string, data any) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
|
||||
s.Log.Error("render diagnostics", "template", name, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func diagnosticChanged(w http.ResponseWriter, id string) {
|
||||
event, _ := json.Marshal(map[string]map[string]string{"diagnostics-changed": {"operation": id}})
|
||||
w.Header().Set("HX-Trigger-After-Swap", string(event))
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsAttach(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := diagnosticForm(r)
|
||||
var results []diagnosticResult
|
||||
if err == nil {
|
||||
results, err = s.CA.DiagnosticAttach(r.Context(), items, r.PostFormValue("note"))
|
||||
}
|
||||
diagnosticChanged(w, "")
|
||||
s.renderFragment(w, "diagnostics_results", results, err)
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsStart(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := diagnosticForm(r)
|
||||
if err != nil {
|
||||
s.renderFragment(w, "diagnostics_operation", diagnosticOperation{}, err)
|
||||
return
|
||||
}
|
||||
id := r.PostFormValue("operation_id")
|
||||
start := time.Now()
|
||||
err = s.CA.StartDiagnosticOperation(r.Context(), id, items, r.PostFormValue("note"))
|
||||
s.logDiagnosticRequest(id, "start_operation", start, err)
|
||||
if err != nil {
|
||||
op := diagnosticOperation{}
|
||||
var ae *apiErr
|
||||
if errors.As(err, &ae) && (ae.Status == 0 || ae.Status >= 500) {
|
||||
op.Message = "Запуск операции пока не подтверждён. Можно проверить её статус или повторить отправку."
|
||||
op.RetryID = id
|
||||
}
|
||||
s.renderFragment(w, "diagnostics_operation", op, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("HX-Replace-Url", "/diagnostics?operation="+url.QueryEscape(id))
|
||||
op := diagnosticOperation{ID: id, Poll: true, Immediate: true, NextKey: rand.Text()}
|
||||
for _, item := range items {
|
||||
op.Items = append(op.Items, diagnosticResult{Address: item.Address, Status: "queued"})
|
||||
}
|
||||
s.renderFragment(w, "diagnostics_operation", op, nil)
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsOperation(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
id := r.PathValue("id")
|
||||
op, err := s.CA.GetDiagnosticOperation(r.Context(), id)
|
||||
if err != nil {
|
||||
op.Message = "Не удалось получить статус операции."
|
||||
var ae *apiErr
|
||||
if errors.As(err, &ae) {
|
||||
switch {
|
||||
case ae.Status == http.StatusNotFound:
|
||||
op.Message = "Операция не найдена."
|
||||
case ae.Status == 0 || ae.Status >= 500:
|
||||
op.Poll = true
|
||||
op.Message = "Статус временно недоступен. Продолжаем проверять…"
|
||||
}
|
||||
}
|
||||
s.renderDiagnosticsTemplate(w, "diagnostics_operation", op)
|
||||
return
|
||||
}
|
||||
for _, item := range op.Items {
|
||||
if item.Status == "queued" || item.Status == "running" {
|
||||
op.Poll = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !op.Poll {
|
||||
diagnosticChanged(w, id)
|
||||
}
|
||||
s.renderDiagnosticsTemplate(w, "diagnostics_operation", op)
|
||||
}
|
||||
|
||||
func (s *Server) handleDiagnosticsDetach(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
s.renderFragment(w, "diagnostics_results", nil, fmt.Errorf("invalid form: %w", err))
|
||||
return
|
||||
}
|
||||
all := r.PostFormValue("all") != ""
|
||||
var addrs []string
|
||||
for _, v := range r.PostForm["addresses"] {
|
||||
addrs = append(addrs, splitList(v)...)
|
||||
}
|
||||
if !all && len(addrs) == 0 {
|
||||
s.renderFragment(w, "diagnostics_results", nil, &apiErr{Status: http.StatusBadRequest, Message: "выберите хотя бы один адрес"})
|
||||
return
|
||||
}
|
||||
results, err := s.CA.DiagnosticDetach(r.Context(), addrs, all)
|
||||
diagnosticChanged(w, "")
|
||||
s.renderFragment(w, "diagnostics_results", results, err)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// newDiagAPI is a minimal control-api serving the diagnostics endpoints.
|
||||
func newDiagAPI(t *testing.T, attachBody *string) string {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/admin/diagnostics", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, []diagnosticDTO{{Address: "203.0.113.5", ValidatorID: "vkiplab-v1", FIPID: "fip-1", Note: "проверка", CreatedAt: time.Now().Add(-time.Hour)}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/admin/config/validators", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, []validatorDTO{
|
||||
{ValidatorID: "vkiplab-v2", OSPortID: "port-2", State: "idle"},
|
||||
{ValidatorID: "vkiplab-v3", OSPortID: "", State: "idle"},
|
||||
{ValidatorID: "vkiplab-v4", OSPortID: "port-4", State: "checking"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/admin/diagnostics/attach", func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
*attachBody = string(b)
|
||||
mu.Unlock()
|
||||
writeJSON(w, 200, map[string]interface{}{"results": []diagnosticResult{
|
||||
{Address: "203.0.113.5", Status: "attached", ValidatorID: "vkiplab-v2"},
|
||||
{Address: "203.0.113.6", Status: "rejected", Reason: "нет свободных валидаторов"},
|
||||
}})
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
t.Cleanup(ts.Close)
|
||||
return ts.URL
|
||||
}
|
||||
|
||||
func TestDiagnosticsPageRendersList(t *testing.T) {
|
||||
var sent string
|
||||
ts := newTestServer(t, newDiagAPI(t, &sent))
|
||||
body := get(t, ts, "/diagnostics")
|
||||
for _, want := range []string{"203.0.113.5", "vkiplab-v1", "fip-1", "проверка", "Отвязать"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("expected %q in page, got:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(body, `value="vkiplab-v2"`) || strings.Contains(body, `value="vkiplab-v3"`) || strings.Contains(body, `value="vkiplab-v4"`) {
|
||||
t.Fatalf("dropdown must hold only idle validators with a port, got:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnosticsAttachBodyAndRejectedReason(t *testing.T) {
|
||||
var sent string
|
||||
ts := newTestServer(t, newDiagAPI(t, &sent))
|
||||
body := postForm(t, ts, "POST", "/diagnostics/attach", url.Values{
|
||||
"addresses": {"203.0.113.5\n203.0.113.6"},
|
||||
"validator_id": {"vkiplab-v2"},
|
||||
"note": {"n1"},
|
||||
})
|
||||
var got struct {
|
||||
Items []diagnosticAttachItem `json:"items"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(sent), &got); err != nil {
|
||||
t.Fatalf("attach body: %v (%q)", err, sent)
|
||||
}
|
||||
if len(got.Items) != 2 || got.Items[0].ValidatorID != "vkiplab-v2" || got.Items[1].ValidatorID != "" || got.Note != "n1" {
|
||||
t.Fatalf("unexpected attach body: %s", sent)
|
||||
}
|
||||
if !strings.Contains(body, "привязан к vkiplab-v2") || !strings.Contains(body, "нет свободных валидаторов") {
|
||||
t.Fatalf("expected attached and rejected results, got:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnosticsOperationRefreshesListsAfterResult(t *testing.T) {
|
||||
const opID = "diagnostic-operation-test"
|
||||
var lists, statusCalls atomic.Int32
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/admin/diagnostics/operations", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.ID != opID {
|
||||
t.Errorf("start operation: %+v, %v", body, err)
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"id": opID})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/admin/diagnostics/operations/"+opID, func(w http.ResponseWriter, r *http.Request) {
|
||||
status := "running"
|
||||
if statusCalls.Add(1) == 2 {
|
||||
status = "attached"
|
||||
}
|
||||
writeJSON(w, http.StatusOK, diagnosticOperation{
|
||||
ID: opID, Items: []diagnosticResult{{Address: "203.0.113.5", Status: status, ValidatorID: "vkiplab-v1"}},
|
||||
})
|
||||
})
|
||||
for _, path := range []string{"/api/v1/admin/diagnostics", "/api/v1/admin/config/validators"} {
|
||||
mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
|
||||
lists.Add(1)
|
||||
writeJSON(w, 200, []struct{}{})
|
||||
})
|
||||
}
|
||||
api := httptest.NewServer(mux)
|
||||
t.Cleanup(api.Close)
|
||||
ts := newTestServer(t, api.URL)
|
||||
form := url.Values{"operation_id": {opID}, "addresses": {"203.0.113.5"}}
|
||||
body := postForm(t, ts, "POST", "/diagnostics/operations", form)
|
||||
if !strings.Contains(body, "В очереди") || !strings.Contains(body, "load, every 1s") {
|
||||
t.Fatalf("missing initial progress: %s", body)
|
||||
}
|
||||
body = get(t, ts, "/diagnostics/operations/"+opID)
|
||||
if !strings.Contains(body, "Привязываем…") || !strings.Contains(body, "every 1s") {
|
||||
t.Fatalf("missing running progress: %s", body)
|
||||
}
|
||||
resp, err := ts.Client().Get(ts.URL + "/diagnostics/operations/" + opID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
completed, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if err != nil || !strings.Contains(string(completed), "привязан к vkiplab-v1") || strings.Contains(string(completed), "every 1s") {
|
||||
t.Fatalf("wrong terminal fragment: %s, %v", completed, err)
|
||||
}
|
||||
if event := resp.Header.Get("HX-Trigger-After-Swap"); !strings.Contains(event, opID) || lists.Load() != 0 {
|
||||
t.Fatalf("refresh event=%q, premature list requests=%d", event, lists.Load())
|
||||
}
|
||||
body = get(t, ts, "/diagnostics?operation="+opID)
|
||||
if !strings.Contains(body, `hx-get="/diagnostics/operations/`+opID+`"`) {
|
||||
t.Fatalf("page refresh lost the operation: %s", body)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package dashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -122,6 +123,39 @@ type ipsPageData struct {
|
||||
type ipDetailData struct {
|
||||
PageData
|
||||
Detail ipDetailResponse
|
||||
Events []eventView
|
||||
}
|
||||
|
||||
// tracerouteView is a parsed traceroute_result event payload.
|
||||
type tracerouteView struct {
|
||||
Target string `json:"target"`
|
||||
Host string `json:"host"`
|
||||
IP string `json:"ip"`
|
||||
Status string `json:"status"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// eventView is an event plus, for traceroute_result, its parsed payload
|
||||
// (nil = render the raw payload as for any other event).
|
||||
type eventView struct {
|
||||
event
|
||||
Trace *tracerouteView
|
||||
}
|
||||
|
||||
func buildEventViews(events []event) []eventView {
|
||||
out := make([]eventView, len(events))
|
||||
for i, e := range events {
|
||||
out[i].event = e
|
||||
if e.EventType == "traceroute_result" {
|
||||
var t tracerouteView
|
||||
if json.Unmarshal([]byte(e.Payload), &t) == nil {
|
||||
out[i].Trace = &t
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// loadIPsData fetches the page of the queue selected by the request's
|
||||
@@ -193,7 +227,7 @@ func (s *Server) handleIPsPage(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) handleIPDetail(w http.ResponseWriter, r *http.Request) {
|
||||
ip := r.PathValue("ip")
|
||||
detail, err := s.CA.GetIP(r.Context(), ip)
|
||||
data := ipDetailData{Detail: detail}
|
||||
data := ipDetailData{Detail: detail, Events: buildEventViews(detail.Events)}
|
||||
data.ActiveNav = "ips"
|
||||
data.Banner = bannerFor(err)
|
||||
s.renderPage(w, r, "ip_detail_page", data)
|
||||
|
||||
@@ -47,6 +47,9 @@ type overviewData struct {
|
||||
// nil when the scan status is unavailable.
|
||||
AutoCycle *autoCycleDTO
|
||||
Scan *scanStatusDTO
|
||||
// Diagnostics is the number of addresses held in diagnostic mode (0 when
|
||||
// none or when the list could not be fetched — the line is then omitted).
|
||||
Diagnostics int
|
||||
}
|
||||
|
||||
func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
|
||||
@@ -106,6 +109,11 @@ func (s *Server) loadOverview(r *http.Request) (overviewData, error) {
|
||||
} else if sc.Running {
|
||||
data.Scan = &sc
|
||||
}
|
||||
if diag, dErr := s.CA.ListDiagnostics(ctx); dErr != nil {
|
||||
s.Log.Warn("overview: diagnostics list unavailable", "err", dErr)
|
||||
} else {
|
||||
data.Diagnostics = len(diag)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,14 @@ func (s *Server) routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /analytics/compare/lists/{group}", s.handleAnalyticsCompareList)
|
||||
mux.HandleFunc("GET /analytics/compare/csv/{group}", s.handleAnalyticsCompareCSV)
|
||||
|
||||
mux.HandleFunc("GET /diagnostics", s.handleDiagnosticsPage)
|
||||
mux.HandleFunc("POST /diagnostics/attach", s.handleDiagnosticsAttach)
|
||||
mux.HandleFunc("POST /diagnostics/detach", s.handleDiagnosticsDetach)
|
||||
mux.HandleFunc("POST /diagnostics/operations", s.handleDiagnosticsStart)
|
||||
mux.HandleFunc("GET /diagnostics/operations/{id}", s.handleDiagnosticsOperation)
|
||||
mux.HandleFunc("GET /diagnostics/holds", s.handleDiagnosticsHolds)
|
||||
mux.HandleFunc("GET /diagnostics/validators", s.handleDiagnosticsValidators)
|
||||
|
||||
mux.HandleFunc("GET /validators", s.handleValidatorsPage)
|
||||
mux.HandleFunc("POST /validators", s.handleValidatorCreate)
|
||||
mux.HandleFunc("PUT /validators/{id}", s.handleValidatorUpdate)
|
||||
|
||||
@@ -718,3 +718,5 @@ table.compact td, table.compact th { padding-top: 6px; padding-bottom: 6px; }
|
||||
.settings-tls-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.settings-tls-row .btn { grid-column: 1 / -1; justify-self: end; }
|
||||
}
|
||||
|
||||
.trace-output { margin: 6px 0 0; padding: 8px 10px; max-height: 320px; overflow: auto; white-space: pre-wrap; word-break: break-all; font-family: var(--font-mono); font-size: 12px; background: var(--surface-2, rgba(127,127,127,.12)); border-radius: 6px; }
|
||||
@@ -0,0 +1,61 @@
|
||||
(() => {
|
||||
const form = document.getElementById("diagnostics-attach");
|
||||
const submit = document.getElementById("diagnostics-submit");
|
||||
const connection = document.getElementById("diagnostics-connection");
|
||||
const operation = () => document.getElementById("diagnostics-operation");
|
||||
const statusLink = connection.querySelector("a");
|
||||
let sending = false;
|
||||
|
||||
function updateSubmit() {
|
||||
const current = operation();
|
||||
if (current) {
|
||||
submit.disabled = sending || current.dataset.pending === "true";
|
||||
}
|
||||
}
|
||||
|
||||
document.body.addEventListener("htmx:configRequest", (event) => {
|
||||
const { triggeringEvent, parameters } = event.detail;
|
||||
if (triggeringEvent?.type === "diagnostics-changed") {
|
||||
parameters.operation = triggeringEvent.detail.operation;
|
||||
}
|
||||
});
|
||||
document.body.addEventListener("htmx:beforeRequest", (event) => {
|
||||
if (event.detail.elt === form) {
|
||||
if (sending || operation()?.dataset.pending === "true") {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
sending = true;
|
||||
connection.hidden = true;
|
||||
}
|
||||
});
|
||||
|
||||
document.body.addEventListener("htmx:afterSettle", (event) => {
|
||||
if (event.detail.elt.id === "diagnostics-operation") {
|
||||
updateSubmit();
|
||||
connection.hidden = true;
|
||||
}
|
||||
});
|
||||
document.body.addEventListener("htmx:afterRequest", (event) => {
|
||||
if (event.detail.requestConfig.elt === form) {
|
||||
sending = false;
|
||||
updateSubmit();
|
||||
}
|
||||
});
|
||||
|
||||
for (const name of ["htmx:sendError", "htmx:timeout", "htmx:responseError"]) {
|
||||
document.body.addEventListener(name, (event) => {
|
||||
const source = event.detail.requestConfig?.elt;
|
||||
if (source === form) {
|
||||
connection.firstElementChild.textContent = "Запуск пока не подтверждён. Можно повторить отправку.";
|
||||
statusLink.href = "/diagnostics?operation=" + encodeURIComponent(document.getElementById("diagnostics-key").value);
|
||||
statusLink.hidden = false;
|
||||
connection.hidden = false;
|
||||
} else if (source?.id === "diagnostics-operation") {
|
||||
connection.firstElementChild.textContent = "Связь со страницей статуса прервалась. Продолжаем проверять…";
|
||||
statusLink.hidden = true;
|
||||
connection.hidden = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,131 @@
|
||||
{{define "diagnostics_page"}}
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>{{template "html_head" .}}<script src="/static/diagnostics.js" defer></script></head>
|
||||
<body>
|
||||
<div class="bg-grid"></div>
|
||||
<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>
|
||||
<div class="topbar"><h1>Диагностика</h1></div>
|
||||
{{template "diagnostics_form" .}}
|
||||
{{template "diagnostics_operation" .Operation}}
|
||||
<div id="diagnostics-action-result" aria-live="polite"></div>
|
||||
{{template "diagnostics_holds" .}}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
|
||||
{{define "diagnostics_form"}}
|
||||
<div class="panel">
|
||||
<div class="panel-body">
|
||||
<form id="diagnostics-attach" hx-post="/diagnostics/operations" hx-target="#diagnostics-operation" hx-swap="outerHTML"
|
||||
hx-disabled-elt="#diagnostics-submit" hx-indicator="#diagnostics-sending">
|
||||
<input type="hidden" id="diagnostics-key" name="operation_id" value="{{.OperationKey}}">
|
||||
<div class="field-row">
|
||||
<div class="field" style="flex: 1 1 320px;">
|
||||
<label for="diag-addresses">Адреса (по одному на строку или через запятую)</label>
|
||||
<textarea id="diag-addresses" name="addresses" rows="2" placeholder="203.0.113.10 203.0.113.11" required></textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="diag-validator">Валидатор</label>
|
||||
{{template "diagnostics_validators" .}}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="diag-note">Заметка</label>
|
||||
<input type="text" id="diag-note" name="note">
|
||||
</div>
|
||||
<button id="diagnostics-submit" type="submit" class="btn btn-primary"{{if .Operation.Poll}} disabled{{end}}>Привязать</button>
|
||||
<span id="diagnostics-sending" class="htmx-indicator" role="status">Отправляем запрос…</span>
|
||||
<span id="diagnostics-connection" role="status" hidden><span></span> <a hidden>Проверить статус</a></span>
|
||||
</div>
|
||||
</form>
|
||||
<p class="muted" style="margin-top:8px">На время диагностики валидатор не берёт задания. Команды (traceroute, curl, tcpdump)
|
||||
выполняются вручную по SSH на валидаторе. После работы адрес нужно отвязать. Если выбран конкретный валидатор, а адресов
|
||||
несколько, он назначается первому адресу, остальные уходят на любые свободные.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{end}}
|
||||
|
||||
{{define "diagnostics_validators"}}
|
||||
<select id="diag-validator" name="validator_id" hx-get="/diagnostics/validators"
|
||||
hx-trigger="diagnostics-changed from:body" hx-swap="outerHTML">
|
||||
<option value="">любой свободный</option>
|
||||
{{range .FreeValidators}}<option value="{{.ValidatorID}}">{{.ValidatorID}} ({{.OSPortID}})</option>{{end}}
|
||||
</select>
|
||||
{{end}}
|
||||
|
||||
{{define "diagnostics_operation"}}
|
||||
<section id="diagnostics-operation" aria-live="polite"
|
||||
{{if .Poll}}data-pending="true" hx-get="/diagnostics/operations/{{.ID}}"
|
||||
hx-trigger="{{if .Immediate}}load, {{end}}every 1s" hx-swap="outerHTML"{{end}}>
|
||||
{{if .Message}}<p role="status">{{.Message}}{{if .RetryID}} <a href="/diagnostics?operation={{.RetryID}}">Проверить статус</a>{{end}}</p>{{end}}
|
||||
{{if and .Poll (not .Items) (not .Message)}}<p role="status">Проверяем статус операции…</p>{{end}}
|
||||
{{template "diagnostics_results" .Items}}
|
||||
</section>
|
||||
{{if .NextKey}}<input type="hidden" id="diagnostics-key" name="operation_id" value="{{.NextKey}}" hx-swap-oob="outerHTML">{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "diagnostics_results"}}
|
||||
{{if .}}
|
||||
<h2 class="section-title">Результат операции</h2>
|
||||
<div class="panel">
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th>Адрес</th><th>Результат</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .}}
|
||||
<tr>
|
||||
<td class="mono" data-label="Адрес">{{.Address}}</td>
|
||||
<td data-label="Результат">{{if eq .Status "queued"}}<span class="pill">В очереди</span>{{else if eq .Status "running"}}<span class="pill">Привязываем…</span> {{.Reason}}{{else if eq .Status "attached"}}<span class="pill pill-success">привязан к {{.ValidatorID}}</span>{{else if eq .Status "detached"}}<span class="pill pill-success">отвязан</span>{{else}}<span class="pill pill-danger">отказ</span> {{.Reason}}{{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "diagnostics_holds"}}
|
||||
<div id="diagnostics-wrap" hx-get="/diagnostics/holds" hx-trigger="diagnostics-changed from:body"
|
||||
hx-swap="outerHTML">
|
||||
<h2 class="section-title">Удерживаемые адреса</h2>
|
||||
{{if .Rows}}
|
||||
<form id="diag-list" hx-post="/diagnostics/detach" hx-target="#diagnostics-action-result" hx-swap="innerHTML" hx-confirm="Отвязать выбранные адреса?">
|
||||
<div class="actions" style="margin-bottom:8px">
|
||||
<button type="submit" class="btn btn-ghost btn-sm">Отвязать выбранные</button>
|
||||
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/diagnostics/detach" hx-vals='{"all":"1"}' hx-target="#diagnostics-action-result" hx-swap="innerHTML" hx-confirm="Отвязать все адреса ({{len .Rows}})?">Отвязать все</button>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<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>fip_id</th><th>С какого времени</th><th>Заметка</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Rows}}
|
||||
<tr>
|
||||
<td data-label=""><input type="checkbox" name="addresses" value="{{.Address}}"></td>
|
||||
<td class="mono" data-label="Адрес">{{.Address}}</td>
|
||||
<td class="mono" data-label="Валидатор">{{.ValidatorID}}</td>
|
||||
<td class="mono" data-label="fip_id">{{.FIPID}}</td>
|
||||
<td data-label="С какого времени">{{fmtTime .CreatedAt}} ({{.Duration}})</td>
|
||||
<td data-label="Заметка">{{if .Note}}{{.Note}}{{else}}—{{end}}</td>
|
||||
<td data-label=""><button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/diagnostics/detach" hx-vals='{"addresses":"{{.Address}}"}' hx-target="#diagnostics-action-result" hx-swap="innerHTML" hx-confirm="Отвязать {{.Address}}?">Отвязать</button></td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{{else}}<p class="muted">Удерживаемых адресов нет.</p>{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -57,14 +57,14 @@
|
||||
{{else}}<p class="muted">Проверок пока нет.</p>{{end}}
|
||||
|
||||
<h2 class="section-title">События</h2>
|
||||
{{if .Detail.Events}}
|
||||
{{if .Events}}
|
||||
<div class="panel">
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th>Время</th><th>Тип</th><th>Источник</th><th>Данные</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Detail.Events}}
|
||||
<tr><td class="num" data-label="Время">{{fmtTime .OccurredAt}}</td><td data-label="Тип">{{.EventType}}</td><td data-label="Источник">{{.SourceType}} {{.SourceID}}</td><td data-label="Данные">{{.Payload}}</td></tr>
|
||||
{{range .Events}}
|
||||
<tr><td class="num" data-label="Время">{{fmtTime .OccurredAt}}</td><td data-label="Тип">{{.EventType}}</td><td data-label="Источник">{{.SourceType}} {{.SourceID}}</td><td data-label="Данные">{{with .Trace}}<div>цель {{.Target}}{{if .Host}} ({{.Host}}){{end}} · IP {{.IP}} · {{.Status}} · {{.DurationMS}} мс{{if .Error}} · ошибка: {{.Error}}{{end}}</div>{{if .Output}}<pre class="trace-output">{{.Output}}</pre>{{end}}{{else}}{{.Payload}}{{end}}</td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -75,6 +75,10 @@
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></svg>
|
||||
Аналитика
|
||||
</a>
|
||||
<a class="nav-link{{if eq .ActiveNav "diagnostics"}} active{{end}}" {{if eq .ActiveNav "diagnostics"}}aria-current="page"{{end}} href="/diagnostics">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
|
||||
Диагностика
|
||||
</a>
|
||||
<div class="nav-group-title">Настройка</div>
|
||||
<a class="nav-link{{if eq .ActiveNav "validators"}} active{{end}}" {{if eq .ActiveNav "validators"}}aria-current="page"{{end}} href="/validators">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="3" width="16" height="7" rx="1.5"/><rect x="4" y="14" width="16" height="7" rx="1.5"/><circle cx="8" cy="6.5" r="1"/><circle cx="8" cy="17.5" r="1"/></svg>
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
{{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}}
|
||||
{{if .Diagnostics}}
|
||||
<p class="muted" id="overview-diagnostics" style="margin-top:8px">На диагностике: <a href="/diagnostics">{{.Diagnostics}}</a></p>
|
||||
{{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}}
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
<td data-label="Heartbeat">{{fmtTime .LastHeartbeatAt}}</td>
|
||||
<td data-label="">
|
||||
<div class="actions">
|
||||
<button class="btn btn-danger-ghost btn-sm" hx-delete="/validators/{{.ValidatorID}}" hx-target="#validators-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить валидатор {{.ValidatorID}}?">Удалить</button>
|
||||
{{if eq .State "diagnostic"}}<a class="btn btn-ghost btn-sm" href="/diagnostics">Диагностика</a>{{else}}<button class="btn btn-danger-ghost btn-sm" hx-delete="/validators/{{.ValidatorID}}" hx-target="#validators-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить валидатор {{.ValidatorID}}?">Удалить</button>{{end}}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -59,6 +59,9 @@ var diagnosticHoldsSchema string
|
||||
//go:embed migrations/0015_inbound_tls_checks.sql
|
||||
var inboundTLSChecksSchema string
|
||||
|
||||
//go:embed migrations/0016_diagnostic_operations.sql
|
||||
var diagnosticOperationsSchema string
|
||||
|
||||
// migrations is the ordered list of schema versions. Each entry's SQL is
|
||||
// applied, in order, for any version greater than the database's current
|
||||
// PRAGMA user_version — so a fresh database walks the whole list and an
|
||||
@@ -82,6 +85,7 @@ var migrations = []struct {
|
||||
{13, dropChecksIndexSchema},
|
||||
{14, diagnosticHoldsSchema},
|
||||
{15, inboundTLSChecksSchema},
|
||||
{16, diagnosticOperationsSchema},
|
||||
}
|
||||
|
||||
// connPragmas are applied to every new connection. A larger WAL checkpoint
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE diagnostic_operations (
|
||||
id TEXT PRIMARY KEY,
|
||||
note TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE diagnostic_operation_items (
|
||||
id INTEGER PRIMARY KEY,
|
||||
operation_id TEXT NOT NULL REFERENCES diagnostic_operations(id),
|
||||
address TEXT NOT NULL,
|
||||
requested_validator TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'queued' CHECK(status IN ('queued', 'running', 'attached', 'rejected')),
|
||||
validator_id TEXT NOT NULL DEFAULT '',
|
||||
port_id TEXT NOT NULL DEFAULT '',
|
||||
fip_id TEXT NOT NULL DEFAULT '',
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
retry_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_diagnostic_operation_items ON diagnostic_operation_items(operation_id, id);
|
||||
CREATE INDEX idx_diagnostic_pending ON diagnostic_operation_items(id) WHERE status IN ('queued', 'running');
|
||||
ALTER TABLE diagnostic_holds ADD COLUMN pending_item_id INTEGER REFERENCES diagnostic_operation_items(id);
|
||||
CREATE UNIQUE INDEX idx_diagnostic_pending_hold ON diagnostic_holds(pending_item_id) WHERE pending_item_id IS NOT NULL;
|
||||
@@ -20,16 +20,43 @@ type DiagnosticHold struct {
|
||||
// the hold, in one transaction. ErrNotFound: no such validator; ErrBusy: the
|
||||
// validator is not idle; ErrConflict: the address or validator is already held.
|
||||
func (d *DB) ClaimDiagnostic(ctx context.Context, validatorID, address, fipID, note string) error {
|
||||
return d.claimDiagnostic(ctx, validatorID, address, fipID, note, nil)
|
||||
}
|
||||
|
||||
func (d *DB) claimDiagnostic(ctx context.Context, validatorID, address, fipID, note string, item *DiagnosticOperationItem) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
now := timeToDB(Now())
|
||||
var active bool
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM ip_queue WHERE ip_address=? AND state IN (?, ?, ?, ?))
|
||||
`, address, IPAssigningFIP, IPAwaitingSelfCheck, IPChecking, IPAggregating).Scan(&active)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if active {
|
||||
return fmt.Errorf("address %q is being checked: %w", address, ErrBusy)
|
||||
}
|
||||
var held bool
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM diagnostic_holds WHERE address=? OR validator_id=?)
|
||||
`, address, validatorID).Scan(&held); err != nil {
|
||||
return err
|
||||
}
|
||||
if held {
|
||||
return fmt.Errorf("address %q or validator %q is already held: %w", address, validatorID, ErrConflict)
|
||||
}
|
||||
var expectedPort string
|
||||
if item != nil {
|
||||
expectedPort = item.PortID
|
||||
}
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
UPDATE validators SET state=?, updated_at=?
|
||||
WHERE validator_id=? AND state=? AND current_ip_id IS NULL
|
||||
`, ValidatorDiagnostic, now, validatorID, ValidatorIdle)
|
||||
WHERE validator_id=? AND state=? AND current_ip_id IS NULL AND (?='' OR os_port_id=?)
|
||||
`, ValidatorDiagnostic, now, validatorID, ValidatorIdle, expectedPort, expectedPort)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -42,12 +69,22 @@ func (d *DB) ClaimDiagnostic(ctx context.Context, validatorID, address, fipID, n
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("validator %q is not idle: %w", validatorID, ErrBusy)
|
||||
return fmt.Errorf("validator %q is no longer idle on the selected port: %w", validatorID, ErrBusy)
|
||||
}
|
||||
var pendingID *int64
|
||||
if item != nil {
|
||||
pendingID = &item.ID
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET validator_id=?, port_id=?, fip_id=? WHERE id=? AND status='running'
|
||||
`, validatorID, item.PortID, fipID, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at) VALUES (?, ?, ?, ?, ?)
|
||||
`, address, validatorID, fipID, note, now); err != nil {
|
||||
return fmt.Errorf("address %q or validator %q is already held: %w", address, validatorID, ErrConflict)
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`, address, validatorID, fipID, note, now, pendingID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -60,26 +97,37 @@ func (d *DB) ReleaseDiagnostic(ctx context.Context, address string) (*Diagnostic
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
h, err := scanHold(tx.QueryRowContext(ctx, holdSelect+` WHERE address=?`, address))
|
||||
h, err := scanHold(tx.QueryRowContext(ctx, holdSelect+` WHERE address=? AND pending_item_id IS NULL`, address))
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("address %q is not on diagnostic: %w", address, ErrNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE address=?`, address); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE address=? AND pending_item_id IS NULL`, address); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE validators SET state=?, updated_at=? WHERE validator_id=? AND state=?
|
||||
`, ValidatorIdle, timeToDB(Now()), h.ValidatorID, ValidatorDiagnostic); err != nil {
|
||||
if err := resetDiagnosticValidator(ctx, tx, h.ValidatorID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h, tx.Commit()
|
||||
}
|
||||
|
||||
func resetDiagnosticValidator(ctx context.Context, tx *sql.Tx, validatorID string) error {
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE validators SET state=?, updated_at=? WHERE validator_id=? AND state=?
|
||||
`, ValidatorIdle, timeToDB(Now()), validatorID, ValidatorDiagnostic)
|
||||
return err
|
||||
}
|
||||
|
||||
const holdSelect = `SELECT address, validator_id, fip_id, note, created_at FROM diagnostic_holds`
|
||||
|
||||
func (d *DB) HasDiagnosticHold(ctx context.Context, address string) (bool, error) {
|
||||
var exists bool
|
||||
err := d.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM diagnostic_holds WHERE address=?)`, address).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func scanHold(row rowScanner) (*DiagnosticHold, error) {
|
||||
var h DiagnosticHold
|
||||
var created string
|
||||
@@ -93,9 +141,9 @@ func scanHold(row rowScanner) (*DiagnosticHold, error) {
|
||||
return &h, nil
|
||||
}
|
||||
|
||||
// ListDiagnosticHolds returns all holds, oldest first.
|
||||
// ListDiagnosticHolds returns confirmed holds, oldest first.
|
||||
func (d *DB) ListDiagnosticHolds(ctx context.Context) ([]DiagnosticHold, error) {
|
||||
rows, err := d.QueryContext(ctx, holdSelect+` ORDER BY id`)
|
||||
rows, err := d.QueryContext(ctx, holdSelect+` WHERE pending_item_id IS NULL ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DiagnosticOperation struct {
|
||||
ID string `json:"id"`
|
||||
Items []DiagnosticOperationItem `json:"items"`
|
||||
}
|
||||
|
||||
type DiagnosticOperationItem struct {
|
||||
ID int64 `json:"-"`
|
||||
OperationID string `json:"-"`
|
||||
Note string `json:"-"`
|
||||
Address string `json:"address"`
|
||||
RequestedValidator string `json:"-"`
|
||||
Status string `json:"status"`
|
||||
ValidatorID string `json:"validator_id,omitempty"`
|
||||
PortID string `json:"-"`
|
||||
FIPID string `json:"fip_id,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
func (d *DB) CreateDiagnosticOperation(ctx context.Context, id, note, requestHash string, items []DiagnosticOperationItem) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_operations (id, note, request_hash, created_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO NOTHING
|
||||
`, id, note, requestHash, timeToDB(Now()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
var storedHash string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT request_hash FROM diagnostic_operations WHERE id=?`, id).Scan(&storedHash); err != nil {
|
||||
return err
|
||||
}
|
||||
if storedHash != requestHash {
|
||||
return fmt.Errorf("operation ID already used for a different request: %w", ErrConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, item := range items {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_operation_items (operation_id, address, requested_validator) VALUES (?, ?, ?)
|
||||
`, id, item.Address, item.RequestedValidator); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (d *DB) GetDiagnosticOperation(ctx context.Context, id string) (DiagnosticOperation, error) {
|
||||
op := DiagnosticOperation{ID: id}
|
||||
rows, err := d.QueryContext(ctx, `
|
||||
SELECT address, status, validator_id, fip_id, reason FROM diagnostic_operation_items
|
||||
WHERE operation_id=? ORDER BY id
|
||||
`, id)
|
||||
if err != nil {
|
||||
return op, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var item DiagnosticOperationItem
|
||||
if err := rows.Scan(&item.Address, &item.Status, &item.ValidatorID, &item.FIPID, &item.Reason); err != nil {
|
||||
return op, err
|
||||
}
|
||||
op.Items = append(op.Items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return op, err
|
||||
}
|
||||
if len(op.Items) == 0 {
|
||||
return op, ErrNotFound
|
||||
}
|
||||
return op, nil
|
||||
}
|
||||
|
||||
// NextDiagnosticOperationItem is called by the Control API's single worker.
|
||||
// A retrying item blocks only the later addresses in its own operation.
|
||||
func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperationItem, error) {
|
||||
var item DiagnosticOperationItem
|
||||
err := d.QueryRowContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET status='running'
|
||||
WHERE id=(
|
||||
SELECT i.id FROM diagnostic_operation_items i
|
||||
WHERE i.status IN ('queued', 'running') AND i.retry_at<=?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM diagnostic_operation_items earlier
|
||||
WHERE earlier.operation_id=i.operation_id AND earlier.id<i.id
|
||||
AND earlier.status IN ('queued', 'running')
|
||||
)
|
||||
ORDER BY i.id LIMIT 1
|
||||
)
|
||||
RETURNING id, operation_id, address, requested_validator, validator_id, port_id, fip_id,
|
||||
(SELECT note FROM diagnostic_operations WHERE id=diagnostic_operation_items.operation_id)
|
||||
`, Now().UnixMilli()).Scan(&item.ID, &item.OperationID, &item.Address, &item.RequestedValidator,
|
||||
&item.ValidatorID, &item.PortID, &item.FIPID, &item.Note)
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (d *DB) ReserveDiagnosticOperationItem(ctx context.Context, item DiagnosticOperationItem) error {
|
||||
return d.claimDiagnostic(ctx, item.ValidatorID, item.Address, item.FIPID, item.Note, &item)
|
||||
}
|
||||
|
||||
func (d *DB) RetryDiagnosticOperationItem(ctx context.Context, id int64, reason string, delay time.Duration) error {
|
||||
_, err := d.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET reason=?, retry_at=? WHERE id=? AND status='running'
|
||||
`, reason, Now().Add(delay).UnixMilli(), id)
|
||||
return err
|
||||
}
|
||||
|
||||
// FinishDiagnosticOperationItem commits the outcome together with its hold
|
||||
// and audit event, so recovery cannot publish a success twice.
|
||||
func (d *DB) FinishDiagnosticOperationItem(ctx context.Context, item DiagnosticOperationItem, reason string, event *Event) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
status := "rejected"
|
||||
if event != nil {
|
||||
status = "attached"
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE diagnostic_holds SET pending_item_id=NULL WHERE pending_item_id=?`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := insertEvent(ctx, tx, *event); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if item.FIPID != "" {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE pending_item_id=?`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := resetDiagnosticValidator(ctx, tx, item.ValidatorID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET status=?, reason=?, retry_at=0 WHERE id=? AND status='running'
|
||||
`, status, reason, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -10,7 +10,13 @@ import (
|
||||
// event stays traceable to its address (via registry_id) and prunable at
|
||||
// the right cycle boundary even after the ip_queue row itself is deleted.
|
||||
func (d *DB) InsertEvent(ctx context.Context, e Event) error {
|
||||
_, err := d.ExecContext(ctx, `
|
||||
return insertEvent(ctx, d, e)
|
||||
}
|
||||
|
||||
func insertEvent(ctx context.Context, q interface {
|
||||
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||
}, e Event) error {
|
||||
_, err := q.ExecContext(ctx, `
|
||||
INSERT INTO events (source_type, source_id, ip_id, registry_id, cycle_id, event_type, payload, occurred_at, created_at)
|
||||
VALUES (?, ?, ?, (SELECT registry_id FROM ip_queue WHERE id=?), COALESCE((SELECT cycle_id FROM ip_queue WHERE id=?), 0), ?, ?, ?, ?)
|
||||
`, e.SourceType, e.SourceID, e.IPID, e.IPID, e.IPID, e.EventType, e.Payload, timeToDB(e.OccurredAt), timeToDB(Now()))
|
||||
|
||||
@@ -391,7 +391,7 @@ func TestMigration0011BuildsRunsFromExistingData(t *testing.T) {
|
||||
}
|
||||
var ver int
|
||||
d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver)
|
||||
if ver != 15 {
|
||||
if ver != migrations[len(migrations)-1].version {
|
||||
t.Errorf("user_version = %d", ver)
|
||||
}
|
||||
}
|
||||
@@ -240,7 +240,7 @@ func TestMigration0010MarksRowsAfterVerdict(t *testing.T) {
|
||||
t.Errorf("ssh: after_verdict=%d recorded=%s created=%s", a, rec, cr)
|
||||
}
|
||||
var ver int
|
||||
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 15 {
|
||||
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != migrations[len(migrations)-1].version {
|
||||
t.Errorf("user_version=%d err=%v", ver, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ func TestRouteTableIsClassified(t *testing.T) {
|
||||
t.Fatalf("admin route %q is %s, want admin", rt.Pattern, rt.Access)
|
||||
}
|
||||
}
|
||||
if counts["admin"] != 49 || counts["agent"] != 5 || counts["open"] != 8 {
|
||||
t.Fatalf("access counts = %v, want admin=49 agent=5 open=8", counts)
|
||||
if counts["admin"] != 51 || counts["agent"] != 5 || counts["open"] != 8 {
|
||||
t.Fatalf("access counts = %v, want admin=51 agent=5 open=8", counts)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"cloudipvalidator/internal/db"
|
||||
"cloudipvalidator/internal/orchestrator"
|
||||
)
|
||||
|
||||
type diagnosticAttachRequest struct {
|
||||
ID string `json:"id"`
|
||||
Items []struct {
|
||||
Address string `json:"address"`
|
||||
ValidatorID string `json:"validator_id"`
|
||||
@@ -25,25 +31,72 @@ type diagnosticResultsResponse struct {
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminDiagnosticAttach(w http.ResponseWriter, r *http.Request) {
|
||||
req, items, ok := readDiagnosticAttach(w, r)
|
||||
if ok {
|
||||
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticAttach(r.Context(), items, req.Note)})
|
||||
}
|
||||
}
|
||||
|
||||
func readDiagnosticAttach(w http.ResponseWriter, r *http.Request) (diagnosticAttachRequest, []orchestrator.DiagnosticItem, bool) {
|
||||
var req diagnosticAttachRequest
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
|
||||
return
|
||||
return req, nil, false
|
||||
}
|
||||
if len(req.Items) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "items must not be empty")
|
||||
return
|
||||
return req, nil, false
|
||||
}
|
||||
items := make([]orchestrator.DiagnosticItem, len(req.Items))
|
||||
for i, it := range req.Items {
|
||||
addr := strings.TrimSpace(it.Address)
|
||||
if addr == "" {
|
||||
writeError(w, http.StatusBadRequest, "address must not be empty")
|
||||
return
|
||||
return req, nil, false
|
||||
}
|
||||
items[i] = orchestrator.DiagnosticItem{Address: addr, ValidatorID: strings.TrimSpace(it.ValidatorID)}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticAttach(r.Context(), items, req.Note)})
|
||||
return req, items, true
|
||||
}
|
||||
|
||||
var diagnosticOperationID = regexp.MustCompile(`^[A-Za-z0-9_-]{16,80}$`)
|
||||
|
||||
func (s *Server) handleAdminStartDiagnosticOperation(w http.ResponseWriter, r *http.Request) {
|
||||
req, items, ok := readDiagnosticAttach(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !diagnosticOperationID.MatchString(req.ID) {
|
||||
writeError(w, http.StatusBadRequest, "invalid operation ID")
|
||||
return
|
||||
}
|
||||
canonical, _ := json.Marshal(struct {
|
||||
Items []orchestrator.DiagnosticItem
|
||||
Note string
|
||||
}{items, req.Note})
|
||||
entries := make([]db.DiagnosticOperationItem, len(items))
|
||||
for i, item := range items {
|
||||
entries[i] = db.DiagnosticOperationItem{Address: item.Address, RequestedValidator: item.ValidatorID}
|
||||
}
|
||||
if err := s.DB.CreateDiagnosticOperation(r.Context(), req.ID, req.Note, fmt.Sprintf("%x", sha256.Sum256(canonical)), entries); err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
s.Orch.WakeDiagnosticOperations()
|
||||
w.Header().Set("Location", "/api/v1/admin/diagnostics/operations/"+req.ID)
|
||||
writeJSON(w, http.StatusAccepted, struct {
|
||||
ID string `json:"id"`
|
||||
}{ID: req.ID})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminDiagnosticOperation(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
op, err := s.DB.GetDiagnosticOperation(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeDBError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, op)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminDiagnosticDetach(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cloudipvalidator/internal/db"
|
||||
"cloudipvalidator/internal/openstack"
|
||||
)
|
||||
|
||||
type gatedDiagnosticCloud struct {
|
||||
*openstack.MockClient
|
||||
started chan struct{}
|
||||
proceed chan struct{}
|
||||
}
|
||||
|
||||
func (c *gatedDiagnosticCloud) AssociateFloatingIP(ctx context.Context, fipID, portID string) error {
|
||||
close(c.started)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-c.proceed:
|
||||
return c.MockClient.AssociateFloatingIP(ctx, fipID, portID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnosticOperationAcceptedWhileNeutronRuns(t *testing.T) {
|
||||
s, _ := newAuthTestServer(t, testAdminToken, testAgentToken)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
mock := s.Orch.OS.(*openstack.MockClient)
|
||||
mock.Seed("fip", "203.0.113.5", "test")
|
||||
cloud := &gatedDiagnosticCloud{MockClient: mock, started: make(chan struct{}), proceed: make(chan struct{})}
|
||||
s.Orch.OS = cloud
|
||||
if err := s.DB.RegisterValidator(ctx, "validator", "host", "port", "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
s.Orch.RunDiagnosticOperations(ctx)
|
||||
}()
|
||||
defer func() {
|
||||
cancel()
|
||||
<-done
|
||||
}()
|
||||
|
||||
handler := s.Handler()
|
||||
call := func(method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequestWithContext(ctx, method, path, strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+testAdminToken)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
const operations = "/api/v1/admin/diagnostics/operations"
|
||||
const id = "api-diagnostic-operation"
|
||||
const requestBody = `{"id":"` + id + `","items":[{"address":"203.0.113.5","validator_id":"validator"}]}`
|
||||
rec := call(http.MethodPost, operations, requestBody)
|
||||
if rec.Code != http.StatusAccepted || rec.Header().Get("Location") != operations+"/"+id {
|
||||
t.Fatalf("start: %d, %v, %s", rec.Code, rec.Header(), rec.Body)
|
||||
}
|
||||
select {
|
||||
case <-cloud.started:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("Neutron association did not start")
|
||||
}
|
||||
rec = call(http.MethodPost, operations, requestBody)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("retry: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
var op db.DiagnosticOperation
|
||||
readOperation := func() {
|
||||
t.Helper()
|
||||
rec := call(http.MethodGet, operations+"/"+id, "")
|
||||
err := json.Unmarshal(rec.Body.Bytes(), &op)
|
||||
if rec.Code != http.StatusOK || err != nil || len(op.Items) != 1 {
|
||||
t.Fatalf("get: %d %s, %v", rec.Code, rec.Body, err)
|
||||
}
|
||||
}
|
||||
readOperation()
|
||||
if op.Items[0].Status != "running" {
|
||||
t.Fatalf("before Neutron confirms: %+v", op)
|
||||
}
|
||||
close(cloud.proceed)
|
||||
for {
|
||||
readOperation()
|
||||
if op.Items[0].Status == "attached" {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("final status: %+v", op)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,8 @@ func (s *Server) routeTable() []route {
|
||||
{"POST /api/v1/admin/ips/clear", s.handleAdminClearQueue, accessAdmin},
|
||||
{"GET /api/v1/admin/validators", s.handleAdminValidators, accessAdmin},
|
||||
{"POST /api/v1/admin/diagnostics/attach", s.handleAdminDiagnosticAttach, accessAdmin},
|
||||
{"POST /api/v1/admin/diagnostics/operations", s.handleAdminStartDiagnosticOperation, accessAdmin},
|
||||
{"GET /api/v1/admin/diagnostics/operations/{id}", s.handleAdminDiagnosticOperation, accessAdmin},
|
||||
{"POST /api/v1/admin/diagnostics/detach", s.handleAdminDiagnosticDetach, accessAdmin},
|
||||
{"GET /api/v1/admin/diagnostics", s.handleAdminDiagnosticList, accessAdmin},
|
||||
{"GET /api/v1/admin/auto-cycle", s.handleAdminGetAutoCycle, accessAdmin},
|
||||
|
||||
@@ -64,6 +64,12 @@ type statusCoder interface{ GetStatusCode() int }
|
||||
// RemoteDisconnected), HTTP 429 and HTTP 5xx. Any other 4xx, context
|
||||
// cancellation and unknown errors are not retried.
|
||||
func IsRetryableListError(err error) bool {
|
||||
return IsRetryableRequestError(err)
|
||||
}
|
||||
|
||||
// IsRetryableRequestError reports failures that can be transient. Callers
|
||||
// performing a mutation should verify its effect before repeating it.
|
||||
func IsRetryableRequestError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -56,33 +56,13 @@ func (o *Orchestrator) DiagnosticAttach(ctx context.Context, items []DiagnosticI
|
||||
|
||||
func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult {
|
||||
addr := it.Address
|
||||
holds, err := o.DB.ListDiagnosticHolds(ctx)
|
||||
v, fip, reason, err := o.prepareDiagnosticAttach(ctx, it, "")
|
||||
if err != nil {
|
||||
return rejected(addr, "internal error: "+err.Error())
|
||||
}
|
||||
for _, h := range holds {
|
||||
if h.Address == addr {
|
||||
return rejected(addr, "address is already on diagnostic")
|
||||
}
|
||||
}
|
||||
if item, err := o.DB.GetIPByAddress(ctx, addr); err == nil && activeQueueStates[item.State] {
|
||||
return rejected(addr, "address is being checked ("+item.State+")")
|
||||
}
|
||||
fip, err := o.OS.GetFloatingIPByAddress(ctx, addr)
|
||||
if err != nil {
|
||||
if openstack.IsNotFound(err) {
|
||||
return rejected(addr, "floating ip not found in the project")
|
||||
}
|
||||
return rejected(addr, "cloud lookup failed: "+err.Error())
|
||||
}
|
||||
|
||||
v, reason := o.pickDiagnosticValidator(ctx, it.ValidatorID)
|
||||
if v == nil {
|
||||
if reason != "" {
|
||||
return rejected(addr, reason)
|
||||
}
|
||||
if fip.PortID != "" && fip.PortID != v.OSPortID {
|
||||
return rejected(addr, "floating ip is attached to another port")
|
||||
}
|
||||
if err := o.DB.ClaimDiagnostic(ctx, v.ValidatorID, addr, fip.ID, note); err != nil {
|
||||
return rejected(addr, "validator "+v.ValidatorID+" cannot be claimed: "+err.Error())
|
||||
}
|
||||
@@ -97,6 +77,36 @@ func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticIte
|
||||
return DiagnosticResult{Address: addr, Status: DiagAttached, ValidatorID: v.ValidatorID, FIPID: fip.ID}
|
||||
}
|
||||
|
||||
func (o *Orchestrator) prepareDiagnosticAttach(ctx context.Context, it DiagnosticItem, operationID string) (*db.Validator, *openstack.FloatingIP, string, error) {
|
||||
addr := it.Address
|
||||
held, err := o.DB.HasDiagnosticHold(ctx, addr)
|
||||
if err != nil {
|
||||
return nil, nil, "", err
|
||||
}
|
||||
if held {
|
||||
return nil, nil, "address is already on diagnostic", nil
|
||||
}
|
||||
if item, err := o.DB.GetIPByAddress(ctx, addr); err == nil && activeQueueStates[item.State] {
|
||||
return nil, nil, "address is being checked (" + item.State + ")", nil
|
||||
}
|
||||
fip, err := o.lookupDiagnosticFIP(ctx, operationID, addr)
|
||||
if err != nil {
|
||||
if openstack.IsNotFound(err) {
|
||||
return nil, nil, "floating ip not found in the project", nil
|
||||
}
|
||||
return nil, nil, "cloud lookup failed: " + err.Error(), nil
|
||||
}
|
||||
|
||||
v, reason := o.pickDiagnosticValidator(ctx, it.ValidatorID)
|
||||
if v == nil {
|
||||
return nil, nil, reason, nil
|
||||
}
|
||||
if fip.PortID != "" && fip.PortID != v.OSPortID {
|
||||
return nil, nil, "floating ip is attached to another port", nil
|
||||
}
|
||||
return v, fip, "", nil
|
||||
}
|
||||
|
||||
// pickDiagnosticValidator returns the requested validator if it is idle, or
|
||||
// the first idle one with a port when none is requested.
|
||||
func (o *Orchestrator) pickDiagnosticValidator(ctx context.Context, id string) (*db.Validator, string) {
|
||||
@@ -180,8 +190,12 @@ func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold,
|
||||
}
|
||||
|
||||
func (o *Orchestrator) diagnosticEvent(ctx context.Context, typ, addr, validatorID, fipID, note string) {
|
||||
o.event(ctx, "control-api", validatorID, nil, typ, diagnosticPayload(addr, validatorID, fipID, note))
|
||||
}
|
||||
|
||||
func diagnosticPayload(addr, validatorID, fipID, note string) string {
|
||||
payload, _ := json.Marshal(map[string]string{
|
||||
"address": addr, "validator_id": validatorID, "fip_id": fipID, "note": note,
|
||||
})
|
||||
o.event(ctx, "control-api", validatorID, nil, typ, string(payload))
|
||||
return string(payload)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"cloudipvalidator/internal/db"
|
||||
"cloudipvalidator/internal/openstack"
|
||||
)
|
||||
|
||||
func (o *Orchestrator) WakeDiagnosticOperations() {
|
||||
select {
|
||||
case o.diagnosticWake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// RunDiagnosticOperations owns the single worker. Persistent running items
|
||||
// are picked up on startup along with work accepted while the worker is busy.
|
||||
func (o *Orchestrator) RunDiagnosticOperations(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for ctx.Err() == nil {
|
||||
item, err := o.DB.NextDiagnosticOperationItem(ctx)
|
||||
if err == nil {
|
||||
err = o.applyDiagnosticOperationItem(ctx, item)
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) && ctx.Err() == nil {
|
||||
o.Log.Error("process diagnostic operation item", "operation_id", item.OperationID, "ip", item.Address, "err", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
case <-o.diagnosticWake:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Orchestrator) lookupDiagnosticFIP(ctx context.Context, operationID, address string) (*openstack.FloatingIP, error) {
|
||||
start := time.Now()
|
||||
fip, err := o.OS.GetFloatingIPByAddress(ctx, address)
|
||||
o.logDiagnosticStage(operationID, address, "lookup", start, err)
|
||||
return fip, err
|
||||
}
|
||||
|
||||
func (o *Orchestrator) logDiagnosticStage(operationID, address, stage string, start time.Time, err error) {
|
||||
o.Log.Info("diagnostic stage", "operation_id", operationID, "ip", address, "stage", stage, "duration_ms", time.Since(start).Milliseconds(), "err", err)
|
||||
}
|
||||
|
||||
func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db.DiagnosticOperationItem) error {
|
||||
var fip *openstack.FloatingIP
|
||||
if item.FIPID == "" {
|
||||
validator, found, reason, err := o.prepareDiagnosticAttach(ctx, DiagnosticItem{
|
||||
Address: item.Address, ValidatorID: item.RequestedValidator,
|
||||
}, item.OperationID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if reason != "" {
|
||||
return o.DB.FinishDiagnosticOperationItem(ctx, item, reason, nil)
|
||||
}
|
||||
reserved := item
|
||||
reserved.ValidatorID, reserved.PortID, reserved.FIPID = validator.ValidatorID, validator.OSPortID, found.ID
|
||||
start := time.Now()
|
||||
err = o.DB.ReserveDiagnosticOperationItem(ctx, reserved)
|
||||
o.logDiagnosticStage(item.OperationID, item.Address, "reserve", start, err)
|
||||
if errors.Is(err, db.ErrBusy) || errors.Is(err, db.ErrConflict) || errors.Is(err, db.ErrNotFound) {
|
||||
return o.DB.FinishDiagnosticOperationItem(ctx, item, err.Error(), nil)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
item, fip = reserved, found
|
||||
} else {
|
||||
// A previous process could have exited after Neutron applied the PUT.
|
||||
found, err := o.lookupDiagnosticFIP(ctx, item.OperationID, item.Address)
|
||||
if err != nil {
|
||||
if openstack.IsNotFound(err) {
|
||||
return o.DB.FinishDiagnosticOperationItem(ctx, item, "floating ip no longer exists", nil)
|
||||
}
|
||||
return o.retryDiagnosticVerification(ctx, item)
|
||||
}
|
||||
fip = found
|
||||
}
|
||||
|
||||
if fip.ID != item.FIPID || (fip.PortID != "" && fip.PortID != item.PortID) {
|
||||
return o.DB.FinishDiagnosticOperationItem(ctx, item, "floating ip changed or is attached to another port", nil)
|
||||
}
|
||||
if fip.PortID != item.PortID {
|
||||
start := time.Now()
|
||||
err := o.OS.AssociateFloatingIP(ctx, item.FIPID, item.PortID)
|
||||
o.logDiagnosticStage(item.OperationID, item.Address, "associate", start, err)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
found, lookupErr := o.lookupDiagnosticFIP(ctx, item.OperationID, item.Address)
|
||||
if lookupErr != nil && !openstack.IsNotFound(lookupErr) {
|
||||
return o.retryDiagnosticVerification(ctx, item)
|
||||
}
|
||||
if lookupErr == nil && found.ID == item.FIPID && found.PortID == "" && openstack.IsRetryableRequestError(err) {
|
||||
return o.retryDiagnosticVerification(ctx, item)
|
||||
}
|
||||
if lookupErr != nil || found.ID != item.FIPID || found.PortID != item.PortID {
|
||||
return o.DB.FinishDiagnosticOperationItem(ctx, item, "associate floating ip: "+err.Error(), nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
event := db.Event{
|
||||
SourceType: "control-api", SourceID: item.ValidatorID, EventType: "diagnostic_attached",
|
||||
Payload: diagnosticPayload(item.Address, item.ValidatorID, item.FIPID, item.Note), OccurredAt: db.Now(),
|
||||
}
|
||||
if err := o.DB.FinishDiagnosticOperationItem(ctx, item, "", &event); err != nil {
|
||||
return err
|
||||
}
|
||||
o.Log.Info("diagnostic hold attached", "operation_id", item.OperationID, "ip", item.Address, "validator", item.ValidatorID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Orchestrator) retryDiagnosticVerification(ctx context.Context, item db.DiagnosticOperationItem) error {
|
||||
return o.DB.RetryDiagnosticOperationItem(ctx, item.ID, "Проверяем состояние привязки в OpenStack", 2*time.Second)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"cloudipvalidator/internal/db"
|
||||
"cloudipvalidator/internal/openstack"
|
||||
)
|
||||
|
||||
func TestDiagnosticOperationPartialSuccess(t *testing.T) {
|
||||
o, d, ctx, _ := diagSetup(t)
|
||||
id := "diagnostic-partial"
|
||||
items := []db.DiagnosticOperationItem{
|
||||
{Address: "1.1.1.1", RequestedValidator: "validator-2"},
|
||||
{Address: "9.9.9.9"},
|
||||
}
|
||||
for range 2 {
|
||||
if err := d.CreateDiagnosticOperation(ctx, id, "trace", "same request", items); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := d.CreateDiagnosticOperation(ctx, id, "", "changed request", items); !errors.Is(err, db.ErrConflict) {
|
||||
t.Fatalf("different request with the same ID: %v", err)
|
||||
}
|
||||
for _, expected := range items {
|
||||
item, err := d.NextDiagnosticOperationItem(ctx)
|
||||
if err != nil || item.Address != expected.Address || item.Note != "trace" {
|
||||
t.Fatalf("claim was %+v, err=%v", item, err)
|
||||
}
|
||||
if err := o.applyDiagnosticOperationItem(ctx, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
op, err := d.GetDiagnosticOperation(ctx, id)
|
||||
if err != nil || len(op.Items) != 2 || op.Items[0].Status != DiagAttached ||
|
||||
op.Items[0].ValidatorID != "validator-2" || op.Items[1].Status != DiagRejected || op.Items[1].Reason == "" {
|
||||
t.Fatalf("operation was %+v, err=%v", op, err)
|
||||
}
|
||||
}
|
||||
|
||||
type diagnosticLostResponse struct {
|
||||
*openstack.MockClient
|
||||
lookups int
|
||||
associations int
|
||||
}
|
||||
|
||||
func (c *diagnosticLostResponse) GetFloatingIPByAddress(ctx context.Context, addr string) (*openstack.FloatingIP, error) {
|
||||
c.lookups++
|
||||
if c.lookups == 2 {
|
||||
return nil, errors.New("Neutron temporarily unreachable")
|
||||
}
|
||||
return c.MockClient.GetFloatingIPByAddress(ctx, addr)
|
||||
}
|
||||
|
||||
func (c *diagnosticLostResponse) AssociateFloatingIP(ctx context.Context, fipID, portID string) error {
|
||||
c.associations++
|
||||
if err := c.MockClient.AssociateFloatingIP(ctx, fipID, portID); err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("lost response after successful PUT")
|
||||
}
|
||||
|
||||
func TestDiagnosticOperationRecoversAppliedReservationAfterRestart(t *testing.T) {
|
||||
o, d, ctx, mock := diagSetup(t)
|
||||
cloud := &diagnosticLostResponse{MockClient: mock}
|
||||
o.OS = cloud
|
||||
id := "diagnostic-restart"
|
||||
if err := d.CreateDiagnosticOperation(ctx, id, "", "attach", []db.DiagnosticOperationItem{
|
||||
{Address: "1.1.1.1", RequestedValidator: "validator-1"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item, err := d.NextDiagnosticOperationItem(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := o.applyDiagnosticOperationItem(ctx, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
op, err := d.GetDiagnosticOperation(ctx, id)
|
||||
if err != nil || len(op.Items) != 1 || op.Items[0].Status != "running" || op.Items[0].Reason == "" {
|
||||
t.Fatalf("unconfirmed operation was %+v, err=%v", op, err)
|
||||
}
|
||||
if holds, err := o.DiagnosticList(ctx); err != nil || len(holds) != 0 {
|
||||
t.Fatalf("unconfirmed hold exposed: %+v, err=%v", holds, err)
|
||||
}
|
||||
if result := o.DiagnosticDetach(ctx, []string{"1.1.1.1"}, false); result[0].Status != DiagRejected {
|
||||
t.Fatalf("detach accepted before confirmation: %+v", result)
|
||||
}
|
||||
if _, err := d.ExecContext(ctx, `UPDATE diagnostic_operation_items SET retry_at=0 WHERE id=?`, item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A fresh orchestrator uses only persistent state and the current Neutron port.
|
||||
restarted := &Orchestrator{DB: d, OS: cloud, Log: o.Log}
|
||||
item, err = d.NextDiagnosticOperationItem(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := restarted.applyDiagnosticOperationItem(ctx, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
op, err = d.GetDiagnosticOperation(ctx, id)
|
||||
if err != nil || len(op.Items) != 1 || op.Items[0].Status != DiagAttached || cloud.associations != 1 {
|
||||
t.Fatalf("operation was %+v, PUT count=%d, err=%v", op, cloud.associations, err)
|
||||
}
|
||||
events, err := d.ListRecentEvents(ctx, 10)
|
||||
if err != nil || len(events) != 1 || events[0].EventType != "diagnostic_attached" {
|
||||
t.Fatalf("events: %+v, err=%v", events, err)
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,8 @@ type Orchestrator struct {
|
||||
// value is ready to use.
|
||||
scan scanJob
|
||||
|
||||
diagnosticWake chan struct{}
|
||||
|
||||
// Async makes Tick return without waiting for the slow per-address work
|
||||
// (OpenStack calls): each address is handled in its own goroutine, so one
|
||||
// slow cloud call never delays another validator. With Async=false (the
|
||||
@@ -104,8 +106,9 @@ func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI,
|
||||
Agg: cfg.Aggregation,
|
||||
Log: log,
|
||||
|
||||
ScanPageSize: cfg.OpenStack.ListPageSize,
|
||||
hb: heartbeatState{startedAt: time.Now()},
|
||||
ScanPageSize: cfg.OpenStack.ListPageSize,
|
||||
diagnosticWake: make(chan struct{}, 1),
|
||||
hb: heartbeatState{startedAt: time.Now()},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user