-
Notifications
You must be signed in to change notification settings - Fork 0
/
self_evict.go
303 lines (250 loc) · 8.02 KB
/
self_evict.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package swim
import (
"errors"
"math"
"sync"
"sync/atomic"
"time"
"github.com/uber-common/bark"
"github.com/uber/ringpop-go/util"
)
var (
// ErrDuplicateHook is returned when a hook that has already been registered
// is registered again
ErrDuplicateHook = errors.New("hook already registered")
// ErrSelfEvictionInProgress is returned when ringpop is already in the process
// of evicting itself from the network.
ErrSelfEvictionInProgress = errors.New("ringpop is already executing a self-eviction")
)
// SelfEvict defines the functions that interact with the self eviction of nodes
// from the membership prior to shutting down
type SelfEvict interface {
// RegisterSelfEvictHook is used to register a SelfEvictHook interface to be
// called during the shutting down of ringpop. Hooks can't be registered
// after the self eviction has started.
RegisterSelfEvictHook(hooks SelfEvictHook) error
// SelfEvict should be called before shutting down the application to notify
// the members of the membership that this node is going down and should not
// receive reqeusts anymore.
SelfEvict() error
}
// SelfEvictHook is an interface describing a module that can be registered to
// the self eviction hooks
type SelfEvictHook interface {
// PreEvict is the hook that will be called before ringpop evicts itself
// from the membership
PreEvict()
// PostEvict is the hook that will be called after ringpop has evicted
// itself from them memership
PostEvict()
}
type hookFn func(SelfEvictHook)
// SelfEvictOptions configures how self eviction should behave. Applications can
// configure if ringpop should proactively ping members of the network on self
// eviction and what percentage/ratio of the memberlist should be pinged at most
type SelfEvictOptions struct {
PingRatio float64
}
func mergeSelfEvictOptions(opt, def SelfEvictOptions) SelfEvictOptions {
return SelfEvictOptions{
PingRatio: util.SelectFloat(opt.PingRatio, def.PingRatio),
}
}
type evictionPhase int
const (
preEvict evictionPhase = iota
evicting
postEvict
done
)
type phase struct {
phase evictionPhase
start time.Time
end time.Time
// phase specific information
// phase: evicting
numberOfPings int
numberOfSuccessfulPings int32
}
type selfEvict struct {
// lock is used to gate access to state changing operations like registering
// hooks and starting self eviction. After eviction has started all state
// changing functions should return ErrSelfEvictionInProgress
lock sync.Mutex
node *Node
options SelfEvictOptions
logger bark.Logger
phases []*phase
hooks []SelfEvictHook
}
func newSelfEvict(node *Node, options SelfEvictOptions) *selfEvict {
return &selfEvict{
node: node,
options: options,
logger: node.logger,
}
}
// RegisterSelfEvictHook registers a pre/post eviction hook pair. If the hook
// has already been registered before it returns the ErrDuplicateHook and does
// not register it twice.
func (s *selfEvict) RegisterSelfEvictHook(hook SelfEvictHook) error {
// lock the phases to prevent reading the current phase in a race. Unlocking
// will happen when this function terminates to prevent self-eviction to
// start while a hook is being added
s.lock.Lock()
defer s.lock.Unlock()
if s.currentPhase() != nil {
return ErrSelfEvictionInProgress
}
for _, h := range s.hooks {
if h == hook {
return ErrDuplicateHook
}
}
s.hooks = append(s.hooks, hook)
return nil
}
func (s *selfEvict) SelfEvict() error {
// preEvict makes sure that SelfEvict will return ErrSelfEvictionInProgress
// when eviction is already in progress
err := s.preEvict()
if err != nil {
return err
}
s.evict()
s.postEvict()
s.done()
return nil
}
func (s *selfEvict) preEvict() error {
s.lock.Lock()
if s.currentPhase() != nil {
s.lock.Unlock()
return ErrSelfEvictionInProgress
}
s.transitionTo(preEvict)
s.lock.Unlock()
s.logger.Info("ringpop is initiating self eviction sequence")
s.runHooks(SelfEvictHook.PreEvict)
return nil
}
func (s *selfEvict) evict() {
s.lock.Lock()
phase := s.transitionTo(evicting)
s.lock.Unlock()
s.node.memberlist.SetLocalStatus(Faulty)
numberOfPingableMembers := s.node.memberlist.NumPingableMembers()
maxNumberOfPings := int(math.Ceil(float64(numberOfPingableMembers) * s.options.PingRatio))
// final number of members to ping should not exceed any of:
numberOfPings := util.Min(
s.node.disseminator.maxP, // the piggyback counter
numberOfPingableMembers, // the number of members we can ping
maxNumberOfPings, // a configured percentage of members
)
if numberOfPings <= 0 {
// there are no nodes to be pinged, a value below 0 can be caused by a
// negative ping ratio
return
}
// select the members we are going to ping
targets := s.node.memberlist.RandomPingableMembers(numberOfPings, nil)
phase.numberOfPings = len(targets)
s.logger.WithFields(bark.Fields{
"numberOfPings": phase.numberOfPings,
"targets": targets,
}).Debug("starting proactive gossip on self evict")
var wg sync.WaitGroup
wg.Add(len(targets))
for _, target := range targets {
go func(target Member) {
defer wg.Done()
_, err := sendPing(s.node, target.address(), s.node.pingTimeout)
if err == nil {
atomic.AddInt32(&phase.numberOfSuccessfulPings, 1)
}
}(target)
}
wg.Wait()
s.logger.WithFields(bark.Fields{
"numberOfPings": phase.numberOfPings,
"numberOfSuccessfulPings": phase.numberOfSuccessfulPings,
}).Debug("finished proactive gossip on self evict")
}
func (s *selfEvict) postEvict() {
s.lock.Lock()
s.transitionTo(postEvict)
s.lock.Unlock()
s.runHooks(SelfEvictHook.PostEvict)
}
func (s *selfEvict) done() {
s.lock.Lock()
s.transitionTo(done)
phasesCount := len(s.phases)
firstPhase := s.phases[0].start
lastPhase := s.phases[phasesCount-1]
s.lock.Unlock()
duration := lastPhase.end.Sub(firstPhase)
s.logger.WithFields(bark.Fields{
"phases": s.phases,
"totalDuration": duration,
}).Info("ringpop self eviction done")
s.node.EmitEvent(SelfEvictedEvent{
PhasesCount: phasesCount,
Duration: duration,
})
}
func (s *selfEvict) transitionTo(newPhase evictionPhase) *phase {
p := &phase{
phase: newPhase,
start: s.node.clock.Now(),
}
previousPhase := s.currentPhase()
s.phases = append(s.phases, p)
if previousPhase != nil {
previousPhase.end = p.start
}
s.logger.WithFields(bark.Fields{
"newPhase": p,
"oldPhase": previousPhase,
}).Debug("ringpop self eviction phase-transitioning")
return p
}
func (s *selfEvict) currentPhase() *phase {
if len(s.phases) > 0 {
return s.phases[len(s.phases)-1]
}
return nil
}
func (s *selfEvict) runHooks(dispatch hookFn) {
var wg sync.WaitGroup
wg.Add(len(s.hooks))
for _, hook := range s.hooks {
go func(hook SelfEvictHook) {
defer wg.Done()
s.logger.Debugf("ringpop self eviction running hook: %+v", hook)
dispatch(hook)
s.logger.Debugf("ringpop self eviction hook done: %+v", hook)
}(hook)
}
wg.Wait()
s.logger.Debug("ringpop self eviction done running hooks")
}