1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
package ipmanager
import (
"context"
"log"
"sync"
"time"
)
type ipConfigurer interface {
queryAddress() bool
configureAddress() bool
deconfigureAddress() bool
getCIDR() string
cleanupArp()
}
// IPManager implements the main functionality of the VIP manager
type IPManager struct {
configurer ipConfigurer
states <-chan bool
currentState bool
stateLock sync.Mutex
recheck *sync.Cond
}
// NewIPManager returns a new instance of IPManager
func NewIPManager(hostingType string, config *IPConfiguration, states <-chan bool, verbose bool) (m *IPManager, err error) {
m = &IPManager{
states: states,
currentState: false,
}
m.recheck = sync.NewCond(&m.stateLock)
switch hostingType {
case "hetzner":
m.configurer, err = newHetznerConfigurer(config, verbose)
if err != nil {
return nil, err
}
case "basic":
fallthrough
default:
m.configurer, err = newBasicConfigurer(config)
}
if err != nil {
m = nil
}
return
}
func (m *IPManager) applyLoop(ctx context.Context) {
timeout := 0
for {
// Check if we should exit
select {
case <-ctx.Done():
m.configurer.deconfigureAddress()
return
case <-time.After(time.Duration(timeout) * time.Second):
actualState := m.configurer.queryAddress()
m.stateLock.Lock()
desiredState := m.currentState
log.Printf("IP address %s state is %t, desired %t", m.configurer.getCIDR(), actualState, desiredState)
if actualState != desiredState {
m.stateLock.Unlock()
var configureState bool
if desiredState {
configureState = m.configurer.configureAddress()
} else {
configureState = m.configurer.deconfigureAddress()
}
if !configureState {
log.Printf("Error while acquiring virtual ip for this machine")
//Sleep a little bit to avoid busy waiting due to the for loop.
timeout = 10
} else {
timeout = 0
}
} else {
// Wait for notification
m.recheck.Wait()
// Want to query actual state anyway, so unlock
m.stateLock.Unlock()
}
}
}
}
// SyncStates implements states synchronization
func (m *IPManager) SyncStates(ctx context.Context, states <-chan bool) {
ticker := time.NewTicker(10 * time.Second)
var wg sync.WaitGroup
wg.Add(1)
go func() {
m.applyLoop(ctx)
wg.Done()
}()
for {
select {
case newState := <-states:
m.stateLock.Lock()
if m.currentState != newState {
m.currentState = newState
m.recheck.Broadcast()
}
m.stateLock.Unlock()
case <-ticker.C:
m.recheck.Broadcast()
case <-ctx.Done():
m.recheck.Broadcast()
wg.Wait()
m.configurer.cleanupArp()
return
}
}
}
|