diff --git a/pkg/icingadb/ha.go b/pkg/icingadb/ha.go index 6460ac32d..1bb04b17c 100644 --- a/pkg/icingadb/ha.go +++ b/pkg/icingadb/ha.go @@ -7,7 +7,6 @@ import ( "encoding/hex" "github.com/google/uuid" "github.com/icinga/icinga-go-library/backoff" - "github.com/icinga/icinga-go-library/com" "github.com/icinga/icinga-go-library/database" "github.com/icinga/icinga-go-library/logging" "github.com/icinga/icinga-go-library/retry" @@ -19,6 +18,7 @@ import ( "github.com/pkg/errors" "go.uber.org/zap" "sync" + "sync/atomic" "time" ) @@ -35,7 +35,7 @@ type haState struct { // HA provides high availability and indicates whether a Takeover or Handover must be made. type HA struct { - state com.Atomic[haState] + state atomic.Pointer[haState] ctx context.Context cancelCtx context.CancelFunc instanceId types.Binary @@ -71,6 +71,8 @@ func NewHA(ctx context.Context, db *database.DB, heartbeat *icingaredis.Heartbea done: make(chan struct{}), } + ha.state.Store(&haState{}) + go ha.controller() return ha @@ -121,7 +123,8 @@ func (h *HA) Takeover() chan string { // State returns the status quo. func (h *HA) State() (responsibleTsMilli int64, responsible, otherResponsible bool) { - state, _ := h.state.Load() + state := h.state.Load() + return state.responsibleTsMilli, state.responsible, state.otherResponsible } @@ -428,9 +431,12 @@ func (h *HA) realize( h.signalTakeover(takeover) } else if otherResponsible { - if state, _ := h.state.Load(); !state.otherResponsible { - state.otherResponsible = true - h.state.Store(state) + if state := h.state.Load(); !state.otherResponsible { + // Dereference pointer to create a copy of the value it points to. + // Ensures that any modifications do not directly affect the original data unless explicitly stored back. + newState := *state + newState.otherResponsible = true + h.state.Store(&newState) } } @@ -496,7 +502,7 @@ func (h *HA) removeOldInstances(s *icingaredisv1.IcingaStatus, envId types.Binar // signalHandover gives up HA.responsible and notifies the HA.Handover chan. func (h *HA) signalHandover(reason string) { if h.responsible { - h.state.Store(haState{ + h.state.Store(&haState{ responsibleTsMilli: time.Now().UnixMilli(), responsible: false, otherResponsible: false, @@ -514,7 +520,7 @@ func (h *HA) signalHandover(reason string) { // signalTakeover claims HA.responsible and notifies the HA.Takeover chan. func (h *HA) signalTakeover(reason string) { if !h.responsible { - h.state.Store(haState{ + h.state.Store(&haState{ responsibleTsMilli: time.Now().UnixMilli(), responsible: true, otherResponsible: false,