package election
import (
"fmt"
"sort"
"strings"
"sync"
"k8s.io/klog/v2"
)
type MasterTracker struct {
mu sync.RWMutex
masterFor map[string]bool
masterCount int
notify func(id string, isMaster bool)
}
func NewMasterTracker(ids []string, notify func(id string, isMaster bool)) *MasterTracker {
mf := make(map[string]bool)
for _, id := range ids {
mf[id] = false
}
return &MasterTracker{masterFor: mf, notify: notify}
}
func (mt *MasterTracker) Set(id string, isMaster bool) {
mt.mu.Lock()
defer mt.mu.Unlock()
wasMaster, ok := mt.masterFor[id]
if ok && isMaster == wasMaster {
klog.Warningf("toggle masterFor[%s] from %v to %v!", id, wasMaster, isMaster)
}
mt.masterFor[id] = isMaster
if isMaster && !wasMaster {
mt.masterCount++
} else if !isMaster && wasMaster {
mt.masterCount--
}
if mt.notify != nil {
mt.notify(id, isMaster)
}
}
func (mt *MasterTracker) Count() int {
mt.mu.RLock()
defer mt.mu.RUnlock()
return mt.masterCount
}
func (mt *MasterTracker) Held() []string {
mt.mu.RLock()
defer mt.mu.RUnlock()
ids := make([]string, 0, mt.masterCount)
for id := range mt.masterFor {
if mt.masterFor[id] {
ids = append(ids, id)
}
}
sort.Strings(ids)
return ids
}
func (mt *MasterTracker) IDs() []string {
mt.mu.RLock()
defer mt.mu.RUnlock()
ids := make([]string, 0, len(mt.masterFor))
for id := range mt.masterFor {
ids = append(ids, id)
}
sort.Strings(ids)
return ids
}
func (mt *MasterTracker) String() string {
return HeldInfo(mt.Held(), mt.IDs())
}
func HeldInfo(held []string, ids []string) string {
result := ""
prefix := ""
for _, id := range ids {
show := strings.Repeat(".", len(id))
for _, h := range held {
if h == id {
show = id
}
if h >= id {
break
}
}
result += fmt.Sprintf("%s%s", prefix, show)
prefix = " "
}
return result
}