-
Notifications
You must be signed in to change notification settings - Fork 471
/
TP.java
2212 lines (1827 loc) · 81.7 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.GuardedBy;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.*;
import org.jgroups.util.Queue;
import org.jgroups.util.ThreadFactory;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.DataOutputStream;
import java.net.*;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.*;
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.160.2.23 2008/05/26 09:14:41 belaban Exp $
*/
public abstract class TP extends Protocol {
/** The address (host and port) of this member */
protected Address local_addr=null;
/** The name of the group to which this member is connected */
protected String channel_name=null;
/** The interface (NIC) which should be used by this transport */
protected InetAddress bind_addr=null;
/** Overrides bind_addr, -Djgroups.bind_addr and -Dbind.address: let's the OS return the local host address */
boolean use_local_host=false;
/** If true, the transport should use all available interfaces to receive multicast messages */
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 override receive_on_all_interfaces.
*/
List<NetworkInterface> receive_interfaces=null;
/** If true, the transport should use all available interfaces to send multicast messages. This means
* the same multicast message is sent N times, so use with care */
boolean send_on_all_interfaces=false;
/** List<NetworkInterface> of interfaces to send multicasts on. The multicast send socket will send the
* same multicast message 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.
* If this property is set, it override send_on_all_interfaces.
*/
List<NetworkInterface> send_interfaces=null;
/** The port to which the transport binds. 0 means to bind to any (ephemeral) port */
int bind_port=0;
int port_range=1; // 27-6-2003 bgooren, Only try one port by default
/** The members of this group (updated when a member joins or leaves) */
final protected HashSet<Address> members=new HashSet<Address>(11);
protected View view=null;
final ExposedByteArrayInputStream in_stream=new ExposedByteArrayInputStream(new byte[]{'0'});
final DataInputStream dis=new DataInputStream(in_stream);
/** 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 */
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 */
protected boolean discard_incompatible_packets=false;
/** Sometimes receivers are overloaded (they have to handle de-serialization etc).
* Packet handler is a separate thread taking care of de-serialization, receiver
* thread(s) simply put packet in queue and return immediately. Setting this to
* true adds one more thread */
boolean use_incoming_packet_handler=true;
/** Used by packet handler to store incoming DatagramPackets */
Queue incoming_packet_queue=null;
/** Dequeues DatagramPackets from packet_queue, unmarshalls them and
* calls <tt>handleIncomingUdpPacket()</tt> */
IncomingPacketHandler incoming_packet_handler=null;
/** Used by packet handler to store incoming Messages */
Queue incoming_msg_queue=null;
IncomingMessageHandler incoming_msg_handler;
boolean use_concurrent_stack=true;
ThreadGroup pool_thread_group=new ThreadGroup(Util.getGlobalThreadGroup(), "Thread Pools");
/**
* 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"
*/
protected String thread_naming_pattern="cl";
public String getThreadNamingPattern() {return thread_naming_pattern;}
/** Keeps track of connects and disconnects, in order to start and stop threads */
int connect_count=0;
/** Number of times init() was called. Incremented on init(), decremented on destroy() */
int init_count=0;
/** ================================== OOB thread pool ============================== */
/** The thread pool which handles OOB messages */
Executor oob_thread_pool;
/** Factory which is used by oob_thread_pool */
ThreadFactory oob_thread_factory=null;
boolean oob_thread_pool_enabled=true;
int oob_thread_pool_min_threads=2;
int oob_thread_pool_max_threads=10;
/** Number of milliseconds after which an idle thread is removed */
long oob_thread_pool_keep_alive_time=30000;
long num_oob_msgs_received=0;
/** Used if oob_thread_pool is a ThreadPoolExecutor and oob_thread_pool_queue_enabled is true */
BlockingQueue<Runnable> oob_thread_pool_queue=null;
/** Whether of not to use a queue with ThreadPoolExecutor (ignored with direct executor) */
boolean oob_thread_pool_queue_enabled=true;
/** max number of elements in queue (bounded) */
int oob_thread_pool_queue_max_size=500;
/** Possible values are "Abort", "Discard", "DiscardOldest" and "Run". These values might change once we switch to
* JDK 5's java.util.concurrent package */
String oob_thread_pool_rejection_policy="Run";
public Executor getOOBThreadPool() {
return oob_thread_pool;
}
public void setOOBThreadPool(Executor oob_thread_pool) {
if(this.oob_thread_pool != null) {
shutdownThreadPool(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;
}
/** ================================== Regular thread pool ============================== */
/** The thread pool which handles unmarshalling, version checks and dispatching of regular messages */
Executor thread_pool;
/** Factory which is used by oob_thread_pool */
ThreadFactory default_thread_factory=null;
boolean thread_pool_enabled=true;
int thread_pool_min_threads=2;
int thread_pool_max_threads=10;
/** Number of milliseconds after which an idle thread is removed */
long thread_pool_keep_alive_time=30000;
long num_incoming_msgs_received=0;
/** Used if thread_pool is a ThreadPoolExecutor and thread_pool_queue_enabled is true */
BlockingQueue<Runnable> thread_pool_queue=null;
/** Whether of not to use a queue with ThreadPoolExecutor (ignored with directE decutor) */
boolean thread_pool_queue_enabled=true;
/** max number of elements in queue (bounded) */
int thread_pool_queue_max_size=500;
/** Possible values are "Abort", "Discard", "DiscardOldest" and "Run". These values might change once we switch to
* JDK 5's java.util.concurrent package */
String thread_pool_rejection_policy="Run";
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;
}
/** ================================== Timer thread pool ================================= */
protected TimeScheduler timer=null;
protected ThreadFactory timer_thread_factory;
/** Max number of threads to be used by the timer thread pool */
int max_timer_threads=4;
public ThreadFactory getTimerThreadFactory() {
return timer_thread_factory;
}
public void setTimerThreadFactory(ThreadFactory factory) {
timer_thread_factory=factory;
timer.setThreadFactory(factory);
}
public TimeScheduler getTimer() {return timer;}
/** =================================Default thread factory ================================== */
/** Used by all threads created by JGroups outside of the thread pools */
protected ThreadFactory global_thread_factory=null;
public ThreadFactory getThreadFactory() {
return global_thread_factory;
}
public void setThreadFactory(ThreadFactory factory) {
global_thread_factory=factory;
}
/** ============================= End of default thread factory ============================== */
/** If set it will be added to <tt>local_addr</tt>. Used to implement
* for example transport independent addresses */
byte[] additional_data=null;
/** 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 */
int max_bundle_size=65535;
/** 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)
*/
long max_bundle_timeout=20;
/** Enable bundling of smaller messages into bigger ones */
boolean enable_bundling=false;
/** Enable bundling for unicast messages. Ignored if enable_bundling is off */
boolean enable_unicast_bundling=true;
private Bundler bundler=null;
private DiagnosticsHandler diag_handler=null;
boolean enable_diagnostics=true;
String diagnostics_addr="224.0.0.75";
int diagnostics_port=7500;
/** If this transport is shared, identifies all the transport instances which are to be shared */
String singleton_name=null;
/** 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>();
TpHeader header;
final String name=getName();
protected PortsManager pm=null;
protected String persistent_ports_file=null;
protected long pm_expiry_time=30000L;
protected boolean persistent_ports=false;
static final byte LIST = 1; // we have a list of messages rather than a single message when set
static final byte MULTICAST = 2; // message is a multicast (versus a unicast) message when set
static final byte OOB = 4; // message has OOB flag set (Message.OOB)
long num_msgs_sent=0, num_msgs_received=0, num_bytes_sent=0, num_bytes_received=0;
static NumberFormat f;
private static final int INITIAL_BUFSIZE=1024;
static {
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
}
/**
* 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 name + "(local address: " + local_addr + ')';
}
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 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 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 java.util.List getReceiveInterfaces() {return receive_interfaces;}
public boolean isSendOnAllInterfaces() {return send_on_all_interfaces;}
public java.util.List getSendInterfaces() {return send_interfaces;}
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 isEnable_unicast_bundling() {
return enable_unicast_bundling;
}
public void setEnable_unicast_bundling(boolean enable_unicast_bundling) {
this.enable_unicast_bundling=enable_unicast_bundling;
}
public int getMaxBundleSize() {return max_bundle_size;}
public void setMaxBundleSize(int size) {max_bundle_size=size;}
public long getMaxBundleTimeout() {return max_bundle_timeout;}
public void setMaxBundleTimeout(long timeout) {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;}
public boolean isUseIncomingPacketHandler() {return use_incoming_packet_handler;}
public ConcurrentMap<String,Protocol> getUpProtocols() {
return up_prots;
}
public int getOOBMinPoolSize() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getCorePoolSize() : 0;
}
public void setOOBMinPoolSize(int size) {
if(oob_thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)oob_thread_pool).setCorePoolSize(size);
}
public int getOOBMaxPoolSize() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getMaximumPoolSize() : 0;
}
public void setOOBMaxPoolSize(int size) {
if(oob_thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)oob_thread_pool).setMaximumPoolSize(size);
}
public int getOOBPoolSize() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getPoolSize() : 0;
}
public long getOOBKeepAliveTime() {
return oob_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)oob_thread_pool).getKeepAliveTime(TimeUnit.MILLISECONDS) : 0;
}
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;
}
public int getOOBQueueSize() {
return oob_thread_pool_queue.size();
}
public int getOOBMaxQueueSize() {
return oob_thread_pool_queue_max_size;
}
public int getIncomingMinPoolSize() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getCorePoolSize() : 0;
}
public void setIncomingMinPoolSize(int size) {
if(thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)thread_pool).setCorePoolSize(size);
}
public int getIncomingMaxPoolSize() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getMaximumPoolSize() : 0;
}
public void setIncomingMaxPoolSize(int size) {
if(thread_pool instanceof ThreadPoolExecutor)
((ThreadPoolExecutor)thread_pool).setMaximumPoolSize(size);
}
public int getIncomingPoolSize() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getPoolSize() : 0;
}
public long getIncomingKeepAliveTime() {
return thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)thread_pool).getKeepAliveTime(TimeUnit.MILLISECONDS) : 0;
}
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;
}
public int getIncomingQueueSize() {
return thread_pool_queue.size();
}
public int getIncomingMaxQueueSize() {
return thread_pool_queue_max_size;
}
public Map<String,Object> dumpStats() {
Map<String,Object> retval=super.dumpStats();
if(retval == null)
retval=new HashMap<String,Object>();
retval.put("num_msgs_sent", new Long(num_msgs_sent));
retval.put("num_msgs_received", new Long(num_msgs_received));
retval.put("num_bytes_sent", new Long(num_bytes_sent));
retval.put("num_bytes_received", new Long(num_bytes_received));
return retval;
}
/**
* 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);
private StringBuilder _getInfo(Channel ch) {
StringBuilder sb=new StringBuilder();
sb.append(ch.getLocalAddress()).append(" (").append(ch.getClusterName()).append(") ").append("\n");
sb.append("local_addr=").append(ch.getLocalAddress()).append("\n");
sb.append("group_name=").append(ch.getClusterName()).append("\n");
sb.append("version=").append(Version.description).append(", cvs=\"").append(Version.cvs).append("\"\n");
sb.append("view: ").append(ch.getView()).append('\n');
sb.append(getInfo());
return sb;
}
private void handleDiagnosticProbe(SocketAddress sender, DatagramSocket sock, String request) {
if(singleton_name != null && singleton_name.length() > 0) {
for(Protocol prot: up_prots.values()) {
ProtocolStack st=prot.getProtocolStack();
handleDiagnosticProbe(sender, sock, request, st);
}
}
else {
handleDiagnosticProbe(sender, sock, request, stack);
}
}
private void handleDiagnosticProbe(SocketAddress sender, DatagramSocket sock, String request, ProtocolStack stack) {
try {
StringTokenizer tok=new StringTokenizer(request);
String req=tok.nextToken();
StringBuilder info=new StringBuilder("n/a");
if(req.trim().toLowerCase().startsWith("query")) {
ArrayList<String> l=new ArrayList<String>(tok.countTokens());
while(tok.hasMoreTokens())
l.add(tok.nextToken().trim().toLowerCase());
info=_getInfo(stack.getChannel());
if(l.contains("jmx")) {
Channel ch=stack.getChannel();
if(ch != null) {
Map<String,Object> m=ch.dumpStats();
StringBuilder sb=new StringBuilder();
sb.append("stats:\n");
for(Iterator<Map.Entry<String,Object>> it=m.entrySet().iterator(); it.hasNext();) {
sb.append(it.next()).append("\n");
}
info.append(sb);
}
}
if(l.contains("props")) {
String p=stack.printProtocolSpecAsXML();
info.append("\nprops:\n").append(p);
}
if(l.contains("info")) {
Map<String, Object> tmp=stack.getChannel().getInfo();
info.append("INFO:\n");
for(Map.Entry<String,Object> entry: tmp.entrySet()) {
info.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
}
}
byte[] diag_rsp=info.toString().getBytes();
if(log.isDebugEnabled())
log.debug("sending diag response to " + sender);
sendResponse(sock, sender, diag_rsp);
}
catch(Throwable t) {
if(log.isErrorEnabled())
log.error("failed sending diag rsp to " + sender, t);
}
}
private static void sendResponse(DatagramSocket sock, SocketAddress sender, byte[] buf) throws IOException {
DatagramPacket p=new DatagramPacket(buf, 0, buf.length, sender);
sock.send(p);
}
/* ------------------------------------------------------------------------------- */
/*------------------------------ Protocol interface ------------------------------ */
public void init() throws Exception {
if(init_count++ >= 1) {
return;
}
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(singleton_name != null && singleton_name.trim().length() > 0) {
((ExtendedThreadFactory)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, max_timer_threads);
verifyRejectionPolicy(oob_thread_pool_rejection_policy);
verifyRejectionPolicy(thread_pool_rejection_policy);
// ========================================== 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));
}
Map<String, Object> map=new HashMap<String, Object>();
map.put("thread_naming_pattern", thread_naming_pattern);
map.put("timer", timer);
up(new Event(Event.INFO,map));
}
public void destroy() {
if(init_count == 0)
return;
init_count=Math.max(init_count -1, 0);
if(init_count == 0) {
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();
}
if(use_incoming_packet_handler && !use_concurrent_stack) {
incoming_packet_queue=new Queue();
incoming_packet_handler=new IncomingPacketHandler();
incoming_packet_handler.start();
}
if(loopback && !use_concurrent_stack) {
incoming_msg_queue=new Queue();
incoming_msg_handler=new IncomingMessageHandler();
incoming_msg_handler.start();
}
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;
}
// 1. Stop the incoming packet handler thread
if(incoming_packet_handler != null)
incoming_packet_handler.stop();
// 2. Stop the incoming message handler
if(incoming_msg_handler != null)
incoming_msg_handler.stop();
}
protected void handleConnect() throws Exception {
connect_count++;
}
protected void handleDisconnect() {
connect_count=Math.max(0, connect_count -1);
}
public String getSingletonName() {
return singleton_name;
}
/**
* Setup the Protocol instance according to the configuration string
* @return true if no other properties are left.
* false if the properties still have data in them, ie ,
* properties are left over and not handled by the protocol stack
*/
public boolean setProperties(Properties props) {
super.setProperties(props);
String str;
try {
bind_addr=Util.getBindAddress(props);
}
catch(IOException unknown) {
throw new IllegalArgumentException("failed determining bind address", unknown);
}
str=props.getProperty("use_local_host");
if(str != null) {
use_local_host=Boolean.parseBoolean(str);
props.remove("use_local_host");
}
str=props.getProperty("bind_to_all_interfaces");
if(str != null) {
receive_on_all_interfaces=Boolean.parseBoolean(str);
props.remove("bind_to_all_interfaces");
log.warn("bind_to_all_interfaces has been deprecated; use receive_on_all_interfaces instead");
}
str=props.getProperty("receive_on_all_interfaces");
if(str != null) {
receive_on_all_interfaces=Boolean.parseBoolean(str);
props.remove("receive_on_all_interfaces");
}
str=props.getProperty("receive_interfaces");
if(str != null) {
try {
receive_interfaces=Util.parseInterfaceList(str);
props.remove("receive_interfaces");
}
catch(Exception e) {
log.error("error determining interfaces (" + str + ")", e);
return false;
}
}
str=props.getProperty("send_on_all_interfaces");
if(str != null) {
send_on_all_interfaces=Boolean.parseBoolean(str);
props.remove("send_on_all_interfaces");
}
str=props.getProperty("send_interfaces");
if(str != null) {
try {
send_interfaces=Util.parseInterfaceList(str);
props.remove("send_interfaces");
}
catch(Exception e) {
log.error("error determining interfaces (" + str + ")", e);
return false;
}
}
str=props.getProperty("bind_port");
if(str != null) {
bind_port=Integer.parseInt(str);
props.remove("bind_port");
}
str=props.getProperty("port_range");
if(str != null) {
port_range=Integer.parseInt(str);
props.remove("port_range");
}
str=props.getProperty("persistent_ports_file");
if(str != null) {
persistent_ports_file=str;
props.remove("persistent_ports_file");
}
str=props.getProperty("ports_expiry_time");
if(str != null) {
pm_expiry_time=Integer.parseInt(str);
if(pm != null)
pm.setExpiryTime(pm_expiry_time);
props.remove("ports_expiry_time");
}
str=props.getProperty("persistent_ports");
if(str != null) {
if(Boolean.valueOf(str).booleanValue())
pm=new PortsManager(pm_expiry_time, persistent_ports_file);
props.remove("persistent_ports");
}
str=props.getProperty("loopback");
if(str != null) {
loopback=Boolean.valueOf(str).booleanValue();
props.remove("loopback");
}
str=props.getProperty("discard_incompatible_packets");
if(str != null) {
discard_incompatible_packets=Boolean.valueOf(str).booleanValue();
props.remove("discard_incompatible_packets");
}
// this is deprecated, just left for compatibility (use use_incoming_packet_handler)
str=props.getProperty("use_packet_handler");
if(str != null) {
use_incoming_packet_handler=Boolean.valueOf(str).booleanValue();
props.remove("use_packet_handler");
if(log.isWarnEnabled()) log.warn("'use_packet_handler' is deprecated; use 'use_incoming_packet_handler' instead");
}
str=props.getProperty("use_incoming_packet_handler");
if(str != null) {
use_incoming_packet_handler=Boolean.valueOf(str).booleanValue();
props.remove("use_incoming_packet_handler");
}
str=props.getProperty("use_concurrent_stack");
if(str != null) {
use_concurrent_stack=Boolean.valueOf(str).booleanValue();
props.remove("use_concurrent_stack");
}
str=props.getProperty("thread_naming_pattern");
if(str != null) {
thread_naming_pattern=str;
props.remove("thread_naming_pattern");
}
// ======================================= OOB thread pool =========================================
str=props.getProperty("oob_thread_pool.enabled");
if(str != null) {
oob_thread_pool_enabled=Boolean.valueOf(str).booleanValue();
props.remove("oob_thread_pool.enabled");
}
str=props.getProperty("oob_thread_pool.min_threads");
if(str != null) {
oob_thread_pool_min_threads=Integer.valueOf(str).intValue();
props.remove("oob_thread_pool.min_threads");
}
str=props.getProperty("oob_thread_pool.max_threads");
if(str != null) {
oob_thread_pool_max_threads=Integer.valueOf(str).intValue();
props.remove("oob_thread_pool.max_threads");
}
str=props.getProperty("oob_thread_pool.keep_alive_time");
if(str != null) {
oob_thread_pool_keep_alive_time=Long.valueOf(str).longValue();
props.remove("oob_thread_pool.keep_alive_time");
}
str=props.getProperty("oob_thread_pool.queue_enabled");
if(str != null) {
oob_thread_pool_queue_enabled=Boolean.valueOf(str).booleanValue();
props.remove("oob_thread_pool.queue_enabled");
}
str=props.getProperty("oob_thread_pool.queue_max_size");
if(str != null) {
oob_thread_pool_queue_max_size=Integer.valueOf(str).intValue();
props.remove("oob_thread_pool.queue_max_size");
}
str=props.getProperty("oob_thread_pool.rejection_policy");
if(str != null) {
str=str.toLowerCase().trim();
oob_thread_pool_rejection_policy=str;
if(!(str.equals("run") || str.equals("abort")|| str.equals("discard")|| str.equals("discardoldest"))) {
log.error("rejection policy of " + str + " is unknown");
return false;
}
props.remove("oob_thread_pool.rejection_policy");
}
// ======================================= Regular thread pool =========================================
str=props.getProperty("thread_pool.enabled");
if(str != null) {
thread_pool_enabled=Boolean.valueOf(str).booleanValue();
props.remove("thread_pool.enabled");
}
str=props.getProperty("thread_pool.min_threads");
if(str != null) {
thread_pool_min_threads=Integer.valueOf(str).intValue();
props.remove("thread_pool.min_threads");
}
str=props.getProperty("thread_pool.max_threads");
if(str != null) {
thread_pool_max_threads=Integer.valueOf(str).intValue();
props.remove("thread_pool.max_threads");
}
str=props.getProperty("thread_pool.keep_alive_time");
if(str != null) {
thread_pool_keep_alive_time=Long.valueOf(str).longValue();
props.remove("thread_pool.keep_alive_time");
}
str=props.getProperty("thread_pool.queue_enabled");
if(str != null) {
thread_pool_queue_enabled=Boolean.valueOf(str).booleanValue();
props.remove("thread_pool.queue_enabled");
}
str=props.getProperty("thread_pool.queue_max_size");
if(str != null) {
thread_pool_queue_max_size=Integer.valueOf(str).intValue();