/
OpenWireConnection.java
1723 lines (1475 loc) · 62.5 KB
/
OpenWireConnection.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.protocol.openwire;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import javax.jms.IllegalStateException;
import javax.jms.InvalidClientIDException;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSSecurityException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.artemis.api.core.ActiveMQAddressExistsException;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ActiveMQNonExistentQueueException;
import org.apache.activemq.artemis.api.core.ActiveMQQueueExistsException;
import org.apache.activemq.artemis.api.core.ActiveMQRemoteDisconnectException;
import org.apache.activemq.artemis.api.core.ActiveMQSecurityException;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.client.ActiveMQClientLogger;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.persistence.OperationContext;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.Bindings;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQCompositeConsumerBrokerExchange;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQConnectionContext;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQConsumer;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQConsumerBrokerExchange;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQProducerBrokerExchange;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQSession;
import org.apache.activemq.artemis.core.protocol.openwire.amq.AMQSingleConsumerBrokerExchange;
import org.apache.activemq.artemis.core.protocol.openwire.util.OpenWireUtil;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.core.security.SecurityAuth;
import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.BindingQueryResult;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.server.ServerConsumer;
import org.apache.activemq.artemis.core.server.ServerSession;
import org.apache.activemq.artemis.core.server.SlowConsumerDetectionListener;
import org.apache.activemq.artemis.core.server.TempQueueObserver;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.server.impl.RefsOperation;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.core.transaction.ResourceManager;
import org.apache.activemq.artemis.core.transaction.Transaction;
import org.apache.activemq.artemis.core.transaction.TransactionOperationAbstract;
import org.apache.activemq.artemis.core.transaction.TransactionPropertyIndexes;
import org.apache.activemq.artemis.spi.core.protocol.AbstractRemotingConnection;
import org.apache.activemq.artemis.spi.core.protocol.ConnectionEntry;
import org.apache.activemq.artemis.spi.core.remoting.Connection;
import org.apache.activemq.artemis.utils.UUIDGenerator;
import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTempQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.BrokerInfo;
import org.apache.activemq.command.BrokerSubscriptionInfo;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.ConnectionControl;
import org.apache.activemq.command.ConnectionError;
import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerControl;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.ControlCommand;
import org.apache.activemq.command.DataArrayResponse;
import org.apache.activemq.command.DestinationInfo;
import org.apache.activemq.command.ExceptionResponse;
import org.apache.activemq.command.FlushCommand;
import org.apache.activemq.command.IntegerResponse;
import org.apache.activemq.command.KeepAliveInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageDispatch;
import org.apache.activemq.command.MessageDispatchNotification;
import org.apache.activemq.command.MessagePull;
import org.apache.activemq.command.ProducerAck;
import org.apache.activemq.command.ProducerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.command.RemoveSubscriptionInfo;
import org.apache.activemq.command.Response;
import org.apache.activemq.command.SessionId;
import org.apache.activemq.command.SessionInfo;
import org.apache.activemq.command.ShutdownInfo;
import org.apache.activemq.command.TransactionId;
import org.apache.activemq.command.TransactionInfo;
import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.command.XATransactionId;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.state.CommandVisitor;
import org.apache.activemq.state.ConnectionState;
import org.apache.activemq.state.ConsumerState;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.state.SessionState;
import org.apache.activemq.transport.TransmitCallback;
import org.apache.activemq.util.ByteSequence;
import org.jboss.logging.Logger;
/**
* Represents an activemq connection.
*/
public class OpenWireConnection extends AbstractRemotingConnection implements SecurityAuth, TempQueueObserver {
private static final Logger logger = Logger.getLogger(OpenWireConnection.class);
private static final KeepAliveInfo PING = new KeepAliveInfo();
private final OpenWireProtocolManager protocolManager;
private boolean destroyed = false;
//separated in/out wireFormats allow deliveries (eg async and consumers) to not slow down bufferReceived
private final OpenWireFormat inWireFormat;
private final OpenWireFormat outWireFormat;
private AMQConnectionContext context;
private final AtomicBoolean stopping = new AtomicBoolean(false);
private final Map<String, SessionId> sessionIdMap = new ConcurrentHashMap<>();
private final Map<ConsumerId, AMQConsumerBrokerExchange> consumerExchanges = new ConcurrentHashMap<>();
private final Map<ProducerId, AMQProducerBrokerExchange> producerExchanges = new ConcurrentHashMap<>();
private final Map<SessionId, AMQSession> sessions = new ConcurrentHashMap<>();
private ConnectionState state;
private volatile boolean noLocal;
/**
* Openwire doesn't sen transactions associated with any sessions.
* It will however send beingTX / endTX as it would be doing it with XA Transactions.
* But always without any association with Sessions.
* This collection will hold nonXA transactions. Hopefully while they are in transit only.
*/
private final Map<TransactionId, Transaction> txMap = new ConcurrentHashMap<>();
private volatile AMQSession advisorySession;
private final ActiveMQServer server;
/**
* This is to be used with connection operations that don't have a session.
* Such as TM operations.
*/
private ServerSession internalSession;
private final OperationContext operationContext;
private static final AtomicLongFieldUpdater<OpenWireConnection> LAST_SENT_UPDATER = AtomicLongFieldUpdater.newUpdater(OpenWireConnection.class, "lastSent");
private volatile long lastSent = -1;
private ConnectionEntry connectionEntry;
private boolean useKeepAlive;
private long maxInactivityDuration;
private final Set<SimpleString> knownDestinations = new ConcurrentHashSet<>();
private final AtomicBoolean disableTtl = new AtomicBoolean(false);
public OpenWireConnection(Connection connection,
ActiveMQServer server,
Executor executor,
OpenWireProtocolManager openWireProtocolManager,
OpenWireFormat wf) {
super(connection, executor);
this.server = server;
this.operationContext = server.newOperationContext();
this.protocolManager = openWireProtocolManager;
this.inWireFormat = wf;
this.outWireFormat = wf.copy();
this.useKeepAlive = openWireProtocolManager.isUseKeepAlive();
this.maxInactivityDuration = openWireProtocolManager.getMaxInactivityDuration();
}
// SecurityAuth implementation
@Override
public String getUsername() {
ConnectionInfo info = getConnectionInfo();
if (info == null) {
return null;
}
return info.getUserName();
}
public OperationContext getOperationContext() {
return operationContext;
}
// SecurityAuth implementation
@Override
public OpenWireConnection getRemotingConnection() {
return this;
}
// SecurityAuth implementation
@Override
public String getPassword() {
ConnectionInfo info = getConnectionInfo();
if (info == null) {
return null;
}
return info.getPassword();
}
private ConnectionInfo getConnectionInfo() {
if (state == null) {
return null;
}
ConnectionInfo info = state.getInfo();
if (info == null) {
return null;
}
return info;
}
//tells the connection that
//some bytes just sent
private void bufferSent() {
//much cheaper than a volatile set if contended, but less precise (ie allows stale loads)
LAST_SENT_UPDATER.lazySet(this, System.currentTimeMillis());
}
/**
* Log packaged into a separate method for performance reasons.
*/
private static void traceBufferReceived(Object connectionID, Command command) {
logger.trace("connectionID: " + connectionID + " RECEIVED: " + (command == null ? "NULL" : command));
}
@Override
public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) {
super.bufferReceived(connectionID, buffer);
try {
recoverOperationContext();
Command command = (Command) inWireFormat.unmarshal(buffer);
// log the openwire command
if (logger.isTraceEnabled()) {
traceBufferReceived(connectionID, command);
}
boolean responseRequired = command.isResponseRequired();
int commandId = command.getCommandId();
// ignore pings
if (command.getClass() != KeepAliveInfo.class) {
Response response = null;
try {
setLastCommand(command);
response = command.visit(commandProcessorInstance);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.warn("Errors occurred during the buffering operation ", e);
if (responseRequired) {
response = convertException(e);
}
} finally {
setLastCommand(null);
}
if (response instanceof ExceptionResponse) {
Throwable cause = ((ExceptionResponse)response).getException();
if (!responseRequired) {
serviceException(cause);
response = null;
}
// If there was an exception when processing ConnectionInfo we should
// stop the connection to prevent dangling sockets
if (command instanceof ConnectionInfo) {
delayedStop(2000, cause.getMessage(), cause);
}
}
if (responseRequired) {
if (response == null) {
response = new Response();
response.setCorrelationId(commandId);
}
}
// The context may have been flagged so that the response is not
// sent.
if (context != null) {
if (context.isDontSendReponse()) {
context.setDontSendReponse(false);
response = null;
}
}
sendAsyncResponse(commandId, response);
}
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.debug(e);
sendException(e);
} finally {
clearupOperationContext();
}
}
/** It will send the response through the operation context, as soon as everything is confirmed on disk */
private void sendAsyncResponse(final int commandId, final Response response) throws Exception {
if (response != null) {
operationContext.executeOnCompletion(new IOCallback() {
@Override
public void done() {
if (!protocolManager.isStopping()) {
try {
response.setCorrelationId(commandId);
dispatchSync(response);
} catch (Exception e) {
sendException(e);
}
}
}
@Override
public void onError(int errorCode, String errorMessage) {
sendException(new IOException(errorCode + "-" + errorMessage));
}
});
}
}
public void sendException(Exception e) {
Response resp = convertException(e);
if (context != null) {
Command command = context.getLastCommand();
if (command != null) {
resp.setCorrelationId(command.getCommandId());
}
}
try {
dispatch(resp);
} catch (IOException e2) {
ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e2);
}
}
private Response convertException(Exception e) {
Response resp;
if (e instanceof ActiveMQSecurityException) {
resp = new ExceptionResponse(new JMSSecurityException(e.getMessage()));
} else if (e instanceof ActiveMQNonExistentQueueException) {
resp = new ExceptionResponse(new InvalidDestinationException(e.getMessage()));
} else {
resp = new ExceptionResponse(e);
}
return resp;
}
private void setLastCommand(Command command) {
if (context != null) {
context.setLastCommand(command);
}
}
@Override
public void destroy() {
fail(null, null);
}
@Override
public boolean isClient() {
return false;
}
@Override
public boolean isDestroyed() {
return destroyed;
}
@Override
public void disconnect(boolean criticalError) {
this.disconnect(null, null, criticalError);
}
@Override
public void flush() {
checkInactivity();
}
private void checkInactivity() {
if (!this.useKeepAlive) {
return;
}
long dur = System.currentTimeMillis() - lastSent;
if (dur >= this.maxInactivityDuration / 2) {
this.sendCommand(PING);
}
}
private void callFailureListeners(final ActiveMQException me) {
final List<FailureListener> listenersClone = new ArrayList<>(failureListeners);
for (final FailureListener listener : listenersClone) {
try {
listener.connectionFailed(me, false);
} catch (final Throwable t) {
// Failure of one listener to execute shouldn't prevent others
// from
// executing
ActiveMQServerLogger.LOGGER.errorCallingFailureListener(t);
}
}
}
// send a WireFormatInfo to the peer
public void sendHandshake() {
WireFormatInfo info = inWireFormat.getPreferedWireFormatInfo();
sendCommand(info);
}
public ConnectionState getState() {
return state;
}
/**
* Log packaged into a separate method for performance reasons.
*/
private static void tracePhysicalSend(Connection transportConnection, Command command) {
logger.trace("connectionID: " + (transportConnection == null ? "" : transportConnection.getID()) + " SENDING: " + (command == null ? "NULL" : command));
}
public void physicalSend(Command command) throws IOException {
if (logger.isTraceEnabled()) {
tracePhysicalSend(transportConnection, command);
}
try {
final ByteSequence bytes = outWireFormat.marshal(command);
final int bufferSize = bytes.length;
final ActiveMQBuffer buffer = transportConnection.createTransportBuffer(bufferSize);
buffer.writeBytes(bytes.data, bytes.offset, bufferSize);
transportConnection.write(buffer, false, false);
bufferSent();
} catch (IOException e) {
throw e;
} catch (Throwable t) {
ActiveMQServerLogger.LOGGER.error("error sending", t);
}
}
public void dispatchAsync(Command message) throws Exception {
dispatchSync(message);
}
public void dispatchSync(Command message) throws Exception {
processDispatch(message);
}
public void serviceException(Throwable e) throws Exception {
ConnectionError ce = new ConnectionError();
ce.setException(e);
dispatchAsync(ce);
}
public void dispatch(Command command) throws IOException {
this.physicalSend(command);
}
protected void processDispatch(Command command) throws IOException {
MessageDispatch messageDispatch = (MessageDispatch) (command.isMessageDispatch() ? command : null);
try {
if (!stopping.get()) {
if (messageDispatch != null) {
protocolManager.preProcessDispatch(messageDispatch);
}
dispatch(command);
}
} catch (IOException e) {
if (messageDispatch != null) {
TransmitCallback sub = messageDispatch.getTransmitCallback();
protocolManager.postProcessDispatch(messageDispatch);
if (sub != null) {
sub.onFailure();
}
messageDispatch = null;
throw e;
}
} finally {
if (messageDispatch != null) {
TransmitCallback sub = messageDispatch.getTransmitCallback();
protocolManager.postProcessDispatch(messageDispatch);
if (sub != null) {
sub.onSuccess();
}
}
}
}
private void addConsumerBrokerExchange(ConsumerId id, AMQSession amqSession, List<AMQConsumer> consumerList) {
AMQConsumerBrokerExchange result = consumerExchanges.get(id);
if (result == null) {
if (consumerList.size() == 1) {
result = new AMQSingleConsumerBrokerExchange(amqSession, consumerList.get(0));
} else {
result = new AMQCompositeConsumerBrokerExchange(amqSession, consumerList);
}
synchronized (consumerExchanges) {
consumerExchanges.put(id, result);
}
}
}
private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException {
AMQProducerBrokerExchange result = producerExchanges.get(id);
if (result == null) {
synchronized (producerExchanges) {
result = new AMQProducerBrokerExchange();
result.setConnectionContext(context);
//todo implement reconnect https://issues.apache.org/jira/browse/ARTEMIS-194
//todo: this used to check for && this.acceptorUsed.isAuditNetworkProducers()
if (context.isReconnect() || (context.isNetworkConnection())) {
// once implemented ARTEMIS-194, we need to set the storedSequenceID here somehow
// We have different semantics on Artemis Journal, but we could adapt something for this
// TBD during the implementation of ARTEMIS-194
result.setLastStoredSequenceId(0);
}
SessionState ss = state.getSessionState(id.getParentId());
if (ss != null) {
result.setProducerState(ss.getProducerState(id));
ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo();
}
}
producerExchanges.put(id, result);
}
}
return result;
}
public void deliverMessage(MessageDispatch dispatch) {
Message m = dispatch.getMessage();
if (m != null) {
long endTime = System.currentTimeMillis();
m.setBrokerOutTime(endTime);
}
sendCommand(dispatch);
}
public OpenWireFormat wireFormat() {
return this.inWireFormat;
}
private void shutdown(boolean fail) {
if (fail) {
transportConnection.forceClose();
} else {
transportConnection.close();
}
}
private void disconnect(ActiveMQException me, String reason, boolean fail) {
if (context == null || destroyed) {
return;
}
// Don't allow things to be added to the connection state while we
// are shutting down.
// is it necessary? even, do we need state at all?
state.shutdown();
try {
for (SessionId sessionId : sessionIdMap.values()) {
AMQSession session = sessions.get(sessionId);
if (session != null) {
session.close();
}
}
internalSession.close(false);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e);
}
// Then call the listeners
// this should closes underlying sessions
callFailureListeners(me);
// this should clean up temp dests
callClosingListeners();
destroyed = true;
//before closing transport, sendCommand the last response if any
Command command = context.getLastCommand();
if (command != null && command.isResponseRequired()) {
Response lastResponse = new Response();
lastResponse.setCorrelationId(command.getCommandId());
try {
dispatchSync(lastResponse);
} catch (Throwable e) {
ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e);
}
}
}
@Override
public void disconnect(String reason, boolean fail) {
this.disconnect(null, reason, fail);
}
@Override
public void fail(ActiveMQException me, String message) {
if (me != null) {
//filter it like the other protocols
if (!(me instanceof ActiveMQRemoteDisconnectException)) {
ActiveMQClientLogger.LOGGER.connectionFailureDetected(me.getMessage(), me.getType());
}
}
try {
if (this.getConnectionInfo() != null) {
protocolManager.removeConnection(this.getConnectionInfo(), me);
}
} catch (InvalidClientIDException e) {
ActiveMQServerLogger.LOGGER.warn("Couldn't close connection because invalid clientID", e);
}
shutdown(true);
}
private void delayedStop(final int waitTimeMillis, final String reason, Throwable cause) {
if (waitTimeMillis > 0) {
try {
protocolManager.getScheduledPool().schedule(() -> {
fail(new ActiveMQException(reason, cause, ActiveMQExceptionType.GENERIC_EXCEPTION), reason);
ActiveMQServerLogger.LOGGER.warn("Stopping " + transportConnection.getRemoteAddress() + "because " +
reason);
}, waitTimeMillis, TimeUnit.MILLISECONDS);
} catch (Throwable t) {
ActiveMQServerLogger.LOGGER.warn("Cannot stop connection. This exception will be ignored.", t);
}
}
}
public void setAdvisorySession(AMQSession amqSession) {
this.advisorySession = amqSession;
}
public AMQSession getAdvisorySession() {
return this.advisorySession;
}
public AMQConnectionContext getContext() {
return this.context;
}
public void updateClient(ConnectionControl control) throws Exception {
if (protocolManager.isUpdateClusterClients()) {
dispatchAsync(control);
}
}
public AMQConnectionContext initContext(ConnectionInfo info) throws Exception {
WireFormatInfo wireFormatInfo = inWireFormat.getPreferedWireFormatInfo();
// Older clients should have been defaulting this field to true.. but
// they were not.
if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) {
info.setClientMaster(true);
}
state = new ConnectionState(info);
context = new AMQConnectionContext();
state.reset(info);
// Setup the context.
String clientId = info.getClientId();
context.setBroker(protocolManager);
context.setClientId(clientId);
context.setClientMaster(info.isClientMaster());
context.setConnection(this);
context.setConnectionId(info.getConnectionId());
// for now we pass the manager as the connector and see what happens
// it should be related to activemq's Acceptor
context.setFaultTolerant(info.isFaultTolerant());
context.setUserName(info.getUserName());
context.setWireFormatInfo(wireFormatInfo);
context.setReconnect(info.isFailoverReconnect());
context.setConnectionState(state);
if (info.getClientIp() == null) {
info.setClientIp(getRemoteAddress());
}
createInternalSession(info);
return context;
}
private void createInternalSession(ConnectionInfo info) throws Exception {
internalSession = server.createSession(UUIDGenerator.getInstance().generateStringUUID(), context.getUserName(), info.getPassword(), -1, this, true, false, false, false, null, null, true, operationContext, protocolManager.getPrefixes());
}
//raise the refCount of context
public void reconnect(AMQConnectionContext existingContext, ConnectionInfo info) {
this.context = existingContext;
WireFormatInfo wireFormatInfo = inWireFormat.getPreferedWireFormatInfo();
// Older clients should have been defaulting this field to true.. but
// they were not.
if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) {
info.setClientMaster(true);
}
if (info.getClientIp() == null) {
info.setClientIp(getRemoteAddress());
}
state = new ConnectionState(info);
state.reset(info);
context.setConnection(this);
context.setConnectionState(state);
context.setClientMaster(info.isClientMaster());
context.setFaultTolerant(info.isFaultTolerant());
context.setReconnect(true);
context.incRefCount();
}
/**
* This will answer with commands to the client
*/
public boolean sendCommand(final Command command) {
if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) {
ActiveMQServerLogger.LOGGER.trace("sending " + command);
}
if (isDestroyed()) {
return false;
}
try {
physicalSend(command);
} catch (Exception e) {
return false;
} catch (Throwable t) {
return false;
}
return true;
}
public void addDestination(DestinationInfo info) throws Exception {
boolean created = false;
ActiveMQDestination dest = info.getDestination();
if (!protocolManager.isSupportAdvisory() && AdvisorySupport.isAdvisoryTopic(dest)) {
return;
}
SimpleString qName = SimpleString.toSimpleString(dest.getPhysicalName());
if (server.locateQueue(qName) == null) {
AddressSettings addressSettings = server.getAddressSettingsRepository().getMatch(dest.getPhysicalName());
AddressInfo addressInfo = new AddressInfo(qName, dest.isTopic() ? RoutingType.MULTICAST : RoutingType.ANYCAST);
if (AdvisorySupport.isAdvisoryTopic(dest) && protocolManager.isSuppressInternalManagementObjects()) {
addressInfo.setInternal(true);
}
if (dest.isQueue() && (addressSettings.isAutoCreateQueues() || dest.isTemporary())) {
try {
internalSession.createQueue(addressInfo, qName, null, dest.isTemporary(), !dest.isTemporary(), !dest.isTemporary());
created = true;
} catch (ActiveMQQueueExistsException exists) {
// The queue may have been created by another thread in the mean time. Catch and do nothing.
}
} else if (dest.isTopic() && (addressSettings.isAutoCreateAddresses() || dest.isTemporary())) {
try {
if (internalSession.getAddress(addressInfo.getName()) == null) {
internalSession.createAddress(addressInfo, !dest.isTemporary());
created = true;
}
} catch (ActiveMQAddressExistsException exists) {
// The address may have been created by another thread in the mean time. Catch and do nothing.
}
}
}
if (dest.isTemporary()) {
//Openwire needs to store the DestinationInfo in order to send
//Advisory messages to clients
this.state.addTempDestination(info);
}
if (created && !AdvisorySupport.isAdvisoryTopic(dest)) {
AMQConnectionContext context = getContext();
DestinationInfo advInfo = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, dest);
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(dest);
protocolManager.fireAdvisory(context, topic, advInfo);
}
}
public void updateConsumer(ConsumerControl consumerControl) {
ConsumerId consumerId = consumerControl.getConsumerId();
AMQConsumerBrokerExchange exchange = this.consumerExchanges.get(consumerId);
if (exchange != null) {
exchange.updateConsumerPrefetchSize(consumerControl.getPrefetch());
}
}
public void addConsumer(ConsumerInfo info) throws Exception {
// Todo: add a destination interceptors holder here (amq supports this)
SessionId sessionId = info.getConsumerId().getParentId();
ConnectionId connectionId = sessionId.getParentId();
ConnectionState cs = getState();
if (cs == null) {
throw new IllegalStateException("Cannot add a consumer to a connection that had not been registered: " + connectionId);
}
SessionState ss = cs.getSessionState(sessionId);
if (ss == null) {
throw new IllegalStateException(server + " Cannot add a consumer to a session that had not been registered: " + sessionId);
}
// Avoid replaying dup commands
if (!ss.getConsumerIds().contains(info.getConsumerId())) {
AMQSession amqSession = sessions.get(sessionId);
if (amqSession == null) {
throw new IllegalStateException("Session not exist! : " + sessionId);
}
List<AMQConsumer> consumersList = amqSession.createConsumer(info, new SlowConsumerDetection());
if (consumersList.size() == 0) {
return;
}
this.addConsumerBrokerExchange(info.getConsumerId(), amqSession, consumersList);
ss.addConsumer(info);
amqSession.start();
if (AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
//advisory for temp destinations
if (AdvisorySupport.isTempDestinationAdvisoryTopic(info.getDestination())) {
// Replay the temporary destinations.
List<DestinationInfo> tmpDests = this.protocolManager.getTemporaryDestinations();
for (DestinationInfo di : tmpDests) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(di.getDestination());
String originalConnectionId = di.getConnectionId().getValue();
protocolManager.fireAdvisory(context, topic, di, info.getConsumerId(), originalConnectionId);
}
}
}
}
}
public void setConnectionEntry(ConnectionEntry connectionEntry) {
this.connectionEntry = connectionEntry;
}
@Override
public boolean checkDataReceived() {
if (disableTtl.get()) {
return true;
}
return super.checkDataReceived();
}
public void setUpTtl(final long inactivityDuration,
final long inactivityDurationInitialDelay,
final boolean useKeepAlive) {
this.useKeepAlive = useKeepAlive;
this.maxInactivityDuration = inactivityDuration;
protocolManager.getScheduledPool().schedule(new Runnable() {
@Override
public void run() {
if (inactivityDuration >= 0) {
connectionEntry.ttl = inactivityDuration;
}
}
}, inactivityDurationInitialDelay, TimeUnit.MILLISECONDS);
checkInactivity();
}
public void addKnownDestination(final SimpleString address) {
knownDestinations.add(address);
}
public boolean containsKnownDestination(final SimpleString address) {
return knownDestinations.contains(address);
}
@Override
public void tempQueueDeleted(SimpleString bindingName) {
ActiveMQDestination dest = new ActiveMQTempQueue(bindingName.toString());
state.removeTempDestination(dest);
if (!AdvisorySupport.isAdvisoryTopic(dest)) {
AMQConnectionContext context = getContext();
DestinationInfo advInfo = new DestinationInfo(context.getConnectionId(), DestinationInfo.REMOVE_OPERATION_TYPE, dest);
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(dest);
try {
protocolManager.fireAdvisory(context, topic, advInfo);
} catch (Exception e) {
logger.warn("Failed to fire advisory on " + topic, e);
}
}
}
public void disableTtl() {
disableTtl.set(true);
}
public void enableTtl() {
disableTtl.set(false);
}
public boolean isNoLocal() {
return noLocal;
}
public void setNoLocal(boolean noLocal) {
this.noLocal = noLocal;
}
public List<DestinationInfo> getTemporaryDestinations() {
return state.getTempDestinations();
}
public boolean isSuppressInternalManagementObjects() {
return protocolManager.isSuppressInternalManagementObjects();
}
public boolean isSuppportAdvisory() {
return protocolManager.isSupportAdvisory();
}
class SlowConsumerDetection implements SlowConsumerDetectionListener {
@Override
public void onSlowConsumer(ServerConsumer consumer) {
if (consumer.getProtocolData() != null && consumer.getProtocolData() instanceof AMQConsumer) {
AMQConsumer amqConsumer = (AMQConsumer) consumer.getProtocolData();
ActiveMQTopic topic = AdvisorySupport.getSlowConsumerAdvisoryTopic(amqConsumer.getOpenwireDestination());
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
try {
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, amqConsumer.getId().toString());
protocolManager.fireAdvisory(context, topic, advisoryMessage, amqConsumer.getId(), null);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.warn("Error during method invocation", e);
}
}
}
}
public void addSessions(Set<SessionId> sessionSet) {
for (SessionId sid : sessionSet) {
addSession(getState().getSessionState(sid).getInfo(), true);
}
}
public AMQSession addSession(SessionInfo ss) {
return addSession(ss, false);
}
public AMQSession addSession(SessionInfo ss, boolean internal) {