Run manual diagnostic attachments in the background

This commit is contained in:
ayurishchev committed 2026-11-22 20:50:39 +03:00
1 parent d845a5e4b6
commit 89ac4d5bcd
40 files changed
+1560 -58

No files matched your search

+2 -2
View File
@@ -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)
}
}
+57 -4
View File
@@ -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)
}
}
}
+2
View File
@@ -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},