-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcluster.go
287 lines (238 loc) · 6.89 KB
/
cluster.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package libring
import (
"fmt"
"sort"
"github.com/Sirupsen/logrus"
"github.com/hashicorp/serf/serf"
)
// Cluster is the primary libring interface
type Cluster struct {
exit chan bool
config Config
memberMap map[string]*serf.Member
ring *ring
Serf *serf.Serf
serfEvents chan serf.Event
logger *logrus.Logger
}
// NewCluster returns a new cluster with the given config
func NewCluster(config Config) (*Cluster, error) {
logger := logrus.New()
logger.Out = config.LogOutput
logger.Level = logrus.Level(config.LogLevel)
if config.SerfConfig == nil {
return nil, fmt.Errorf("Config.SerfConfig cannot be nil")
}
if config.SerfConfig.EventCh != nil {
return nil, fmt.Errorf("SerfConfig.EventCh must be nil (try using Config.SerfEvents instead)")
}
memberMap := make(map[string]*serf.Member)
ring := &ring{
distribution: config.PartitionDistribution,
partitionCount: config.Partitions,
members: make([]*serf.Member, 0, 0),
}
serfEvents := make(chan serf.Event, 256)
config.SerfConfig.EventCh = serfEvents
nodeSerf, err := serf.Create(config.SerfConfig)
if err != nil {
return nil, fmt.Errorf("Unable to create serf: %v", err)
}
exit := make(chan bool)
cluster := &Cluster{
exit: exit,
config: config,
memberMap: memberMap,
ring: ring,
serfEvents: serfEvents,
Serf: nodeSerf,
logger: logger,
}
return cluster, nil
}
// Run starts the Serf protocol and begins listening for Serf events.
func (c *Cluster) Run() {
c.logger.Info("Running node")
if len(c.config.BootstrapHosts) > 0 {
c.Serf.Join(c.config.BootstrapHosts, true)
}
for {
select {
case e := <-c.serfEvents:
c.handleSerfEvent(e)
case <-c.exit:
c.exit <- true
return
}
}
}
// Stop gracefully leaves the Serf cluster and terminates background tasks
func (c *Cluster) Stop() {
c.logger.Info("Stopping node")
c.Serf.Leave()
c.exit <- true
<-c.exit
}
// MembersForKey returns a channel of Serf members for a given key. The first member in the
// channel is "replica 0". All members of the cluster (including failed nodes)
// will be written to the channel once, then it will be closed. Nodes which have
// left the clsuter gracefully or have been reaped will not be included.
//
// The first N members in the channel can be seen as a key's "preference set" as
// described in the dynamo paper.
func (c *Cluster) MembersForKey(key string) []serf.Member {
c.logger.Infof("Getting members for key: %s", key)
return c.ring.membersForKey(key)
}
// MembersForPartition does the same as MembersForKey, but takes a partition
// rather than a key
func (c *Cluster) MembersForPartition(partition uint) []serf.Member {
c.logger.Infof("Getting members for partition: %d", partition)
return c.ring.membersForPartition(partition)
}
func (c *Cluster) handleRingChange(event *serf.Event, oldRing *ring, newRing *ring) {
for partition := uint(0); partition < c.config.Partitions; partition++ {
oldMembers := oldRing.membersForPartition(partition)
newMembers := newRing.membersForPartition(partition)
if len(oldMembers) > int(c.config.Redundancy) {
oldMembers = oldMembers[:c.config.Redundancy]
}
if len(newMembers) > int(c.config.Redundancy) {
newMembers = newMembers[:c.config.Redundancy]
}
if c.config.Events != nil {
for replica := uint(0); replica < c.config.Redundancy; replica++ {
// If partition/replica used to be owned by the local node
for _, oldMember := range oldMembers {
if oldMember.Name == c.Serf.LocalMember().Name {
// ...but isn't any longer
newMember := newRing.member(partition, replica)
if newMember == nil || newMember.Name != c.Serf.LocalMember().Name {
event := Event{
Type: Release,
Partition: partition,
Replica: replica,
To: newMember,
SerfEvent: event,
}
c.config.Events <- event
}
}
}
}
}
if c.config.Events != nil {
for replica := uint(0); replica < c.config.Redundancy; replica++ {
for _, newMember := range newMembers {
if newMember.Name == c.Serf.LocalMember().Name {
// ...but didn't used to be
oldMember := oldRing.member(partition, replica)
if oldMember == nil || oldMember.Name != c.Serf.LocalMember().Name {
event := Event{
Type: Acquisition,
Partition: partition,
Replica: replica,
From: oldRing.member(partition, replica),
SerfEvent: event,
}
c.config.Events <- event
}
}
}
}
}
}
}
func (c *Cluster) addEventMembers(e serf.Event) {
oldRing := *c.ring
for _, member := range e.(serf.MemberEvent).Members {
c.memberMap[member.Name] = &member
}
c.recomputeRing()
newRing := *c.ring
c.handleRingChange(&e, &oldRing, &newRing)
}
func (c *Cluster) updateEventMembers(e serf.Event) {
oldRing := *c.ring
for _, member := range e.(serf.MemberEvent).Members {
c.memberMap[member.Name] = &member
}
c.recomputeRing()
newRing := *c.ring
c.handleRingChange(&e, &oldRing, &newRing)
}
func (c *Cluster) removeEventMembers(e serf.Event) {
oldRing := *c.ring
for _, member := range e.(serf.MemberEvent).Members {
delete(c.memberMap, member.Name)
}
c.recomputeRing()
newRing := *c.ring
c.handleRingChange(&e, &oldRing, &newRing)
}
func (c *Cluster) handleSerfEvent(e serf.Event) {
switch e.EventType() {
case serf.EventMemberJoin:
c.logger.Debug("Handling member join event")
c.addEventMembers(e)
case serf.EventMemberLeave:
c.logger.Debug("Handling graceful member exit event")
c.removeEventMembers(e)
case serf.EventMemberFailed:
c.logger.Debug("Handling unresponsive member event")
c.removeEventMembers(e)
case serf.EventMemberUpdate:
c.logger.Debug("Handling member metadata update event")
c.updateEventMembers(e)
case serf.EventMemberReap:
c.logger.Debug("Handling forced member exit event")
c.removeEventMembers(e)
default:
c.logger.Warnf("Unhandled Serf event: %#v", e)
}
if c.config.SerfEvents != nil {
c.config.SerfEvents <- e
}
}
func (c *Cluster) recomputeRing() {
keys := make([]string, 0, len(c.memberMap))
for k, member := range c.memberMap {
if c.hasWatchedTag(member) {
keys = append(keys, k)
}
}
members := make([]*serf.Member, len(keys), len(keys))
if len(keys) == 0 {
c.ring = &ring{
members: members,
partitionCount: c.config.Partitions,
distribution: c.config.PartitionDistribution,
}
return
}
sort.Strings(keys)
for i, k := range keys {
members[i], _ = c.memberMap[k]
}
c.ring = &ring{
members: members,
partitionCount: c.config.Partitions,
distribution: c.config.PartitionDistribution,
}
}
func (c *Cluster) hasWatchedTag(member *serf.Member) bool {
if len(c.config.WatchTags) == 0 {
return true
}
for tag, re := range c.config.WatchTags {
memberTag, ok := member.Tags[tag]
if !ok {
continue
}
if !re.MatchString(memberTag) {
continue
}
return true
}
return false
}