-
Notifications
You must be signed in to change notification settings - Fork 33
/
IMQIPConnection.java
1750 lines (1492 loc) · 62.6 KB
/
IMQIPConnection.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
/*
* Copyright (c) 2000, 2017 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.messaging.jmq.jmsserver.service.imq;
import java.net.*;
import java.util.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.io.*;
import com.sun.messaging.jmq.jmsserver.service.*;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.util.log.Logger;
import com.sun.messaging.jmq.jmsserver.resources.BrokerResources;
import java.security.Principal;
import com.sun.messaging.jmq.jmsserver.auth.AccessController;
import com.sun.messaging.jmq.io.*;
import com.sun.messaging.jmq.util.admin.ConnectionInfo;
import com.sun.messaging.jmq.util.timer.MQTimer;
import com.sun.messaging.jmq.util.GoodbyeReason;
import com.sun.messaging.jmq.jmsserver.core.PacketReference;
import com.sun.messaging.jmq.jmsserver.core.Session;
import com.sun.messaging.jmq.jmsserver.memory.*;
import com.sun.messaging.jmq.jmsserver.data.PacketRouter;
import com.sun.messaging.jmq.util.net.IPAddress;
import com.sun.messaging.jmq.jmsserver.util.BrokerException;
import com.sun.messaging.jmq.jmsserver.util.BrokerShutdownRuntimeException;
import com.sun.messaging.jmq.jmsserver.net.*;
import com.sun.messaging.jmq.util.lists.*;
public class IMQIPConnection extends IMQBasicConnection implements Operation, MemoryCallback {
public static final boolean expectPingReply = false;
/**
* a value of -1 or 0 turns off feature
*/
public static final int closeInterval = Globals.getConfig().getIntProperty(Globals.IMQ + ".ping.close.interval", 5);
public static final boolean enablePingReply = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".ping.reply.enable", true);
protected int ctrlPktsToConsumer = 0;
boolean STREAMS = true;
boolean BLOCKING = false;
protected Set tmpDestinations = Collections.synchronizedSet(new HashSet());
protected Object timerLock = new Object();
public int packetVersion = NO_VERSION;
ConvertPacket convertPkt = null; // for old to new pkts
public static final int DEFAULT_INTERVAL = 180; // 180sec
// XXX-CODE TO OVERRIDE BEHAVIOR OF PACKETS
// to override the type of packet ...
// jmq.packet.[ctrl|read|fill].override = [direct/heap/unset]
// direct -> always use direct packets
// heap -> always use heap packets
// unset -> current behavior
// fill is the "waitingForWrite packet"
private static boolean OVERRIDE_CTRL_PACKET = false;
private static boolean OVERRIDE_READ_PACKET = false;
private static boolean OVERRIDE_FILL_PACKET = false;
private static boolean O_CTRL_USE_DIRECT = false;
private static boolean O_READ_USE_DIRECT = false;
private static boolean O_FILL_USE_DIRECT = false;
static {
try {
String ctrlover = Globals.getConfig().getProperty(Globals.IMQ + ".packet.ctrl.override");
if (ctrlover != null && ctrlover.trim().length() > 0) {
ctrlover = ctrlover.trim();
if (ctrlover.equalsIgnoreCase("direct")) {
OVERRIDE_CTRL_PACKET = true;
O_CTRL_USE_DIRECT = true;
Globals.getLogger().log(Logger.DEBUG, "DEBUG: Overriding ctrl message " + " packet behavior to DIRECT BUFFERS");
} else if (ctrlover.equalsIgnoreCase("heap")) {
OVERRIDE_CTRL_PACKET = true;
O_CTRL_USE_DIRECT = false;
Globals.getLogger().log(Logger.DEBUG, "DEBUG: Overriding ctrl message " + " packet behavior to HEAP BUFFERS");
} else {
Globals.getLogger().log(Logger.ERROR, "DEBUG: Can not determine behavior from " + " imq.packet.ctrl.override = " + ctrlover
+ " not one of the valid setting [heap,direct]");
}
}
String readover = Globals.getConfig().getProperty(Globals.IMQ + ".packet.read.override");
if (readover != null && readover.trim().length() > 0) {
readover = readover.trim();
if (readover.equalsIgnoreCase("direct")) {
OVERRIDE_READ_PACKET = true;
O_READ_USE_DIRECT = true;
Globals.getLogger().log(Logger.DEBUG, "DEBUG: Overriding read packet" + " behavior to DIRECT BUFFERS");
} else if (readover.equalsIgnoreCase("heap")) {
OVERRIDE_READ_PACKET = true;
O_READ_USE_DIRECT = false;
Globals.getLogger().log(Logger.DEBUG, "DEBUG: Overriding read packet " + " behavior to HEAP BUFFERS");
} else {
Globals.getLogger().log(Logger.ERROR, "DEBUG: Can not determine behavior from " + " imq.packet.read.override = " + readover
+ " not one of the valid setting [heap,direct]");
}
}
String fillover = Globals.getConfig().getProperty(Globals.IMQ + ".packet.fill.override");
if (fillover != null && fillover.trim().length() > 0) {
fillover = fillover.trim();
if (fillover.equalsIgnoreCase("direct")) {
OVERRIDE_FILL_PACKET = true;
O_FILL_USE_DIRECT = true;
Globals.getLogger().log(Logger.DEBUG, "DEBUG: Overriding fill packet " + " behavior to DIRECT BUFFERS");
} else if (fillover.equalsIgnoreCase("heap")) {
OVERRIDE_FILL_PACKET = true;
O_FILL_USE_DIRECT = false;
Globals.getLogger().log(Logger.DEBUG, "DEBUG: Overriding fill packet " + " behavior to HEAP BUFFERS");
} else {
Globals.getLogger().log(Logger.ERROR, "DEBUG: Can not determine " + " behavior from jmq.packet.fill.override = " + fillover
+ " not one of the valid setting [heap,direct]");
}
}
} catch (Exception ex) {
Globals.getLogger().logStack(Logger.DEBUG, "DEBUG: error setting overrides", ex);
}
}
byte[] empty = { 0 };
Object ctrlEL = null;
/**
* Ping class
*/
static class StateWatcher extends TimerTask {
private int state;
IMQIPConnection con = null;
StateWatcher(int state, IMQIPConnection con) {
this.state = state;
this.con = con;
}
@Override
public boolean cancel() {
con = null;
return super.cancel();
}
@Override
public void run() {
con.checkConnection(state);
}
}
private StateWatcher stateWatcher = null;
private long interval = DEFAULT_INTERVAL;
protected ProtocolStreams ps = null;
protected SocketChannel channel;
protected InputStream is = null;
protected OutputStream os = null;
protected boolean critical = false;
private boolean flush = false;
private boolean flushCtrl = false;
private Object flushLock = new Object();
private Object flushCtrlLock = new Object();
private boolean flushCritical = false;
private boolean lockCritical = false;
private OperationRunnable read_assigned = null;
private OperationRunnable write_assigned = null;
/**
* constructor
*/
public IMQIPConnection(Service svc, ProtocolStreams ps, PacketRouter router) throws IOException, BrokerException {
super(svc, router);
this.ps = ps;
InetAddress ia = getRemoteAddress();
if (ia != null) {
this.setRemoteIP(ia.getAddress());
}
if (ps != null) {
STREAMS = (ps.getChannel() == null);
BLOCKING = ps.getBlocking();
channel = (SocketChannel) ps.getChannel();
is = ps.getInputStream();
os = ps.getOutputStream();
}
accessController = AccessController.getInstance(svc.getName(), svc.getServiceType());
if (ia != null) {
accessController.setClientIP(ia.getHostAddress());
}
// LKS - XXX we want notification, but it doesnt need to have
// filters -> could created an orderedNLset
this.control = new NFLPriorityFifoSet();
ctrlEL = this.control.addEventListener(this, EventType.EMPTY, null);
setConnectionState(Connection.STATE_CONNECTED);
waitingWritePkt = new Packet(OVERRIDE_FILL_PACKET ? O_FILL_USE_DIRECT : !STREAMS);
if (!isAdminConnection() && Globals.getMemManager() != null) {
Globals.getMemManager().registerMemoryCallback(this);
}
}
protected InetAddress getRemoteAddress() {
if (ps != null) {
return ps.getRemoteAddress();
}
return null;
}
// -------------------------------------------------------------------------
// General connection information and metrics
// -------------------------------------------------------------------------
@Override
public void dumpState() {
super.dumpState();
logger.log(Logger.INFO, "\tcontrol = " + control.size());
logger.log(Logger.INFO, "\tread_assigned = " + read_assigned);
logger.log(Logger.INFO, "\twrite_assigned = " + write_assigned);
if (ninfo != null) {
ninfo.dumpState();
}
}
@Override
public int getLocalPort() {
if (ps == null) {
return 0;
}
return ps.getLocalPort();
}
/**
* The debug state of this object
*/
@Override
public synchronized Hashtable getDebugState() {
Hashtable ht = super.getDebugState();
ht.put("pkts[TOTAL](in,out) ", "(" + msgsIn + "," + (ctrlPktsToConsumer + msgsToConsumer) + ")");
for (int i = 0; i < pktsIn.length; i++) {
if (pktsIn[i] == 0 && pktsOut[i] == 0) {
continue;
}
ht.put("pkts[" + PacketType.getString(i) + "] (in,out)", "(" + pktsIn[i] + "," + pktsOut[i] + ")");
}
ht.put("ctrlPktsToConsumer", String.valueOf(ctrlPktsToConsumer));
ht.put("critical", String.valueOf(critical));
ht.put("controlSize", String.valueOf(control.size()));
if (control.size() > 0) {
Vector v = new Vector();
Iterator itr = control.iterator();
while (itr.hasNext()) {
Packet p = (Packet) itr.next();
v.add(p.toString());
}
ht.put("control", v);
}
if (ps != null) {
ht.put("transport", ps.getDebugState());
}
return ht;
}
@Override
public Vector getDebugMessages(boolean full) {
Vector ht = new Vector();
synchronized (control) {
Iterator itr = control.iterator();
while (itr.hasNext()) {
PacketReference pr = (PacketReference) itr.next();
ht.add((full ? pr.getPacket().dumpPacketString() : pr.getPacket().toString()));
}
}
return ht;
}
@Override
public ConnectionInfo getConnectionInfo() {
coninfo = super.getConnectionInfo();
coninfo.remPort = getRemotePort();
return coninfo;
}
@Override
public boolean useDirectBuffers() {
return (OVERRIDE_CTRL_PACKET ? O_CTRL_USE_DIRECT : !STREAMS);
// return !STREAMS;
}
// -------------------------------------------------------------------------
// Basic Operation implementation
// -------------------------------------------------------------------------
NotificationInfo ninfo = null;
public synchronized AbstractSelectableChannel getChannel() {
if (ps == null) {
return null;
}
return ps.getChannel();
}
@Override
public boolean canKill() {
return !critical;
}
@Override
public void setCritical(boolean critical) {
this.critical = critical;
}
@Override
public boolean waitUntilDestroyed(long time) {
long targettime = System.currentTimeMillis() + time;
while (isValid() && System.currentTimeMillis() < targettime) {
waitForWork(time);
}
return isValid();
}
Object releaseWaitLock = new Object();
/**
* called when the thread is not longer processing the operation this mask used when a thread is assigned or released,
* which is returned from the notificationInfo object (if any)
*/
@Override
public synchronized void notifyRelease(OperationRunnable runner, int events) {
/*
* the thread is giving us UP ...
*/
int release_events = 0;
if ((events & SelectionKey.OP_WRITE) != 0 && runner == write_assigned) {
release_events = release_events | SelectionKey.OP_WRITE;
write_assigned = null;
}
if ((events & SelectionKey.OP_READ) != 0 && runner == read_assigned) {
release_events = release_events | SelectionKey.OP_READ;
read_assigned = null;
}
if (ninfo != null && release_events != 0) {
ninfo.released(this, release_events);
}
notifyAll();
return;
}
@Override
public synchronized void waitForRelease(long timeout) {
long waitt = 5000;
while (read_assigned != null || write_assigned != null) {
if (timeout <= 0) {
Globals.getLogger().log(Logger.WARNING, "Timeout in waiting for runnable threads release in " + this);
return;
}
Globals.getLogger().log(Logger.INFO, "Waiting for runnable threads release in " + this);
if (timeout < waitt) {
waitt = timeout;
}
try {
wait(waitt);
} catch (InterruptedException e) {
Globals.getLogger().log(Logger.WARNING, "Interrupted in waiting for runnable threads release in " + this);
return;
}
timeout -= waitt;
}
}
public synchronized void clearAssigned() {
read_assigned = null;
write_assigned = null;
}
public synchronized OperationRunnable getReadRunnable() {
return read_assigned;
}
public synchronized OperationRunnable getWriteRunnable() {
return write_assigned;
}
@Override
public synchronized void threadAssigned(OperationRunnable runner, int events) throws IllegalAccessException {
int release_events = 0;
if ((events & SelectionKey.OP_WRITE) != 0) {
if (write_assigned != null) {
// we havent released yet ... its a timing thing
release_events = release_events | SelectionKey.OP_WRITE;
}
write_assigned = runner;
}
if ((events & SelectionKey.OP_READ) != 0) {
if (read_assigned != null) {
// we havent released yet ... its a timing thing
release_events = release_events | SelectionKey.OP_READ;
}
read_assigned = runner;
}
if (ninfo != null) {
if (release_events != 0) {
ninfo.released(this, release_events);
}
ninfo.assigned(this, events);
}
}
@Override
public void attach(NotificationInfo obj) {
ninfo = obj;
}
@Override
public NotificationInfo attachment() {
return ninfo;
}
/*
* private String getKeyString(int events) { String str = ""; if ((events & SelectionKey.OP_WRITE) > 0) { str +=
* " WRITE "; } if ((events & SelectionKey.OP_READ) > 0) { str += " READ "; } return str; }
*/
@Override
public boolean process(int events, boolean wait) throws IOException {
boolean didSomething = false;
boolean processedLastIteration = true;
try {
while (processedLastIteration) {
// process all writes
processedLastIteration = false;
if ((events & SelectionKey.OP_WRITE) != 0) {
while (true) {
if (writeData(wait) != Operation.PROCESS_PACKETS_REMAINING) {
// wasnt able to write anymore
// break out of the loop
break;
}
processedLastIteration = true;
}
}
// process one write
if ((events & SelectionKey.OP_READ) != 0) {
int returnval = readData();
switch (returnval) {
case Operation.PROCESS_PACKETS_REMAINING:
processedLastIteration = true;
case Operation.PROCESS_PACKETS_COMPLETE:
case Operation.PROCESS_WRITE_INCOMPLETE:
default:
break;
}
}
didSomething |= processedLastIteration;
}
} catch (Throwable t) {
handleWriteException(t);
}
return !didSomething;
}
@Override
public String getRemoteConnectionString() {
if (remoteConString != null) {
return remoteConString;
}
boolean userset = false;
String remotePortString = "???";
String userString = "???";
if (state >= Connection.STATE_AUTHENTICATED) {
try {
Principal principal = getAuthenticatedName();
if (principal != null) {
userString = principal.getName();
userset = true;
}
} catch (BrokerException e) {
if (IMQBasicConnection.DEBUG) {
logger.log(Logger.DEBUG, "Exception getting authentication name " + conId, e);
}
}
}
remotePortString = Integer.toString(getRemotePort());
String retstr = userString + "@" + IPAddress.rawIPToString(getRemoteIP(), true, true) + ":" + remotePortString;
if (userset) {
remoteConString = retstr;
}
return retstr;
}
protected int getRemotePort() {
return (ps == null ? 0 : ps.getRemotePort());
}
String localsvcstring = null;
@Override
protected String localServiceString() {
if (localsvcstring != null) {
return localsvcstring;
}
String localPortString = "???";
localPortString = Integer.toString(getLocalPort());
localsvcstring = service.getName() + ":" + localPortString;
return localsvcstring;
}
// -------------------------------------------------------------------------
// Basic Connection Management
// -------------------------------------------------------------------------
@Override
public synchronized void closeConnection(boolean force, int reason, String reasonStr) {
if (state >= Connection.STATE_CLOSED) {
logger.log(logger.DEBUG, "Requested close of already closed connection:" + this);
return;
}
stopConnection();
if (Globals.getMemManager() != null) {
Globals.getMemManager().removeMemoryCallback(this);
}
if (force) { // we are shutting it down, say goodbye
sayGoodbye(false, reason, reasonStr);
flushControl(1000);
}
// CR 6798464: Don't mark connection as closed until we've flushed the queue and sent the GOODBYE
state = Connection.STATE_CLOSED;
notifyConnectionClosed();
// clean up everything
this.control.removeEventListener(ctrlEL);
cleanup(reason == GoodbyeReason.SHUTDOWN_BKR);
// OK - we are done with the flush, we dont need to be
// notified anymore
if (ninfo != null) {
ninfo.destroy(reasonStr);
}
try {
closeProtocolStream();
} catch (IOException ex) {
// its OK if we cant close the socket ..,
// aother thread may have already done it
// ignore
}
if (reason == GoodbyeReason.SHUTDOWN_BKR) {
cleanupConnection(); // OK if we do it twice
} else {
cleanup(false);
}
}
protected void closeProtocolStream() throws IOException {
if (ps != null) {
ps.close(); // close socket
}
ps = null;
}
@Override
protected void cleanupControlPackets(boolean shutdown) {
while (!control.isEmpty()) {
Packet p = (Packet) control.removeNext();
if (p == null) {
continue;
}
p.destroy();
}
}
int destroyRecurse = 0;
/**
* destroy the connection to the client clearing out messages, etc
*/
@Override
public void destroyConnection(boolean force, int reason, String reasonstr) {
int oldstate = 0;
boolean destroyOK = false;
try {
synchronized (this) {
oldstate = state;
if (state >= Connection.STATE_DESTROYING) {
return;
}
if (state < Connection.STATE_CLOSED) {
closeConnection(force, reason, reasonstr);
}
setConnectionState(Connection.STATE_DESTROYING);
}
Globals.getConnectionManager().removeConnection(getConnectionUID(), force, reason, reasonstr);
if (accessController.isAuthenticated()) {
accessController.logout();
}
// The connection is going away. Deposit our metric totals
// with the metric manager
MetricManager mm = Globals.getMetricManager();
if (mm != null) {
mm.depositTotals(service.getName(), counters);
}
// Clear, just in case we are called twice
counters.reset();
synchronized (timerLock) {
if (stateWatcher != null) {
try {
stateWatcher.cancel();
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "Error destroying " + " connection " + this + " to state " + state, ex);
}
stateWatcher = null;
}
}
if (this.getDestroyReason() != null) {
logConnectionInfo(true, this.getDestroyReason());
} else {
logConnectionInfo(true, reasonstr);
}
setConnectionState(Connection.STATE_DESTROYED);
destroyOK = true;
wakeup();
} finally {
if (!destroyOK && reason != GoodbyeReason.SHUTDOWN_BKR && (Globals.getMemManager() == null || Globals.getMemManager().getCurrentLevel() > 0)) {
state = oldstate;
if (destroyRecurse < 2) {
destroyRecurse++;
destroyConnection(force, reason, reasonstr);
}
}
// free the lock
Globals.getClusterBroadcast().connectionClosed(getConnectionUID(), isAdminConnection());
}
}
/**
* sets the connection state
*
* @return false if connection being destroyed
*/
@Override
public boolean setConnectionState(int state) {
synchronized (timerLock) {
this.state = state;
if (this.state >= Connection.STATE_CLOSED) {
if (stateWatcher != null) {
try {
stateWatcher.cancel();
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "Error setting state on " + " connection " + this + " to state " + state, ex);
}
stateWatcher = null;
}
wakeup();
return false;
} else if (state == Connection.STATE_CONNECTED) {
interval = Globals.getConfig().getLongProperty(Globals.IMQ + ".authentication.client.response.timeout", DEFAULT_INTERVAL);
MQTimer timer = Globals.getTimer(true);
stateWatcher = new StateWatcher(Connection.STATE_INITIALIZED, this);
try {
timer.schedule(stateWatcher, interval * 1000);
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "InternalError: timer canceled ", ex);
}
} else if (state == Connection.STATE_INITIALIZED || state == Connection.STATE_AUTH_REQUESTED || state == Connection.STATE_AUTH_RESPONSED) {
if (stateWatcher != null) {
try {
stateWatcher.cancel();
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "Error setting state on " + " connection " + this + " to state " + state, ex);
}
stateWatcher = null;
}
// if next state not from client, return
if (state == Connection.STATE_INITIALIZED) {
return true;
}
if (state == Connection.STATE_AUTH_RESPONSED) {
return true;
}
MQTimer timer = Globals.getTimer(true);
stateWatcher = new StateWatcher(Connection.STATE_AUTH_RESPONSED, this);
try {
timer.schedule(stateWatcher, interval * 1000);
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "InternalError: timer canceled ", ex);
}
} else if (state >= Connection.STATE_AUTHENTICATED || state == Connection.STATE_UNAVAILABLE) {
if (stateWatcher != null) {
try {
stateWatcher.cancel();
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "Error setting state on " + " connection " + this + " to state " + state, ex);
}
stateWatcher = null;
}
if (state == Connection.STATE_AUTHENTICATED) {
logConnectionInfo(false);
}
}
}
return true;
}
@Override
public void logConnectionInfo(boolean closing) {
this.logConnectionInfo(closing, "Unknown");
}
public void logConnectionInfo(boolean closing, String reason) {
String[] args = { getRemoteConnectionString(), localServiceString(), Integer.toString(Globals.getConnectionManager().size()), reason,
String.valueOf(control.size()), Integer.toString(service.size()) };
if (!closing) {
logger.log(Logger.INFO, BrokerResources.I_ACCEPT_CONNECTION, args);
} else {
logger.log(Logger.INFO, BrokerResources.I_DROP_CONNECTION, args);
}
}
// -------------------------------------------------------------------------
// Queuing Messages
// -------------------------------------------------------------------------
private NFLPriorityFifoSet control = null;
boolean hasCtrl = true;
/**
* send a control (reply) message back to the client
*
* @param msg message to send back to the client
*/
@Override
public void sendControlMessage(Packet msg) {
if (!isValid() && msg.getPacketType() != PacketType.GOODBYE) {
logger.log(Logger.INFO, "Internal Warning: message " + msg + "queued on destroyed connection " + this);
}
control.add(msg);
synchronized (control) {
hasCtrl = !control.isEmpty();
}
}
protected void sendControlMessage(Packet msg, boolean priority) {
if (IMQBasicConnection.DEBUG) {
logger.log(Logger.DEBUGHIGH, "IMQIPConnection[ {0} ] queueing Admin packet {1}", this.toString(), msg.toString());
}
if (!isValid()) { // we are being destroyed
return;
}
// I am assuming that there isnt any issue
// with priority
// if there is, I may need a new list type
assert priority == false;
sendControlMessage(msg);
}
/**
* Flush all control messages on this connection to the client.
*
* @param timeout the lenght of time to try and flush the messages (0 indicates wait forever)
*/
@Override
public void flushControl(long timeout) {
if (read_assigned == write_assigned && read_assigned != null) {
localFlushCtrl();
return;
}
synchronized (flushCtrlLock) {
if (IMQBasicConnection.DEBUG) {
logger.log(Logger.DEBUG, "Flushing Control Messages with timeout of " + timeout);
}
// dont worry about syncing here -> if we miss the
// window we should still be woken up w/ the ctrl
// notify -> since that happens AFTER a message is
// removed from the list
if (ctrlpkt == null && control.isEmpty() && !flushCritical) {
return;
}
if (!isValid()) {
return;
}
long time = System.currentTimeMillis();
flushCtrl = true;
if (timeout < 0) {
return;
}
while (flushCtrl && isValid()) {
try {
if (timeout != 0) {
flushCtrlLock.wait(timeout);
} else {
flushCtrlLock.wait(1000 /* 1 second */);
}
} catch (InterruptedException ex) {
// no reason to do anything w/ it
}
if (flushCtrl && timeout > 0 && System.currentTimeMillis() >= time + timeout) {
break;
}
}
flushCtrl = false;
if (IMQBasicConnection.DEBUG) {
if (flush) {
logger.log(Logger.DEBUG, "Control Flush did not complete in timeout of " + timeout);
} else {
logger.log(Logger.DEBUG, "Contrl Flush completed");
}
}
}
}
protected void localFlushCtrl() {
// OK .. if we are in the SAME thread as write do it inline
flushCtrl = true;
writeDataUntilComplete();
flushCtrl = false;
}
protected void localFlush() {
// OK .. if we are in the SAME thread as write do it inline
flush = true;
writeDataUntilComplete();
flush = false;
}
private void writeDataUntilComplete() {
try {
while (true) {
if (writeData(false) == Operation.PROCESS_PACKETS_COMPLETE) {
break;
}
}
} catch (Exception ex) {
// got exception while flushing, connection is probably gone
logger.log(Logger.DEBUG, "error in flush " + this, ex);
}
}
/**
* Flush all control and JMS messages on this connection to the client.
*
* @param timeout the lenght of time to try and flush the messages (0 indicates wait forever)
*/
public void flush(long timeout) {
if (read_assigned == write_assigned && read_assigned != null) {
localFlush();
return;
}
if (!inCtrlWrite && control.isEmpty() && !inJMSWrite && hasBusySessions() && !flushCritical && !lockCritical) {
// nothing to do
return;
}
synchronized (flushLock) {
if (IMQBasicConnection.DEBUG) {
logger.log(Logger.DEBUG, "Flushing Messages with timeout of " + timeout);
}
if (!isValid()) {
return;
}
// dont worry about syncing here -> if we miss the
// window we should still be woken up w/ the ctrl
// notify -> since that happens AFTER a message is
// removed from the list
if (!inCtrlWrite && control.isEmpty() && !inJMSWrite && hasBusySessions() && !flushCritical && !lockCritical) {
// nothing to do
return;
}
long time = System.currentTimeMillis();
flush = true;
while (flush && isValid()) {
try {
if (timeout != 0) {
flushLock.wait(timeout);
} else {
flushLock.wait(1000 /* 1 second */);
}
} catch (InterruptedException ex) {
// valid, no reason to check
}
if (flush && timeout > 0 && System.currentTimeMillis() >= time + timeout) {
break;
}
}
if (IMQBasicConnection.DEBUG) {
if (flush) {
logger.log(Logger.DEBUG, "Flush did not complete in timeout of " + timeout);
} else {
logger.log(Logger.DEBUG, "Flush completed");
}
}
}
}
void dumpConnectionInfo() {
if (ninfo != null) {
logger.log(Logger.INFO, "Connection Information [" + this + "]" + ninfo.getStateInfo());
}
}
void checkConnection(int state) {
synchronized (timerLock) {
try {
stateWatcher.cancel();
} catch (IllegalStateException ex) {
logger.log(Logger.DEBUG, "Error destroying " + " connection " + this + " to state " + state, ex);
}
stateWatcher = null;
}
String[] args = { toString(), getConnectionStateString(this.state), getConnectionStateString(state), String.valueOf(interval) };
synchronized (this) {
if (this.state >= state) {
return;
}
if (this.state >= Connection.STATE_CLOSED || this.state == Connection.STATE_UNAVAILABLE) {
return;
}
logger.log(Logger.WARNING, Globals.getBrokerResources().getKString(BrokerResources.W_CONNECTION_TIMEOUT, args));
}
// FOR DEBUG ... add additional state information
if (IMQBasicConnection.DEBUG) {
dumpConnectionInfo();
}
// dont bother being nice
destroyConnection(false, GoodbyeReason.CON_FATAL_ERROR, Globals.getBrokerResources().getKString(BrokerResources.W_CONNECTION_TIMEOUT, args));
}
// -------------------------------------------------------------------------