-
Notifications
You must be signed in to change notification settings - Fork 612
/
JGroupsTransport.java
1621 lines (1470 loc) · 65.9 KB
/
JGroupsTransport.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
package org.infinispan.remoting.transport.jgroups;
import static org.infinispan.remoting.transport.jgroups.JGroupsAddressCache.fromJGroupsAddress;
import static org.infinispan.util.logging.Log.CLUSTER;
import static org.infinispan.util.logging.Log.CONTAINER;
import static org.infinispan.util.logging.Log.XSITE;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.management.ObjectName;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.FileLookup;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.commons.util.TypedProperties;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.logging.TraceException;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.TransportConfiguration;
import org.infinispan.configuration.global.TransportConfigurationBuilder;
import org.infinispan.external.JGroupsProtocolComponent;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.impl.MBeanMetadata;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.jmx.ObjectNameKeys;
import org.infinispan.metrics.impl.MetricsCollector;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.remoting.inboundhandler.DeliverOrder;
import org.infinispan.remoting.inboundhandler.InboundInvocationHandler;
import org.infinispan.remoting.inboundhandler.Reply;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.responses.ValidResponse;
import org.infinispan.remoting.rpc.ResponseFilter;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.transport.AbstractRequest;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.BackupResponse;
import org.infinispan.remoting.transport.ResponseCollector;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.XSiteResponse;
import org.infinispan.remoting.transport.impl.FilterMapResponseCollector;
import org.infinispan.remoting.transport.impl.MapResponseCollector;
import org.infinispan.remoting.transport.impl.MultiTargetRequest;
import org.infinispan.remoting.transport.impl.Request;
import org.infinispan.remoting.transport.impl.RequestRepository;
import org.infinispan.remoting.transport.impl.SingleResponseCollector;
import org.infinispan.remoting.transport.impl.SingleTargetRequest;
import org.infinispan.remoting.transport.impl.SingletonMapResponseCollector;
import org.infinispan.remoting.transport.impl.SiteUnreachableXSiteResponse;
import org.infinispan.remoting.transport.impl.XSiteResponseImpl;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.GlobalXSiteAdminOperations;
import org.infinispan.xsite.XSiteBackup;
import org.infinispan.xsite.XSiteNamedCache;
import org.infinispan.xsite.XSiteReplicateCommand;
import org.infinispan.xsite.commands.XSiteViewNotificationCommand;
import org.jgroups.ChannelListener;
import org.jgroups.Event;
import org.jgroups.Header;
import org.jgroups.JChannel;
import org.jgroups.MergeView;
import org.jgroups.Message;
import org.jgroups.PhysicalAddress;
import org.jgroups.UpHandler;
import org.jgroups.View;
import org.jgroups.blocks.RequestCorrelator;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.jmx.JmxConfigurator;
import org.jgroups.protocols.relay.RELAY2;
import org.jgroups.protocols.relay.RouteStatusListener;
import org.jgroups.protocols.relay.SiteAddress;
import org.jgroups.protocols.relay.SiteMaster;
import org.jgroups.stack.Protocol;
import org.jgroups.util.ExtendedUUID;
import org.jgroups.util.MessageBatch;
import org.jgroups.util.SocketFactory;
/**
* An encapsulation of a JGroups transport. JGroups transports can be configured using a variety of methods, usually by
* passing in one of the following properties:
* <ul>
* <li><tt>configurationString</tt> - a JGroups configuration String</li>
* <li><tt>configurationXml</tt> - JGroups configuration XML as a String</li>
* <li><tt>configurationFile</tt> - String pointing to a JGroups XML configuration file</li>
* <li><tt>channelLookup</tt> - Fully qualified class name of a
* {@link JGroupsChannelLookup} instance</li>
* </ul>
* These are normally passed in as Properties in
* {@link TransportConfigurationBuilder#withProperties(Properties)} or
* in the Infinispan XML configuration file.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
@JGroupsProtocolComponent("JGroupsMetricsMetadata")
public class JGroupsTransport implements Transport, ChannelListener {
public static final String CONFIGURATION_STRING = "configurationString";
public static final String CONFIGURATION_XML = "configurationXml";
public static final String CONFIGURATION_FILE = "configurationFile";
public static final String CHANNEL_LOOKUP = "channelLookup";
public static final String CHANNEL_CONFIGURATOR = "channelConfigurator";
public static final String SOCKET_FACTORY = "socketFactory";
private static final String METRICS_PREFIX = "jgroups_";
public static final short REQUEST_FLAGS_UNORDERED =
(short) (Message.Flag.OOB.value() | Message.Flag.NO_TOTAL_ORDER.value());
public static final short REQUEST_FLAGS_PER_SENDER = Message.Flag.NO_TOTAL_ORDER.value();
public static final short REPLY_FLAGS =
(short) (Message.Flag.NO_FC.value() | Message.Flag.OOB.value() |
Message.Flag.NO_TOTAL_ORDER.value());
protected static final String DEFAULT_JGROUPS_CONFIGURATION_FILE = "default-configs/default-jgroups-udp.xml";
public static final Log log = LogFactory.getLog(JGroupsTransport.class);
private static final CompletableFuture<Map<Address, Response>> EMPTY_RESPONSES_FUTURE =
CompletableFuture.completedFuture(Collections.emptyMap());
private static final short CORRELATOR_ID = (short) 0;
private static final short HEADER_ID = ClassConfigurator.getProtocolId(RequestCorrelator.class);
private static final byte REQUEST = 0;
private static final byte RESPONSE = 1;
private static final byte SINGLE_MESSAGE = 2;
@Inject protected GlobalConfiguration configuration;
@Inject @ComponentName(KnownComponentNames.INTERNAL_MARSHALLER)
protected StreamingMarshaller marshaller;
@Inject protected CacheManagerNotifier notifier;
@Inject protected TimeService timeService;
@Inject protected InboundInvocationHandler invocationHandler;
@Inject @ComponentName(KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR)
protected ScheduledExecutorService timeoutExecutor;
@Inject @ComponentName(KnownComponentNames.NON_BLOCKING_EXECUTOR)
protected ExecutorService nonBlockingExecutor;
@Inject protected CacheManagerJmxRegistration jmxRegistration;
@Inject protected GlobalXSiteAdminOperations globalXSiteAdminOperations;
@Inject protected ComponentRef<MetricsCollector> metricsCollector;
private final Lock viewUpdateLock = new ReentrantLock();
private final Condition viewUpdateCondition = viewUpdateLock.newCondition();
private final ThreadPoolProbeHandler probeHandler;
private final ChannelCallbacks channelCallbacks = new ChannelCallbacks();
private final Map<JChannel, Set<Object>> clusters = new HashMap<>();
protected boolean connectChannel = true, disconnectChannel = true, closeChannel = true;
protected TypedProperties props;
protected JChannel channel;
protected Address address;
protected Address physicalAddress;
// these members are not valid until we have received the first view on a second thread
// and channelConnectedLatch is signaled
protected volatile ClusterView clusterView =
new ClusterView(ClusterView.INITIAL_VIEW_ID, Collections.emptyList(), null);
private CompletableFuture<Void> nextViewFuture = new CompletableFuture<>();
private RequestRepository requests;
private final Map<String, SiteUnreachableReason> unreachableSites;
private String localSite;
// ------------------------------------------------------------------------------------------------------------------
// Lifecycle and setup stuff
// ------------------------------------------------------------------------------------------------------------------
private boolean running;
/**
* This form is used when the transport is created by an external source and passed in to the GlobalConfiguration.
*
* @param channel created and running channel to use
*/
public JGroupsTransport(JChannel channel) {
this();
this.channel = channel;
if (channel == null)
throw new IllegalArgumentException("Cannot deal with a null channel!");
if (channel.isConnected())
throw new IllegalArgumentException("Channel passed in cannot already be connected!");
}
public JGroupsTransport() {
this.probeHandler = new ThreadPoolProbeHandler();
this.unreachableSites = new ConcurrentHashMap<>();
}
@Override
public CompletableFuture<Map<Address, Response>> invokeRemotelyAsync(Collection<Address> recipients,
ReplicableCommand command,
ResponseMode mode, long timeout,
ResponseFilter responseFilter,
DeliverOrder deliverOrder,
boolean anycast) {
if (recipients != null && recipients.isEmpty()) {
// don't send if recipients list is empty
log.tracef("Destination list is empty: no need to send command %s", command);
return EMPTY_RESPONSES_FUTURE;
}
ClusterView view = this.clusterView;
List<Address> localMembers = view.getMembers();
int membersSize = localMembers.size();
boolean ignoreLeavers =
mode == ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS || mode == ResponseMode.WAIT_FOR_VALID_RESPONSE;
boolean sendStaggeredRequest = mode == ResponseMode.WAIT_FOR_VALID_RESPONSE &&
deliverOrder == DeliverOrder.NONE && recipients != null && recipients.size() > 1 && timeout > 0;
// ISPN-6997: Never allow a switch from anycast -> broadcast and broadcast -> unicast
// We're still keeping the option to switch for a while in case forcing a broadcast in a 2-node replicated cache
// impacts performance significantly. If that is the case, we may need to use UNICAST3.closeConnection() instead.
boolean broadcast = recipients == null;
if (recipients == null && membersSize == 1) {
// don't send if recipients list is empty
log.tracef("The cluster has a single node: no need to broadcast command %s", command);
return EMPTY_RESPONSES_FUTURE;
}
Address singleTarget = computeSingleTarget(recipients, localMembers, membersSize, broadcast);
if (address.equals(singleTarget)) {
log.tracef("Skipping request to self for command %s", command);
return EMPTY_RESPONSES_FUTURE;
}
if (mode.isAsynchronous()) {
// Asynchronous RPC. Send the message, but don't wait for responses.
return performAsyncRemoteInvocation(recipients, command, deliverOrder, broadcast, singleTarget);
}
Collection<Address> actualTargets = broadcast ? localMembers : recipients;
return performSyncRemoteInvocation(actualTargets, command, mode, timeout, responseFilter, deliverOrder,
ignoreLeavers, sendStaggeredRequest, broadcast, singleTarget);
}
@Override
public void sendTo(Address destination, ReplicableCommand command, DeliverOrder deliverOrder) {
if (destination.equals(address)) { //removed requireNonNull. this will throw a NPE in that case
if (log.isTraceEnabled())
log.tracef("%s not sending command to self: %s", address, command);
return;
}
logCommand(command, destination);
sendCommand(destination, command, Request.NO_REQUEST_ID, deliverOrder, true, true);
}
@Override
public void sendToMany(Collection<Address> targets, ReplicableCommand command, DeliverOrder deliverOrder) {
if (targets == null) {
logCommand(command, "all");
sendCommandToAll(command, Request.NO_REQUEST_ID, deliverOrder);
} else {
logCommand(command, targets);
sendCommand(targets, command, Request.NO_REQUEST_ID, deliverOrder, true);
}
}
@Override
@Deprecated
public Map<Address, Response> invokeRemotely(Map<Address, ReplicableCommand> commands, ResponseMode mode,
long timeout, ResponseFilter responseFilter, DeliverOrder deliverOrder,
boolean anycast)
throws Exception {
if (commands == null || commands.isEmpty()) {
// don't send if recipients list is empty
log.trace("Destination list is empty: no need to send message");
return Collections.emptyMap();
}
if (mode.isSynchronous()) {
MapResponseCollector collector = MapResponseCollector.validOnly(commands.size());
CompletionStage<Map<Address, Response>> request =
invokeCommands(commands.keySet(), commands::get, collector, deliverOrder, timeout, TimeUnit.MILLISECONDS);
try {
return CompletableFutures.await(request.toCompletableFuture());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
cause.addSuppressed(new TraceException());
throw Util.rewrapAsCacheException(cause);
}
} else {
commands.forEach(
(a, command) -> {
logCommand(command, a);
sendCommand(a, command, Request.NO_REQUEST_ID, deliverOrder, true, true);
});
return Collections.emptyMap();
}
}
@Override
public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand command) {
if (log.isTraceEnabled())
log.tracef("About to send to backups %s, command %s", backups, command);
Map<XSiteBackup, CompletableFuture<ValidResponse>> backupCalls = new HashMap<>(backups.size());
for (XSiteBackup xsb : backups) {
assert !localSite.equals(xsb.getSiteName()) : "sending to local site";
Address recipient = JGroupsAddressCache.fromJGroupsAddress(new SiteMaster(xsb.getSiteName()));
long requestId = requests.newRequestId();
logRequest(requestId, command, recipient, "backup");
SingleSiteRequest<ValidResponse> request =
new SingleSiteRequest<>(SingleResponseCollector.validOnly(), requestId, requests, xsb.getSiteName());
addRequest(request);
backupCalls.put(xsb, request);
DeliverOrder order = xsb.isSync() ? DeliverOrder.NONE : DeliverOrder.PER_SENDER;
long timeout = xsb.getTimeout();
try {
sendCommand(recipient, command, request.getRequestId(), order, false, false);
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, TimeUnit.MILLISECONDS);
}
} catch (Throwable t) {
request.cancel(true);
throw t;
}
}
return new JGroupsBackupResponse(backupCalls, timeService);
}
@Override
public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) {
assert !localSite.equals(backup.getSiteName()) : "sending to local site";
if (unreachableSites.containsKey(backup.getSiteName())) {
// fail fast if we have thread handling a SITE_UNREACHABLE event.
return new SiteUnreachableXSiteResponse<>(backup, timeService);
}
Address recipient = JGroupsAddressCache.fromJGroupsAddress(new SiteMaster(backup.getSiteName()));
long requestId = requests.newRequestId();
logRequest(requestId, rpcCommand, recipient, "backup");
SingleSiteRequest<ValidResponse> request =
new SingleSiteRequest<>(SingleResponseCollector.validOnly(), requestId, requests, backup.getSiteName());
addRequest(request);
DeliverOrder order = backup.isSync() ? DeliverOrder.NONE : DeliverOrder.PER_SENDER;
long timeout = backup.getTimeout();
XSiteResponseImpl<O> xSiteResponse = new XSiteResponseImpl<>(timeService, backup);
try {
sendCommand(recipient, rpcCommand, request.getRequestId(), order, false, false);
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, TimeUnit.MILLISECONDS);
}
request.whenComplete(xSiteResponse);
} catch (Throwable t) {
request.cancel(true);
xSiteResponse.completeExceptionally(t);
}
return xSiteResponse;
}
@Override
public boolean isCoordinator() {
return clusterView.isCoordinator();
}
@Override
public Address getCoordinator() {
return clusterView.getCoordinator();
}
@Override
public Address getAddress() {
return address;
}
@Override
public List<Address> getPhysicalAddresses() {
if (physicalAddress == null && channel != null) {
org.jgroups.Address addr =
(org.jgroups.Address) channel.down(new Event(Event.GET_PHYSICAL_ADDRESS, channel.getAddress()));
if (addr == null) {
return Collections.emptyList();
}
physicalAddress = new JGroupsAddress(addr);
}
return Collections.singletonList(physicalAddress);
}
@Override
public List<Address> getMembers() {
return clusterView.getMembers();
}
@Override
public List<Address> getMembersPhysicalAddresses() {
if (channel != null) {
View v = channel.getView();
org.jgroups.Address[] rawMembers = v.getMembersRaw();
List<Address> addresses = new ArrayList<>(rawMembers.length);
for (org.jgroups.Address rawMember : rawMembers) {
PhysicalAddress physical_addr = (PhysicalAddress) channel.down(new Event(Event.GET_PHYSICAL_ADDRESS, rawMember));
addresses.add(new JGroupsAddress(physical_addr));
}
return addresses;
} else {
return Collections.emptyList();
}
}
@Override
public boolean isMulticastCapable() {
return channel.getProtocolStack().getTransport().supportsMulticasting();
}
@Override
public void checkCrossSiteAvailable() throws CacheConfigurationException {
if (localSite == null) {
throw CLUSTER.crossSiteUnavailable();
}
}
@Override
public String localSiteName() {
return localSite;
}
@Start
@Override
public void start() {
if (running)
throw new IllegalStateException("Two or more cache managers are using the same JGroupsTransport instance");
probeHandler.updateThreadPool(nonBlockingExecutor);
props = TypedProperties.toTypedProperties(configuration.transport().properties());
requests = new RequestRepository();
String stack = configuration.transport().stack();
if (stack != null) {
CLUSTER.startingJGroupsChannel(configuration.transport().clusterName(), configuration.transport().stack());
} else {
CLUSTER.startingJGroupsChannel(configuration.transport().clusterName());
}
initChannel();
channel.setUpHandler(channelCallbacks);
setXSiteViewListener(channelCallbacks);
startJGroupsChannelIfNeeded();
waitForInitialNodes();
channel.getProtocolStack().getTransport().registerProbeHandler(probeHandler);
RELAY2 relay2 = findRelay2();
if (relay2 != null) {
localSite = XSiteNamedCache.cachedString(relay2.site());
}
running = true;
}
protected void initChannel() {
TransportConfiguration transportCfg = configuration.transport();
if (channel == null) {
buildChannel();
if (connectChannel) {
// Cannot change the name if the channelLookup already connected the channel
String transportNodeName = transportCfg.nodeName();
if (transportNodeName != null && !transportNodeName.isEmpty()) {
channel.setName(transportNodeName);
}
}
}
// Channel.LOCAL *must* be set to false so we don't see our own messages - otherwise
// invalidations targeted at remote instances will be received by self.
// NOTE: total order needs to deliver own messages. the invokeRemotely method has a total order boolean
// that when it is false, it discard our own messages, maintaining the property needed
channel.setDiscardOwnMessages(false);
// if we have a TopologyAwareConsistentHash, we need to set our own address generator in JGroups
if (transportCfg.hasTopologyInfo()) {
// We can do this only if the channel hasn't been started already
if (connectChannel) {
channel.addAddressGenerator(() -> JGroupsTopologyAwareAddress
.randomUUID(channel.getName(), transportCfg.siteId(), transportCfg.rackId(),
transportCfg.machineId()));
} else {
org.jgroups.Address jgroupsAddress = channel.getAddress();
if (jgroupsAddress instanceof ExtendedUUID) {
JGroupsTopologyAwareAddress address = new JGroupsTopologyAwareAddress((ExtendedUUID) jgroupsAddress);
if (!address.matches(transportCfg.siteId(), transportCfg.rackId(), transportCfg.machineId())) {
throw new CacheException(
"Topology information does not match the one set by the provided JGroups channel");
}
} else {
throw new CacheException("JGroups address does not contain topology coordinates");
}
}
}
}
private void setXSiteViewListener(RouteStatusListener listener) {
RELAY2 relay2 = findRelay2();
if (relay2 != null) {
relay2.setRouteStatusListener(listener);
// if a node join, and is a site master, to a running cluster, it does not get any site up/down event.
// there is a chance to get a duplicated log entry but it does not matter.
Collection<String> view = getSitesView();
if (view != null && !view.isEmpty()) {
XSITE.receivedXSiteClusterView(view);
}
}
}
/**
* When overwriting this method, it allows third-party libraries to create a new behavior like: After {@link
* JChannel} has been created and before it is connected.
*/
protected void startJGroupsChannelIfNeeded() {
String clusterName = configuration.transport().clusterName();
if (log.isDebugEnabled()) {
log.debugf("JGroups protocol stack: %s\n", channel.getProtocolStack().printProtocolSpec(true));
}
if (connectChannel) {
try {
channel.connect(clusterName);
} catch (Exception e) {
throw new CacheException("Unable to start JGroups Channel", e);
}
}
registerMBeansIfNeeded(clusterName);
if (!connectChannel) {
// the channel was already started externally, we need to initialize our member list
receiveClusterView(channel.getView());
}
CLUSTER.localAndPhysicalAddress(clusterName, getAddress(), getPhysicalAddresses());
}
// This needs to stay as a separate method to allow for substitution for Substrate
private void registerMBeansIfNeeded(String clusterName) {
try {
// Normally this would be done by CacheManagerJmxRegistration but
// the channel is not started when the cache manager starts but
// when first cache starts, so it's safer to do it here.
if (jmxRegistration.enabled()) {
ObjectName namePrefix = new ObjectName(jmxRegistration.getDomain() + ":" + ObjectNameKeys.MANAGER + "=" + ObjectName.quote(configuration.cacheManagerName()));
JmxConfigurator.registerChannel(channel, jmxRegistration.getMBeanServer(), namePrefix, clusterName, true);
}
} catch (Exception e) {
throw new CacheException("Channel connected, but unable to register MBeans", e);
}
}
private void waitForInitialNodes() {
int initialClusterSize = configuration.transport().initialClusterSize();
if (initialClusterSize <= 1)
return;
long timeout = configuration.transport().initialClusterTimeout();
long remainingNanos = TimeUnit.MILLISECONDS.toNanos(timeout);
viewUpdateLock.lock();
try {
while (channel != null && channel.getView().getMembers().size() < initialClusterSize &&
remainingNanos > 0) {
log.debugf("Waiting for %d nodes, current view has %d", initialClusterSize,
channel.getView().getMembers().size());
remainingNanos = viewUpdateCondition.awaitNanos(remainingNanos);
}
} catch (InterruptedException e) {
CLUSTER.interruptedWaitingForCoordinator(e);
Thread.currentThread().interrupt();
} finally {
viewUpdateLock.unlock();
}
if (remainingNanos <= 0) {
throw CLUSTER.timeoutWaitingForInitialNodes(initialClusterSize, channel.getView().getMembers());
}
log.debugf("Initial cluster size of %d nodes reached", initialClusterSize);
}
// This is per CM, so the CL in use should be the CM CL
private void buildChannel() {
FileLookup fileLookup = FileLookupFactory.newInstance();
// in order of preference - we first look for an external JGroups file, then a set of XML
// properties, and finally the legacy JGroups String properties.
String cfg;
if (props != null) {
if (props.containsKey(CHANNEL_LOOKUP)) {
String channelLookupClassName = props.getProperty(CHANNEL_LOOKUP);
try {
JGroupsChannelLookup lookup = Util.getInstance(channelLookupClassName, configuration.classLoader());
channel = lookup.getJGroupsChannel(props);
connectChannel = lookup.shouldConnect();
disconnectChannel = lookup.shouldDisconnect();
closeChannel = lookup.shouldClose();
} catch (ClassCastException e) {
CLUSTER.wrongTypeForJGroupsChannelLookup(channelLookupClassName, e);
throw new CacheException(e);
} catch (Exception e) {
CLUSTER.errorInstantiatingJGroupsChannelLookup(channelLookupClassName, e);
throw new CacheException(e);
}
}
if (channel == null && props.containsKey(CHANNEL_CONFIGURATOR)) {
channelFromConfigurator((JGroupsChannelConfigurator) props.get(CHANNEL_CONFIGURATOR));
}
if (channel == null && props.containsKey(CONFIGURATION_FILE)) {
cfg = props.getProperty(CONFIGURATION_FILE);
Collection<URL> confs = Collections.emptyList();
try {
confs = fileLookup.lookupFileLocations(cfg, configuration.classLoader());
} catch (IOException io) {
//ignore, we check confs later for various states
}
if (confs.isEmpty()) {
throw CLUSTER.jgroupsConfigurationNotFound(cfg);
} else if (confs.size() > 1) {
CLUSTER.ambiguousConfigurationFiles(Util.toStr(confs));
}
try {
URL url = confs.iterator().next();
channel = new JChannel(url.openStream());
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigFile(cfg, e);
}
}
if (channel == null && props.containsKey(CONFIGURATION_XML)) {
cfg = props.getProperty(CONFIGURATION_XML);
try {
channel = new JChannel(new ByteArrayInputStream(cfg.getBytes()));
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromXML(cfg, e);
}
}
if (channel == null && props.containsKey(CONFIGURATION_STRING)) {
cfg = props.getProperty(CONFIGURATION_STRING);
try {
channel = new JChannel(new ByteArrayInputStream(cfg.getBytes()));
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigString(cfg, e);
}
}
if (channel == null && configuration.transport().stack() != null) {
channelFromConfigurator(configuration.transport().jgroups().configurator(configuration.transport().stack()));
}
}
if (channel == null) {
CLUSTER.unableToUseJGroupsPropertiesProvided(props);
try (InputStream is = fileLookup.lookupFileLocation(DEFAULT_JGROUPS_CONFIGURATION_FILE, configuration.classLoader()).openStream()) {
channel = new JChannel(is);
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigFile(DEFAULT_JGROUPS_CONFIGURATION_FILE, e);
}
}
if (props != null && props.containsKey(SOCKET_FACTORY) && !props.containsKey(CHANNEL_CONFIGURATOR)) {
Protocol protocol = channel.getProtocolStack().getTopProtocol();
protocol.setSocketFactory((SocketFactory) props.get(SOCKET_FACTORY));
}
}
private void channelFromConfigurator(JGroupsChannelConfigurator configurator) {
if (props.containsKey(SOCKET_FACTORY)) {
SocketFactory socketFactory = (SocketFactory) props.get(SOCKET_FACTORY);
if (socketFactory instanceof NamedSocketFactory) {
((NamedSocketFactory) socketFactory).setName(configuration.transport().clusterName());
}
configurator.setSocketFactory(socketFactory);
}
configurator.addChannelListener(this);
try {
channel = configurator.createChannel(configuration.transport().clusterName());
} catch (Exception e) {
throw CLUSTER.errorCreatingChannelFromConfigurator(configurator.getProtocolStackString(), e);
}
}
protected void receiveClusterView(View newView) {
// The first view is installed before returning from JChannel.connect
// So we need to set the local address here
if (address == null) {
org.jgroups.Address jgroupsAddress = channel.getAddress();
this.address = fromJGroupsAddress(jgroupsAddress);
if (log.isTraceEnabled()) {
String uuid = (jgroupsAddress instanceof org.jgroups.util.UUID) ?
((org.jgroups.util.UUID) jgroupsAddress).toStringLong() : "N/A";
log.tracef("Local address %s, uuid %s", jgroupsAddress, uuid);
}
}
List<List<Address>> subGroups;
if (newView instanceof MergeView) {
CLUSTER.receivedMergedView(channel.clusterName(), newView);
subGroups = new ArrayList<>();
List<View> jgroupsSubGroups = ((MergeView) newView).getSubgroups();
for (View group : jgroupsSubGroups) {
subGroups.add(fromJGroupsAddressList(group.getMembers()));
}
} else {
CLUSTER.receivedClusterView(channel.clusterName(), newView);
subGroups = Collections.emptyList();
}
long viewId = newView.getViewId().getId();
List<Address> members = fromJGroupsAddressList(newView.getMembers());
if (members.isEmpty()) {
return;
}
ClusterView oldView = this.clusterView;
// Update every view-related field while holding the lock so that waitForView only returns
// after everything was updated.
CompletableFuture<Void> oldFuture = null;
viewUpdateLock.lock();
try {
// Delta view debug log for large cluster
if (log.isDebugEnabled() && oldView.getMembers() != null) {
List<Address> joined = new ArrayList<>(members);
joined.removeAll(oldView.getMembers());
List<Address> left = new ArrayList<>(oldView.getMembers());
left.removeAll(members);
log.debugf("Joined: %s, Left: %s", joined, left);
}
this.clusterView = new ClusterView((int) viewId, members, address);
// Create a completable future for the new view
oldFuture = nextViewFuture;
nextViewFuture = new CompletableFuture<>();
// Wake up any threads that are waiting to know about who the isCoordinator is
// do it before the notifications, so if a listener throws an exception we can still start
viewUpdateCondition.signalAll();
} finally {
viewUpdateLock.unlock();
// Complete the future for the old view
if (oldFuture != null) {
CompletableFuture<Void> future = oldFuture;
nonBlockingExecutor.execute(() -> future.complete(null));
}
}
// now notify listeners - *after* updating the isCoordinator. - JBCACHE-662
boolean hasNotifier = notifier != null;
if (hasNotifier) {
if (!subGroups.isEmpty()) {
final Address address1 = getAddress();
CompletionStages.join(notifier.notifyMerge(members, oldView.getMembers(), address1, (int) viewId, subGroups));
} else {
CompletionStages.join(notifier.notifyViewChange(members, oldView.getMembers(), getAddress(), (int) viewId));
}
}
// Targets leaving may finish some requests and potentially potentially block for a long time.
// We don't want to block view handling, so we unblock the commands on a separate thread.
nonBlockingExecutor.execute(() -> {
if (requests != null) {
requests.forEach(request -> request.onNewView(clusterView.getMembersSet()));
}
});
JGroupsAddressCache.pruneAddressCache();
}
private static List<Address> fromJGroupsAddressList(List<org.jgroups.Address> list) {
return Collections.unmodifiableList(list.stream()
.map(JGroupsAddressCache::fromJGroupsAddress)
.collect(Collectors.toList()));
}
@Stop
@Override
public void stop() {
running = false;
if (channel != null) {
channel.getProtocolStack().getTransport().unregisterProbeHandler(probeHandler);
}
String clusterName = configuration.transport().clusterName();
try {
if (disconnectChannel && channel != null && channel.isConnected()) {
CLUSTER.disconnectJGroups(clusterName);
channel.disconnect();
}
if (closeChannel && channel != null && channel.isOpen()) {
channel.close();
}
unregisterMBeansIfNeeded(clusterName);
} catch (Exception toLog) {
CLUSTER.problemClosingChannel(toLog, clusterName);
}
if (requests != null) {
requests.forEach(request -> request.cancel(CONTAINER.cacheManagerIsStopping()));
}
// Don't keep a reference to the channel, but keep the address and physical address
channel = null;
clusterView = new ClusterView(ClusterView.FINAL_VIEW_ID, Collections.emptyList(), null);
CompletableFuture<Void> oldFuture = null;
viewUpdateLock.lock();
try {
// Create a completable future for the new view
oldFuture = nextViewFuture;
nextViewFuture = new CompletableFuture<>();
// Wake up any threads blocked in waitForView()
viewUpdateCondition.signalAll();
} finally {
viewUpdateLock.unlock();
// And finally, complete the future for the old view
if (oldFuture != null) {
oldFuture.complete(null);
}
}
}
// This needs to stay as a separate method to allow for substitution for Substrate
private void unregisterMBeansIfNeeded(String clusterName) throws Exception {
if (jmxRegistration.enabled() && channel != null) {
ObjectName namePrefix = new ObjectName(jmxRegistration.getDomain() + ":" + ObjectNameKeys.MANAGER + "=" + ObjectName.quote(configuration.cacheManagerName()));
JmxConfigurator.unregisterChannel(channel, jmxRegistration.getMBeanServer(), namePrefix, clusterName);
}
}
@Override
public int getViewId() {
if (channel == null)
throw new IllegalLifecycleStateException("The cache has been stopped and invocations are not allowed!");
return clusterView.getViewId();
}
@Override
public CompletableFuture<Void> withView(int expectedViewId) {
ClusterView view = this.clusterView;
if (view.isViewIdAtLeast(expectedViewId))
return CompletableFutures.completedNull();
if (log.isTraceEnabled())
log.tracef("Waiting for view %d, current view is %d", expectedViewId, view.getViewId());
viewUpdateLock.lock();
try {
view = this.clusterView;
if (view.isViewIdAtLeast(ClusterView.FINAL_VIEW_ID)) {
throw new IllegalLifecycleStateException();
} else if (view.isViewIdAtLeast(expectedViewId)) {
return CompletableFutures.completedNull();
} else {
return nextViewFuture.thenCompose(nil -> withView(expectedViewId));
}
} finally {
viewUpdateLock.unlock();
}
}
@Override
public void waitForView(int viewId) throws InterruptedException {
if (channel == null)
return;
long remainingNanos = Long.MAX_VALUE;
viewUpdateLock.lock();
try {
while (channel != null && getViewId() < viewId && remainingNanos > 0) {
log.tracef("Waiting for view %d, current view is %d", viewId, clusterView.getViewId());
remainingNanos = viewUpdateCondition.awaitNanos(remainingNanos);
}
} finally {
viewUpdateLock.unlock();
}
}
@Override
public Log getLog() {
return log;
}
@Override
public Set<String> getSitesView() {
RELAY2 relay2 = findRelay2();
if (relay2 == null) {
return null;
}
List<String> sites = relay2.getCurrentSites();
return sites == null ? Collections.emptySet() : new TreeSet<>(sites);
}
@Override
public boolean isSiteCoordinator() {
RELAY2 relay2 = findRelay2();
return relay2 != null && relay2.isSiteMaster();
}
@Override
public Collection<Address> getRelayNodesAddress() {
RELAY2 relay2 = findRelay2();
if (relay2 == null) {
return Collections.emptyList();
}
return relay2.siteMasters().stream()
.map(JGroupsAddressCache::fromJGroupsAddress)
.collect(Collectors.toList());
}
@Override
public <T> CompletionStage<T> invokeCommand(Address target, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
if (target.equals(address)) {
return CompletableFuture.completedFuture(collector.finish());
}
long requestId = requests.newRequestId();
logRequest(requestId, command, target, "single");
SingleTargetRequest<T> request = new SingleTargetRequest<>(collector, requestId, requests, target);
addRequest(request);
boolean invalidTarget = request.onNewView(clusterView.getMembersSet());
if (!invalidTarget) {
sendCommand(target, command, requestId, deliverOrder, true, false);
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, unit);
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector, DeliverOrder deliverOrder,
long timeout, TimeUnit unit) {
long requestId = requests.newRequestId();
logRequest(requestId, command, targets, "multi");
if (targets.isEmpty()) {
return CompletableFuture.completedFuture(collector.finish());
}
Address excludedTarget = getAddress();
MultiTargetRequest<T> request =
new MultiTargetRequest<>(collector, requestId, requests, targets, excludedTarget);
// Request may be completed due to exclusion of target nodes, so only send it if it isn't complete
if (request.isDone()) {
return request;
}
try {
addRequest(request);
boolean checkView = request.onNewView(clusterView.getMembersSet());
sendCommand(targets, command, requestId, deliverOrder, checkView);
} catch (Throwable t) {
request.cancel(true);
throw t;
}
if (timeout > 0) {
request.setTimeout(timeoutExecutor, timeout, unit);
}
return request;
}
@Override
public <T> CompletionStage<T> invokeCommandOnAll(ReplicableCommand command, ResponseCollector<T> collector,
DeliverOrder deliverOrder, long timeout, TimeUnit unit) {