/
TP.java
1554 lines (1247 loc) · 64.9 KB
/
TP.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.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.*;
import org.jgroups.blocks.LazyRemovalCache;
import org.jgroups.conf.AttributeType;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.conf.PropertyConverters;
import org.jgroups.logging.LogFactory;
import org.jgroups.stack.DiagnosticsHandler;
import org.jgroups.stack.MessageProcessingPolicy;
import org.jgroups.stack.Protocol;
import org.jgroups.util.UUID;
import org.jgroups.util.*;
import java.io.DataInput;
import java.io.InterruptedIOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import static org.jgroups.conf.AttributeType.SCALAR;
/**
* Generic transport - specific implementations should extend this abstract class.
* Features which are provided to the subclasses include
* <ul>
* <li>version checking
* <li>marshalling and unmarshalling
* <li>message bundling (handling single messages, and message lists)
* <li>incoming packet handler
* </ul>
* A subclass has to override
* <ul>
* <li>{@link #sendUnicast(org.jgroups.PhysicalAddress, byte[], int, int)}
* <li>{@link #init()}
* <li>{@link #start()}: subclasses <em>must</em> call super.start() <em>after</em> they initialize themselves
* (e.g., created their sockets).
* <li>{@link #stop()}: subclasses <em>must</em> call super.stop() after they deinitialized themselves
* <li>{@link #destroy()}
* </ul>
* The create() or start() method has to create a local address.<br>
* The {@link #receive(Address, byte[], int, int)} method must
* be called by subclasses when a unicast or multicast message has been received.
* @author Bela Ban
*/
@MBean(description="Transport protocol")
public abstract class TP extends Protocol implements DiagnosticsHandler.ProbeHandler {
public static final byte LIST=1; // we have a list of messages rather than a single message when set
public static final byte MULTICAST=2; // message is a multicast (versus a unicast) message when set
public static final int MSG_OVERHEAD=Global.SHORT_SIZE*2 + Global.BYTE_SIZE; // version + flags
protected static final long MIN_WAIT_BETWEEN_DISCOVERIES=TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS); // ns
/* ------------------------------------------ JMX and Properties ------------------------------------------ */
@LocalAddress
@Property(name="bind_addr",
description="The bind address which should be used by this transport. The following special values " +
"are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL, NON_LOOPBACK, match-interface, match-host, match-address",
defaultValueIPv4=Global.NON_LOOPBACK_ADDRESS, defaultValueIPv6=Global.NON_LOOPBACK_ADDRESS,
systemProperty={Global.BIND_ADDR},writable=false)
protected InetAddress bind_addr;
@Property(description="Use \"external_addr\" if you have hosts on different networks, behind " +
"firewalls. On each firewall, set up a port forwarding rule (sometimes called \"virtual server\") to " +
"the local IP (e.g. 192.168.1.100) of the host then on each host, set \"external_addr\" TCP transport " +
"parameter to the external (public IP) address of the firewall.",
systemProperty=Global.EXTERNAL_ADDR,writable=false)
protected InetAddress external_addr;
@Property(description="Used to map the internal port (bind_port) to an external port. Only used if > 0",
systemProperty=Global.EXTERNAL_PORT,writable=false)
protected int external_port;
@ManagedAttribute(description="tracing is enabled or disabled for the given log",writable=true)
protected boolean is_trace=log.isTraceEnabled();
@Property(description="If true, the transport should use all available interfaces to receive multicast messages")
protected boolean receive_on_all_interfaces;
/**
* List<NetworkInterface> of interfaces to receive multicasts on. The multicast receive socket will listen
* on all of these interfaces. This is a comma-separated list of IP addresses or interface names. E.g.
* "192.168.5.1,eth1,127.0.0.1". Duplicates are discarded; we only bind to
* an interface once. If this property is set, it overrides receive_on_all_interfaces.
*/
@Property(converter=PropertyConverters.NetworkInterfaceList.class,
description="Comma delimited list of interfaces (IP addresses or interface names) to receive multicasts on")
protected List<NetworkInterface> receive_interfaces;
@Property(description="Max number of elements in the logical address cache before eviction starts")
protected int logical_addr_cache_max_size=2000;
@Property(description="Time (in ms) after which entries in the logical address cache marked as removable " +
"can be removed. 0 never removes any entries (not recommended)",type=AttributeType.TIME)
protected long logical_addr_cache_expiration=360000;
@Property(description="Interval (in ms) at which the reaper task scans logical_addr_cache and removes entries " +
"marked as removable. 0 disables reaping.",type=AttributeType.TIME)
protected long logical_addr_cache_reaper_interval=60000;
/** The port to which the transport binds. 0 means to bind to any (ephemeral) port. See also {@link #port_range} */
@Property(description="The port to which the transport binds. Default of 0 binds to any (ephemeral) port." +
" See also port_range",systemProperty={Global.BIND_PORT},writable=false)
protected int bind_port;
@Property(description="The range of valid ports: [bind_port .. bind_port+port_range ]. " +
"0 only binds to bind_port and fails if taken")
protected int port_range=10; // 27-6-2003 bgooren, Only try one port by default
@Property(description="Whether or not to make a copy of a message before looping it back up. Don't use this; might " +
"get removed without warning")
protected boolean loopback_copy;
@Property(description="Loop back the message on a separate thread or use the current thread. Don't use this; " +
"might get removed without warning")
protected boolean loopback_separate_thread=true;
@Property(description="The fully qualified name of a class implementing MessageProcessingPolicy")
protected String message_processing_policy;
@Property(description="The fully qualified name of a class implementing LocalTransport")
protected String local_transport_class;
@Property(description="If true, create virtual threads, otherwise create native threads")
protected boolean use_virtual_threads;
@Property(description="Thread naming pattern for threads in this channel. Valid values are \"pcl\": " +
"\"p\": includes the thread name, e.g. \"Incoming thread-1\", \"UDP ucast receiver\", " +
"\"c\": includes the cluster name, e.g. \"MyCluster\", " +
"\"l\": includes the local address of the current member, e.g. \"192.168.5.1:5678\"")
protected String thread_naming_pattern="cl";
@Property(description="Interval (in ms) at which the time service updates its timestamp. 0 disables the time service",
type=AttributeType.TIME)
protected long time_service_interval=500;
/** Whether warnings about messages from different groups are logged - private flag, not for common use */
@Property(description="whether or not warnings about messages from different groups are logged")
protected boolean log_discard_msgs=true;
@Property(description="whether or not warnings about messages from members with a different version are discarded")
protected boolean log_discard_msgs_version=true;
@Property(description="Timeout (in ms) to determine how long to wait until a request to fetch the physical address " +
"for a given logical address will be sent again. Subsequent requests for the same physical address will therefore " +
"be spaced at least who_has_cache_timeout ms apart",type=AttributeType.TIME)
protected long who_has_cache_timeout=2000;
@Property(description="Time during which identical warnings about messages from a member with a different version " +
"will be suppressed. 0 disables this (every warning will be logged). Setting the log level to ERROR also " +
"disables this.",type=AttributeType.TIME)
protected long suppress_time_different_version_warnings=60000;
@Property(description="Time during which identical warnings about messages from a member from a different cluster " +
"will be suppressed. 0 disables this (every warning will be logged). Setting the log level to ERROR also " +
"disables this.",type=AttributeType.TIME)
protected long suppress_time_different_cluster_warnings=60000;
@Property(description="The fully qualified name of a MessageFactory implementation",exposeAsManagedAttribute=false)
protected String msg_factory_class;
protected MessageFactory msg_factory=new DefaultMessageFactory();
@Property(description="The type of bundler used (\"ring-buffer\", \"transfer-queue\" (default), \"sender-sends\" or " +
"\"no-bundler\") or the fully qualified classname of a Bundler implementation")
protected String bundler_type="transfer-queue";
@ManagedAttribute(description="Fully qualified classname of bundler")
public String getBundlerClass() {
return bundler != null? bundler.getClass().getName() : "null";
}
public MessageFactory getMessageFactory() {return msg_factory;}
public <T extends TP> T setMessageFactory(MessageFactory m) {msg_factory=m; return (T)this;}
public InetAddress getBindAddr() {return bind_addr;}
public <T extends TP> T setBindAddr(InetAddress b) {this.bind_addr=b; return (T)this;}
public InetAddress getExternalAddr() {return external_addr;}
public <T extends TP> T setExternalAddr(InetAddress e) {this.external_addr=e; return (T)this;}
public int getExternalPort() {return external_port;}
public <T extends TP> T setExternalPort(int e) {this.external_port=e; return (T)this;}
public boolean isTrace() {return is_trace;}
public <T extends TP> T isTrace(boolean i) {this.is_trace=i; return (T)this;}
public boolean receiveOnAllInterfaces() {return receive_on_all_interfaces;}
public <T extends TP> T receiveOnAllInterfaces(boolean r) {this.receive_on_all_interfaces=r; return (T)this;}
public int getLogicalAddrCacheMaxSize() {return logical_addr_cache_max_size;}
public <T extends TP> T setLogicalAddrCacheMaxSize(int l) {this.logical_addr_cache_max_size=l; return (T)this;}
public long getLogicalAddrCacheExpiration() {return logical_addr_cache_expiration;}
public <T extends TP> T setLogicalAddrCacheExpiration(long l) {this.logical_addr_cache_expiration=l; return (T)this;}
public long getLogicalAddrCacheReaperInterval() {return logical_addr_cache_reaper_interval;}
public <T extends TP> T setLogicalAddrCacheReaperInterval(long l) {this.logical_addr_cache_reaper_interval=l; return (T)this;}
public boolean loopbackCopy() {return loopback_copy;}
public <T extends TP> T loopbackCopy(boolean l) {this.loopback_copy=l; return (T)this;}
public boolean loopbackSeparateThread() {return loopback_separate_thread;}
public <T extends TP> T loopbackSeparateThread(boolean l) {this.loopback_separate_thread=l; return (T)this;}
public boolean useVirtualThreads() {return use_virtual_threads;}
public <T extends TP> T useVirtualThreads(boolean b) {use_virtual_threads=b; return (T)this;}
public long getTimeServiceInterval() {return time_service_interval;}
public <T extends TP> T setTimeServiceInterval(long t) {this.time_service_interval=t; return (T)this;}
public boolean logDiscardMsgs() {return log_discard_msgs;}
public <T extends TP> T logDiscardMsgs(boolean l) {this.log_discard_msgs=l; return (T)this;}
public boolean logDiscardMsgsVersion() {return log_discard_msgs_version;}
public <T extends TP> T logDiscardMsgsVersion(boolean l) {this.log_discard_msgs_version=l; return (T)this;}
public long getWhoHasCacheTimeout() {return who_has_cache_timeout;}
public <T extends TP> T setWhoHasCacheTimeout(long w) {this.who_has_cache_timeout=w; return (T)this;}
public long getSuppressTimeDifferentVersionWarnings() {return suppress_time_different_version_warnings;}
public <T extends TP> T setSuppressTimeDifferentVersionWarnings(long s) {this.suppress_time_different_version_warnings=s; return (T)this;}
public long getSuppressTimeDifferentClusterWarnings() {return suppress_time_different_cluster_warnings;}
public <T extends TP> T setSuppressTimeDifferentClusterWarnings(long s) {this.suppress_time_different_cluster_warnings=s; return (T)this;}
public String getMsgFactoryClass() {return msg_factory_class;}
public <T extends TP> T setMsgFactoryClass(String m) {this.msg_factory_class=m; return (T)this;}
public String getBundlerType() {return bundler_type;}
public <T extends TP> T setBundlerType(String b) {this.bundler_type=b; return (T)this;}
@ManagedAttribute
public String getMessageFactoryClass() {
return msg_factory != null? msg_factory.getClass().getName() : "n/a";
}
@ManagedAttribute(description="Is the logical_addr_cache reaper task running")
public boolean isLogicalAddressCacheReaperRunning() {
return logical_addr_cache_reaper != null && !logical_addr_cache_reaper.isDone();
}
@Property(name="level", description="Sets the level")
public <T extends Protocol> T setLevel(String level) {
T retval=super.setLevel(level);
is_trace=log.isTraceEnabled();
return retval;
}
@ManagedOperation(description="Changes the message processing policy. The fully qualified name of a class " +
"implementing MessageProcessingPolicy needs to be given")
public void setMessageProcessingPolicy(String policy) {
if(policy == null)
return;
msg_processing_policy=policy.startsWith("submit")? new SubmitToThreadPool() :
policy.startsWith("max")? new MaxOneThreadPerSender() :
policy.startsWith("direct")? new PassRegularMessagesUpDirectly() : null;
try {
if(msg_processing_policy == null) {
Class<MessageProcessingPolicy> clazz=(Class<MessageProcessingPolicy>)Util.loadClass(policy, getClass());
msg_processing_policy=clazz.getDeclaredConstructor().newInstance();
message_processing_policy=policy;
}
msg_processing_policy.init(this);
}
catch(Exception e) {
log.error("failed setting message_processing_policy", e);
}
}
public MessageProcessingPolicy getMessageProcessingPolicy() {return msg_processing_policy;}
/* --------------------------------------------- JMX ---------------------------------------------- */
@Component(name="msg_stats")
protected final MsgStats msg_stats=new MsgStats().enable(stats);
/** The name of the group to which this member is connected. With a shared transport, the channel name is
* in TP.ProtocolAdapter (cluster_name), and this field is not used */
@ManagedAttribute(description="Channel (cluster) name")
protected AsciiString cluster_name;
@ManagedAttribute(description="If enabled, the timer will run non-blocking tasks on its own (runner) thread, and " +
"not submit them to the thread pool. Otherwise, all tasks are submitted to the thread pool. This attribute is " +
"experimental and may be removed without notice.")
protected boolean timer_handle_non_blocking_tasks=true;
@ManagedAttribute(description="Class of the timer implementation")
public String getTimerClass() {
return timer != null? timer.getClass().getSimpleName() : "null";
}
@ManagedAttribute(description="Name of the cluster to which this transport is connected")
public String getClusterName() {
return cluster_name != null? cluster_name.toString() : null;
}
public AsciiString getClusterNameAscii() {return cluster_name;}
@ManagedAttribute(description="Number of messages from members in a different cluster",type=SCALAR)
public int getDifferentClusterMessages() {
return suppress_log_different_cluster != null? suppress_log_different_cluster.getCache().size() : 0;
}
@ManagedAttribute(description="Number of messages from members with a different JGroups version",type=SCALAR)
public int getDifferentVersionMessages() {
return suppress_log_different_version != null? suppress_log_different_version.getCache().size() : 0;
}
@ManagedOperation(description="Clears the cache for messages from different clusters")
public <T extends TP> T clearDifferentClusterCache() {
if(suppress_log_different_cluster != null)
suppress_log_different_cluster.getCache().clear();
return (T)this;
}
@ManagedOperation(description="Clears the cache for messages from members with different versions")
public <T extends TP> T clearDifferentVersionCache() {
if(suppress_log_different_version != null)
suppress_log_different_version.getCache().clear();
return (T)this;
}
@ManagedAttribute(description="Type of logger used")
public static String loggerType() {return LogFactory.loggerType();}
/* --------------------------------------------- Fields ------------------------------------------------------ */
@ManagedOperation(description="If enabled, the timer will run non-blocking tasks on its own (runner) thread, and " +
"not submit them to the thread pool. Otherwise, all tasks are submitted to the thread pool. This attribute is " +
"experimental and may be removed without notice.")
public <T extends TP> T enableBlockingTimerTasks(boolean flag) {
if(flag != this.timer_handle_non_blocking_tasks) {
this.timer_handle_non_blocking_tasks=flag;
timer.setNonBlockingTaskHandling(flag);
}
return (T)this;
}
/** The address (host and port) of this member */
protected PhysicalAddress local_physical_addr;
protected volatile View view;
/** The members of this group (updated when a member joins or leaves). With a shared transport,
* members contains _all_ members from all channels sitting on the shared transport */
protected final Set<Address> members=new CopyOnWriteArraySet<>();
//https://issues.redhat.com/browse/JGRP-849
protected final ReentrantLock connectLock = new ReentrantLock();
// ================================== Thread pool ======================
/** The thread pool which handles unmarshalling, version checks and dispatching of messages */
@Component(name="thread_pool")
protected ThreadPool thread_pool=new ThreadPool().log(this.log);
@Component(name="async_executor")
protected AsyncExecutor<Object> async_executor=new AsyncExecutor<>(thread_pool);
/** Factory which is used by the thread pool */
protected ThreadFactory thread_factory;
// ================================== Timer thread pool =========================
protected TimeScheduler timer;
protected TimeService time_service;
// ================================= Default SocketFactory ========================
protected SocketFactory socket_factory=new DefaultSocketFactory();
@Component(name="bundler")
protected Bundler bundler;
@Component(name="msg_processing_policy")
protected MessageProcessingPolicy msg_processing_policy=new MaxOneThreadPerSender();
@Component(name="local_transport")
protected LocalTransport local_transport;
@Component(name="diag")
protected DiagnosticsHandler diag_handler;
/** The header including the cluster name, sent with each message */
protected TpHeader header;
/**
* Cache which maintains mappings between logical and physical addresses. When sending a message to a logical
* address, we look up the physical address from logical_addr_cache and send the message to the physical address<br/>
* The keys are logical addresses, the values physical addresses
*/
protected LazyRemovalCache<Address,PhysicalAddress> logical_addr_cache;
// last time (in ns) we sent a discovery request
protected long last_discovery_request;
protected Future<?> logical_addr_cache_reaper;
protected static final LazyRemovalCache.Printable<Address,LazyRemovalCache.Entry<PhysicalAddress>> print_function=
(logical_addr, entry) -> {
StringBuilder sb=new StringBuilder();
String tmp_logical_name=NameCache.get(logical_addr);
if(tmp_logical_name != null)
sb.append(tmp_logical_name).append(": ");
if(logical_addr instanceof UUID)
sb.append(((UUID)logical_addr).toStringLong()).append(": ");
sb.append(entry.toString(val -> val instanceof PhysicalAddress? val.printIpAddress() : val.toString()));
sb.append("\n");
return sb.toString();
};
/** Cache keeping track of WHO_HAS requests for physical addresses (given a logical address) and expiring
* them after who_has_cache_timeout ms */
protected ExpiryCache<Address> who_has_cache;
/** Log to suppress identical warnings for messages from members with different (incompatible) versions */
protected SuppressLog<Address> suppress_log_different_version;
/** Log to suppress identical warnings for messages from members in different clusters */
protected SuppressLog<Address> suppress_log_different_cluster;
protected TP() {
}
public MsgStats getMessageStats() {return msg_stats;}
@Override
public void enableStats(boolean flag) {
super.enableStats(flag);
msg_stats.enable(flag);
}
/** Whether hardware multicasting is supported */
public abstract boolean supportsMulticasting();
public boolean isMulticastCapable() {return supportsMulticasting();}
public LazyRemovalCache<Address,PhysicalAddress> getLogicalAddressCache() {return logical_addr_cache;}
public String toString() {
return local_addr != null? getName() + "(local address: " + local_addr + ')' : getName();
}
public <T extends Protocol> T setAddress(Address addr) {
super.setAddress(addr);
registerLocalAddress(addr);
return (T)this;
}
public PhysicalAddress localPhysicalAddress() {return local_physical_addr;}
public View view() {return view;}
@ManagedAttribute(description="The physical address of the channel")
public String getLocalPhysicalAddress() {return local_physical_addr != null? local_physical_addr.printIpAddress() : null;}
public void resetStats() {
msg_stats.reset();
msg_processing_policy.reset();
if(local_transport != null)
local_transport.resetStats();
if(thread_pool != null)
thread_pool.resetStats();
async_executor.resetStats();
}
public <T extends TP> T registerProbeHandler(DiagnosticsHandler.ProbeHandler handler) {
diag_handler.registerProbeHandler(handler);
return (T)this;
}
public <T extends TP> T unregisterProbeHandler(DiagnosticsHandler.ProbeHandler handler) {
diag_handler.unregisterProbeHandler(handler);
return (T)this;
}
public DiagnosticsHandler getDiagnosticsHandler() {return diag_handler;}
/**
* Sets a {@link DiagnosticsHandler}. Should be set before the stack is started
*/
public <T extends TP> T setDiagnosticsHandler(DiagnosticsHandler handler) throws Exception {
if(handler != null) {
diag_handler.stop();
diag_handler=handler;
diag_handler.start();
}
return (T)this;
}
public LocalTransport getLocalTransport() {return local_transport;}
public <T extends TP> T setLocalTransport(LocalTransport l) {
if(this.local_transport != null) {
this.local_transport.resetStats();
this.local_transport.stop();
this.local_transport.destroy();
this.local_transport_class=null;
}
this.local_transport=l;
if(this.local_transport != null) {
try {
this.local_transport_class=l.getClass().toString();
this.local_transport.init(this);
this.local_transport.start();
}
catch(Exception ex) {
log.error("failed setting new local transport", ex);
}
}
return (T)this;
}
public <T extends TP> T setLocalTransport(String tp_class) throws Exception {
if(tp_class == null || tp_class.trim().equals("null"))
return setLocalTransport((LocalTransport)null);
Class<?> cl=Util.loadClass(tp_class, getClass());
LocalTransport ltp=(LocalTransport)cl.getDeclaredConstructor().newInstance();
return setLocalTransport(ltp);
}
public Bundler getBundler() {return bundler;}
/** Installs a bundler. Needs to be done before the channel is connected */
public <T extends TP> T setBundler(Bundler bundler) {
if(bundler != null)
this.bundler=bundler;
return (T)this;
}
public ThreadPool getThreadPool() {
return thread_pool;
}
public <T extends TP> T setThreadPool(Executor thread_pool) {
if(this.thread_pool != null)
this.thread_pool.destroy();
this.thread_pool.setThreadPool(thread_pool);
return (T)this;
}
public ThreadFactory getThreadFactory() {
return thread_factory;
}
public <T extends TP> T setThreadFactory(ThreadFactory factory) {
thread_factory=factory;
if(thread_pool != null)
thread_pool.setThreadFactory(factory);
return (T)this;
}
public AsyncExecutor<Object> getAsyncExecutor() {return async_executor;}
public <T extends TP> T setAsyncExecutor(AsyncExecutor<Object> e) {async_executor=e; return (T)this;}
public TimeScheduler getTimer() {return timer;}
/**
* Sets a new timer. This should be done before the transport is initialized; be very careful, as replacing a
* running timer with tasks in it can wreak havoc !
* @param timer
*/
public <T extends TP> T setTimer(TimeScheduler timer) {this.timer=timer; return (T)this;}
public TimeService getTimeService() {return time_service;}
public <T extends TP> T setTimeService(TimeService ts) {
if(ts == null)
return (T)this;
if(time_service != null)
time_service.stop();
time_service=ts;
time_service.start();
return (T)this;
}
public SocketFactory getSocketFactory() {
return socket_factory;
}
@Override public void setSocketFactory(SocketFactory factory) {
if(factory != null)
socket_factory=factory;
}
/**
* Names the current thread. Valid values are "pcl":
* p: include the previous (original) name, e.g. "Incoming thread-1", "UDP ucast receiver"
* c: include the cluster name, e.g. "MyCluster"
* l: include the local address of the current member, e.g. "192.168.5.1:5678"
*/
public String getThreadNamingPattern() {return thread_naming_pattern;}
public InetAddress getBindAddress() {return bind_addr;}
public <T extends TP> T setBindAddress(InetAddress a) {this.bind_addr=a; return (T)this;}
public int getBindPort() {return bind_port;}
public <T extends TP> T setBindPort(int port) {this.bind_port=port; return (T)this;}
public <T extends TP> T setBindToAllInterfaces(boolean f) {this.receive_on_all_interfaces=f; return (T)this;}
public boolean isReceiveOnAllInterfaces() {return receive_on_all_interfaces;}
public List<NetworkInterface> getReceiveInterfaces() {return receive_interfaces;}
public <T extends TP> T setPortRange(int range) {this.port_range=range; return (T)this;}
public int getPortRange() {return port_range;}
@ManagedAttribute(name="timer_tasks",description="Number of timer tasks queued up for execution",type=SCALAR)
public int getNumTimerTasks() {return timer.size();}
@ManagedOperation public String dumpTimerTasks() {return timer.dumpTimerTasks();}
@ManagedOperation(description="Purges cancelled tasks from the timer queue")
public void removeCancelledTimerTasks() {timer.removeCancelledTasks();}
@ManagedAttribute(description="Number of threads currently in the pool",type=SCALAR)
public int getTimerThreads() {return timer.getCurrentThreads();}
@ManagedAttribute(description="Returns the number of live threads in the JVM",type=SCALAR)
public static int getNumThreads() {return ManagementFactory.getThreadMXBean().getThreadCount();}
public <T extends TP> T setLogDiscardMessages(boolean flag) {log_discard_msgs=flag; return (T)this;}
public boolean getLogDiscardMessages() {return log_discard_msgs;}
public <T extends TP> T setLogDiscardMessagesVersion(boolean f) {log_discard_msgs_version=f; return (T)this;}
public boolean getLogDiscardMessagesVersion() {return log_discard_msgs_version;}
@ManagedOperation(description="Dumps the contents of the logical address cache")
public String printLogicalAddressCache() {
return logical_addr_cache.printCache(print_function);
}
@ManagedOperation(description="Prints the contents of the who-has cache")
public String printWhoHasCache() {return who_has_cache.toString();}
@ManagedOperation(description="Evicts elements in the logical address cache which have expired")
public void evictLogicalAddressCache() {
evictLogicalAddressCache(false);
}
public void evictLogicalAddressCache(boolean force) {
logical_addr_cache.removeMarkedElements(force);
fetchLocalAddresses();
}
public String defaultHeaders(boolean detailed) {
int num_members=view != null? view.size() : 0;
String fmt=detailed? "%s (ip=%s)\nview=%s\ncluster=%s\nversion=%s %s\n"
: "%s [ip=%s, %d mbr(s), cluster=%s, version=%s %s]\n";
return String.format(fmt, local_addr != null? local_addr.toString() : "n/a", local_physical_addr,
detailed? view : num_members, cluster_name, Version.description,
Util.JAVA_VERSION.isEmpty()? "" : String.format("(java %s)", Util.JAVA_VERSION));
}
/**
* Send a unicast to a member. Note that the destination address is a *physical*, not a logical address
* @param dest Must be a non-null unicast address
* @param data The data to be sent. This is not a copy, so don't modify it
*/
public abstract void sendUnicast(PhysicalAddress dest, byte[] data, int offset, int length) throws Exception;
public abstract String getInfo();
/* ------------------------------------------------------------------------------- */
/*------------------------------ Protocol interface ------------------------------ */
public void init() throws Exception {
this.id=ClassConfigurator.getProtocolId(TP.class);
if(use_virtual_threads && !Util.virtualThreadsAvailable()) {
log.debug("use_virtual_threads was set to false, as virtual threads are not available in this Java version");
use_virtual_threads=false;
}
thread_pool.useVirtualThreads(this.use_virtual_threads);
if(local_transport_class != null) {
Class<?> cl=Util.loadClass(local_transport_class, getClass());
local_transport=(LocalTransport)cl.getDeclaredConstructor().newInstance();
local_transport.init(this);
}
if(thread_factory == null)
setThreadFactory(new LazyThreadFactory("jgroups", false, true)
.useVirtualThreads(use_virtual_threads).log(this.log));
// local_addr is null when shared transport, channel_name is not used
setInAllThreadFactories(cluster_name != null? cluster_name.toString() : null, local_addr, thread_naming_pattern);
diag_handler=createDiagnosticsHandler();
who_has_cache=new ExpiryCache<>(who_has_cache_timeout);
if(suppress_time_different_version_warnings > 0)
suppress_log_different_version=new SuppressLog<>(log, "VersionMismatch", "SuppressMsg");
if(suppress_time_different_cluster_warnings > 0)
suppress_log_different_cluster=new SuppressLog<>(log, "MsgDroppedDiffCluster", "SuppressMsg");
// ========================================== Timer ==============================
if(timer == null) {
timer=new TimeScheduler3(thread_pool, thread_factory, false); // don't start the timer thread yet (JGRP-2332)
timer.setNonBlockingTaskHandling(timer_handle_non_blocking_tasks);
}
if(time_service_interval > 0)
time_service=new TimeService(timer, time_service_interval);
Map<String, Object> m=new HashMap<>(2);
if(bind_addr != null)
m.put("bind_addr", bind_addr);
if(external_addr != null)
m.put("external_addr", external_addr);
if(external_port > 0)
m.put("external_port", external_port);
if(!m.isEmpty())
up(new Event(Event.CONFIG, m));
logical_addr_cache=new LazyRemovalCache<>(logical_addr_cache_max_size, logical_addr_cache_expiration);
if(logical_addr_cache_reaper_interval > 0 && (logical_addr_cache_reaper == null || logical_addr_cache_reaper.isDone())) {
logical_addr_cache_reaper=timer.scheduleWithFixedDelay(new Runnable() {
public void run() {
evictLogicalAddressCache();
}
public String toString() {
return TP.this.getClass().getSimpleName() + ": LogicalAddressCacheReaper (interval=" + logical_addr_cache_reaper_interval + " ms)";
}
}, logical_addr_cache_reaper_interval, logical_addr_cache_reaper_interval, TimeUnit.MILLISECONDS, false);
}
if(message_processing_policy != null)
setMessageProcessingPolicy(message_processing_policy);
else
msg_processing_policy.init(this);
if(msg_factory_class != null) {
Class<MessageFactory> clazz=(Class<MessageFactory>)Util.loadClass(msg_factory_class, getClass());
msg_factory=clazz.getDeclaredConstructor().newInstance();
}
bundler=createBundler(bundler_type, getClass());
bundler.init(this);
}
/** Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads */
public void start() throws Exception {
timer.start();
thread_pool.setAddress(local_addr);
async_executor.start();
if(time_service != null)
time_service.start();
fetchLocalAddresses();
startDiagnostics();
bundler.start();
// local_addr is null when shared transport
setInAllThreadFactories(cluster_name != null? cluster_name.toString() : null, local_addr, thread_naming_pattern);
}
public void stop() {
stopDiagnostics();
bundler.stop();
if(msg_processing_policy != null)
msg_processing_policy.destroy();
if(time_service != null)
time_service.stop();
timer.stop();
async_executor.stop();
}
public void destroy() {
super.destroy();
if(local_transport != null)
local_transport.destroy();
if(logical_addr_cache_reaper != null) {
logical_addr_cache_reaper.cancel(false);
logical_addr_cache_reaper=null;
}
if(thread_pool != null)
thread_pool.destroy();
}
@ManagedOperation(description="Creates and sets a new bundler. Type has to be either a bundler_type or the fully " +
"qualified classname of a Bundler impl. Stops the current bundler (if running)")
public <T extends TP> T bundler(String type) throws Exception {
Bundler new_bundler=createBundler(type, getClass());
String old_bundler_class=null;
if(bundler != null) {
bundler.stop();
old_bundler_class=bundler.getClass().getName();
}
new_bundler.init(this);
new_bundler.start();
bundler=new_bundler;
bundler_type=type;
if(old_bundler_class != null)
log.debug("%s: replaced bundler %s with %s", local_addr, old_bundler_class, bundler.getClass().getName());
return (T)this;
}
@ManagedOperation(description="Enables diagnostics and starts DiagnosticsHandler (if not running)")
public <T extends TP> T enableDiagnostics() {
diag_handler.setEnabled(true);
try {
startDiagnostics();
}
catch(Exception e) {
log.error(Util.getMessage("FailedStartingDiagnostics"), e);
}
return (T)this;
}
@ManagedOperation(description="Disables diagnostics and stops DiagnosticsHandler (if running)")
public void disableDiagnostics() {
stopDiagnostics();
}
protected void startDiagnostics() throws Exception {
if(diag_handler != null) {
diag_handler.registerProbeHandler(this);
diag_handler.start();
}
}
protected void stopDiagnostics() {
if(diag_handler != null) {
diag_handler.unregisterProbeHandler(this);
diag_handler.stop();
}
}
public Map<String, String> handleProbe(String... keys) {
Map<String,String> retval=new HashMap<>(keys != null? keys.length : 2);
if(keys == null)
return retval;
for(String key: keys) {
switch(key) {
case "dump":
retval.put(key, Util.dumpThreads());
break;
case "uuids":
retval.put(key, printLogicalAddressCache());
if(!retval.containsKey("local_addr"))
retval.put("local_addr", local_addr != null? local_addr.toString() : null);
break;
case "keys":
StringBuilder sb=new StringBuilder();
for(DiagnosticsHandler.ProbeHandler handler : diag_handler.getProbeHandlers()) {
String[] tmp=handler.supportedKeys();
if(tmp != null) {
for(String s : tmp)
sb.append(s).append(" ");
}
}
retval.put(key, sb.toString());
break;
case "member-addrs":
Set<PhysicalAddress> physical_addrs=logical_addr_cache.nonRemovedValues();
String list=Util.print(physical_addrs);
retval.put(key, list);
break;
}
}
return retval;
}
public String[] supportedKeys() {
return new String[]{"dump", "keys", "uuids", "member-addrs"};
}
protected void handleConnect() throws Exception {
}
protected void handleDisconnect() {
}
public Object down(Event evt) {
switch(evt.getType()) {
case Event.TMP_VIEW:
case Event.VIEW_CHANGE:
Collection<Address> old_members;
synchronized(members) {
View v=evt.getArg();
this.view=v;
old_members=new ArrayList<>(members);
members.clear();
members.addAll(v.getMembers());
// fix for https://issues.redhat.com/browse/JGRP-918
logical_addr_cache.retainAll(members);
fetchLocalAddresses();
List<Address> left_mbrs=Util.leftMembers(old_members,members);
if(left_mbrs != null && !left_mbrs.isEmpty())
NameCache.removeAll(left_mbrs);
if(suppress_log_different_version != null)
suppress_log_different_version.removeExpired(suppress_time_different_version_warnings);
if(suppress_log_different_cluster != null)
suppress_log_different_cluster.removeExpired(suppress_time_different_cluster_warnings);
}
who_has_cache.removeExpiredElements();
if(bundler != null)
bundler.viewChange(evt.getArg());
if(msg_processing_policy instanceof MaxOneThreadPerSender)
((MaxOneThreadPerSender)msg_processing_policy).viewChange(view.getMembers());
if(local_transport != null)
local_transport.viewChange(this.view);
// Increase thread pool size when view.size() > max_threads (https://issues.redhat.com/browse/JGRP-2655)
if(ergonomics && thread_pool.getIncreaseMaxSizeDynamically()) {
int size=view.size();
if(size >= thread_pool.getMaxThreads()) {
int new_size=size+thread_pool.getDelta();
log.warn("%s: view size=%d, thread_pool.max-threads=%d: increasing max-threads to %d",
local_addr, size, thread_pool.getMaxThreads(), new_size);
thread_pool.setMaxThreads(new_size);
}
}
break;
case Event.CONNECT:
case Event.CONNECT_WITH_STATE_TRANSFER:
cluster_name=new AsciiString((String)evt.getArg());
header=new TpHeader(cluster_name);
setInAllThreadFactories(cluster_name != null? cluster_name.toString() : null, local_addr, thread_naming_pattern);
setThreadNames();
connectLock.lock();
try {
if(local_transport != null)
local_transport.start();
handleConnect();
}
catch(Exception e) {
throw new RuntimeException(e);
}
finally {
connectLock.unlock();
}
return null;
case Event.DISCONNECT:
unsetThreadNames();
connectLock.lock();
try {
if(local_transport != null)
local_transport.stop();
handleDisconnect();
}
finally {
connectLock.unlock();
}
break;
case Event.GET_PHYSICAL_ADDRESS:
Address addr=evt.getArg();
PhysicalAddress physical_addr=getPhysicalAddressFromCache(addr);
if(physical_addr != null)
return physical_addr;
if(Objects.equals(addr, local_addr)) {
physical_addr=getPhysicalAddress();