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>
This commit is contained in:
1 parent
d0ab6b94f9
commit
55d383bd34
41 files changed
+1214
-94
No files matched your search
@@ -0,0 +1,187 @@
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cloudipvalidator/internal/db"
|
||||
"cloudipvalidator/internal/openstack"
|
||||
)
|
||||
|
||||
func diagSetup(t *testing.T) (*Orchestrator, *db.DB, context.Context, *openstack.MockClient) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
o, d, mock := newTestOrchestrator(t, 180)
|
||||
mock.Seed("fip-a", "1.1.1.1", "svc")
|
||||
mock.Seed("fip-b", "2.2.2.2", "svc")
|
||||
_ = d.RegisterValidator(ctx, "validator-1", "host", "port-1", "v")
|
||||
_ = d.RegisterValidator(ctx, "validator-2", "host", "port-2", "v")
|
||||
return o, d, ctx, mock
|
||||
}
|
||||
|
||||
func validatorState(t *testing.T, d *db.DB, id string) string {
|
||||
t.Helper()
|
||||
v, err := d.GetValidator(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v.State
|
||||
}
|
||||
|
||||
func TestDiagnosticAttachDetach(t *testing.T) {
|
||||
o, d, ctx, _ := diagSetup(t)
|
||||
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "trace")
|
||||
if len(res) != 1 || res[0].Status != DiagAttached || res[0].ValidatorID != "validator-1" {
|
||||
t.Fatalf("attach: %+v", res)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
|
||||
t.Fatalf("state = %s, want diagnostic", s)
|
||||
}
|
||||
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 1 {
|
||||
t.Fatalf("fips on port-1 = %v", fips)
|
||||
}
|
||||
|
||||
// The held address is queued but never handed out; the other validator stays idle.
|
||||
o.Tick(ctx)
|
||||
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State != db.IPQueued {
|
||||
t.Fatalf("held address state = %s, want queued", ip.State)
|
||||
}
|
||||
// Reconcile and heartbeat leave the diagnostic state alone.
|
||||
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
|
||||
t.Fatalf("after heartbeat/reconcile state = %s", s)
|
||||
}
|
||||
if list, _ := o.DiagnosticList(ctx); len(list) != 1 || list[0].Note != "trace" {
|
||||
t.Fatalf("list: %+v", list)
|
||||
}
|
||||
|
||||
res = o.DiagnosticDetach(ctx, nil, true)
|
||||
if len(res) != 1 || res[0].Status != DiagDetached {
|
||||
t.Fatalf("detach: %+v", res)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
|
||||
t.Fatalf("state = %s, want idle", s)
|
||||
}
|
||||
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 0 {
|
||||
t.Fatalf("fip still attached: %v", fips)
|
||||
}
|
||||
o.Tick(ctx)
|
||||
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State == db.IPQueued {
|
||||
t.Fatal("released address was not claimed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnosticRejections(t *testing.T) {
|
||||
o, d, ctx, _ := diagSetup(t)
|
||||
// Busy validator.
|
||||
if _, err := d.ExecContext(ctx, `UPDATE validators SET state='assigned' WHERE validator_id='validator-1'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "")
|
||||
if res[0].Status != DiagRejected {
|
||||
t.Fatalf("busy validator: %+v", res)
|
||||
}
|
||||
// Unknown address and a cloud error roll back the claim.
|
||||
res = o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "9.9.9.9"}}, "")
|
||||
if res[0].Status != DiagRejected {
|
||||
t.Fatalf("unknown fip: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagnosticCloudErrorRollsBack(t *testing.T) {
|
||||
o, d, ctx, mock := diagSetup(t)
|
||||
mock.AssociateFailures = map[string]error{"fip-a": errors.New("neutron down")}
|
||||
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "")
|
||||
if res[0].Status != DiagRejected {
|
||||
t.Fatalf("attach: %+v", res)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
|
||||
t.Fatalf("state = %s, want idle after rollback", s)
|
||||
}
|
||||
if list, _ := o.DiagnosticList(ctx); len(list) != 0 {
|
||||
t.Fatalf("hold left behind: %+v", list)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSweepAndReleasePortsSkipDiagnosticValidator(t *testing.T) {
|
||||
o, d, ctx, _ := diagSetup(t)
|
||||
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, ""); res[0].Status != DiagAttached {
|
||||
t.Fatalf("attach: %+v", res)
|
||||
}
|
||||
old := db.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano)
|
||||
if _, err := d.ExecContext(ctx, `UPDATE validators SET last_heartbeat_at=?`, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.EndStartupGrace()
|
||||
if err := o.SweepStaleHeartbeats(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
|
||||
t.Fatalf("sweep changed diagnostic validator to %s", s)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-2"); s != db.ValidatorUnreachable {
|
||||
t.Fatalf("validator-2 = %s, want unreachable", s)
|
||||
}
|
||||
|
||||
vs := o.validatorsByID(ctx, "validator-1")
|
||||
o.releaseValidatorPorts(ctx, vs)
|
||||
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 1 {
|
||||
t.Fatalf("releaseValidatorPorts detached a held fip: %v", fips)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeartbeatPersistThrottle(t *testing.T) {
|
||||
o, d, ctx, _ := diagSetup(t)
|
||||
stored := func() string {
|
||||
var s string
|
||||
d.QueryRowContext(ctx, `SELECT COALESCE(last_heartbeat_at,'') FROM validators WHERE validator_id='validator-1'`).Scan(&s)
|
||||
return s
|
||||
}
|
||||
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := stored()
|
||||
if first == "" {
|
||||
t.Fatal("first heartbeat was not written")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored() != first {
|
||||
t.Fatal("second heartbeat within the interval was written to the database")
|
||||
}
|
||||
// Memory is newer, and the admin overlay shows it.
|
||||
v, _ := d.GetValidator(ctx, "validator-1")
|
||||
o.OverlayValidatorHeartbeat(v)
|
||||
if !v.LastHeartbeatAt.After(mustParse(t, first)) {
|
||||
t.Fatal("overlay did not show the in-memory heartbeat")
|
||||
}
|
||||
// A state change is written at once.
|
||||
_ = d.MarkValidatorUnreachable(ctx, "validator-1")
|
||||
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
|
||||
t.Fatalf("state = %s, want idle", s)
|
||||
}
|
||||
if err := o.ValidatorHeartbeat(ctx, "nobody"); err == nil {
|
||||
t.Fatal("unknown validator must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func mustParse(t *testing.T, s string) time.Time {
|
||||
t.Helper()
|
||||
tm, err := time.Parse(time.RFC3339Nano, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tm
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"cloudipvalidator/internal/db"
|
||||
)
|
||||
|
||||
// heartbeatPersistInterval is how often a steady heartbeat is written to the
|
||||
// database. Between writes the last signal lives in memory only.
|
||||
const heartbeatPersistInterval = 60 * time.Second
|
||||
|
||||
// heartbeatState keeps the last signal of every validator and site in memory,
|
||||
// so a heartbeat does not cost a database commit.
|
||||
type heartbeatState struct {
|
||||
mu sync.Mutex
|
||||
startedAt time.Time
|
||||
seen map[string]time.Time // key "v:<id>" or "s:<id>": last signal
|
||||
persisted map[string]time.Time // key: last database write
|
||||
}
|
||||
|
||||
// touch records a signal now and reports whether it must be written to the
|
||||
// database (forced by a state change, or the last write is old enough).
|
||||
func (h *heartbeatState) touch(key string, force bool) bool {
|
||||
now := time.Now()
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.seen == nil {
|
||||
h.seen = map[string]time.Time{}
|
||||
h.persisted = map[string]time.Time{}
|
||||
}
|
||||
h.seen[key] = now
|
||||
if last, ok := h.persisted[key]; !force && ok && now.Sub(last) < heartbeatPersistInterval {
|
||||
return false
|
||||
}
|
||||
h.persisted[key] = now
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *heartbeatState) lastSeen(key string) (time.Time, bool) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
t, ok := h.seen[key]
|
||||
return t, ok
|
||||
}
|
||||
|
||||
// newest returns the later of the in-memory signal and the stored one.
|
||||
func (h *heartbeatState) newest(key string, stored *time.Time) *time.Time {
|
||||
t, ok := h.lastSeen(key)
|
||||
if !ok {
|
||||
return stored
|
||||
}
|
||||
t = t.UTC().Truncate(time.Millisecond)
|
||||
if stored != nil && !t.After(*stored) {
|
||||
return stored
|
||||
}
|
||||
return &t
|
||||
}
|
||||
|
||||
// ValidatorHeartbeat handles a validator's sign of life. It returns
|
||||
// sql.ErrNoRows for an unknown validator. The database is written only when
|
||||
// the validator is unreachable (state change) or the last write is older than
|
||||
// heartbeatPersistInterval.
|
||||
func (o *Orchestrator) ValidatorHeartbeat(ctx context.Context, id string) error {
|
||||
v, err := o.DB.GetValidator(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !o.hb.touch("v:"+id, v.State == db.ValidatorUnreachable) {
|
||||
return nil
|
||||
}
|
||||
return o.DB.Heartbeat(ctx, id)
|
||||
}
|
||||
|
||||
// SiteHeartbeat is ValidatorHeartbeat for prober sites.
|
||||
func (o *Orchestrator) SiteHeartbeat(ctx context.Context, siteID string) error {
|
||||
state, err := o.siteState(ctx, siteID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !o.hb.touch("s:"+siteID, state == db.SiteUnreachable) {
|
||||
return nil
|
||||
}
|
||||
return o.DB.SiteHeartbeat(ctx, siteID)
|
||||
}
|
||||
|
||||
func (o *Orchestrator) siteState(ctx context.Context, siteID string) (string, error) {
|
||||
sites, err := o.DB.ListSites(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, s := range sites {
|
||||
if s.SiteID == siteID {
|
||||
return s.State, nil
|
||||
}
|
||||
}
|
||||
return "", sql.ErrNoRows
|
||||
}
|
||||
|
||||
// OverlayValidatorHeartbeat replaces v.LastHeartbeatAt with the in-memory
|
||||
// value when it is newer.
|
||||
func (o *Orchestrator) OverlayValidatorHeartbeat(v *db.Validator) {
|
||||
v.LastHeartbeatAt = o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt)
|
||||
}
|
||||
|
||||
// OverlaySiteHeartbeat is OverlayValidatorHeartbeat for sites.
|
||||
func (o *Orchestrator) OverlaySiteHeartbeat(s *db.Site) {
|
||||
s.LastHeartbeatAt = o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt)
|
||||
}
|
||||
|
||||
// EndStartupGrace ends the post-start sweep delay early (for tests).
|
||||
func (o *Orchestrator) EndStartupGrace() { o.hb.startedAt = time.Time{} }
|
||||
|
||||
// inStartupGrace is true during the first HeartbeatTimeoutSeconds after
|
||||
// start: agents have not had time to report in memory yet.
|
||||
func (o *Orchestrator) inStartupGrace() bool {
|
||||
return time.Since(o.hb.startedAt) < time.Duration(o.Cfg.HeartbeatTimeoutSeconds)*time.Second
|
||||
}
|
||||
|
||||
// SweepStaleHeartbeats marks validators unreachable if they haven't
|
||||
// heartbeated within HeartbeatTimeoutSeconds (the later of the in-memory and
|
||||
// stored signal counts). It does not itself reclaim their in-flight IP — that
|
||||
// happens independently via lease expiry. Validators on a diagnostic hold are
|
||||
// never touched, and nothing is marked in the startup grace period.
|
||||
func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error {
|
||||
if o.inStartupGrace() {
|
||||
return nil
|
||||
}
|
||||
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
|
||||
all, err := o.DB.ListValidators(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, v := range all {
|
||||
if v.State == db.ValidatorUnreachable || v.State == db.ValidatorDiagnostic {
|
||||
continue
|
||||
}
|
||||
last := o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt)
|
||||
if last == nil || !last.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil {
|
||||
o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err)
|
||||
continue
|
||||
}
|
||||
o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't
|
||||
// heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats.
|
||||
func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error {
|
||||
if o.inStartupGrace() {
|
||||
return nil
|
||||
}
|
||||
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
|
||||
all, err := o.DB.ListSites(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range all {
|
||||
if s.State == db.SiteUnreachable {
|
||||
continue
|
||||
}
|
||||
last := o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt)
|
||||
if last == nil || !last.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil {
|
||||
o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err)
|
||||
continue
|
||||
}
|
||||
o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -62,6 +62,9 @@ type Orchestrator struct {
|
||||
// next Tick does not start the same work twice.
|
||||
inflight sync.Map
|
||||
wg sync.WaitGroup
|
||||
|
||||
// hb is the in-memory heartbeat state (see heartbeat.go).
|
||||
hb heartbeatState
|
||||
}
|
||||
|
||||
// Wait blocks until all background work started by Tick has finished.
|
||||
@@ -99,6 +102,7 @@ func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI,
|
||||
Log: log,
|
||||
|
||||
ScanPageSize: cfg.OpenStack.ListPageSize,
|
||||
hb: heartbeatState{startedAt: time.Now()},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,6 +399,12 @@ func (o *Orchestrator) RecordCheckIfOpen(ctx context.Context, c db.Check) (bool,
|
||||
return o.DB.UpsertCheckIfOpen(ctx, c)
|
||||
}
|
||||
|
||||
// RecordChecksIfOpen is RecordCheckIfOpen for a batch, written in one
|
||||
// transaction; written[i] reports whether checks[i] was stored.
|
||||
func (o *Orchestrator) RecordChecksIfOpen(ctx context.Context, checks []db.Check) ([]bool, error) {
|
||||
return o.DB.UpsertChecksIfOpen(ctx, checks)
|
||||
}
|
||||
|
||||
// RecordCheck is RecordCheckIfOpen for callers that do not need to know
|
||||
// whether the result was dropped.
|
||||
func (o *Orchestrator) RecordCheck(ctx context.Context, c db.Check) error {
|
||||
@@ -419,8 +429,8 @@ func (o *Orchestrator) MarkSiteComplete(ctx context.Context, ipID int64, siteInd
|
||||
func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []db.Validator) {
|
||||
var wg sync.WaitGroup
|
||||
for _, v := range validators {
|
||||
if v.OSPortID == "" {
|
||||
continue
|
||||
if v.OSPortID == "" || v.State == db.ValidatorDiagnostic {
|
||||
continue // a diagnostic hold keeps its floating ip attached
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(v db.Validator) {
|
||||
@@ -893,46 +903,6 @@ func (o *Orchestrator) sweepExpiredLeases(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// sweepStaleHeartbeats marks validators unreachable if they haven't
|
||||
// heartbeated within HeartbeatTimeoutSeconds. It does not itself reclaim
|
||||
// their in-flight IP — that happens independently via lease expiry, so a
|
||||
// validator that stops heartbeating but whose lease hasn't yet expired
|
||||
// still finishes its current check window if it recovers in time.
|
||||
func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error {
|
||||
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
|
||||
stale, err := o.DB.ListStaleHeartbeats(ctx, cutoff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, v := range stale {
|
||||
if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil {
|
||||
o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err)
|
||||
continue
|
||||
}
|
||||
o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't
|
||||
// heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats
|
||||
// exactly, for sites instead of validators.
|
||||
func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error {
|
||||
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
|
||||
stale, err := o.DB.ListStaleSiteHeartbeats(ctx, cutoff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, s := range stale {
|
||||
if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil {
|
||||
o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err)
|
||||
continue
|
||||
}
|
||||
o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecordEvent is the exported entry point httpapi uses to log
|
||||
// agent/prober-reported audit events (config_received, fip_changed,
|
||||
// error, etc.) through the same path as internally generated events
|
||||
|
||||
Reference in new issue
Block a user