forked from AcalephStorage/consul-alerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leader-election.go
70 lines (60 loc) · 1.51 KB
/
leader-election.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 main
import (
log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
consulapi "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/hashicorp/consul/api"
)
const LockKey = "consul-alerts/leader"
type LeaderElection struct {
lock *consulapi.Lock
cleanupChannel chan struct{}
stopChannel chan struct{}
leader bool
}
func (l *LeaderElection) start() {
clean := false
for !clean {
select {
case <-l.cleanupChannel:
clean = true
default:
log.Infoln("Running for leader election...")
intChan, _ := l.lock.Lock(l.stopChannel)
if intChan != nil {
log.Infoln("Now acting as leader.")
l.leader = true
<-intChan
l.leader = false
log.Infoln("Lost leadership.")
l.lock.Unlock()
l.lock.Destroy()
}
}
}
}
func (l *LeaderElection) stop() {
log.Infoln("cleaning up")
l.cleanupChannel <- struct{}{}
l.stopChannel <- struct{}{}
l.lock.Unlock()
l.lock.Destroy()
l.leader = false
log.Infoln("cleanup done")
}
func startLeaderElection(addr, dc, acl string) *LeaderElection {
config := consulapi.DefaultConfig()
config.Address = addr
config.Datacenter = dc
config.Token = acl
client, _ := consulapi.NewClient(config)
lock, _ := client.LockKey(LockKey)
leader := &LeaderElection{
lock: lock,
cleanupChannel: make(chan struct{}, 1),
stopChannel: make(chan struct{}, 1),
}
go leader.start()
return leader
}
func hasLeader() bool {
return consulClient.CheckKeyExists(LockKey)
}