/
TP.java
1832 lines (1479 loc) · 68.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.conf.PropertyConverters;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.Protocol;
import org.jgroups.util.*;
import org.jgroups.util.ThreadFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 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
* <li>loopback
* </ul>
* A subclass has to override
* <ul>
* <li>{@link #sendToAllMembers(byte[], int, int)}
* <li>{@link #sendToSingleMember(org.jgroups.Address, 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, Address, byte[], int, int)} method must
* be called by subclasses when a unicast or multicast message has been received.
* @author Bela Ban
* @version $Id: TP.java,v 1.239 2008/12/12 08:10:22 belaban Exp $
*/
@MBean(description="Transport protocol")
@DeprecatedProperty(names={"bind_to_all_interfaces", "use_incoming_packet_handler", "use_outgoing_packet_handler",
"use_concurrent_stack"})
public abstract class TP extends Protocol {
private static final byte LIST=1; // we have a list of messages rather than a single message when set
private static final byte MULTICAST=2; // message is a multicast (versus a unicast) message when set
private static final byte OOB=4; // message has OOB flag set (Message.OOB)
private static NumberFormat f;
private static final int INITIAL_BUFSIZE=4095;
static {
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
}
private ExposedByteArrayOutputStream out_stream=null;
private ExposedDataOutputStream dos=null;
private final Lock out_stream_lock=new ReentrantLock();
/* ------------------------------------------ JMX and Properties ------------------------------------------ */
@ManagedAttribute
@Property(converter=PropertyConverters.BindAddress.class,
description="The interface (NIC) which should be used by this transport ")
protected InetAddress bind_addr=null;
@Property(description="Ignores all bind address parameters and let's the OS return the local host address. Default is false")
protected boolean use_local_host=false;
@ManagedAttribute
@Property(description=" If true, the transport should use all available interfaces to receive multicast messages. Default is false")
protected boolean receive_on_all_interfaces=false;
/**
* 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.
*/
@ManagedAttribute
@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=null;
/** The port to which the transport binds. 0 means to bind to any (ephemeral) port */
@Property(name="start_port", deprecatedMessage="start_port is deprecated; use bind_port instead",
description="The port to which the transport binds. Default of 0 binds to any (ephemeral) port")
protected int bind_port=0;
@Property(name="end_port", deprecatedMessage="end_port is deprecated; use port_range instead")
protected int port_range=1; // 27-6-2003 bgooren, Only try one port by default
@Property(description="TODO")
protected boolean prevent_port_reuse=false;
/**
* If true, messages sent to self are treated specially: unicast messages are looped back immediately,
* multicast messages get a local copy first and - when the real copy arrives - it will be discarded. Useful for
* Window media (non)sense
*/
@ManagedAttribute(description="", writable=true)
@Property(description="Messages to self are looped back immediately if true. Default is false")
protected boolean loopback=false;
/**
* Discard packets with a different version. Usually minor version differences are okay. Setting this property
* to true means that we expect the exact same version on all incoming packets
*/
@ManagedAttribute(description="Discard packets with a different version", writable=true)
@Property(description="Discard packets with a different version if true. Default is false")
protected boolean discard_incompatible_packets=false;
@Property(description="Thread naming pattern for threads in this channel. Default is cl")
protected String thread_naming_pattern="cl";
@Property(name="oob_thread_pool.enabled",description="Switch for enabling thread pool for OOB messages. Default true")
protected boolean oob_thread_pool_enabled=true;
@ManagedAttribute(description="Minimum thread pool size for OOB messages. Default is 2")
@Property(name="oob_thread_pool.min_threads",description="Minimum thread pool size for OOB messages. Default is 2")
protected int oob_thread_pool_min_threads=2;
@ManagedAttribute(description="Maximum thread pool size for OOB messages. Default is 10")
@Property(name="oob_thread_pool.max_threads",description="Maximum thread pool size for OOB messages. Default is 10")
protected int oob_thread_pool_max_threads=10;
@ManagedAttribute(description="Timeout in milliseconds to remove idle thread from OOB pool. Default is 30000")
@Property(name="oob_thread_pool.keep_alive_time",description="Timeout in milliseconds to remove idle thread from OOB pool. Default is 30000")
protected long oob_thread_pool_keep_alive_time=30000;
@ManagedAttribute(description="Use queue to enqueue incoming OOB messages. Default is true")
@Property(name="oob_thread_pool.queue_enabled",
description="Use queue to enqueue incoming OOB messages. Default is true")
protected boolean oob_thread_pool_queue_enabled=true;
@ManagedAttribute(description="Maximum queue size for incoming OOB messages. Default is 500")
@Property(name="oob_thread_pool.queue_max_size",description="Maximum queue size for incoming OOB messages. Default is 500")
protected int oob_thread_pool_queue_max_size=500;
@ManagedAttribute
@Property(name="oob_thread_pool.rejection_policy",
description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run. Default is Run")
String oob_thread_pool_rejection_policy="Run";
@ManagedAttribute(description="Minimum thread pool size for regular messages. Default is 2")
@Property(name="thread_pool.min_threads",description="Minimum thread pool size for regular messages. Default is 2")
protected int thread_pool_min_threads=2;
@ManagedAttribute(description="Maximum thread pool size for regular messages. Default is 10")
@Property(name="thread_pool.max_threads",description="Maximum thread pool size for regular messages. Default is 10")
protected int thread_pool_max_threads=10;
@ManagedAttribute(description="Timeout in milliseconds to remove idle thread from regular pool. Default is 30000")
@Property(name="thread_pool.keep_alive_time",description="Timeout in milliseconds to remove idle thread from regular pool. Default is 30000")
protected long thread_pool_keep_alive_time=30000;
@ManagedAttribute(description="Switch for enabling thread pool for regular messages. Default true")
@Property(name="thread_pool.enabled",description="Switch for enabling thread pool for regular messages. Default true")
protected boolean thread_pool_enabled=true;
@ManagedAttribute(description="Use queue to enqueue incoming regular messages")
@Property(name="thread_pool.queue_enabled",
description="Use queue to enqueue incoming regular messages. Default is true")
protected boolean thread_pool_queue_enabled=true;
@ManagedAttribute(description="Maximum queue size for incoming OOB messages")
@Property(name="thread_pool.queue_max_size",
description="Maximum queue size for incoming OOB messages. Default is 500")
protected int thread_pool_queue_max_size=500;
@ManagedAttribute
@Property(name="thread_pool.rejection_policy",
description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run Default is Run")
protected String thread_pool_rejection_policy="Run";
@ManagedAttribute(description="Number of threads to be used by the timer thread pool")
@Property(name="timer.num_threads",description="Number of threads to be used by the timer thread pool. Default is 4")
protected int num_timer_threads=4;
@ManagedAttribute(description="Enable bundling of smaller messages into bigger ones", writable=true)
@Property(description="Enable bundling of smaller messages into bigger ones. Default is true")
protected boolean enable_bundling=true;
/** Enable bundling for unicast messages. Ignored if enable_bundling is off */
@Property(description="Enable bundling of smaller messages into bigger ones for unicast messages. Default is false")
protected boolean enable_unicast_bundling=false;
@Property(description="Switch to enable diagnostic probing. Default is true")
protected boolean enable_diagnostics=true;
@Property(description="Address for diagnostic probing. Default is 224.0.75.75")
protected String diagnostics_addr="224.0.75.75";
@Property(description="Port for diagnostic probing. Default is 7500")
protected int diagnostics_port=7500;
@Property(description="If assigned enable this transport to be a singleton (shared) transport")
protected String singleton_name=null;
@Property(description="Path to a file to store currently used ports on this machine.")
protected String persistent_ports_file=null;
@Property(name="ports_expiry_time",description="Timeout to expire ports used with PortManager. Default is 30000 msec")
protected long pm_expiry_time=30000L;
@Property(description="Switch to enable tracking of currently used ports on this machine. Default is false")
protected boolean persistent_ports=false;
/**
* Maximum number of bytes for messages to be queued until they are sent.
* This value needs to be smaller than the largest datagram packet size in case of UDP
*/
protected int max_bundle_size=64000;
/**
* Max number of milliseconds until queued messages are sent. Messages are sent when max_bundle_size
* or max_bundle_timeout has been exceeded (whichever occurs faster)
*/
protected long max_bundle_timeout=20;
/* --------------------------------------------- JMX ---------------------------------------------- */
@ManagedAttribute
protected long num_msgs_sent=0;
@ManagedAttribute
protected long num_msgs_received=0;
@ManagedAttribute
protected long num_bytes_sent=0;
@ManagedAttribute
protected long num_bytes_received=0;
/** The name of the group to which this member is connected */
@ManagedAttribute
protected String channel_name=null;
/** whether or not warnings about messages from different groups are logged - private flag, not for common use */
@ManagedAttribute(writable=true, description="whether or not warnings about messages from different groups are logged")
private boolean log_discard_msgs=true;
@ManagedAttribute
protected long num_oob_msgs_received=0;
@ManagedAttribute
protected long num_incoming_msgs_received=0;
/* --------------------------------------------- Fields ------------------------------------------------------ */
/** The address (host and port) of this member */
protected Address local_addr=null;
/** The members of this group (updated when a member joins or leaves) */
protected final HashSet<Address> members=new HashSet<Address>(11);
protected View view=null;
protected final ExposedByteArrayInputStream in_stream=new ExposedByteArrayInputStream(new byte[] { '0' });
protected final DataInputStream dis=new DataInputStream(in_stream);
protected ThreadGroup pool_thread_group=new ThreadGroup(Util.getGlobalThreadGroup(), "Thread Pools");
/** Keeps track of connects and disconnects, in order to start and stop threads */
protected int connect_count=0;
//http://jira.jboss.org/jira/browse/JGRP-849
protected final ReentrantLock connectLock = new ReentrantLock();
/**
* ================================== OOB thread pool ========================
*/
protected Executor oob_thread_pool;
/** Factory which is used by oob_thread_pool */
protected ThreadFactory oob_thread_factory=null;
/** Used if oob_thread_pool is a ThreadPoolExecutor and oob_thread_pool_queue_enabled is true */
protected BlockingQueue<Runnable> oob_thread_pool_queue=null;
/**
* ================================== Regular thread pool =======================
*/
/** The thread pool which handles unmarshalling, version checks and dispatching of regular messages */
protected Executor thread_pool;
/** Factory which is used by oob_thread_pool */
protected ThreadFactory default_thread_factory=null;
/** Used if thread_pool is a ThreadPoolExecutor and thread_pool_queue_enabled is true */
protected BlockingQueue<Runnable> thread_pool_queue=null;
/**
* ================================== Timer thread pool =========================
*/
protected TimeScheduler timer=null;
protected ThreadFactory timer_thread_factory;
/**
* =================================Default thread factory ========================
*/
/** Used by all threads created by JGroups outside of the thread pools */
protected ThreadFactory global_thread_factory=null;
/**
* If set it will be added to <tt>local_addr</tt>. Used to implement for example transport independent addresses
*/
protected byte[] additional_data=null;
private Bundler bundler=null;
private DiagnosticsHandler diag_handler=null;
private final List<ProbeHandler> preregistered_probe_handlers=new LinkedList<ProbeHandler>();
/**
* If singleton_name is enabled, this map is used to de-multiplex incoming messages according to their cluster
* names (attached to the message by the transport anyway). The values are the next protocols above the
* transports.
*/
private final ConcurrentMap<String,Protocol> up_prots=new ConcurrentHashMap<String,Protocol>();
protected TpHeader header;
protected final String name=getName();
protected PortsManager pm=null;
/**
* Creates the TP protocol, and initializes the state variables, does
* however not start any sockets or threads.
*/
protected TP() {
}
/**
* debug only
*/
public String toString() {
return local_addr != null? name + "(local address: " + local_addr + ')' : name;
}
public void resetStats() {
num_msgs_sent=num_msgs_received=num_bytes_sent=num_bytes_received=0;
num_oob_msgs_received=num_incoming_msgs_received=0;
}
public void registerProbeHandler(ProbeHandler handler) {
if(diag_handler != null)
diag_handler.registerProbeHandler(handler);
else
preregistered_probe_handlers.add(handler);
}
public void unregisterProbeHandler(ProbeHandler handler) {
if(diag_handler != null)
diag_handler.unregisterProbeHandler(handler);
}
public void setThreadPoolQueueEnabled(boolean flag) {thread_pool_queue_enabled=flag;}
public Executor getDefaultThreadPool() {
return thread_pool;
}
public void setDefaultThreadPool(Executor thread_pool) {
if(this.thread_pool != null)
shutdownThreadPool(this.thread_pool);
this.thread_pool=thread_pool;
}
public ThreadFactory getDefaultThreadPoolThreadFactory() {
return default_thread_factory;
}
public void setDefaultThreadPoolThreadFactory(ThreadFactory factory) {
default_thread_factory=factory;
if(thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)thread_pool).setThreadFactory(factory);
}
public Executor getOOBThreadPool() {
return oob_thread_pool;
}
public void setOOBThreadPool(Executor oob_thread_pool) {
if(this.oob_thread_pool != null) {
shutdownThreadPool(this.oob_thread_pool);
}
this.oob_thread_pool=oob_thread_pool;
}
public ThreadFactory getOOBThreadPoolThreadFactory() {
return oob_thread_factory;
}
public void setOOBThreadPoolThreadFactory(ThreadFactory factory) {
oob_thread_factory=factory;
if(oob_thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)oob_thread_pool).setThreadFactory(factory);
}
public ThreadFactory getTimerThreadFactory() {
return timer_thread_factory;
}
public void setTimerThreadFactory(ThreadFactory factory) {
timer_thread_factory=factory;
timer.setThreadFactory(factory);
}
public TimeScheduler getTimer() {return timer;}
public ThreadFactory getThreadFactory() {
return global_thread_factory;
}
public void setThreadFactory(ThreadFactory factory) {
global_thread_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 long getNumMessagesSent() {return num_msgs_sent;}
public long getNumMessagesReceived() {return num_msgs_received;}
public long getNumBytesSent() {return num_bytes_sent;}
public long getNumBytesReceived() {return num_bytes_received;}
public String getBindAddress() {return bind_addr != null? bind_addr.toString() : "null";}
public void setBindAddress(String bind_addr) throws UnknownHostException {
this.bind_addr=InetAddress.getByName(bind_addr);
}
public InetAddress getBindAddressAsInetAddress() {return bind_addr;}
public int getBindPort() {return bind_port;}
public void setBindPort(int port) {this.bind_port=port;}
/** @deprecated Use {@link #isReceiveOnAllInterfaces()} instead */
public boolean getBindToAllInterfaces() {return receive_on_all_interfaces;}
public void setBindToAllInterfaces(boolean flag) {this.receive_on_all_interfaces=flag;}
public boolean isReceiveOnAllInterfaces() {return receive_on_all_interfaces;}
public List<NetworkInterface> getReceiveInterfaces() {return receive_interfaces;}
/** @deprecated This property was removed in 2.7*/
public static boolean isSendOnAllInterfaces() {return false;}
/** @deprecated This property was removed in 2.7*/
public static List<NetworkInterface> getSendInterfaces() {return null;}
public boolean isDiscardIncompatiblePackets() {return discard_incompatible_packets;}
public void setDiscardIncompatiblePackets(boolean flag) {discard_incompatible_packets=flag;}
public boolean isEnableBundling() {return enable_bundling;}
public void setEnableBundling(boolean flag) {enable_bundling=flag;}
public boolean isEnableUnicastBundling() {return enable_unicast_bundling;}
public void setEnableUnicastBundling(boolean enable_unicast_bundling) {this.enable_unicast_bundling=enable_unicast_bundling;}
public void setPortRange(int range) {this.port_range=range;}
/** @deprecated the concurrent stack is used by default */
@Deprecated
public void setUseConcurrentStack(boolean flag) {}
@ManagedAttribute
public String getLocalAddressAsString() {return local_addr != null? local_addr.toString() : "n/a";}
@ManagedAttribute
public boolean isOOBThreadPoolEnabled() { return oob_thread_pool_enabled; }
@ManagedAttribute
public boolean isDefaulThreadPoolEnabled() { return thread_pool_enabled; }
@ManagedAttribute(description="Maximum number of bytes for messages to be queued until they are sent")
public int getMaxBundleSize() {return max_bundle_size;}
@ManagedAttribute(description="Maximum number of bytes for messages to be queued until they are sent",writable=true)
@Property(name="max_bundle_size")
public void setMaxBundleSize(int size) {
if(size <= 0) {
throw new IllegalArgumentException("max_bundle_size (" + size + ") is <= 0");
}
max_bundle_size=size;
}
@ManagedAttribute(description="Max number of milliseconds until queued messages are sent")
public long getMaxBundleTimeout() {return max_bundle_timeout;}
@ManagedAttribute(description="Max number of milliseconds until queued messages are sent", writable=true)
@Property(name="max_bundle_timeout")
public void setMaxBundleTimeout(long timeout) {
if(timeout <= 0) {
throw new IllegalArgumentException("max_bundle_timeout of " + timeout + " is invalid");
}
max_bundle_timeout=timeout;
}
public Address getLocalAddress() {return local_addr;}
public String getChannelName() {return channel_name;}
public boolean isLoopback() {return loopback;}
public void setLoopback(boolean b) {loopback=b;}
/** @deprecated With the concurrent stack being the default, this property is ignored */
public static boolean isUseIncomingPacketHandler() {return false;}
public ConcurrentMap<String,Protocol> getUpProtocols() {
return up_prots;
}
@ManagedAttribute
public int getOOBMinPoolSize() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getCorePoolSize() : 0;
}
@ManagedAttribute
public void setOOBMinPoolSize(int size) {
if(oob_thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)oob_thread_pool).setCorePoolSize(size);
}
@ManagedAttribute
public int getOOBMaxPoolSize() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getMaximumPoolSize() : 0;
}
@ManagedAttribute
public void setOOBMaxPoolSize(int size) {
if(oob_thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)oob_thread_pool).setMaximumPoolSize(size);
}
@ManagedAttribute
public int getOOBPoolSize() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getPoolSize() : 0;
}
@ManagedAttribute
public long getOOBKeepAliveTime() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getKeepAliveTime(TimeUnit.MILLISECONDS) : 0;
}
@ManagedAttribute
public void setOOBKeepAliveTime(long time) {
if(oob_thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)oob_thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS);
}
public long getOOBMessages() {
return num_oob_msgs_received;
}
@ManagedAttribute
public int getOOBQueueSize() {
return oob_thread_pool_queue.size();
}
public int getOOBMaxQueueSize() {
return oob_thread_pool_queue_max_size;
}
@ManagedAttribute
public int getIncomingMinPoolSize() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getCorePoolSize() : 0;
}
@ManagedAttribute
public void setIncomingMinPoolSize(int size) {
if(thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)thread_pool).setCorePoolSize(size);
}
@ManagedAttribute
public int getIncomingMaxPoolSize() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getMaximumPoolSize() : 0;
}
@ManagedAttribute
public void setIncomingMaxPoolSize(int size) {
if(thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)thread_pool).setMaximumPoolSize(size);
}
@ManagedAttribute
public int getIncomingPoolSize() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getPoolSize() : 0;
}
@ManagedAttribute
public long getIncomingKeepAliveTime() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getKeepAliveTime(TimeUnit.MILLISECONDS) : 0;
}
@ManagedAttribute
public void setIncomingKeepAliveTime(long time) {
if(thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)thread_pool).setKeepAliveTime(time, TimeUnit.MILLISECONDS);
}
public long getIncomingMessages() {
return num_incoming_msgs_received;
}
@ManagedAttribute
public int getIncomingQueueSize() {
return thread_pool_queue.size();
}
public int getIncomingMaxQueueSize() {
return thread_pool_queue_max_size;
}
public void setLogDiscardMessages(boolean flag) {
log_discard_msgs=flag;
}
public boolean getLogDiscardMessages() {
return log_discard_msgs;
}
/**
* Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N
* messages, one for each member
* @param data The data to be sent. This is not a copy, so don't modify it
* @param offset
* @param length
* @throws Exception
*/
public abstract void sendToAllMembers(byte[] data, int offset, int length) throws Exception;
/**
* Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N
* messages, one for each member
* @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
* @param offset
* @param length
* @throws Exception
*/
public abstract void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception;
public abstract String getInfo();
public abstract void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast);
public abstract void postUnmarshallingList(Message msg, Address dest, boolean multicast);
/* ------------------------------------------------------------------------------- */
/*------------------------------ Protocol interface ------------------------------ */
public void init() throws Exception {
super.init();
// Create the default thread factory
global_thread_factory=new DefaultThreadFactory(Util.getGlobalThreadGroup(), "", false);
// Create the timer and the associated thread factory - depends on singleton_name
// timer_thread_factory=new DefaultThreadFactory(Util.getGlobalThreadGroup(), "Timer", true, true);
timer_thread_factory=new LazyThreadFactory(Util.getGlobalThreadGroup(), "Timer", true, true);
if(isSingleton()) {
timer_thread_factory.setIncludeClusterName(false);
}
default_thread_factory=new DefaultThreadFactory(pool_thread_group, "Incoming", false, true);
oob_thread_factory=new DefaultThreadFactory(pool_thread_group, "OOB", false, true);
setInAllThreadFactories(channel_name, local_addr, thread_naming_pattern);
timer=new TimeScheduler(timer_thread_factory, num_timer_threads);
verifyRejectionPolicy(oob_thread_pool_rejection_policy);
verifyRejectionPolicy(thread_pool_rejection_policy);
out_stream=new ExposedByteArrayOutputStream(INITIAL_BUFSIZE);
dos=new ExposedDataOutputStream(out_stream);
// ========================================== OOB thread pool ==============================
if(oob_thread_pool_enabled) {
if(oob_thread_pool_queue_enabled)
oob_thread_pool_queue=new LinkedBlockingQueue<Runnable>(oob_thread_pool_queue_max_size);
else
oob_thread_pool_queue=new SynchronousQueue<Runnable>();
oob_thread_pool=createThreadPool(oob_thread_pool_min_threads, oob_thread_pool_max_threads, oob_thread_pool_keep_alive_time,
oob_thread_pool_rejection_policy, oob_thread_pool_queue, oob_thread_factory);
}
else { // otherwise use the caller's thread to unmarshal the byte buffer into a message
oob_thread_pool=new DirectExecutor();
}
// ====================================== Regular thread pool ===========================
if(thread_pool_enabled) {
if(thread_pool_queue_enabled)
thread_pool_queue=new LinkedBlockingQueue<Runnable>(thread_pool_queue_max_size);
else
thread_pool_queue=new SynchronousQueue<Runnable>();
thread_pool=createThreadPool(thread_pool_min_threads, thread_pool_max_threads, thread_pool_keep_alive_time,
thread_pool_rejection_policy, thread_pool_queue, default_thread_factory);
}
else { // otherwise use the caller's thread to unmarshal the byte buffer into a message
thread_pool=new DirectExecutor();
}
if(persistent_ports){
pm = new PortsManager(pm_expiry_time,persistent_ports_file);
}
if(bind_addr != null) {
Map<String, Object> m=new HashMap<String, Object>(1);
m.put("bind_addr", bind_addr);
up(new Event(Event.CONFIG, m));
}
}
public void destroy() {
super.destroy();
if(timer != null) {
try {
timer.stop();
}
catch(InterruptedException e) {
log.error("failed stopping the timer", e);
}
}
// 3. Stop the thread pools
if(oob_thread_pool instanceof ThreadPoolExecutor) {
shutdownThreadPool(oob_thread_pool);
oob_thread_pool=null;
}
if(thread_pool instanceof ThreadPoolExecutor) {
shutdownThreadPool(thread_pool);
thread_pool=null;
}
}
/**
* Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads
*/
public void start() throws Exception {
if(timer == null)
throw new Exception("timer is null");
if(enable_diagnostics) {
diag_handler=new DiagnosticsHandler();
diag_handler.start();
for(ProbeHandler handler: preregistered_probe_handlers)
diag_handler.registerProbeHandler(handler);
preregistered_probe_handlers.clear();
}
if(enable_bundling) {
bundler=new Bundler();
}
setInAllThreadFactories(channel_name, local_addr, thread_naming_pattern);
sendUpLocalAddressEvent();
}
public void stop() {
if(diag_handler != null) {
diag_handler.stop();
diag_handler=null;
}
preregistered_probe_handlers.clear();
}
protected void handleConnect() throws Exception {
connect_count++;
}
protected void handleDisconnect() {
connect_count=Math.max(0, connect_count -1);
}
public String getSingletonName() {
return singleton_name;
}
public boolean isSingleton(){
return singleton_name != null && singleton_name.length() >0;
}
/**
* handle the UP event.
* @param evt - the event being send from the stack
*/
public Object up(Event evt) {
switch(evt.getType()) {
case Event.CONFIG:
if(isSingleton())
passToAllUpProtocols(evt);
else
up_prot.up(evt);
if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg());
handleConfigEvent((Map<String,Object>)evt.getArg());
return null;
}
if(isSingleton()) {
passToAllUpProtocols(evt);
return null;
}
else
return up_prot.up(evt);
}
/**
* Caller by the layer above this layer. Usually we just put this Message
* into the send queue and let one or more worker threads handle it. A worker thread
* then removes the Message from the send queue, performs a conversion and adds the
* modified Message to the send queue of the layer below it, by calling down()).
*/
public Object down(Event evt) {
if(evt.getType() != Event.MSG) { // unless it is a message handle it and respond
return handleDownEvent(evt);
}
Message msg=(Message)evt.getArg();
if(header != null) {
// added patch by Roland Kurmann (March 20 2003)
// msg.putHeader(name, new TpHeader(channel_name));
msg.putHeaderIfAbsent(name, header);
}
setSourceAddress(msg); // very important !! listToBuffer() will fail with a null src address !!
if(log.isTraceEnabled()) {
log.trace("sending msg to " + msg.getDest() + ", src=" + msg.getSrc() + ", headers are " + msg.printHeaders());
}
// Don't send if destination is local address. Instead, switch dst and src and put in up_queue.
// If multicast message, loopback a copy directly to us (but still multicast). Once we receive this,
// we will discard our own multicast message
Address dest=msg.getDest();
boolean multicast=dest == null || dest.isMulticastAddress();
if(loopback && (multicast || dest.equals(local_addr))) {
// we *have* to make a copy, or else up_prot.up() might remove headers from msg which will then *not*
// be available for marshalling further down (when sending the message)
final Message copy=msg.copy();
if(log.isTraceEnabled()) log.trace(new StringBuilder("looping back message ").append(copy));
// up_prot.up(new Event(Event.MSG, copy));
// changed to fix http://jira.jboss.com/jira/browse/JGRP-506
Executor pool=msg.isFlagSet(Message.OOB)? oob_thread_pool : thread_pool;
pool.execute(new Runnable() {
public void run() {
passMessageUp(copy, false);
}
});
if(!multicast)
return null;
}
try {
send(msg, dest, multicast);
}
catch(InterruptedException interruptedEx) {
Thread.currentThread().interrupt(); // let someone else handle the interrupt
}
catch(Throwable e) {
if(log.isErrorEnabled()) {
String dst=msg.getDest() == null? "null" : msg.getDest().toString();
log.error("failed sending message to " + dst + " (" + msg.size() + " bytes)", e);
}
}
return null;
}
/*--------------------------- End of Protocol interface -------------------------- */
/* ------------------------------ Private Methods -------------------------------- */
/**
* If the sender is null, set our own address. We cannot just go ahead and set the address
* anyway, as we might be sending a message on behalf of someone else ! E.gin case of
* retransmission, when the original sender has crashed, or in a FLUSH protocol when we
* have to return all unstable messages with the FLUSH_OK response.
*/
private void setSourceAddress(Message msg) {
if(msg.getSrc() == null)
msg.setSrc(local_addr);
}
private void passMessageUp(Message msg, boolean perform_cluster_name_matching) {
TpHeader hdr=(TpHeader)msg.getHeader(name); // replaced removeHeader() with getHeader()
if(hdr == null) {
if(channel_name == null) {
Event evt=new Event(Event.MSG, msg);
if(isSingleton()) {
passMessageToAll(evt);
}
else {
up_prot.up(evt);
}
}
else {
if(log.isErrorEnabled())
log.error(new StringBuilder("message does not have a transport header, msg is ").append(msg).
append(", headers are ").append(msg.printHeaders()).append(", will be discarded"));
}
return;
}
String ch_name=hdr.channel_name;
if(isSingleton()) {
Protocol tmp_prot=up_prots.get(ch_name);
if(tmp_prot != null) {
Event evt=new Event(Event.MSG, msg);
if(log.isTraceEnabled()) {
StringBuilder sb=new StringBuilder("message is ").append(msg).append(", headers are ").append(msg.printHeaders());
log.trace(sb);
}
tmp_prot.up(evt);
}
else {
// we discard messages for a group we don't have. If we had a scenario with channel C1 and A,B on it,
// and channel C2 and only A on it (asymmetric setup), then C2 would always log warnings that B was
// not found (Jan 25 2008 (bela))
// if(log.isWarnEnabled())
// log.warn(new StringBuilder("discarded message from group \"").append(ch_name).
// append("\" (our groups are ").append(up_prots.keySet()).append("). Sender was ").append(msg.getSrc()));
}
}
else {
// Discard if message's group name is not the same as our group name
if(perform_cluster_name_matching && channel_name != null && !channel_name.equals(ch_name)) {
if(log.isWarnEnabled() && log_discard_msgs)
log.warn(new StringBuilder("discarded message from different group \"").append(ch_name).
append("\" (our group is \"").append(channel_name).append("\"). Sender was ").append(msg.getSrc()));
}
else {
Event evt=new Event(Event.MSG, msg);
if(log.isTraceEnabled()) {
StringBuilder sb=new StringBuilder("message is ").append(msg).append(", headers are ").append(msg.printHeaders());
log.trace(sb);
}
up_prot.up(evt);
}
}
}
private void passMessageToAll(Event evt) {