/
Gossiper.java
1168 lines (1054 loc) · 47.8 KB
/
Gossiper.java
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.gms;
import java.io.DataOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.db.SystemTable;
import org.apache.cassandra.io.util.FastByteArrayOutputStream;
import org.apache.cassandra.net.MessageProducer;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.utils.FBUtilities;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.DebuggableScheduledThreadPoolExecutor;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.StorageService;
/**
* This module is responsible for Gossiping information for the local endpoint. This abstraction
* maintains the list of live and dead endpoints. Periodically i.e. every 1 second this module
* chooses a random node and initiates a round of Gossip with it. A round of Gossip involves 3
* rounds of messaging. For instance if node A wants to initiate a round of Gossip with node B
* it starts off by sending node B a GossipDigestSynMessage. Node B on receipt of this message
* sends node A a GossipDigestAckMessage. On receipt of this message node A sends node B a
* GossipDigestAck2Message which completes a round of Gossip. This module as and when it hears one
* of the three above mentioned messages updates the Failure Detector with the liveness information.
*/
public class Gossiper implements IFailureDetectionEventListener, GossiperMBean
{
private static final String MBEAN_NAME = "org.apache.cassandra.net:type=Gossiper";
private static final DebuggableScheduledThreadPoolExecutor executor = new DebuggableScheduledThreadPoolExecutor("GossipTasks");
static final ApplicationState[] STATES = ApplicationState.values();
static final List<String> DEAD_STATES = Arrays.asList(VersionedValue.REMOVING_TOKEN, VersionedValue.REMOVED_TOKEN,
VersionedValue.STATUS_LEFT, VersionedValue.HIBERNATE);
private ScheduledFuture<?> scheduledGossipTask;
public final static int intervalInMillis = 1000;
public final static int QUARANTINE_DELAY = StorageService.RING_DELAY * 2;
private static Logger logger = LoggerFactory.getLogger(Gossiper.class);
public static final Gossiper instance = new Gossiper();
public static final long aVeryLongTime = 259200 * 1000; // 3 days
private long FatClientTimeout;
private Random random = new Random();
private Comparator<InetAddress> inetcomparator = new Comparator<InetAddress>()
{
public int compare(InetAddress addr1, InetAddress addr2)
{
return addr1.getHostAddress().compareTo(addr2.getHostAddress());
}
};
/* subscribers for interest in EndpointState change */
private List<IEndpointStateChangeSubscriber> subscribers = new CopyOnWriteArrayList<IEndpointStateChangeSubscriber>();
/* live member set */
private Set<InetAddress> liveEndpoints = new ConcurrentSkipListSet<InetAddress>(inetcomparator);
/* unreachable member set */
private Map<InetAddress, Long> unreachableEndpoints = new ConcurrentHashMap<InetAddress, Long>();
/* initial seeds for joining the cluster */
private Set<InetAddress> seeds = new ConcurrentSkipListSet<InetAddress>(inetcomparator);
/* map where key is the endpoint and value is the state associated with the endpoint */
Map<InetAddress, EndpointState> endpointStateMap = new ConcurrentHashMap<InetAddress, EndpointState>();
/* map where key is endpoint and value is timestamp when this endpoint was removed from
* gossip. We will ignore any gossip regarding these endpoints for QUARANTINE_DELAY time
* after removal to prevent nodes from falsely reincarnating during the time when removal
* gossip gets propagated to all nodes */
private Map<InetAddress, Long> justRemovedEndpoints = new ConcurrentHashMap<InetAddress, Long>();
private Map<InetAddress, Long> expireTimeEndpointMap = new ConcurrentHashMap<InetAddress, Long>();
// protocol versions of the other nodes in the cluster
private final ConcurrentMap<InetAddress, Integer> versions = new NonBlockingHashMap<InetAddress, Integer>();
private class GossipTask implements Runnable
{
public void run()
{
try
{
//wait on messaging service to start listening
MessagingService.instance().waitUntilListening();
/* Update the local heartbeat counter. */
endpointStateMap.get(FBUtilities.getBroadcastAddress()).getHeartBeatState().updateHeartBeat();
if (logger.isTraceEnabled())
logger.trace("My heartbeat is now " + endpointStateMap.get(FBUtilities.getBroadcastAddress()).getHeartBeatState().getHeartBeatVersion());
final List<GossipDigest> gDigests = new ArrayList<GossipDigest>();
Gossiper.instance.makeRandomGossipDigest(gDigests);
if ( gDigests.size() > 0 )
{
MessageProducer prod = new MessageProducer()
{
public Message getMessage(Integer version) throws IOException
{
return makeGossipDigestSynMessage(gDigests, version);
}
};
/* Gossip to some random live member */
boolean gossipedToSeed = doGossipToLiveMember(prod);
/* Gossip to some unreachable member with some probability to check if he is back up */
doGossipToUnreachableMember(prod);
/* Gossip to a seed if we did not do so above, or we have seen less nodes
than there are seeds. This prevents partitions where each group of nodes
is only gossiping to a subset of the seeds.
The most straightforward check would be to check that all the seeds have been
verified either as live or unreachable. To avoid that computation each round,
we reason that:
either all the live nodes are seeds, in which case non-seeds that come online
will introduce themselves to a member of the ring by definition,
or there is at least one non-seed node in the list, in which case eventually
someone will gossip to it, and then do a gossip to a random seed from the
gossipedToSeed check.
See CASSANDRA-150 for more exposition. */
if (!gossipedToSeed || liveEndpoints.size() < seeds.size())
doGossipToSeed(prod);
if (logger.isTraceEnabled())
logger.trace("Performing status check ...");
doStatusCheck();
}
}
catch (Exception e)
{
logger.error("Gossip error", e);
}
}
}
private Gossiper()
{
// half of QUARATINE_DELAY, to ensure justRemovedEndpoints has enough leeway to prevent re-gossip
FatClientTimeout = (long)(QUARANTINE_DELAY / 2);
/* register with the Failure Detector for receiving Failure detector events */
FailureDetector.instance.registerFailureDetectionEventListener(this);
// Register this instance with JMX
try
{
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(this, new ObjectName(MBEAN_NAME));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Register for interesting state changes.
* @param subscriber module which implements the IEndpointStateChangeSubscriber
*/
public void register(IEndpointStateChangeSubscriber subscriber)
{
subscribers.add(subscriber);
}
/**
* Unregister interest for state changes.
* @param subscriber module which implements the IEndpointStateChangeSubscriber
*/
public void unregister(IEndpointStateChangeSubscriber subscriber)
{
subscribers.remove(subscriber);
}
public void setVersion(InetAddress address, int version)
{
logger.debug("Setting version {} for {}", version, address);
versions.put(address, version);
}
public void resetVersion(InetAddress endpoint)
{
logger.debug("Reseting version for {}", endpoint);
versions.remove(endpoint);
}
public Integer getVersion(InetAddress address)
{
Integer v = versions.get(address);
if (v == null)
{
// we don't know the version. assume current. we'll know soon enough if that was incorrect.
logger.trace("Assuming current protocol version for {}", address);
return MessagingService.version_;
}
else
return v;
}
public Set<InetAddress> getLiveMembers()
{
Set<InetAddress> liveMbrs = new HashSet<InetAddress>(liveEndpoints);
if (!liveMbrs.contains(FBUtilities.getBroadcastAddress()))
liveMbrs.add(FBUtilities.getBroadcastAddress());
return liveMbrs;
}
public Set<InetAddress> getUnreachableMembers()
{
return unreachableEndpoints.keySet();
}
public long getEndpointDowntime(InetAddress ep)
{
Long downtime = unreachableEndpoints.get(ep);
if (downtime != null)
return System.currentTimeMillis() - downtime;
else
return 0L;
}
/**
* This method is part of IFailureDetectionEventListener interface. This is invoked
* by the Failure Detector when it convicts an end point.
*
* param @ endpoint end point that is convicted.
*/
public void convict(InetAddress endpoint, double phi)
{
EndpointState epState = endpointStateMap.get(endpoint);
if (epState.isAlive())
{
markDead(endpoint, epState);
}
}
/**
* Return either: the greatest heartbeat or application state
* @param epState
* @return
*/
int getMaxEndpointStateVersion(EndpointState epState)
{
int maxVersion = epState.getHeartBeatState().getHeartBeatVersion();
for (VersionedValue value : epState.getApplicationStateMap().values())
maxVersion = Math.max(maxVersion, value.version);
return maxVersion;
}
/**
* Removes the endpoint from gossip completely
*
* @param endpoint endpoint to be removed from the current membership.
*/
private void evictFromMembership(InetAddress endpoint)
{
unreachableEndpoints.remove(endpoint);
endpointStateMap.remove(endpoint);
expireTimeEndpointMap.remove(endpoint);
justRemovedEndpoints.put(endpoint, System.currentTimeMillis());
if (logger.isDebugEnabled())
logger.debug("evicting " + endpoint + " from gossip");
}
/**
* Removes the endpoint from Gossip but retains endpoint state
*/
public void removeEndpoint(InetAddress endpoint)
{
// do subscribers first so anything in the subscriber that depends on gossiper state won't get confused
for (IEndpointStateChangeSubscriber subscriber : subscribers)
subscriber.onRemove(endpoint);
liveEndpoints.remove(endpoint);
unreachableEndpoints.remove(endpoint);
// do not remove endpointState until the quarantine expires
FailureDetector.instance.remove(endpoint);
versions.remove(endpoint);
justRemovedEndpoints.put(endpoint, System.currentTimeMillis());
if (logger.isDebugEnabled())
logger.debug("removing endpoint " + endpoint);
}
/**
* Remove the Endpoint and evict immediately, to avoid gossiping about this node.
* This should only be called when a token is taken over by a new IP address.
* @param endpoint The endpoint that has been replaced
*/
public void replacedEndpoint(InetAddress endpoint)
{
removeEndpoint(endpoint);
evictFromMembership(endpoint);
}
/**
* The gossip digest is built based on randomization
* rather than just looping through the collection of live endpoints.
*
* @param gDigests list of Gossip Digests.
*/
private void makeRandomGossipDigest(List<GossipDigest> gDigests)
{
EndpointState epState;
int generation = 0;
int maxVersion = 0;
// local epstate will be part of endpointStateMap
List<InetAddress> endpoints = new ArrayList<InetAddress>(endpointStateMap.keySet());
Collections.shuffle(endpoints, random);
for (InetAddress endpoint : endpoints)
{
epState = endpointStateMap.get(endpoint);
if (epState != null)
{
generation = epState.getHeartBeatState().getGeneration();
maxVersion = getMaxEndpointStateVersion(epState);
}
gDigests.add(new GossipDigest(endpoint, generation, maxVersion));
}
if (logger.isTraceEnabled())
{
StringBuilder sb = new StringBuilder();
for ( GossipDigest gDigest : gDigests )
{
sb.append(gDigest);
sb.append(" ");
}
logger.trace("Gossip Digests are : " + sb.toString());
}
}
/**
* This method will begin removing an existing endpoint from the cluster by spoofing its state
* This should never be called unless this coordinator has had 'removetoken' invoked
*
* @param endpoint - the endpoint being removed
* @param token - the token being removed
* @param mytoken - my own token for replication coordination
* @param delay
*/
public void advertiseRemoving(InetAddress endpoint, Token token, Token mytoken, int delay)
{
EndpointState epState = endpointStateMap.get(endpoint);
// remember this node's generation
int generation = epState.getHeartBeatState().getGeneration();
logger.info("Removing token: " + token);
logger.info("Sleeping for " + StorageService.RING_DELAY + "ms to ensure " + endpoint + " does not change");
try
{
Thread.sleep(delay);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
// make sure it did not change
epState = endpointStateMap.get(endpoint);
if (epState.getHeartBeatState().getGeneration() != generation)
throw new RuntimeException("Endpoint " + endpoint + " generation changed while trying to remove it");
// update the other node's generation to mimic it as if it had changed it itself
logger.info("Advertising removal for " + endpoint);
epState.updateTimestamp(); // make sure we don't evict it too soon
epState.getHeartBeatState().forceNewerGenerationUnsafe();
epState.addApplicationState(ApplicationState.STATUS, StorageService.instance.valueFactory.removingNonlocal(token));
epState.addApplicationState(ApplicationState.REMOVAL_COORDINATOR, StorageService.instance.valueFactory.removalCoordinator(mytoken));
endpointStateMap.put(endpoint, epState);
}
/**
* Handles switching the endpoint's state from REMOVING_TOKEN to REMOVED_TOKEN
* This should only be called after advertiseRemoving
* @param endpoint
* @param token
*/
public void advertiseTokenRemoved(InetAddress endpoint, Token token)
{
EndpointState epState = endpointStateMap.get(endpoint);
epState.updateTimestamp(); // make sure we don't evict it too soon
epState.getHeartBeatState().forceNewerGenerationUnsafe();
epState.addApplicationState(ApplicationState.STATUS, StorageService.instance.valueFactory.removedNonlocal(token,computeExpireTime()));
logger.info("Completing removal of " + endpoint);
endpointStateMap.put(endpoint, epState);
// ensure at least one gossip round occurs before returning
try
{
Thread.sleep(intervalInMillis * 2);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
}
/**
* Do not call this method unless you know what you are doing.
* It will try extremely hard to obliterate any endpoint from the ring,
* even if it does not know about it.
* This should only ever be called by human via JMX.
* @param address
* @throws UnknownHostException
*/
public void unsafeAssassinateEndpoint(String address) throws UnknownHostException
{
InetAddress endpoint = InetAddress.getByName(address);
EndpointState epState = endpointStateMap.get(endpoint);
Token token = null;
logger.warn("Assassinating {} via gossip", endpoint);
if (epState == null)
{
epState = new EndpointState(new HeartBeatState((int)((System.currentTimeMillis() + 60000) / 1000), 9999));
}
else
{
try
{
token = StorageService.instance.getTokenMetadata().getToken(endpoint);
}
catch (AssertionError e)
{
}
int generation = epState.getHeartBeatState().getGeneration();
logger.info("Sleeping for " + StorageService.RING_DELAY + "ms to ensure " + endpoint + " does not change");
try
{
Thread.sleep(StorageService.RING_DELAY);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
// make sure it did not change
epState = endpointStateMap.get(endpoint);
if (epState.getHeartBeatState().getGeneration() != generation)
throw new RuntimeException("Endpoint " + endpoint + " generation changed while trying to remove it");
epState.updateTimestamp(); // make sure we don't evict it too soon
epState.getHeartBeatState().forceNewerGenerationUnsafe();
}
if (token == null)
token = StorageService.instance.getBootstrapToken();
// do not pass go, do not collect 200 dollars, just gtfo
epState.addApplicationState(ApplicationState.STATUS, StorageService.instance.valueFactory.left(token, computeExpireTime()));
handleMajorStateChange(endpoint, epState);
try
{
Thread.sleep(intervalInMillis * 4);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
logger.warn("Finished killing {}", endpoint);
}
public boolean isKnownEndpoint(InetAddress endpoint)
{
return endpointStateMap.containsKey(endpoint);
}
public int getCurrentGenerationNumber(InetAddress endpoint)
{
return endpointStateMap.get(endpoint).getHeartBeatState().getGeneration();
}
Message makeGossipDigestSynMessage(List<GossipDigest> gDigests, int version) throws IOException
{
GossipDigestSynMessage gDigestMessage = new GossipDigestSynMessage(DatabaseDescriptor.getClusterName(), gDigests);
FastByteArrayOutputStream bos = new FastByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream( bos );
GossipDigestSynMessage.serializer().serialize(gDigestMessage, dos, version);
return new Message(FBUtilities.getBroadcastAddress(), StorageService.Verb.GOSSIP_DIGEST_SYN, bos.toByteArray(), version);
}
Message makeGossipDigestAckMessage(GossipDigestAckMessage gDigestAckMessage, int version) throws IOException
{
FastByteArrayOutputStream bos = new FastByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
GossipDigestAckMessage.serializer().serialize(gDigestAckMessage, dos, version);
return new Message(FBUtilities.getBroadcastAddress(), StorageService.Verb.GOSSIP_DIGEST_ACK, bos.toByteArray(), version);
}
Message makeGossipDigestAck2Message(GossipDigestAck2Message gDigestAck2Message, int version) throws IOException
{
FastByteArrayOutputStream bos = new FastByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
GossipDigestAck2Message.serializer().serialize(gDigestAck2Message, dos, version);
return new Message(FBUtilities.getBroadcastAddress(), StorageService.Verb.GOSSIP_DIGEST_ACK2, bos.toByteArray(), version);
}
/**
* Returns true if the chosen target was also a seed. False otherwise
*
* @param prod produces a message to send
* @param epSet a set of endpoint from which a random endpoint is chosen.
* @return true if the chosen endpoint is also a seed.
*/
private boolean sendGossip(MessageProducer prod, Set<InetAddress> epSet)
{
int size = epSet.size();
if (size < 1)
return false;
/* Generate a random number from 0 -> size */
List<InetAddress> liveEndpoints = new ArrayList<InetAddress>(epSet);
int index = (size == 1) ? 0 : random.nextInt(size);
InetAddress to = liveEndpoints.get(index);
if (logger.isTraceEnabled())
logger.trace("Sending a GossipDigestSynMessage to {} ...", to);
try
{
MessagingService.instance().sendOneWay(prod.getMessage(getVersion(to)), to);
}
catch (IOException ex)
{
throw new IOError(ex);
}
return seeds.contains(to);
}
/* Sends a Gossip message to a live member and returns true if the recipient was a seed */
private boolean doGossipToLiveMember(MessageProducer prod)
{
int size = liveEndpoints.size();
if ( size == 0 )
return false;
return sendGossip(prod, liveEndpoints);
}
/* Sends a Gossip message to an unreachable member */
private void doGossipToUnreachableMember(MessageProducer prod)
{
double liveEndpointCount = liveEndpoints.size();
double unreachableEndpointCount = unreachableEndpoints.size();
if ( unreachableEndpointCount > 0 )
{
/* based on some probability */
double prob = unreachableEndpointCount / (liveEndpointCount + 1);
double randDbl = random.nextDouble();
if ( randDbl < prob )
sendGossip(prod, unreachableEndpoints.keySet());
}
}
/* Gossip to a seed for facilitating partition healing */
private void doGossipToSeed(MessageProducer prod)
{
int size = seeds.size();
if ( size > 0 )
{
if ( size == 1 && seeds.contains(FBUtilities.getBroadcastAddress()) )
{
return;
}
if ( liveEndpoints.size() == 0 )
{
sendGossip(prod, seeds);
}
else
{
/* Gossip with the seed with some probability. */
double probability = seeds.size() / (double)( liveEndpoints.size() + unreachableEndpoints.size() );
double randDbl = random.nextDouble();
if ( randDbl <= probability )
sendGossip(prod, seeds);
}
}
}
private void doStatusCheck()
{
long now = System.currentTimeMillis();
Set<InetAddress> eps = endpointStateMap.keySet();
for ( InetAddress endpoint : eps )
{
if ( endpoint.equals(FBUtilities.getBroadcastAddress()) )
continue;
FailureDetector.instance.interpret(endpoint);
EndpointState epState = endpointStateMap.get(endpoint);
if ( epState != null )
{
long duration = now - epState.getUpdateTimestamp();
// check if this is a fat client. fat clients are removed automatically from
// gosip after FatClientTimeout
if (!epState.hasToken() && !epState.isAlive() && !justRemovedEndpoints.containsKey(endpoint) && (duration > FatClientTimeout))
{
if (StorageService.instance.getTokenMetadata().isMember(endpoint))
epState.setHasToken(true);
else
{
logger.info("FatClient " + endpoint + " has been silent for " + FatClientTimeout + "ms, removing from gossip");
removeEndpoint(endpoint); // will put it in justRemovedEndpoints to respect quarantine delay
evictFromMembership(endpoint); // can get rid of the state immediately
}
}
long expireTime = getExpireTimeForEndpoint(endpoint);
if (!epState.isAlive() && (now > expireTime)
&& (!StorageService.instance.getTokenMetadata().isMember(endpoint)))
{
if (logger.isDebugEnabled())
{
logger.debug("time is expiring for endpoint : " + endpoint + " (" + expireTime + ")");
}
evictFromMembership(endpoint);
}
}
}
if (!justRemovedEndpoints.isEmpty())
{
for (Entry<InetAddress, Long> entry : justRemovedEndpoints.entrySet())
{
if ((now - entry.getValue()) > QUARANTINE_DELAY)
{
if (logger.isDebugEnabled())
logger.debug(QUARANTINE_DELAY + " elapsed, " + entry.getKey() + " gossip quarantine over");
justRemovedEndpoints.remove(entry.getKey());
}
}
}
}
protected long getExpireTimeForEndpoint(InetAddress endpoint)
{
/* default expireTime is aVeryLongTime */
long expireTime = computeExpireTime();
if (expireTimeEndpointMap.containsKey(endpoint))
{
expireTime = expireTimeEndpointMap.get(endpoint);
}
return expireTime;
}
public EndpointState getEndpointStateForEndpoint(InetAddress ep)
{
return endpointStateMap.get(ep);
}
public Set<Entry<InetAddress, EndpointState>> getEndpointStates()
{
return endpointStateMap.entrySet();
}
EndpointState getStateForVersionBiggerThan(InetAddress forEndpoint, int version)
{
EndpointState epState = endpointStateMap.get(forEndpoint);
EndpointState reqdEndpointState = null;
if ( epState != null )
{
/*
* Here we try to include the Heart Beat state only if it is
* greater than the version passed in. It might happen that
* the heart beat version maybe lesser than the version passed
* in and some application state has a version that is greater
* than the version passed in. In this case we also send the old
* heart beat and throw it away on the receiver if it is redundant.
*/
int localHbVersion = epState.getHeartBeatState().getHeartBeatVersion();
if ( localHbVersion > version )
{
reqdEndpointState = new EndpointState(epState.getHeartBeatState());
if (logger.isTraceEnabled())
logger.trace("local heartbeat version " + localHbVersion + " greater than " + version + " for " + forEndpoint);
}
/* Accumulate all application states whose versions are greater than "version" variable */
for (Entry<ApplicationState, VersionedValue> entry : epState.getApplicationStateMap().entrySet())
{
VersionedValue value = entry.getValue();
if ( value.version > version )
{
if ( reqdEndpointState == null )
{
reqdEndpointState = new EndpointState(epState.getHeartBeatState());
}
final ApplicationState key = entry.getKey();
if (logger.isTraceEnabled())
logger.trace("Adding state " + key + ": " + value.value);
reqdEndpointState.addApplicationState(key, value);
}
}
}
return reqdEndpointState;
}
/** determine which endpoint started up earlier */
public int compareEndpointStartup(InetAddress addr1, InetAddress addr2)
{
EndpointState ep1 = getEndpointStateForEndpoint(addr1);
EndpointState ep2 = getEndpointStateForEndpoint(addr2);
assert ep1 != null && ep2 != null;
return ep1.getHeartBeatState().getGeneration() - ep2.getHeartBeatState().getGeneration();
}
void notifyFailureDetector(List<GossipDigest> gDigests)
{
for ( GossipDigest gDigest : gDigests )
{
notifyFailureDetector(gDigest.endpoint, endpointStateMap.get(gDigest.endpoint));
}
}
void notifyFailureDetector(Map<InetAddress, EndpointState> remoteEpStateMap)
{
for (Entry<InetAddress, EndpointState> entry : remoteEpStateMap.entrySet())
{
notifyFailureDetector(entry.getKey(), entry.getValue());
}
}
void notifyFailureDetector(InetAddress endpoint, EndpointState remoteEndpointState)
{
EndpointState localEndpointState = endpointStateMap.get(endpoint);
/*
* If the local endpoint state exists then report to the FD only
* if the versions workout.
*/
if ( localEndpointState != null )
{
IFailureDetector fd = FailureDetector.instance;
int localGeneration = localEndpointState.getHeartBeatState().getGeneration();
int remoteGeneration = remoteEndpointState.getHeartBeatState().getGeneration();
if ( remoteGeneration > localGeneration )
{
localEndpointState.updateTimestamp();
// this node was dead and the generation changed, this indicates a reboot, or possibly a takeover
// we will clean the fd intervals for it and relearn them
if (!localEndpointState.isAlive())
{
logger.debug("Clearing interval times for {} due to generation change", endpoint);
fd.clear(endpoint);
}
fd.report(endpoint);
return;
}
if ( remoteGeneration == localGeneration )
{
int localVersion = getMaxEndpointStateVersion(localEndpointState);
int remoteVersion = remoteEndpointState.getHeartBeatState().getHeartBeatVersion();
if ( remoteVersion > localVersion )
{
localEndpointState.updateTimestamp();
// just a version change, report to the fd
fd.report(endpoint);
}
}
}
}
private void markAlive(InetAddress addr, EndpointState localState)
{
if (logger.isTraceEnabled())
logger.trace("marking as alive {}", addr);
localState.markAlive();
localState.updateTimestamp(); // prevents doStatusCheck from racing us and evicting if it was down > aVeryLongTime
liveEndpoints.add(addr);
unreachableEndpoints.remove(addr);
expireTimeEndpointMap.remove(addr);
logger.debug("removing expire time for endpoint : " + addr);
logger.info("InetAddress {} is now UP", addr);
for (IEndpointStateChangeSubscriber subscriber : subscribers)
subscriber.onAlive(addr, localState);
if (logger.isTraceEnabled())
logger.trace("Notified " + subscribers);
}
private void markDead(InetAddress addr, EndpointState localState)
{
if (logger.isTraceEnabled())
logger.trace("marking as dead {}", addr);
localState.markDead();
liveEndpoints.remove(addr);
unreachableEndpoints.put(addr, System.currentTimeMillis());
logger.info("InetAddress {} is now dead.", addr);
for (IEndpointStateChangeSubscriber subscriber : subscribers)
subscriber.onDead(addr, localState);
if (logger.isTraceEnabled())
logger.trace("Notified " + subscribers);
}
/**
* This method is called whenever there is a "big" change in ep state (a generation change for a known node).
*
* @param ep endpoint
* @param epState EndpointState for the endpoint
*/
private void handleMajorStateChange(InetAddress ep, EndpointState epState)
{
if (!isDeadState(epState))
{
if (endpointStateMap.get(ep) != null)
logger.info("Node {} has restarted, now UP", ep);
else
logger.info("Node {} is now part of the cluster", ep);
}
if (logger.isTraceEnabled())
logger.trace("Adding endpoint state for " + ep);
endpointStateMap.put(ep, epState);
// the node restarted: it is up to the subscriber to take whatever action is necessary
for (IEndpointStateChangeSubscriber subscriber : subscribers)
subscriber.onRestart(ep, epState);
if (!isDeadState(epState))
markAlive(ep, epState);
else
{
logger.debug("Not marking " + ep + " alive due to dead state");
markDead(ep, epState);
epState.setHasToken(true); // fat clients won't have a dead state
}
for (IEndpointStateChangeSubscriber subscriber : subscribers)
subscriber.onJoin(ep, epState);
}
private Boolean isDeadState(EndpointState epState)
{
if (epState.getApplicationState(ApplicationState.STATUS) == null)
return false;
String value = epState.getApplicationState(ApplicationState.STATUS).value;
String[] pieces = value.split(VersionedValue.DELIMITER_STR, -1);
assert (pieces.length > 0);
String state = pieces[0];
for (String deadstate : DEAD_STATES)
{
if (state.equals(deadstate))
return true;
}
return false;
}
void applyStateLocally(Map<InetAddress, EndpointState> epStateMap)
{
for (Entry<InetAddress, EndpointState> entry : epStateMap.entrySet())
{
InetAddress ep = entry.getKey();
if ( ep.equals(FBUtilities.getBroadcastAddress()))
continue;
if (justRemovedEndpoints.containsKey(ep))
{
if (logger.isTraceEnabled())
logger.trace("Ignoring gossip for " + ep + " because it is quarantined");
continue;
}
EndpointState localEpStatePtr = endpointStateMap.get(ep);
EndpointState remoteState = entry.getValue();
/*
If state does not exist just add it. If it does then add it if the remote generation is greater.
If there is a generation tie, attempt to break it by heartbeat version.
*/
if ( localEpStatePtr != null )
{
int localGeneration = localEpStatePtr.getHeartBeatState().getGeneration();
int remoteGeneration = remoteState.getHeartBeatState().getGeneration();
if (logger.isTraceEnabled())
logger.trace(ep + "local generation " + localGeneration + ", remote generation " + remoteGeneration);
if (remoteGeneration > localGeneration)
{
if (logger.isTraceEnabled())
logger.trace("Updating heartbeat state generation to " + remoteGeneration + " from " + localGeneration + " for " + ep);
// major state change will handle the update by inserting the remote state directly
handleMajorStateChange(ep, remoteState);
}
else if ( remoteGeneration == localGeneration ) // generation has not changed, apply new states
{
/* find maximum state */
int localMaxVersion = getMaxEndpointStateVersion(localEpStatePtr);
int remoteMaxVersion = getMaxEndpointStateVersion(remoteState);
if ( remoteMaxVersion > localMaxVersion )
{
// apply states, but do not notify since there is no major change
applyNewStates(ep, localEpStatePtr, remoteState);
}
else if (logger.isTraceEnabled())
logger.trace("Ignoring remote version " + remoteMaxVersion + " <= " + localMaxVersion + " for " + ep);
if (!localEpStatePtr.isAlive() && !isDeadState(localEpStatePtr)) // unless of course, it was dead
markAlive(ep, localEpStatePtr);
}
else
{
if (logger.isTraceEnabled())
logger.trace("Ignoring remote generation " + remoteGeneration + " < " + localGeneration);
}
}
else
{
// this is a new node
handleMajorStateChange(ep, remoteState);
}
}
}
private void applyNewStates(InetAddress addr, EndpointState localState, EndpointState remoteState)
{
// don't assert here, since if the node restarts the version will go back to zero
int oldVersion = localState.getHeartBeatState().getHeartBeatVersion();
localState.setHeartBeatState(remoteState.getHeartBeatState());
if (logger.isTraceEnabled())
logger.trace("Updating heartbeat state version to " + localState.getHeartBeatState().getHeartBeatVersion() + " from " + oldVersion + " for " + addr + " ...");
for (Entry<ApplicationState, VersionedValue> remoteEntry : remoteState.getApplicationStateMap().entrySet())
{
ApplicationState remoteKey = remoteEntry.getKey();
VersionedValue remoteValue = remoteEntry.getValue();
assert remoteState.getHeartBeatState().getGeneration() == localState.getHeartBeatState().getGeneration();
localState.addApplicationState(remoteKey, remoteValue);
doNotifications(addr, remoteKey, remoteValue);
}
}
// notify that an application state has changed
private void doNotifications(InetAddress addr, ApplicationState state, VersionedValue value)
{
for (IEndpointStateChangeSubscriber subscriber : subscribers)
{
subscriber.onChange(addr, state, value);
}
}
/* Request all the state for the endpoint in the gDigest */
private void requestAll(GossipDigest gDigest, List<GossipDigest> deltaGossipDigestList, int remoteGeneration)
{
/* We are here since we have no data for this endpoint locally so request everthing. */
deltaGossipDigestList.add( new GossipDigest(gDigest.getEndpoint(), remoteGeneration, 0) );
if (logger.isTraceEnabled())
logger.trace("requestAll for " + gDigest.getEndpoint());
}
/* Send all the data with version greater than maxRemoteVersion */
private void sendAll(GossipDigest gDigest, Map<InetAddress, EndpointState> deltaEpStateMap, int maxRemoteVersion)
{
EndpointState localEpStatePtr = getStateForVersionBiggerThan(gDigest.getEndpoint(), maxRemoteVersion) ;
if ( localEpStatePtr != null )
deltaEpStateMap.put(gDigest.getEndpoint(), localEpStatePtr);
}
/*
This method is used to figure the state that the Gossiper has but Gossipee doesn't. The delta digests
and the delta state are built up.
*/
void examineGossiper(List<GossipDigest> gDigestList, List<GossipDigest> deltaGossipDigestList, Map<InetAddress, EndpointState> deltaEpStateMap)
{
for ( GossipDigest gDigest : gDigestList )
{
int remoteGeneration = gDigest.getGeneration();
int maxRemoteVersion = gDigest.getMaxVersion();
/* Get state associated with the end point in digest */
EndpointState epStatePtr = endpointStateMap.get(gDigest.getEndpoint());
/*
Here we need to fire a GossipDigestAckMessage. If we have some data associated with this endpoint locally
then we follow the "if" path of the logic. If we have absolutely nothing for this endpoint we need to