File: follower.go

package info (click to toggle)
golang-github-docker-leadership 0.1.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 96 kB
  • sloc: makefile: 2
file content (74 lines) | stat: -rw-r--r-- 1,423 bytes parent folder | download | duplicates (2)
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/docker/libkv/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)
	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...")
}