-
Notifications
You must be signed in to change notification settings - Fork 587
/
serf.go
1935 lines (1662 loc) · 54.8 KB
/
serf.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package serf
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net"
"os"
"regexp"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-msgpack/codec"
"github.com/hashicorp/memberlist"
"github.com/hashicorp/serf/coordinate"
)
// These are the protocol versions that Serf can _understand_. These are
// Serf-level protocol versions that are passed down as the delegate
// version to memberlist below.
const (
ProtocolVersionMin uint8 = 2
ProtocolVersionMax = 5
)
const (
// Used to detect if the meta data is tags
// or if it is a raw role
tagMagicByte uint8 = 255
)
const MaxNodeNameLength int = 128
var (
// FeatureNotSupported is returned if a feature cannot be used
// due to an older protocol version being used.
FeatureNotSupported = fmt.Errorf("Feature not supported")
)
func init() {
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
}
// ReconnectTimeoutOverrider is an interface that can be implemented to allow overriding
// the reconnect timeout for individual members.
type ReconnectTimeoutOverrider interface {
ReconnectTimeout(member *Member, timeout time.Duration) time.Duration
}
// Serf is a single node that is part of a single cluster that gets
// events about joins/leaves/failures/etc. It is created with the Create
// method.
//
// All functions on the Serf structure are safe to call concurrently.
type Serf struct {
// The clocks for different purposes. These MUST be the first things
// in this struct due to Golang issue #599.
clock LamportClock
eventClock LamportClock
queryClock LamportClock
broadcasts *memberlist.TransmitLimitedQueue
config *Config
failedMembers []*memberState
leftMembers []*memberState
memberlist *memberlist.Memberlist
memberLock sync.RWMutex
members map[string]*memberState
// recentIntents the lamport time and type of intent for a given node in
// case we get an intent before the relevant memberlist event. This is
// indexed by node, and always store the latest lamport time / intent
// we've seen. The memberLock protects this structure.
recentIntents map[string]nodeIntent
eventBroadcasts *memberlist.TransmitLimitedQueue
eventBuffer []*userEvents
eventJoinIgnore atomic.Value
eventMinTime LamportTime
eventLock sync.RWMutex
queryBroadcasts *memberlist.TransmitLimitedQueue
queryBuffer []*queries
queryMinTime LamportTime
queryResponse map[LamportTime]*QueryResponse
queryLock sync.RWMutex
logger *log.Logger
joinLock sync.Mutex
stateLock sync.Mutex
state SerfState
shutdownCh chan struct{}
snapshotter *Snapshotter
keyManager *KeyManager
coordClient *coordinate.Client
coordCache map[string]*coordinate.Coordinate
coordCacheLock sync.RWMutex
// metricLabels is the slice of labels to put on all emitted metrics
metricLabels []metrics.Label
}
// SerfState is the state of the Serf instance.
type SerfState int
const (
SerfAlive SerfState = iota
SerfLeaving
SerfLeft
SerfShutdown
)
func (s SerfState) String() string {
switch s {
case SerfAlive:
return "alive"
case SerfLeaving:
return "leaving"
case SerfLeft:
return "left"
case SerfShutdown:
return "shutdown"
default:
return "unknown"
}
}
// Member is a single member of the Serf cluster.
type Member struct {
Name string
Addr net.IP
Port uint16
Tags map[string]string
Status MemberStatus
// The minimum, maximum, and current values of the protocol versions
// and delegate (Serf) protocol versions that each member can understand
// or is speaking.
ProtocolMin uint8
ProtocolMax uint8
ProtocolCur uint8
DelegateMin uint8
DelegateMax uint8
DelegateCur uint8
}
// MemberStatus is the state that a member is in.
type MemberStatus int
const (
StatusNone MemberStatus = iota
StatusAlive
StatusLeaving
StatusLeft
StatusFailed
)
func (s MemberStatus) String() string {
switch s {
case StatusNone:
return "none"
case StatusAlive:
return "alive"
case StatusLeaving:
return "leaving"
case StatusLeft:
return "left"
case StatusFailed:
return "failed"
default:
panic(fmt.Sprintf("unknown MemberStatus: %d", s))
}
}
// memberState is used to track members that are no longer active due to
// leaving, failing, partitioning, etc. It tracks the member along with
// when that member was marked as leaving.
type memberState struct {
Member
statusLTime LamportTime // lamport clock time of last received message
leaveTime time.Time // wall clock time of leave
}
// nodeIntent is used to buffer intents for out-of-order deliveries.
type nodeIntent struct {
// Type is the intent being tracked. Only messageJoinType and
// messageLeaveType are tracked.
Type messageType
// WallTime is the wall clock time we saw this intent in order to
// expire it from the buffer.
WallTime time.Time
// LTime is the Lamport time, used for cluster-wide ordering of events.
LTime LamportTime
}
// userEvent is used to buffer events to prevent re-delivery
type userEvent struct {
Name string
Payload []byte
}
func (ue *userEvent) Equals(other *userEvent) bool {
if ue.Name != other.Name {
return false
}
if bytes.Compare(ue.Payload, other.Payload) != 0 {
return false
}
return true
}
// userEvents stores all the user events at a specific time
type userEvents struct {
LTime LamportTime
Events []userEvent
}
// queries stores all the query ids at a specific time
type queries struct {
LTime LamportTime
QueryIDs []uint32
}
const (
snapshotSizeLimit = 128 * 1024 // Maximum 128 KB snapshot
UserEventSizeLimit = 9 * 1024 // Maximum 9KB for event name and payload
)
// Create creates a new Serf instance, starting all the background tasks
// to maintain cluster membership information.
//
// After calling this function, the configuration should no longer be used
// or modified by the caller.
func Create(conf *Config) (*Serf, error) {
conf.Init()
if conf.ProtocolVersion < ProtocolVersionMin {
return nil, fmt.Errorf("Protocol version '%d' too low. Must be in range: [%d, %d]",
conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
} else if conf.ProtocolVersion > ProtocolVersionMax {
return nil, fmt.Errorf("Protocol version '%d' too high. Must be in range: [%d, %d]",
conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
}
if conf.UserEventSizeLimit > UserEventSizeLimit {
return nil, fmt.Errorf("user event size limit exceeds limit of %d bytes", UserEventSizeLimit)
}
logger := conf.Logger
if logger == nil {
logOutput := conf.LogOutput
if logOutput == nil {
logOutput = os.Stderr
}
logger = log.New(logOutput, "", log.LstdFlags)
}
serf := &Serf{
config: conf,
logger: logger,
members: make(map[string]*memberState),
queryResponse: make(map[LamportTime]*QueryResponse),
shutdownCh: make(chan struct{}),
state: SerfAlive,
metricLabels: conf.MetricLabels,
}
serf.eventJoinIgnore.Store(false)
// Check that the meta data length is okay
if len(serf.encodeTags(conf.Tags)) > memberlist.MetaMaxSize {
return nil, fmt.Errorf("Encoded length of tags exceeds limit of %d bytes", memberlist.MetaMaxSize)
}
if err := serf.ValidateNodeNames(); err != nil {
return nil, err
}
// Check if serf member event coalescing is enabled
if conf.CoalescePeriod > 0 && conf.QuiescentPeriod > 0 && conf.EventCh != nil {
c := &memberEventCoalescer{
lastEvents: make(map[string]EventType),
latestEvents: make(map[string]coalesceEvent),
}
conf.EventCh = coalescedEventCh(conf.EventCh, serf.shutdownCh,
conf.CoalescePeriod, conf.QuiescentPeriod, c)
}
// Check if user event coalescing is enabled
if conf.UserCoalescePeriod > 0 && conf.UserQuiescentPeriod > 0 && conf.EventCh != nil {
c := &userEventCoalescer{
events: make(map[string]*latestUserEvents),
}
conf.EventCh = coalescedEventCh(conf.EventCh, serf.shutdownCh,
conf.UserCoalescePeriod, conf.UserQuiescentPeriod, c)
}
// Listen for internal Serf queries. This is setup before the snapshotter, since
// we want to capture the query-time, but the internal listener does not passthrough
// the queries
outCh, err := newSerfQueries(serf, serf.logger, conf.EventCh, serf.shutdownCh)
if err != nil {
return nil, fmt.Errorf("Failed to setup serf query handler: %v", err)
}
conf.EventCh = outCh
// Set up network coordinate client.
if !conf.DisableCoordinates {
coordinateConfig := coordinate.DefaultConfig()
coordinateConfig.MetricLabels = serf.metricLabels
serf.coordClient, err = coordinate.NewClient(coordinateConfig)
if err != nil {
return nil, fmt.Errorf("Failed to create coordinate client: %v", err)
}
}
// Try access the snapshot
var oldClock, oldEventClock, oldQueryClock LamportTime
var prev []*PreviousNode
if conf.SnapshotPath != "" {
eventCh, snap, err := NewSnapshotter(
conf.SnapshotPath,
snapshotSizeLimit,
conf.RejoinAfterLeave,
serf.logger,
&serf.clock,
conf.EventCh,
serf.shutdownCh)
if err != nil {
return nil, fmt.Errorf("Failed to setup snapshot: %v", err)
}
snap.metricLabels = serf.metricLabels
serf.snapshotter = snap
conf.EventCh = eventCh
prev = snap.AliveNodes()
oldClock = snap.LastClock()
oldEventClock = snap.LastEventClock()
oldQueryClock = snap.LastQueryClock()
serf.eventMinTime = oldEventClock + 1
serf.queryMinTime = oldQueryClock + 1
}
// Set up the coordinate cache. We do this after we read the snapshot to
// make sure we get a good initial value from there, if we got one.
if !conf.DisableCoordinates {
serf.coordCache = make(map[string]*coordinate.Coordinate)
serf.coordCache[conf.NodeName] = serf.coordClient.GetCoordinate()
}
// Setup the various broadcast queues, which we use to send our own
// custom broadcasts along the gossip channel.
serf.broadcasts = &memberlist.TransmitLimitedQueue{
NumNodes: serf.NumNodes,
RetransmitMult: conf.MemberlistConfig.RetransmitMult,
}
serf.eventBroadcasts = &memberlist.TransmitLimitedQueue{
NumNodes: serf.NumNodes,
RetransmitMult: conf.MemberlistConfig.RetransmitMult,
}
serf.queryBroadcasts = &memberlist.TransmitLimitedQueue{
NumNodes: serf.NumNodes,
RetransmitMult: conf.MemberlistConfig.RetransmitMult,
}
// Create the buffer for recent intents
serf.recentIntents = make(map[string]nodeIntent)
// Create a buffer for events and queries
serf.eventBuffer = make([]*userEvents, conf.EventBuffer)
serf.queryBuffer = make([]*queries, conf.QueryBuffer)
// Ensure our lamport clock is at least 1, so that the default
// join LTime of 0 does not cause issues
serf.clock.Increment()
serf.eventClock.Increment()
serf.queryClock.Increment()
// Restore the clock from snap if we have one
serf.clock.Witness(oldClock)
serf.eventClock.Witness(oldEventClock)
serf.queryClock.Witness(oldQueryClock)
// Modify the memberlist configuration with keys that we set
conf.MemberlistConfig.Events = &eventDelegate{serf: serf}
conf.MemberlistConfig.Conflict = &conflictDelegate{serf: serf}
conf.MemberlistConfig.Delegate = &delegate{serf: serf}
conf.MemberlistConfig.DelegateProtocolVersion = conf.ProtocolVersion
conf.MemberlistConfig.DelegateProtocolMin = ProtocolVersionMin
conf.MemberlistConfig.DelegateProtocolMax = ProtocolVersionMax
conf.MemberlistConfig.Name = conf.NodeName
conf.MemberlistConfig.ProtocolVersion = ProtocolVersionMap[conf.ProtocolVersion]
if !conf.DisableCoordinates {
conf.MemberlistConfig.Ping = &pingDelegate{serf: serf}
}
// Setup a merge delegate if necessary
if conf.Merge != nil {
md := &mergeDelegate{serf: serf}
conf.MemberlistConfig.Merge = md
conf.MemberlistConfig.Alive = md
}
conf.MemberlistConfig.MetricLabels = conf.MetricLabels
// Create the underlying memberlist that will manage membership
// and failure detection for the Serf instance.
memberlist, err := memberlist.Create(conf.MemberlistConfig)
if err != nil {
return nil, fmt.Errorf("Failed to create memberlist: %v", err)
}
serf.memberlist = memberlist
// Create a key manager for handling all encryption key changes
serf.keyManager = &KeyManager{serf: serf}
// Start the background tasks. See the documentation above each method
// for more information on their role.
go serf.handleReap()
go serf.handleReconnect()
go serf.checkQueueDepth("Intent", serf.broadcasts)
go serf.checkQueueDepth("Event", serf.eventBroadcasts)
go serf.checkQueueDepth("Query", serf.queryBroadcasts)
// Attempt to re-join the cluster if we have known nodes
if len(prev) != 0 {
go serf.handleRejoin(prev)
}
return serf, nil
}
// ProtocolVersion returns the current protocol version in use by Serf.
// This is the Serf protocol version, not the memberlist protocol version.
func (s *Serf) ProtocolVersion() uint8 {
return s.config.ProtocolVersion
}
// EncryptionEnabled is a predicate that determines whether or not encryption
// is enabled, which can be possible in one of 2 cases:
// - Single encryption key passed at agent start (no persistence)
// - Keyring file provided at agent start
func (s *Serf) EncryptionEnabled() bool {
return s.config.MemberlistConfig.Keyring != nil
}
// KeyManager returns the key manager for the current Serf instance.
func (s *Serf) KeyManager() *KeyManager {
return s.keyManager
}
// UserEvent is used to broadcast a custom user event with a given
// name and payload. If the configured size limit is exceeded and error will be returned.
// If coalesce is enabled, nodes are allowed to coalesce this event.
// Coalescing is only available starting in v0.2
func (s *Serf) UserEvent(name string, payload []byte, coalesce bool) error {
payloadSizeBeforeEncoding := len(name) + len(payload)
// Check size before encoding to prevent needless encoding and return early if it's over the specified limit.
if payloadSizeBeforeEncoding > s.config.UserEventSizeLimit {
return fmt.Errorf(
"user event exceeds configured limit of %d bytes before encoding",
s.config.UserEventSizeLimit,
)
}
if payloadSizeBeforeEncoding > UserEventSizeLimit {
return fmt.Errorf(
"user event exceeds sane limit of %d bytes before encoding",
UserEventSizeLimit,
)
}
// Create a message
msg := messageUserEvent{
LTime: s.eventClock.Time(),
Name: name,
Payload: payload,
CC: coalesce,
}
// Start broadcasting the event
raw, err := encodeMessage(messageUserEventType, &msg)
if err != nil {
return err
}
// Check the size after encoding to be sure again that
// we're not attempting to send over the specified size limit.
if len(raw) > s.config.UserEventSizeLimit {
return fmt.Errorf(
"encoded user event exceeds configured limit of %d bytes after encoding",
s.config.UserEventSizeLimit,
)
}
if len(raw) > UserEventSizeLimit {
return fmt.Errorf(
"encoded user event exceeds reasonable limit of %d bytes after encoding",
UserEventSizeLimit,
)
}
s.eventClock.Increment()
// Process update locally
s.handleUserEvent(&msg)
s.eventBroadcasts.QueueBroadcast(&broadcast{
msg: raw,
})
return nil
}
// Query is used to broadcast a new query. The query must be fairly small,
// and an error will be returned if the size limit is exceeded. This is only
// available with protocol version 4 and newer. Query parameters are optional,
// and if not provided, a sane set of defaults will be used.
func (s *Serf) Query(name string, payload []byte, params *QueryParam) (*QueryResponse, error) {
// Check that the latest protocol is in use
if s.ProtocolVersion() < 4 {
return nil, FeatureNotSupported
}
// Provide default parameters if none given
if params == nil {
params = s.DefaultQueryParams()
} else if params.Timeout == 0 {
params.Timeout = s.DefaultQueryTimeout()
}
// Get the local node
local := s.memberlist.LocalNode()
// Encode the filters
filters, err := params.encodeFilters()
if err != nil {
return nil, fmt.Errorf("Failed to format filters: %v", err)
}
// Setup the flags
var flags uint32
if params.RequestAck {
flags |= queryFlagAck
}
// Create a message
q := messageQuery{
LTime: s.queryClock.Time(),
ID: uint32(rand.Int31()),
Addr: local.Addr,
Port: local.Port,
SourceNode: local.Name,
Filters: filters,
Flags: flags,
RelayFactor: params.RelayFactor,
Timeout: params.Timeout,
Name: name,
Payload: payload,
}
// Encode the query
raw, err := encodeMessage(messageQueryType, &q)
if err != nil {
return nil, err
}
// Check the size
if len(raw) > s.config.QuerySizeLimit {
return nil, fmt.Errorf("query exceeds limit of %d bytes", s.config.QuerySizeLimit)
}
// Register QueryResponse to track acks and responses
resp := newQueryResponse(s.memberlist.NumMembers(), &q)
s.registerQueryResponse(params.Timeout, resp)
// Process query locally
s.handleQuery(&q)
// Start broadcasting the event
s.queryBroadcasts.QueueBroadcast(&broadcast{
msg: raw,
})
return resp, nil
}
// registerQueryResponse is used to setup the listeners for the query,
// and to schedule closing the query after the timeout.
func (s *Serf) registerQueryResponse(timeout time.Duration, resp *QueryResponse) {
s.queryLock.Lock()
defer s.queryLock.Unlock()
// Map the LTime to the QueryResponse. This is necessarily 1-to-1,
// since we increment the time for each new query.
s.queryResponse[resp.lTime] = resp
// Setup a timer to close the response and deregister after the timeout
time.AfterFunc(timeout, func() {
s.queryLock.Lock()
delete(s.queryResponse, resp.lTime)
resp.Close()
s.queryLock.Unlock()
})
}
// SetTags is used to dynamically update the tags associated with
// the local node. This will propagate the change to the rest of
// the cluster. Blocks until a the message is broadcast out.
func (s *Serf) SetTags(tags map[string]string) error {
// Check that the meta data length is okay
if len(s.encodeTags(tags)) > memberlist.MetaMaxSize {
return fmt.Errorf("Encoded length of tags exceeds limit of %d bytes",
memberlist.MetaMaxSize)
}
// Update the config
s.config.Tags = tags
// Trigger a memberlist update
return s.memberlist.UpdateNode(s.config.BroadcastTimeout)
}
// Join joins an existing Serf cluster. Returns the number of nodes
// successfully contacted. The returned error will be non-nil only in the
// case that no nodes could be contacted. If ignoreOld is true, then any
// user messages sent prior to the join will be ignored.
func (s *Serf) Join(existing []string, ignoreOld bool) (int, error) {
// Do a quick state check
if s.State() != SerfAlive {
return 0, fmt.Errorf("Serf can't Join after Leave or Shutdown")
}
// Hold the joinLock, this is to make eventJoinIgnore safe
s.joinLock.Lock()
defer s.joinLock.Unlock()
// Ignore any events from a potential join. This is safe since we hold
// the joinLock and nobody else can be doing a Join
if ignoreOld {
s.eventJoinIgnore.Store(true)
defer func() {
s.eventJoinIgnore.Store(false)
}()
}
// Have memberlist attempt to join
num, err := s.memberlist.Join(existing)
// If we joined any nodes, broadcast the join message
if num > 0 {
// Start broadcasting the update
if err := s.broadcastJoin(s.clock.Time()); err != nil {
return num, err
}
}
return num, err
}
// broadcastJoin broadcasts a new join intent with a
// given clock value. It is used on either join, or if
// we need to refute an older leave intent. Cannot be called
// with the memberLock held.
func (s *Serf) broadcastJoin(ltime LamportTime) error {
// Construct message to update our lamport clock
msg := messageJoin{
LTime: ltime,
Node: s.config.NodeName,
}
s.clock.Witness(ltime)
// Process update locally
s.handleNodeJoinIntent(&msg)
// Start broadcasting the update
if err := s.broadcast(messageJoinType, &msg, nil); err != nil {
s.logger.Printf("[WARN] serf: Failed to broadcast join intent: %v", err)
return err
}
return nil
}
// Leave gracefully exits the cluster. It is safe to call this multiple
// times.
// If the Leave broadcast timeout, Leave() will try to finish the sequence as best effort.
func (s *Serf) Leave() error {
// Check the current state
s.stateLock.Lock()
if s.state == SerfLeft {
s.stateLock.Unlock()
return nil
} else if s.state == SerfLeaving {
s.stateLock.Unlock()
return fmt.Errorf("Leave already in progress")
} else if s.state == SerfShutdown {
s.stateLock.Unlock()
return fmt.Errorf("Leave called after Shutdown")
}
s.state = SerfLeaving
s.stateLock.Unlock()
// If we have a snapshot, mark we are leaving
if s.snapshotter != nil {
s.snapshotter.Leave()
}
// Construct the message for the graceful leave
msg := messageLeave{
LTime: s.clock.Time(),
Node: s.config.NodeName,
}
s.clock.Increment()
// Process the leave locally
s.handleNodeLeaveIntent(&msg)
// Only broadcast the leave message if there is at least one
// other node alive.
if s.hasAliveMembers() {
notifyCh := make(chan struct{})
if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil {
return err
}
select {
case <-notifyCh:
case <-time.After(s.config.BroadcastTimeout):
s.logger.Printf("[WARN] serf: timeout while waiting for graceful leave")
}
}
// Attempt the memberlist leave
err := s.memberlist.Leave(s.config.BroadcastTimeout)
if err != nil {
s.logger.Printf("[WARN] serf: timeout waiting for leave broadcast: %s", err.Error())
}
// Wait for the leave to propagate through the cluster. The broadcast
// timeout is how long we wait for the message to go out from our own
// queue, but this wait is for that message to propagate through the
// cluster. In particular, we want to stay up long enough to service
// any probes from other nodes before they learn about us leaving.
time.Sleep(s.config.LeavePropagateDelay)
// Transition to Left only if we not already shutdown
s.stateLock.Lock()
if s.state != SerfShutdown {
s.state = SerfLeft
}
s.stateLock.Unlock()
return nil
}
// hasAliveMembers is called to check for any alive members other than
// ourself.
func (s *Serf) hasAliveMembers() bool {
s.memberLock.RLock()
defer s.memberLock.RUnlock()
hasAlive := false
for _, m := range s.members {
// Skip ourself, we want to know if OTHER members are alive
if m.Name == s.config.NodeName {
continue
}
if m.Status == StatusAlive {
hasAlive = true
break
}
}
return hasAlive
}
// LocalMember returns the Member information for the local node
func (s *Serf) LocalMember() Member {
s.memberLock.RLock()
defer s.memberLock.RUnlock()
return s.members[s.config.NodeName].Member
}
// Members returns a point-in-time snapshot of the members of this cluster.
func (s *Serf) Members() []Member {
s.memberLock.RLock()
defer s.memberLock.RUnlock()
members := make([]Member, 0, len(s.members))
for _, m := range s.members {
members = append(members, m.Member)
}
return members
}
// RemoveFailedNode is a backwards compatible form
// of forceleave
func (s *Serf) RemoveFailedNode(node string) error {
return s.forceLeave(node, false)
}
func (s *Serf) RemoveFailedNodePrune(node string) error {
return s.forceLeave(node, true)
}
// ForceLeave forcibly removes a failed node from the cluster
// immediately, instead of waiting for the reaper to eventually reclaim it.
// This also has the effect that Serf will no longer attempt to reconnect
// to this node.
func (s *Serf) forceLeave(node string, prune bool) error {
// Construct the message to broadcast
msg := messageLeave{
LTime: s.clock.Time(),
Node: node,
Prune: prune,
}
s.clock.Increment()
// Process our own event
s.handleNodeLeaveIntent(&msg)
// If we have no members, then we don't need to broadcast
if !s.hasAliveMembers() {
return nil
}
// Broadcast the remove
notifyCh := make(chan struct{})
if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil {
return err
}
// Wait for the broadcast
select {
case <-notifyCh:
case <-time.After(s.config.BroadcastTimeout):
return fmt.Errorf("timed out broadcasting node removal")
}
return nil
}
// Shutdown forcefully shuts down the Serf instance, stopping all network
// activity and background maintenance associated with the instance.
//
// This is not a graceful shutdown, and should be preceded by a call
// to Leave. Otherwise, other nodes in the cluster will detect this node's
// exit as a node failure.
//
// It is safe to call this method multiple times.
func (s *Serf) Shutdown() error {
s.stateLock.Lock()
defer s.stateLock.Unlock()
if s.state == SerfShutdown {
return nil
}
if s.state != SerfLeft {
s.logger.Printf("[WARN] serf: Shutdown without a Leave")
}
// Wait to close the shutdown channel until after we've shut down the
// memberlist and its associated network resources, since the shutdown
// channel signals that we are cleaned up outside of Serf.
s.state = SerfShutdown
err := s.memberlist.Shutdown()
if err != nil {
return err
}
close(s.shutdownCh)
// Wait for the snapshoter to finish if we have one
if s.snapshotter != nil {
s.snapshotter.Wait()
}
return nil
}
// ShutdownCh returns a channel that can be used to wait for
// Serf to shutdown.
func (s *Serf) ShutdownCh() <-chan struct{} {
return s.shutdownCh
}
// Memberlist is used to get access to the underlying Memberlist instance
func (s *Serf) Memberlist() *memberlist.Memberlist {
return s.memberlist
}
// State is the current state of this Serf instance.
func (s *Serf) State() SerfState {
s.stateLock.Lock()
defer s.stateLock.Unlock()
return s.state
}
// broadcast takes a Serf message type, encodes it for the wire, and queues
// the broadcast. If a notify channel is given, this channel will be closed
// when the broadcast is sent.
func (s *Serf) broadcast(t messageType, msg interface{}, notify chan<- struct{}) error {
raw, err := encodeMessage(t, msg)
if err != nil {
return err
}
s.broadcasts.QueueBroadcast(&broadcast{
msg: raw,
notify: notify,
})
return nil
}
// handleNodeJoin is called when a node join event is received
// from memberlist.
func (s *Serf) handleNodeJoin(n *memberlist.Node) {
s.memberLock.Lock()
defer s.memberLock.Unlock()
if s.config.messageDropper(messageJoinType) {
return
}
var oldStatus MemberStatus
member, ok := s.members[n.Name]
if !ok {
oldStatus = StatusNone
member = &memberState{
Member: Member{
Name: n.Name,
Addr: n.Addr,
Port: n.Port,
Tags: s.decodeTags(n.Meta),
Status: StatusAlive,
},
}
// Check if we have a join or leave intent. The intent buffer
// will only hold one event for this node, so the more recent
// one will take effect.
if join, ok := recentIntent(s.recentIntents, n.Name, messageJoinType); ok {
member.statusLTime = join
}
if leave, ok := recentIntent(s.recentIntents, n.Name, messageLeaveType); ok {
member.Status = StatusLeaving
member.statusLTime = leave
}
s.members[n.Name] = member
} else {
oldStatus = member.Status
deadTime := time.Now().Sub(member.leaveTime)
if oldStatus == StatusFailed && deadTime < s.config.FlapTimeout {
metrics.IncrCounterWithLabels([]string{"serf", "member", "flap"}, 1, s.metricLabels)
}
member.Status = StatusAlive
member.leaveTime = time.Time{}
member.Addr = n.Addr
member.Port = n.Port
member.Tags = s.decodeTags(n.Meta)
}
// Update the protocol versions every time we get an event
member.ProtocolMin = n.PMin
member.ProtocolMax = n.PMax
member.ProtocolCur = n.PCur
member.DelegateMin = n.DMin
member.DelegateMax = n.DMax
member.DelegateCur = n.DCur
// If node was previously in a failed state, then clean up some
// internal accounting.
// TODO(mitchellh): needs tests to verify not reaped
if oldStatus == StatusFailed || oldStatus == StatusLeft {
s.failedMembers = removeOldMember(s.failedMembers, member.Name)
s.leftMembers = removeOldMember(s.leftMembers, member.Name)
}
// Update some metrics
metrics.IncrCounterWithLabels([]string{"serf", "member", "join"}, 1, s.metricLabels)
// Send an event along
s.logger.Printf("[INFO] serf: EventMemberJoin: %s %s",
member.Member.Name, member.Member.Addr)
if s.config.EventCh != nil {