forked from docker-archive/leadership
-
Notifications
You must be signed in to change notification settings - Fork 2
/
follower.go
74 lines (60 loc) · 1.4 KB
/
follower.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
71
72
73
74
package leadership
import (
"errors"
"github.com/abronan/valkeyrie/store"
)
// Follower can follow an election in real-time and push notifications whenever
// there is a change in leadership.
type Follower struct {
client store.Store
key string
leader string
leaderCh chan string
stopCh chan struct{}
errCh chan error
}
// NewFollower creates a new follower.
func NewFollower(client store.Store, key string) *Follower {
return &Follower{
client: client,
key: key,
stopCh: make(chan struct{}),
}
}
// Leader returns the current leader.
func (f *Follower) Leader() string {
return f.leader
}
// FollowElection starts monitoring the election.
func (f *Follower) FollowElection() (<-chan string, <-chan error) {
f.leaderCh = make(chan string)
f.errCh = make(chan error)
go f.follow()
return f.leaderCh, f.errCh
}
// Stop stops monitoring an election.
func (f *Follower) Stop() {
close(f.stopCh)
}
func (f *Follower) follow() {
defer close(f.leaderCh)
defer close(f.errCh)
ch, err := f.client.Watch(f.key, f.stopCh, nil)
if err != nil {
f.errCh <- err
}
f.leader = ""
for kv := range ch {
if kv == nil {
continue
}
curr := string(kv.Value)
if curr == f.leader {
continue
}
f.leader = curr
f.leaderCh <- f.leader
}
// Channel closed, we return an error
f.errCh <- errors.New("Leader Election: watch leader channel closed, the store may be unavailable...")
}