Debian Codegraph @

daemon/cluster.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package daemon
5
6 import (
7 "fmt"
8 "math/rand"
9 "sort"
10 "strconv"
11 "strings"
12 "sync"
13 "time"
14
15 . "github.com/etix/mirrorbits/config"
16 "github.com/etix/mirrorbits/database"
17 "github.com/etix/mirrorbits/mirrors"
18 "github.com/etix/mirrorbits/utils"
19 )
20
21 const (
22 clusterAnnouncePrefix = "HELLO"
23 )
24
25 type cluster struct {
26 redis *database.Redis
27
28 nodeID string
29 nodes []node
30 nodeIndex int
31 nodeTotal int
32 nodesLock sync.RWMutex
33 mirrorsIndex []int
34 stop chan bool
35 wg sync.WaitGroup
36 running bool
37 StartStopLock sync.Mutex
38 announceText string
39 }
40
41 type node struct {
42 ID string
43 LastAnnounce int64
44 }
45
46 type byNodeID []node
47
48 func (n byNodeID) Len() int { return len(n) }
49 func (n byNodeID) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
50 func (n byNodeID) Less(i, j int) bool { return n[i].ID < n[j].ID }
51
52 // NewCluster creates a new instance of the cluster agent
53 func NewCluster(r *database.Redis) *cluster {
54 c := &cluster{
55 redis: r,
56 nodes: make([]node, 0),
57 stop: make(chan bool),
58 }
59
60 hostname := utils.Hostname()
61 if len(hostname) == 0 {
62 hostname = "unknown"
63 }
64 c.nodeID = fmt.Sprintf("%s-%05d", hostname, rand.Intn(32000))
65 c.announceText = clusterAnnouncePrefix + strconv.Itoa(GetConfig().RedisDB)
66 return c
67 }
68
69 func (c *cluster) Start() {
70 c.StartStopLock.Lock()
71 defer c.StartStopLock.Unlock()
72
73 if c.running == true {
74 return
75 }
76 log.Debug("Cluster starting...")
77 c.running = true
78 c.wg.Add(1)
79 c.stop = make(chan bool)
80 go c.clusterLoop()
81 }
82
83 func (c *cluster) Stop() {
84 c.StartStopLock.Lock()
85 defer c.StartStopLock.Unlock()
86
87 select {
88 case _, _ = <-c.stop:
89 return
90 default:
91 close(c.stop)
92 c.wg.Wait()
93 c.running = false
94 log.Debug("Cluster stopped")
95 }
96 }
97
98 func (c *cluster) clusterLoop() {
99 clusterChan := make(chan string, 10)
100 announceTicker := time.NewTicker(1 * time.Second)
101
102 c.refreshNodeList(c.nodeID, c.nodeID)
103 c.redis.Pubsub.SubscribeEvent(database.CLUSTER, clusterChan)
104
105 for {
106 select {
107 case <-c.stop:
108 c.wg.Done()
109 return
110 case <-announceTicker.C:
111 c.announce()
112 case data := <-clusterChan:
113 if !strings.HasPrefix(data, c.announceText+" ") {
114 // Garbage
115 continue
116 }
117 c.refreshNodeList(data[len(c.announceText)+1:], c.nodeID)
118 }
119 }
120 }
121
122 func (c *cluster) announce() {
123 r := c.redis.Get()
124 database.Publish(r, database.CLUSTER, fmt.Sprintf("%s %s", c.announceText, c.nodeID))
125 r.Close()
126 }
127
128 func (c *cluster) refreshNodeList(nodeID, self string) {
129 found := false
130
131 c.nodesLock.Lock()
132
133 // Expire unreachable nodes
134 for i := 0; i < len(c.nodes); i++ {
135 if utils.ElapsedSec(c.nodes[i].LastAnnounce, 5) && c.nodes[i].ID != nodeID && c.nodes[i].ID != self {
136 log.Noticef("<- Node %s left the cluster", c.nodes[i].ID)
137 c.nodes = append(c.nodes[:i], c.nodes[i+1:]...)
138 i--
139 } else if c.nodes[i].ID == nodeID {
140 found = true
141 c.nodes[i].LastAnnounce = time.Now().UTC().Unix()
142 }
143 }
144
145 // Join new node
146 if !found {
147 if nodeID != self {
148 log.Noticef("-> Node %s joined the cluster", nodeID)
149 }
150 n := node{
151 ID: nodeID,
152 LastAnnounce: time.Now().UTC().Unix(),
153 }
154 // TODO use binary search here
155 // See https://golang.org/pkg/sort/#Search
156 c.nodes = append(c.nodes, n)
157 sort.Sort(byNodeID(c.nodes))
158 }
159
160 c.nodeTotal = len(c.nodes)
161
162 // TODO use binary search here
163 // See https://golang.org/pkg/sort/#Search
164 for i, n := range c.nodes {
165 if n.ID == self {
166 c.nodeIndex = i
167 break
168 }
169 }
170
171 c.nodesLock.Unlock()
172 }
173
174 func (c *cluster) AddMirror(mirror *mirrors.Mirror) {
175 c.nodesLock.Lock()
176 c.mirrorsIndex = addMirrorIDToSlice(c.mirrorsIndex, mirror.ID)
177 c.nodesLock.Unlock()
178 }
179
180 func (c *cluster) RemoveMirror(mirror *mirrors.Mirror) {
181 c.nodesLock.Lock()
182 c.mirrorsIndex = removeMirrorIDFromSlice(c.mirrorsIndex, mirror.ID)
183 c.nodesLock.Unlock()
184 }
185
186 func (c *cluster) RemoveMirrorID(id int) {
187 c.nodesLock.Lock()
188 c.mirrorsIndex = removeMirrorIDFromSlice(c.mirrorsIndex, id)
189 c.nodesLock.Unlock()
190 }
191
192 func (c *cluster) IsHandled(mirrorID int) bool {
193 c.nodesLock.RLock()
194 defer c.nodesLock.RUnlock()
195 index := sort.SearchInts(c.mirrorsIndex, mirrorID)
196
197 mRange := int(float32(len(c.mirrorsIndex))/float32(c.nodeTotal) + 0.5)
198 start := mRange * c.nodeIndex
199
200 // Check bounding to see if this mirror must be handled by this node.
201 // The distribution of the nodes should be balanced except for the last node
202 // that could contain one more node.
203 if index >= start && (index < start+mRange || c.nodeIndex == c.nodeTotal-1) {
204 return true
205 }
206 return false
207 }
208
209 func removeMirrorIDFromSlice(slice []int, mirrorID int) []int {
210 // See https://golang.org/pkg/sort/#SearchInts
211 idx := sort.SearchInts(slice, mirrorID)
212 if idx < len(slice) && slice[idx] == mirrorID {
213 slice = append(slice[:idx], slice[idx+1:]...)
214 }
215 return slice
216 }
217
218 func addMirrorIDToSlice(slice []int, mirrorID int) []int {
219 // See https://golang.org/pkg/sort/#SearchInts
220 idx := sort.SearchInts(slice, mirrorID)
221 if idx >= len(slice) || slice[idx] != mirrorID {
222 slice = append(slice[:idx], append([]int{mirrorID}, slice[idx:]...)...)
223 }
224 return slice
225 }