-
Notifications
You must be signed in to change notification settings - Fork 914
/
ServerConsumerImpl.java
1551 lines (1233 loc) · 50.6 KB
/
ServerConsumerImpl.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.server.impl;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.management.CoreNotificationType;
import org.apache.activemq.artemis.api.core.management.ManagementHelper;
import org.apache.activemq.artemis.core.client.impl.ClientConsumerImpl;
import org.apache.activemq.artemis.core.filter.Filter;
import org.apache.activemq.artemis.core.message.LargeBodyReader;
import org.apache.activemq.artemis.core.message.impl.CoreMessage;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.QueueBinding;
import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
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.CoreLargeServerMessage;
import org.apache.activemq.artemis.core.server.HandleStatus;
import org.apache.activemq.artemis.core.server.LargeServerMessage;
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.management.ManagementService;
import org.apache.activemq.artemis.core.server.management.Notification;
import org.apache.activemq.artemis.core.transaction.Transaction;
import org.apache.activemq.artemis.core.transaction.impl.TransactionImpl;
import org.apache.activemq.artemis.logs.AuditLogger;
import org.apache.activemq.artemis.spi.core.protocol.SessionCallback;
import org.apache.activemq.artemis.spi.core.remoting.ReadyListener;
import org.apache.activemq.artemis.utils.FutureLatch;
import org.apache.activemq.artemis.utils.ReusableLatch;
import org.apache.activemq.artemis.utils.collections.LinkedListIterator;
import org.apache.activemq.artemis.utils.collections.TypedProperties;
import org.jboss.logging.Logger;
/**
* Concrete implementation of a ClientConsumer.
*/
public class ServerConsumerImpl implements ServerConsumer, ReadyListener {
// Constants ------------------------------------------------------------------------------------
private static final Logger logger = Logger.getLogger(ServerConsumerImpl.class);
// Static ---------------------------------------------------------------------------------------
// Attributes -----------------------------------------------------------------------------------
private final long id;
private final long sequentialID;
protected final Queue messageQueue;
private final Filter filter;
private final int priority;
private final int minLargeMessageSize;
private final ServerSession session;
protected final Object lock = new Object();
private final boolean supportLargeMessage;
private Object protocolData;
private Object protocolContext;
private final ActiveMQServer server;
private SlowConsumerDetectionListener slowConsumerListener;
private final ReusableLatch pendingDelivery = new ReusableLatch(0);
private volatile AtomicInteger availableCredits = new AtomicInteger(0);
private boolean started;
private volatile CoreLargeMessageDeliverer largeMessageDeliverer = null;
@Override
public String debug() {
String debug = toString() + "::Delivering ";
synchronized (lock) {
return debug + this.deliveringRefs.size();
}
}
/**
* if we are a browse only consumer we don't need to worry about acknowledgements or being
* started/stopped by the session.
*/
private final boolean browseOnly;
protected BrowserDeliverer browserDeliverer;
private final boolean strictUpdateDeliveryCount;
private final StorageManager storageManager;
private final java.util.Deque<MessageReference> deliveringRefs = new ArrayDeque<>();
private final SessionCallback callback;
private boolean preAcknowledge;
private final ManagementService managementService;
private final Binding binding;
private boolean transferring = false;
private final long creationTime;
private AtomicLong consumerRateCheckTime = new AtomicLong(System.currentTimeMillis());
private AtomicLong messageConsumedSnapshot = new AtomicLong(0);
private long acks;
private boolean requiresLegacyPrefix = false;
private boolean anycast = false;
private boolean isClosed = false;
// Constructors ---------------------------------------------------------------------------------
public ServerConsumerImpl(final long id,
final ServerSession session,
final QueueBinding binding,
final Filter filter,
final boolean started,
final boolean browseOnly,
final StorageManager storageManager,
final SessionCallback callback,
final boolean preAcknowledge,
final boolean strictUpdateDeliveryCount,
final ManagementService managementService,
final ActiveMQServer server) throws Exception {
this(id, session, binding, filter, started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, true, null, server);
}
public ServerConsumerImpl(final long id,
final ServerSession session,
final QueueBinding binding,
final Filter filter,
final boolean started,
final boolean browseOnly,
final StorageManager storageManager,
final SessionCallback callback,
final boolean preAcknowledge,
final boolean strictUpdateDeliveryCount,
final ManagementService managementService,
final boolean supportLargeMessage,
final Integer credits,
final ActiveMQServer server) throws Exception {
this(id, session, binding, filter, ActiveMQDefaultConfiguration.getDefaultConsumerPriority(), started, browseOnly, storageManager, callback, preAcknowledge, strictUpdateDeliveryCount, managementService, supportLargeMessage, credits, server);
}
public ServerConsumerImpl(final long id,
final ServerSession session,
final QueueBinding binding,
final Filter filter,
final int priority,
final boolean started,
final boolean browseOnly,
final StorageManager storageManager,
final SessionCallback callback,
final boolean preAcknowledge,
final boolean strictUpdateDeliveryCount,
final ManagementService managementService,
final boolean supportLargeMessage,
final Integer credits,
final ActiveMQServer server) throws Exception {
this.id = id;
this.sequentialID = server.getStorageManager().generateID();
this.filter = filter;
this.priority = priority;
this.session = session;
this.binding = binding;
messageQueue = binding.getQueue();
this.started = browseOnly || started;
this.browseOnly = browseOnly;
this.storageManager = storageManager;
this.callback = callback;
this.preAcknowledge = preAcknowledge;
this.managementService = managementService;
minLargeMessageSize = session.getMinLargeMessageSize();
this.strictUpdateDeliveryCount = strictUpdateDeliveryCount;
this.creationTime = System.currentTimeMillis();
this.supportLargeMessage = supportLargeMessage;
if (credits != null) {
if (credits == -1) {
availableCredits = null;
} else {
availableCredits.set(credits);
}
}
this.server = server;
if (browseOnly) {
browserDeliverer = new BrowserDeliverer(messageQueue.browserIterator());
} else {
messageQueue.addConsumer(this);
}
if (session.getRemotingConnection() instanceof CoreRemotingConnection) {
CoreRemotingConnection coreRemotingConnection = (CoreRemotingConnection) session.getRemotingConnection();
if (session.getMetaData(ClientSession.JMS_SESSION_IDENTIFIER_PROPERTY) != null && coreRemotingConnection.getChannelVersion() < PacketImpl.ADDRESSING_CHANGE_VERSION) {
requiresLegacyPrefix = true;
if (getQueue().getRoutingType().equals(RoutingType.ANYCAST)) {
anycast = true;
}
}
}
}
@Override
public void readyForWriting() {
promptDelivery();
}
// ServerConsumer implementation
// ----------------------------------------------------------------------
@Override
public boolean allowReferenceCallback() {
if (browseOnly) {
return false;
} else {
return messageQueue.allowsReferenceCallback();
}
}
@Override
public long sequentialID() {
return sequentialID;
}
@Override
public Object getProtocolData() {
return protocolData;
}
@Override
public void setProtocolData(Object protocolData) {
this.protocolData = protocolData;
}
@Override
public void setlowConsumerDetection(SlowConsumerDetectionListener listener) {
this.slowConsumerListener = listener;
}
@Override
public SlowConsumerDetectionListener getSlowConsumerDetecion() {
return slowConsumerListener;
}
@Override
public void fireSlowConsumer() {
if (slowConsumerListener != null) {
slowConsumerListener.onSlowConsumer(this);
}
}
@Override
public Object getProtocolContext() {
return protocolContext;
}
@Override
public void setProtocolContext(Object protocolContext) {
this.protocolContext = protocolContext;
}
@Override
public long getID() {
return id;
}
@Override
public boolean isBrowseOnly() {
return browseOnly;
}
@Override
public long getCreationTime() {
return creationTime;
}
@Override
public String getConnectionID() {
return this.session.getConnectionID().toString();
}
@Override
public String getSessionID() {
return this.session.getName();
}
@Override
public List<MessageReference> getDeliveringMessages() {
synchronized (lock) {
int expectedSize = 0;
List<MessageReference> refsOnConsumer = session.getInTXMessagesForConsumer(this.id);
if (refsOnConsumer != null) {
expectedSize = refsOnConsumer.size();
}
expectedSize += deliveringRefs.size();
final List<MessageReference> refs = new ArrayList<>(expectedSize);
if (refsOnConsumer != null) {
refs.addAll(refsOnConsumer);
}
refs.addAll(deliveringRefs);
return refs;
}
}
/** i
*
* @see SessionCallback#supportsDirectDelivery()
*/
@Override
public boolean supportsDirectDelivery() {
return callback.supportsDirectDelivery();
}
@Override
public void errorProcessing(Throwable e, MessageReference deliveryObject) {
messageQueue.errorProcessing(this, e, deliveryObject);
}
@Override
public HandleStatus handle(final MessageReference ref) throws Exception {
// available credits can be set back to null with a flow control option.
AtomicInteger checkInteger = availableCredits;
if (callback != null && !callback.hasCredits(this) || checkInteger != null && checkInteger.get() <= 0) {
if (logger.isDebugEnabled()) {
logger.debug(this + " is busy for the lack of credits. Current credits = " +
availableCredits +
" Can't receive reference " +
ref);
}
return HandleStatus.BUSY;
}
if (server.hasBrokerMessagePlugins() && !server.callBrokerMessagePluginsCanAccept(this, ref)) {
if (logger.isTraceEnabled()) {
logger.trace("Reference " + ref + " is not allowed to be consumed by " + this + " due to message plugin filter.");
}
return HandleStatus.NO_MATCH;
}
synchronized (lock) {
// If the consumer is stopped then we don't accept the message, it
// should go back into the
// queue for delivery later.
// TCP-flow control has to be done first than everything else otherwise we may lose notifications
if ((callback != null && !callback.isWritable(this, protocolContext)) || !started || transferring) {
return HandleStatus.BUSY;
}
// If there is a pendingLargeMessage we can't take another message
// This has to be checked inside the lock as the set to null is done inside the lock
if (largeMessageDeliverer != null) {
if (logger.isDebugEnabled()) {
logger.debug(this + " is busy delivering large message " +
largeMessageDeliverer +
", can't deliver reference " +
ref);
}
return HandleStatus.BUSY;
}
final Message message = ref.getMessage();
if (!message.acceptsConsumer(sequentialID())) {
return HandleStatus.NO_MATCH;
}
if (filter != null && !filter.match(message)) {
if (logger.isTraceEnabled()) {
logger.trace("Reference " + ref + " is a noMatch on consumer " + this);
}
return HandleStatus.NO_MATCH;
}
if (logger.isTraceEnabled()) {
logger.trace("ServerConsumerImpl::" + this + " Handling reference " + ref);
}
if (!browseOnly) {
if (!preAcknowledge) {
deliveringRefs.add(ref);
}
ref.handled();
ref.setConsumerId(this.id);
ref.incrementDeliveryCount();
// If updateDeliveries = false (set by strict-update),
// the updateDeliveryCountAfterCancel would still be updated after c
if (strictUpdateDeliveryCount && !ref.isPaged()) {
if (ref.getMessage().isDurable() && ref.getQueue().isDurable() &&
!ref.getQueue().isInternalQueue() &&
!ref.isPaged()) {
storageManager.updateDeliveryCount(ref);
}
}
// The deliverer will increase the usageUp, so the preAck has to be done after this is created
// otherwise we may have a removed message early on
if (message instanceof CoreLargeServerMessage && this.supportLargeMessage) {
largeMessageDeliverer = new CoreLargeMessageDeliverer((LargeServerMessage) message, ref);
}
if (preAcknowledge) {
// With pre-ack, we ack *before* sending to the client
ref.getQueue().acknowledge(ref, this);
acks++;
}
}
pendingDelivery.countUp();
return HandleStatus.HANDLED;
}
}
@Override
public void proceedDeliver(MessageReference reference) throws Exception {
try {
Message message = reference.getMessage();
if (AuditLogger.isMessageEnabled()) {
AuditLogger.coreConsumeMessage(session.getRemotingConnection().getAuditSubject(), getQueueName().toString());
}
if (server.hasBrokerMessagePlugins()) {
server.callBrokerMessagePlugins(plugin -> plugin.beforeDeliver(this, reference));
}
if (message instanceof CoreLargeServerMessage && supportLargeMessage) {
if (largeMessageDeliverer == null) {
// This can't really happen as handle had already crated the deliverer
// instead of throwing an exception in weird cases there is no problem on just go ahead and create it
// again here
largeMessageDeliverer = new CoreLargeMessageDeliverer((LargeServerMessage) message, reference);
}
// The deliverer was prepared during handle, as we can't have more than one pending large message
// as it would return busy if there is anything pending
largeMessageDeliverer.deliver();
} else {
deliverStandardMessage(reference, message);
}
} finally {
pendingDelivery.countDown();
callback.afterDelivery();
if (server.hasBrokerMessagePlugins()) {
server.callBrokerMessagePlugins(plugin -> plugin.afterDeliver(this, reference));
}
}
}
@Override
public Filter getFilter() {
return filter;
}
@Override
public int getPriority() {
return priority;
}
@Override
public SimpleString getFilterString() {
return filter == null ? null : filter.getFilterString();
}
@Override
public void close(final boolean failed) throws Exception {
close(failed, false);
}
@Override
public synchronized void close(final boolean failed, boolean sorted) throws Exception {
// Close should only ever be done once per consumer.
if (isClosed) return;
isClosed = true;
if (logger.isTraceEnabled()) {
logger.trace("ServerConsumerImpl::" + this + " being closed with failed=" + failed, new Exception("trace"));
}
if (server.hasBrokerConsumerPlugins()) {
server.callBrokerConsumerPlugins(plugin -> plugin.beforeCloseConsumer(this, failed));
}
setStarted(false);
CoreLargeMessageDeliverer del = largeMessageDeliverer;
if (del != null) {
del.finish();
}
removeItself();
List<MessageReference> refs = cancelRefs(failed, false, null);
Transaction tx = new TransactionImpl(storageManager, sorted);
refs.forEach(ref -> {
if (logger.isTraceEnabled()) {
logger.trace("ServerConsumerImpl::" + this + " cancelling reference " + ref);
}
ref.getQueue().cancel(tx, ref, true);
});
tx.rollback();
addLingerRefs();
if (!browseOnly) {
TypedProperties props = new TypedProperties();
props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress());
props.putSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME, binding.getClusterName());
props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, binding.getRoutingName());
props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filter == null ? null : filter.getFilterString());
props.putIntProperty(ManagementHelper.HDR_DISTANCE, binding.getDistance());
props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, messageQueue.getConsumerCount());
// HORNETQ-946
props.putSimpleStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(session.getUsername()));
props.putSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS, SimpleString.toSimpleString(((ServerSessionImpl) session).getRemotingConnection().getRemoteAddress()));
props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME, SimpleString.toSimpleString(session.getName()));
Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CLOSED, props);
managementService.sendNotification(notification);
}
// The check here has to be done after the notification is sent, otherwise the queue will be removed before the consumer.close reach other nodes on a cluster
messageQueue.recheckRefCount(session.getSessionContext());
if (server.hasBrokerConsumerPlugins()) {
server.callBrokerConsumerPlugins(plugin -> plugin.afterCloseConsumer(this, failed));
}
}
private void addLingerRefs() throws Exception {
if (!browseOnly) {
List<MessageReference> lingerRefs = session.getInTXMessagesForConsumer(this.id);
if (lingerRefs != null && !lingerRefs.isEmpty()) {
session.addLingerConsumer(this);
}
}
}
@Override
public void removeItself() throws Exception {
if (browseOnly) {
browserDeliverer.close();
} else {
messageQueue.removeConsumer(this);
}
session.removeConsumer(id);
}
/**
* Prompt delivery and send a "forced delivery" message to the consumer.
* <p>
* When the consumer receives such a "forced delivery" message, it discards it and knows that
* there are no other messages to be delivered.
*/
@Override
public void forceDelivery(final long sequence) {
forceDelivery(sequence, () -> {
Message forcedDeliveryMessage = new CoreMessage(storageManager.generateID(), 50);
MessageReference reference = MessageReference.Factory.createReference(forcedDeliveryMessage, messageQueue, null);
reference.setDeliveryCount(0);
forcedDeliveryMessage.putLongProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE, sequence);
forcedDeliveryMessage.setAddress(messageQueue.getName());
applyPrefixForLegacyConsumer(forcedDeliveryMessage);
callback.sendMessage(reference, forcedDeliveryMessage, ServerConsumerImpl.this, 0);
});
}
public synchronized void forceDelivery(final long sequence, final Runnable r) {
promptDelivery();
// JBPAPP-6030 - Using the executor to avoid distributed dead locks
messageQueue.getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
// We execute this on the same executor to make sure the force delivery message is written after
// any delivery is completed
synchronized (lock) {
if (transferring) {
// Case it's transferring (reattach), we will retry later
messageQueue.getExecutor().execute(new Runnable() {
@Override
public void run() {
forceDelivery(sequence, r);
}
});
return;
}
}
r.run();
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorSendingForcedDelivery(e);
}
}
});
}
@Override
public List<MessageReference> cancelRefs(final boolean failed,
final boolean lastConsumedAsDelivered,
final Transaction tx) throws Exception {
boolean performACK = lastConsumedAsDelivered;
try {
CoreLargeMessageDeliverer pendingLargeMessageDeliverer = largeMessageDeliverer;
if (pendingLargeMessageDeliverer != null) {
pendingLargeMessageDeliverer.finish();
}
} catch (Throwable e) {
ActiveMQServerLogger.LOGGER.errorResttingLargeMessage(e, largeMessageDeliverer);
} finally {
largeMessageDeliverer = null;
}
synchronized (lock) {
if (deliveringRefs.isEmpty()) {
return Collections.emptyList();
}
final List<MessageReference> refs = new ArrayList<>(deliveringRefs.size());
MessageReference ref;
while ((ref = deliveringRefs.poll()) != null) {
if (performACK) {
ref.acknowledge(tx, this);
performACK = false;
} else {
refs.add(ref);
updateDeliveryCountForCanceledRef(ref, failed);
}
if (logger.isTraceEnabled()) {
logger.trace("ServerConsumerImpl::" + this + " Preparing Cancelling list for messageID = " + ref.getMessage().getMessageID() + ", ref = " + ref);
}
}
return refs;
}
}
protected void updateDeliveryCountForCanceledRef(MessageReference ref, boolean failed) {
// We first update the deliveryCount at the protocol callback...
// if that wasn't updated (if there is no specific logic, then we apply the default logic used on most protocols
if (!callback.updateDeliveryCountAfterCancel(this, ref, failed)) {
if (!failed) {
// We don't decrement delivery count if the client failed, since there's a possibility that refs
// were actually delivered but we just didn't get any acks for them
// before failure
ref.decrementDeliveryCount();
}
}
}
@Override
public void setStarted(final boolean started) {
synchronized (lock) {
this.started = browseOnly || started;
}
// Outside the lock
if (started) {
promptDelivery();
} else {
flushDelivery();
}
}
private boolean flushDelivery() {
try {
if (!pendingDelivery.await(30, TimeUnit.SECONDS)) {
ActiveMQServerLogger.LOGGER.timeoutLockingConsumer(this.toString(), session.getRemotingConnection().getTransportConnection().getRemoteAddress());
if (server != null) {
server.threadDump();
}
return false;
}
return true;
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.failedToFinishDelivery(e);
return false;
}
}
@Override
public void setTransferring(final boolean transferring) {
synchronized (lock) {
this.transferring = transferring;
}
// Outside the lock
if (transferring) {
// And we must wait for any force delivery to be executed - this is executed async so we add a future to the
// executor and
// wait for it to complete
FutureLatch future = new FutureLatch();
messageQueue.getExecutor().execute(future);
boolean ok = future.await(10000);
if (!ok) {
ActiveMQServerLogger.LOGGER.errorTransferringConsumer();
}
}
if (!transferring) {
promptDelivery();
} else {
flushDelivery();
}
}
@Override
public void receiveCredits(final int credits) {
if (credits == -1) {
if (logger.isDebugEnabled()) {
logger.debug(this + ":: FlowControl::Received disable flow control message");
}
// No flow control
availableCredits = null;
// There may be messages already in the queue
promptDelivery();
} else if (credits == 0) {
// reset, used on slow consumers
logger.debug(this + ":: FlowControl::Received reset flow control message");
availableCredits.set(0);
} else {
int previous = availableCredits.getAndAdd(credits);
if (logger.isDebugEnabled()) {
logger.debug(this + "::FlowControl::Received " +
credits +
" credits, previous value = " +
previous +
" currentValue = " +
availableCredits.get());
}
if (previous <= 0 && previous + credits > 0) {
if (logger.isTraceEnabled()) {
logger.trace(this + "::calling promptDelivery from receiving credits");
}
promptDelivery();
}
}
}
@Override
public Queue getQueue() {
return messageQueue;
}
/**
* Remove references based on the protocolData.
* there will be an interval defined between protocolDataStart and protocolDataEnd.
* This method will fetch the delivering references, remove them from the delivering list and return a list.
*
* This will be useful for other protocols that will need this such as openWire or MQTT.
*/
@Override
public synchronized List<MessageReference> scanDeliveringReferences(boolean remove,
Function<MessageReference, Boolean> startFunction,
Function<MessageReference, Boolean> endFunction) {
LinkedList<MessageReference> retReferences = new LinkedList<>();
boolean hit = false;
synchronized (lock) {
Iterator<MessageReference> referenceIterator = deliveringRefs.iterator();
while (referenceIterator.hasNext()) {
MessageReference reference = referenceIterator.next();
if (!hit && startFunction.apply(reference)) {
hit = true;
}
if (hit) {
if (remove) {
referenceIterator.remove();
}
retReferences.add(reference);
if (endFunction.apply(reference)) {
break;
}
}
}
}
return retReferences;
}
@Override
public synchronized List<Long> acknowledge(Transaction tx, final long messageID) throws Exception {
if (browseOnly) {
return null;
}
List<Long> ackedRefs = null;
// Acknowledge acknowledges all refs delivered by the consumer up to and including the one explicitly
// acknowledged
// We use a transaction here as if the message is not found, we should rollback anything done
// This could eventually happen on retries during transactions, and we need to make sure we don't ACK things we are not supposed to acknowledge
boolean startedTransaction = false;
if (tx == null) {
startedTransaction = true;
tx = new TransactionImpl(storageManager);
}
try {
MessageReference ref;
ackedRefs = new ArrayList<>();
do {
synchronized (lock) {
ref = deliveringRefs.poll();
}
if (logger.isTraceEnabled()) {
logger.trace("ACKing ref " + ref + " on tx= " + tx + ", consumer=" + this);
}
if (ref == null) {
ActiveMQIllegalStateException ils = ActiveMQMessageBundle.BUNDLE.consumerNoReference(id, messageID, messageQueue.getName());
tx.markAsRollbackOnly(ils);
throw ils;
}
ref.acknowledge(tx, this);
ackedRefs.add(ref.getMessageID());
acks++;
}
while (ref.getMessageID() != messageID);
if (startedTransaction) {
tx.commit();
}
} catch (ActiveMQException e) {
if (startedTransaction) {
tx.rollback();
} else {
tx.markAsRollbackOnly(e);
}
throw e;
} catch (Throwable e) {
ActiveMQServerLogger.LOGGER.errorAckingMessage((Exception) e);
ActiveMQException activeMQIllegalStateException = new ActiveMQIllegalStateException(e.getMessage());
if (startedTransaction) {
tx.rollback();
} else {
tx.markAsRollbackOnly(activeMQIllegalStateException);
}
throw activeMQIllegalStateException;
}
return ackedRefs;
}
@Override
public synchronized void individualAcknowledge(Transaction tx, final long messageID) throws Exception {
if (browseOnly) {
return;
}
boolean startedTransaction = false;
if (logger.isTraceEnabled()) {
logger.trace("individualACK messageID=" + messageID);
}
if (tx == null) {
if (logger.isTraceEnabled()) {
logger.trace("individualACK starting new TX");
}
startedTransaction = true;
tx = new TransactionImpl(storageManager);
}
try {
MessageReference ref;
ref = removeReferenceByID(messageID);
if (logger.isTraceEnabled()) {
logger.trace("ACKing ref " + ref + " on tx= " + tx + ", consumer=" + this);
}
if (ref == null) {
ActiveMQIllegalStateException ils = new ActiveMQIllegalStateException("Cannot find ref to ack " + messageID);
tx.markAsRollbackOnly(ils);
throw ils;
}
ref.acknowledge(tx, this);
acks++;