Skip to content

Commit 0261455

Browse files
committed
Use the new Raft.LeaderCh() to detect leadership
This is available since hashicorp/raft#427 but the code is backwards compatible and detects whether your version of Raft includes it.
1 parent f4d0b09 commit 0261455

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

leaderhealth/leaderhealth.go

+22-12
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,28 @@ func Setup(r *raft.Raft, s *grpc.Server, services []string) {
1919
// Report starts a goroutine that updates the given health.Server with whether we are the Raft leader.
2020
// It will set the given services as SERVING if we are the leader, and as NOT_SERVING otherwise.
2121
func Report(r *raft.Raft, hs *health.Server, services []string) {
22-
ch := make(chan raft.Observation, 1)
23-
r.RegisterObserver(raft.NewObserver(ch, true, func(o *raft.Observation) bool {
24-
_, ok := o.Data.(raft.LeaderObservation)
25-
return ok
26-
}))
27-
setServingStatus(hs, services, r.State() == raft.Leader)
28-
go func() {
29-
for range ch {
30-
// TODO(quis, https://github.com/hashicorp/raft/issues/426): Use a safer method to decide if we are the leader.
31-
setServingStatus(hs, services, r.State() == raft.Leader)
32-
}
33-
}()
22+
lch1 := r.LeaderCh()
23+
lch2 := r.LeaderCh()
24+
if lch1 == lch2 {
25+
ch := make(chan raft.Observation, 1)
26+
r.RegisterObserver(raft.NewObserver(ch, true, func(o *raft.Observation) bool {
27+
_, ok := o.Data.(raft.LeaderObservation)
28+
return ok
29+
}))
30+
setServingStatus(hs, services, r.State() == raft.Leader)
31+
go func() {
32+
for range ch {
33+
setServingStatus(hs, services, r.State() == raft.Leader)
34+
}
35+
}()
36+
} else {
37+
setServingStatus(hs, services, <-lch1)
38+
go func() {
39+
for isLeader := range lch1 {
40+
setServingStatus(hs, services, isLeader)
41+
}
42+
}()
43+
}
3444
}
3545

3646
func setServingStatus(hs *health.Server, services []string, isLeader bool) {

0 commit comments

Comments
 (0)