Files
cloud-ip-validator/internal/orchestrator/diagnostic.go
T
ayurishchevandClaude Opus 5.5 55d383bd34 control-api: reduce SQLite disk writes; add diagnostic mode
Disk writes:
- SQLite pragmas in DSN: wal_autocheckpoint=10000, journal_size_limit=64MB, cache_size=64MB
- migration 0013: drop redundant idx_checks_registry_cycle
- results batched: UpsertChecksIfOpen in one transaction; agent flushes every 5s and before complete
- heartbeat kept in memory, persisted on state change or every 60s; startup grace for stale sweeps

Diagnostic mode:
- POST /api/v1/admin/diagnostics/attach|detach, GET /api/v1/admin/diagnostics
- migration 0014: diagnostic_holds; validator state "diagnostic"
- held addresses are not queued, held validators skip sweeps, port release and delete

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 07:01:24 +03:00

188 lines
6.3 KiB
Go

package orchestrator
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
)
// Diagnostic hold results (per address).
const (
DiagAttached = "attached"
DiagDetached = "detached"
DiagRejected = "rejected"
)
// DiagnosticItem is one address to attach; ValidatorID is optional (an idle
// validator is picked when empty).
type DiagnosticItem struct {
Address string
ValidatorID string
}
// DiagnosticResult is the outcome for one address.
type DiagnosticResult struct {
Address string `json:"address"`
Status string `json:"status"`
ValidatorID string `json:"validator_id,omitempty"`
FIPID string `json:"fip_id,omitempty"`
Reason string `json:"reason,omitempty"`
}
func rejected(address, reason string) DiagnosticResult {
return DiagnosticResult{Address: address, Status: DiagRejected, Reason: reason}
}
// activeQueueStates are the states in which an address is being checked.
var activeQueueStates = map[string]bool{
db.IPAssigningFIP: true, db.IPAwaitingSelfCheck: true, db.IPChecking: true, db.IPAggregating: true,
}
// DiagnosticAttach binds each address to a validator's port and holds it
// there until DiagnosticDetach. Partial success is normal: every address gets
// its own result.
func (o *Orchestrator) DiagnosticAttach(ctx context.Context, items []DiagnosticItem, note string) []DiagnosticResult {
out := make([]DiagnosticResult, 0, len(items))
for _, it := range items {
out = append(out, o.diagnosticAttachOne(ctx, it, note))
}
return out
}
func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult {
addr := it.Address
holds, err := o.DB.ListDiagnosticHolds(ctx)
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 {
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())
}
if err := o.OS.AssociateFloatingIP(ctx, fip.ID, v.OSPortID); err != nil {
if _, rerr := o.DB.ReleaseDiagnostic(ctx, addr); rerr != nil {
o.Log.Error("roll back diagnostic hold", "ip", addr, "err", rerr)
}
return rejected(addr, "associate floating ip: "+err.Error())
}
o.diagnosticEvent(ctx, "diagnostic_attached", addr, v.ValidatorID, fip.ID, note)
o.Log.Info("diagnostic hold attached", "ip", addr, "validator", v.ValidatorID)
return DiagnosticResult{Address: addr, Status: DiagAttached, ValidatorID: v.ValidatorID, FIPID: fip.ID}
}
// 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) {
if id != "" {
v, err := o.DB.GetValidator(ctx, id)
if errors.Is(err, sql.ErrNoRows) {
return nil, "validator not found"
}
if err != nil {
return nil, "internal error: " + err.Error()
}
if v.State != db.ValidatorIdle {
return nil, fmt.Sprintf("validator is not idle (%s)", v.State)
}
if v.OSPortID == "" {
return nil, "validator has no port"
}
return v, ""
}
idle, err := o.DB.ListIdleValidators(ctx)
if err != nil {
return nil, "internal error: " + err.Error()
}
for i := range idle {
if idle[i].OSPortID != "" {
return &idle[i], ""
}
}
return nil, "no idle validators left"
}
// DiagnosticDetach unbinds the given addresses (all holds when all is true)
// and returns their validators to idle. A floating ip that is already free in
// the cloud is not an error; a cloud failure keeps the hold so it can be retried.
func (o *Orchestrator) DiagnosticDetach(ctx context.Context, addresses []string, all bool) []DiagnosticResult {
holds, err := o.DB.ListDiagnosticHolds(ctx)
if err != nil {
return []DiagnosticResult{rejected("", "internal error: "+err.Error())}
}
byAddr := make(map[string]db.DiagnosticHold, len(holds))
for _, h := range holds {
byAddr[h.Address] = h
if all {
addresses = append(addresses, h.Address)
}
}
out := make([]DiagnosticResult, 0, len(addresses))
for _, addr := range addresses {
h, ok := byAddr[addr]
if !ok {
out = append(out, rejected(addr, "address is not on diagnostic"))
continue
}
fipID := h.FIPID
if fip, err := o.OS.GetFloatingIPByAddress(ctx, addr); err == nil {
fipID = fip.ID
if fip.PortID != "" {
if err := o.OS.DisassociateFloatingIP(ctx, fipID); err != nil {
out = append(out, rejected(addr, "disassociate floating ip: "+err.Error()))
continue
}
}
} else if !openstack.IsNotFound(err) {
out = append(out, rejected(addr, "cloud lookup failed: "+err.Error()))
continue
}
if _, err := o.DB.ReleaseDiagnostic(ctx, addr); err != nil {
out = append(out, rejected(addr, "release: "+err.Error()))
continue
}
o.diagnosticEvent(ctx, "diagnostic_detached", addr, h.ValidatorID, fipID, h.Note)
o.Log.Info("diagnostic hold detached", "ip", addr, "validator", h.ValidatorID)
out = append(out, DiagnosticResult{Address: addr, Status: DiagDetached, ValidatorID: h.ValidatorID, FIPID: fipID})
}
return out
}
// DiagnosticList returns the current holds.
func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold, error) {
return o.DB.ListDiagnosticHolds(ctx)
}
func (o *Orchestrator) diagnosticEvent(ctx context.Context, typ, addr, validatorID, fipID, note 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))
}