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>
|
||||
|
||||
Reference in new issue
Block a user