-
Notifications
You must be signed in to change notification settings - Fork 444
/
leader.go
70 lines (58 loc) · 1.37 KB
/
leader.go
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
package leaderelector
import (
"context"
"sync"
"github.com/solo-io/go-utils/contextutils"
)
type LeaderStartupAction struct {
identity Identity
actionLock sync.RWMutex
action func() error
}
func NewLeaderStartupAction(identity Identity) *LeaderStartupAction {
return &LeaderStartupAction{
identity: identity,
}
}
func (a *LeaderStartupAction) SetAction(action func() error) {
a.actionLock.Lock()
a.action = action
a.actionLock.Unlock()
}
func (a *LeaderStartupAction) GetAction() func() error {
a.actionLock.RLock()
defer a.actionLock.RUnlock()
return a.action
}
func (a *LeaderStartupAction) WatchElectionResults(ctx context.Context) {
if a.identity.Elected() == nil {
// no election channel, return early
return
}
doPerformAction := func() {
action := a.GetAction()
if action == nil {
// this case is the result of developer error
contextutils.LoggerFrom(ctx).Warnw("leader startup action not defined")
return
}
err := action()
if err != nil {
contextutils.LoggerFrom(ctx).Warnw("failed to perform leader startup action", "error", err)
}
}
go func(electionCtx context.Context) {
for {
select {
case <-electionCtx.Done():
return
case <-a.identity.Elected():
// channel is closed, signaling leadership
doPerformAction()
return
default:
// receiving from other channels would block
}
}
}(ctx)
}