001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.activemq.broker.region; 018 019import java.io.IOException; 020import java.util.ArrayList; 021import java.util.Collection; 022import java.util.Collections; 023import java.util.Comparator; 024import java.util.HashSet; 025import java.util.Iterator; 026import java.util.LinkedHashMap; 027import java.util.LinkedHashSet; 028import java.util.LinkedList; 029import java.util.List; 030import java.util.Map; 031import java.util.Set; 032import java.util.concurrent.CancellationException; 033import java.util.concurrent.ConcurrentLinkedQueue; 034import java.util.concurrent.CountDownLatch; 035import java.util.concurrent.DelayQueue; 036import java.util.concurrent.Delayed; 037import java.util.concurrent.ExecutorService; 038import java.util.concurrent.TimeUnit; 039import java.util.concurrent.atomic.AtomicBoolean; 040import java.util.concurrent.atomic.AtomicInteger; 041import java.util.concurrent.atomic.AtomicLong; 042import java.util.concurrent.locks.Lock; 043import java.util.concurrent.locks.ReentrantLock; 044import java.util.concurrent.locks.ReentrantReadWriteLock; 045 046import javax.jms.InvalidSelectorException; 047import javax.jms.JMSException; 048import javax.jms.ResourceAllocationException; 049 050import org.apache.activemq.broker.BrokerService; 051import org.apache.activemq.broker.ConnectionContext; 052import org.apache.activemq.broker.ProducerBrokerExchange; 053import org.apache.activemq.broker.region.cursors.OrderedPendingList; 054import org.apache.activemq.broker.region.cursors.PendingList; 055import org.apache.activemq.broker.region.cursors.PendingMessageCursor; 056import org.apache.activemq.broker.region.cursors.PrioritizedPendingList; 057import org.apache.activemq.broker.region.cursors.QueueDispatchPendingList; 058import org.apache.activemq.broker.region.cursors.StoreQueueCursor; 059import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor; 060import org.apache.activemq.broker.region.group.CachedMessageGroupMapFactory; 061import org.apache.activemq.broker.region.group.MessageGroupMap; 062import org.apache.activemq.broker.region.group.MessageGroupMapFactory; 063import org.apache.activemq.broker.region.policy.DeadLetterStrategy; 064import org.apache.activemq.broker.region.policy.DispatchPolicy; 065import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy; 066import org.apache.activemq.broker.util.InsertionCountList; 067import org.apache.activemq.command.ActiveMQDestination; 068import org.apache.activemq.command.ConsumerId; 069import org.apache.activemq.command.ExceptionResponse; 070import org.apache.activemq.command.Message; 071import org.apache.activemq.command.MessageAck; 072import org.apache.activemq.command.MessageDispatchNotification; 073import org.apache.activemq.command.MessageId; 074import org.apache.activemq.command.ProducerAck; 075import org.apache.activemq.command.ProducerInfo; 076import org.apache.activemq.command.RemoveInfo; 077import org.apache.activemq.command.Response; 078import org.apache.activemq.filter.BooleanExpression; 079import org.apache.activemq.filter.MessageEvaluationContext; 080import org.apache.activemq.filter.NonCachedMessageEvaluationContext; 081import org.apache.activemq.selector.SelectorParser; 082import org.apache.activemq.state.ProducerState; 083import org.apache.activemq.store.IndexListener; 084import org.apache.activemq.store.ListenableFuture; 085import org.apache.activemq.store.MessageRecoveryListener; 086import org.apache.activemq.store.MessageStore; 087import org.apache.activemq.thread.Task; 088import org.apache.activemq.thread.TaskRunner; 089import org.apache.activemq.thread.TaskRunnerFactory; 090import org.apache.activemq.transaction.Synchronization; 091import org.apache.activemq.usage.Usage; 092import org.apache.activemq.usage.UsageListener; 093import org.apache.activemq.util.BrokerSupport; 094import org.apache.activemq.util.ThreadPoolUtils; 095import org.slf4j.Logger; 096import org.slf4j.LoggerFactory; 097import org.slf4j.MDC; 098 099import static org.apache.activemq.broker.region.cursors.AbstractStoreCursor.gotToTheStore; 100 101/** 102 * The Queue is a List of MessageEntry objects that are dispatched to matching 103 * subscriptions. 104 */ 105public class Queue extends BaseDestination implements Task, UsageListener, IndexListener { 106 protected static final Logger LOG = LoggerFactory.getLogger(Queue.class); 107 protected final TaskRunnerFactory taskFactory; 108 protected TaskRunner taskRunner; 109 private final ReentrantReadWriteLock consumersLock = new ReentrantReadWriteLock(); 110 protected final List<Subscription> consumers = new ArrayList<Subscription>(50); 111 private final ReentrantReadWriteLock messagesLock = new ReentrantReadWriteLock(); 112 protected PendingMessageCursor messages; 113 private final ReentrantReadWriteLock pagedInMessagesLock = new ReentrantReadWriteLock(); 114 private final PendingList pagedInMessages = new OrderedPendingList(); 115 // Messages that are paged in but have not yet been targeted at a subscription 116 private final ReentrantReadWriteLock pagedInPendingDispatchLock = new ReentrantReadWriteLock(); 117 protected QueueDispatchPendingList dispatchPendingList = new QueueDispatchPendingList(); 118 private AtomicInteger pendingSends = new AtomicInteger(0); 119 private MessageGroupMap messageGroupOwners; 120 private DispatchPolicy dispatchPolicy = new RoundRobinDispatchPolicy(); 121 private MessageGroupMapFactory messageGroupMapFactory = new CachedMessageGroupMapFactory(); 122 final Lock sendLock = new ReentrantLock(); 123 private ExecutorService executor; 124 private final Map<MessageId, Runnable> messagesWaitingForSpace = new LinkedHashMap<MessageId, Runnable>(); 125 private boolean useConsumerPriority = true; 126 private boolean strictOrderDispatch = false; 127 private final QueueDispatchSelector dispatchSelector; 128 private boolean optimizedDispatch = false; 129 private boolean iterationRunning = false; 130 private boolean firstConsumer = false; 131 private int timeBeforeDispatchStarts = 0; 132 private int consumersBeforeDispatchStarts = 0; 133 private CountDownLatch consumersBeforeStartsLatch; 134 private final AtomicLong pendingWakeups = new AtomicLong(); 135 private boolean allConsumersExclusiveByDefault = false; 136 private final AtomicBoolean started = new AtomicBoolean(); 137 138 private boolean resetNeeded; 139 140 private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() { 141 @Override 142 public void run() { 143 asyncWakeup(); 144 } 145 }; 146 private final Runnable expireMessagesTask = new Runnable() { 147 @Override 148 public void run() { 149 expireMessages(); 150 } 151 }; 152 153 private final Object iteratingMutex = new Object(); 154 155 // gate on enabling cursor cache to ensure no outstanding sync 156 // send before async sends resume 157 public boolean singlePendingSend() { 158 return pendingSends.get() <= 1; 159 } 160 161 class TimeoutMessage implements Delayed { 162 163 Message message; 164 ConnectionContext context; 165 long trigger; 166 167 public TimeoutMessage(Message message, ConnectionContext context, long delay) { 168 this.message = message; 169 this.context = context; 170 this.trigger = System.currentTimeMillis() + delay; 171 } 172 173 @Override 174 public long getDelay(TimeUnit unit) { 175 long n = trigger - System.currentTimeMillis(); 176 return unit.convert(n, TimeUnit.MILLISECONDS); 177 } 178 179 @Override 180 public int compareTo(Delayed delayed) { 181 long other = ((TimeoutMessage) delayed).trigger; 182 int returnValue; 183 if (this.trigger < other) { 184 returnValue = -1; 185 } else if (this.trigger > other) { 186 returnValue = 1; 187 } else { 188 returnValue = 0; 189 } 190 return returnValue; 191 } 192 } 193 194 DelayQueue<TimeoutMessage> flowControlTimeoutMessages = new DelayQueue<TimeoutMessage>(); 195 196 class FlowControlTimeoutTask extends Thread { 197 198 @Override 199 public void run() { 200 TimeoutMessage timeout; 201 try { 202 while (true) { 203 timeout = flowControlTimeoutMessages.take(); 204 if (timeout != null) { 205 synchronized (messagesWaitingForSpace) { 206 if (messagesWaitingForSpace.remove(timeout.message.getMessageId()) != null) { 207 ExceptionResponse response = new ExceptionResponse( 208 new ResourceAllocationException( 209 "Usage Manager Memory Limit reached. Stopping producer (" 210 + timeout.message.getProducerId() 211 + ") to prevent flooding " 212 + getActiveMQDestination().getQualifiedName() 213 + "." 214 + " See http://activemq.apache.org/producer-flow-control.html for more info")); 215 response.setCorrelationId(timeout.message.getCommandId()); 216 timeout.context.getConnection().dispatchAsync(response); 217 } 218 } 219 } 220 } 221 } catch (InterruptedException e) { 222 LOG.debug(getName() + "Producer Flow Control Timeout Task is stopping"); 223 } 224 } 225 }; 226 227 private final FlowControlTimeoutTask flowControlTimeoutTask = new FlowControlTimeoutTask(); 228 229 private final Comparator<Subscription> orderedCompare = new Comparator<Subscription>() { 230 231 @Override 232 public int compare(Subscription s1, Subscription s2) { 233 // We want the list sorted in descending order 234 int val = s2.getConsumerInfo().getPriority() - s1.getConsumerInfo().getPriority(); 235 if (val == 0 && messageGroupOwners != null) { 236 // then ascending order of assigned message groups to favour less loaded consumers 237 // Long.compare in jdk7 238 long x = s1.getConsumerInfo().getAssignedGroupCount(destination); 239 long y = s2.getConsumerInfo().getAssignedGroupCount(destination); 240 val = (x < y) ? -1 : ((x == y) ? 0 : 1); 241 } 242 return val; 243 } 244 }; 245 246 public Queue(BrokerService brokerService, final ActiveMQDestination destination, MessageStore store, 247 DestinationStatistics parentStats, TaskRunnerFactory taskFactory) throws Exception { 248 super(brokerService, store, destination, parentStats); 249 this.taskFactory = taskFactory; 250 this.dispatchSelector = new QueueDispatchSelector(destination); 251 if (store != null) { 252 store.registerIndexListener(this); 253 } 254 } 255 256 @Override 257 public List<Subscription> getConsumers() { 258 consumersLock.readLock().lock(); 259 try { 260 return new ArrayList<Subscription>(consumers); 261 } finally { 262 consumersLock.readLock().unlock(); 263 } 264 } 265 266 // make the queue easily visible in the debugger from its task runner 267 // threads 268 final class QueueThread extends Thread { 269 final Queue queue; 270 271 public QueueThread(Runnable runnable, String name, Queue queue) { 272 super(runnable, name); 273 this.queue = queue; 274 } 275 } 276 277 class BatchMessageRecoveryListener implements MessageRecoveryListener { 278 final LinkedList<Message> toExpire = new LinkedList<Message>(); 279 final double totalMessageCount; 280 int recoveredAccumulator = 0; 281 int currentBatchCount; 282 283 BatchMessageRecoveryListener(int totalMessageCount) { 284 this.totalMessageCount = totalMessageCount; 285 currentBatchCount = recoveredAccumulator; 286 } 287 288 @Override 289 public boolean recoverMessage(Message message) { 290 recoveredAccumulator++; 291 if ((recoveredAccumulator % 10000) == 0) { 292 LOG.info("cursor for {} has recovered {} messages. {}% complete", new Object[]{ getActiveMQDestination().getQualifiedName(), recoveredAccumulator, new Integer((int) (recoveredAccumulator * 100 / totalMessageCount))}); 293 } 294 // Message could have expired while it was being 295 // loaded.. 296 message.setRegionDestination(Queue.this); 297 if (message.isExpired() && broker.isExpired(message)) { 298 toExpire.add(message); 299 return true; 300 } 301 if (hasSpace()) { 302 messagesLock.writeLock().lock(); 303 try { 304 try { 305 messages.addMessageLast(message); 306 } catch (Exception e) { 307 LOG.error("Failed to add message to cursor", e); 308 } 309 } finally { 310 messagesLock.writeLock().unlock(); 311 } 312 destinationStatistics.getMessages().increment(); 313 return true; 314 } 315 return false; 316 } 317 318 @Override 319 public boolean recoverMessageReference(MessageId messageReference) throws Exception { 320 throw new RuntimeException("Should not be called."); 321 } 322 323 @Override 324 public boolean hasSpace() { 325 return true; 326 } 327 328 @Override 329 public boolean isDuplicate(MessageId id) { 330 return false; 331 } 332 333 public void reset() { 334 currentBatchCount = recoveredAccumulator; 335 } 336 337 public void processExpired() { 338 for (Message message: toExpire) { 339 messageExpired(createConnectionContext(), createMessageReference(message)); 340 // drop message will decrement so counter 341 // balance here 342 destinationStatistics.getMessages().increment(); 343 } 344 toExpire.clear(); 345 } 346 347 public boolean done() { 348 return currentBatchCount == recoveredAccumulator; 349 } 350 } 351 352 @Override 353 public void setPrioritizedMessages(boolean prioritizedMessages) { 354 super.setPrioritizedMessages(prioritizedMessages); 355 dispatchPendingList.setPrioritizedMessages(prioritizedMessages); 356 } 357 358 @Override 359 public void initialize() throws Exception { 360 361 if (this.messages == null) { 362 if (destination.isTemporary() || broker == null || store == null) { 363 this.messages = new VMPendingMessageCursor(isPrioritizedMessages()); 364 } else { 365 this.messages = new StoreQueueCursor(broker, this); 366 } 367 } 368 369 // If a VMPendingMessageCursor don't use the default Producer System 370 // Usage 371 // since it turns into a shared blocking queue which can lead to a 372 // network deadlock. 373 // If we are cursoring to disk..it's not and issue because it does not 374 // block due 375 // to large disk sizes. 376 if (messages instanceof VMPendingMessageCursor) { 377 this.systemUsage = brokerService.getSystemUsage(); 378 memoryUsage.setParent(systemUsage.getMemoryUsage()); 379 } 380 381 this.taskRunner = taskFactory.createTaskRunner(this, "Queue:" + destination.getPhysicalName()); 382 383 super.initialize(); 384 if (store != null) { 385 // Restore the persistent messages. 386 messages.setSystemUsage(systemUsage); 387 messages.setEnableAudit(isEnableAudit()); 388 messages.setMaxAuditDepth(getMaxAuditDepth()); 389 messages.setMaxProducersToAudit(getMaxProducersToAudit()); 390 messages.setUseCache(isUseCache()); 391 messages.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); 392 final int messageCount = store.getMessageCount(); 393 if (messageCount > 0 && messages.isRecoveryRequired()) { 394 BatchMessageRecoveryListener listener = new BatchMessageRecoveryListener(messageCount); 395 do { 396 listener.reset(); 397 store.recoverNextMessages(getMaxPageSize(), listener); 398 listener.processExpired(); 399 } while (!listener.done()); 400 } else { 401 destinationStatistics.getMessages().add(messageCount); 402 } 403 } 404 } 405 406 /* 407 * Holder for subscription that needs attention on next iterate browser 408 * needs access to existing messages in the queue that have already been 409 * dispatched 410 */ 411 class BrowserDispatch { 412 QueueBrowserSubscription browser; 413 414 public BrowserDispatch(QueueBrowserSubscription browserSubscription) { 415 browser = browserSubscription; 416 browser.incrementQueueRef(); 417 } 418 419 void done() { 420 try { 421 browser.decrementQueueRef(); 422 } catch (Exception e) { 423 LOG.warn("decrement ref on browser: " + browser, e); 424 } 425 } 426 427 public QueueBrowserSubscription getBrowser() { 428 return browser; 429 } 430 } 431 432 ConcurrentLinkedQueue<BrowserDispatch> browserDispatches = new ConcurrentLinkedQueue<BrowserDispatch>(); 433 434 @Override 435 public void addSubscription(ConnectionContext context, Subscription sub) throws Exception { 436 LOG.debug("{} add sub: {}, dequeues: {}, dispatched: {}, inflight: {}", new Object[]{ getActiveMQDestination().getQualifiedName(), sub, getDestinationStatistics().getDequeues().getCount(), getDestinationStatistics().getDispatched().getCount(), getDestinationStatistics().getInflight().getCount() }); 437 438 super.addSubscription(context, sub); 439 // synchronize with dispatch method so that no new messages are sent 440 // while setting up a subscription. avoid out of order messages, 441 // duplicates, etc. 442 pagedInPendingDispatchLock.writeLock().lock(); 443 try { 444 445 sub.add(context, this); 446 447 // needs to be synchronized - so no contention with dispatching 448 // consumersLock. 449 consumersLock.writeLock().lock(); 450 try { 451 // set a flag if this is a first consumer 452 if (consumers.size() == 0) { 453 firstConsumer = true; 454 if (consumersBeforeDispatchStarts != 0) { 455 consumersBeforeStartsLatch = new CountDownLatch(consumersBeforeDispatchStarts - 1); 456 } 457 } else { 458 if (consumersBeforeStartsLatch != null) { 459 consumersBeforeStartsLatch.countDown(); 460 } 461 } 462 463 addToConsumerList(sub); 464 if (sub.getConsumerInfo().isExclusive() || isAllConsumersExclusiveByDefault()) { 465 Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer(); 466 if (exclusiveConsumer == null) { 467 exclusiveConsumer = sub; 468 } else if (sub.getConsumerInfo().getPriority() == Byte.MAX_VALUE || 469 sub.getConsumerInfo().getPriority() > exclusiveConsumer.getConsumerInfo().getPriority()) { 470 exclusiveConsumer = sub; 471 } 472 dispatchSelector.setExclusiveConsumer(exclusiveConsumer); 473 } 474 } finally { 475 consumersLock.writeLock().unlock(); 476 } 477 478 if (sub instanceof QueueBrowserSubscription) { 479 // tee up for dispatch in next iterate 480 QueueBrowserSubscription browserSubscription = (QueueBrowserSubscription) sub; 481 BrowserDispatch browserDispatch = new BrowserDispatch(browserSubscription); 482 browserDispatches.add(browserDispatch); 483 } 484 485 if (!this.optimizedDispatch) { 486 wakeup(); 487 } 488 } finally { 489 pagedInPendingDispatchLock.writeLock().unlock(); 490 } 491 if (this.optimizedDispatch) { 492 // Outside of dispatchLock() to maintain the lock hierarchy of 493 // iteratingMutex -> dispatchLock. - see 494 // https://issues.apache.org/activemq/browse/AMQ-1878 495 wakeup(); 496 } 497 } 498 499 @Override 500 public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId) 501 throws Exception { 502 super.removeSubscription(context, sub, lastDeliveredSequenceId); 503 // synchronize with dispatch method so that no new messages are sent 504 // while removing up a subscription. 505 pagedInPendingDispatchLock.writeLock().lock(); 506 try { 507 LOG.debug("{} remove sub: {}, lastDeliveredSeqId: {}, dequeues: {}, dispatched: {}, inflight: {}, groups: {}", new Object[]{ 508 getActiveMQDestination().getQualifiedName(), 509 sub, 510 lastDeliveredSequenceId, 511 getDestinationStatistics().getDequeues().getCount(), 512 getDestinationStatistics().getDispatched().getCount(), 513 getDestinationStatistics().getInflight().getCount(), 514 sub.getConsumerInfo().getAssignedGroupCount(destination) 515 }); 516 consumersLock.writeLock().lock(); 517 try { 518 removeFromConsumerList(sub); 519 if (sub.getConsumerInfo().isExclusive()) { 520 Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer(); 521 if (exclusiveConsumer == sub) { 522 exclusiveConsumer = null; 523 for (Subscription s : consumers) { 524 if (s.getConsumerInfo().isExclusive() 525 && (exclusiveConsumer == null || s.getConsumerInfo().getPriority() > exclusiveConsumer 526 .getConsumerInfo().getPriority())) { 527 exclusiveConsumer = s; 528 529 } 530 } 531 dispatchSelector.setExclusiveConsumer(exclusiveConsumer); 532 } 533 } else if (isAllConsumersExclusiveByDefault()) { 534 Subscription exclusiveConsumer = null; 535 for (Subscription s : consumers) { 536 if (exclusiveConsumer == null 537 || s.getConsumerInfo().getPriority() > exclusiveConsumer 538 .getConsumerInfo().getPriority()) { 539 exclusiveConsumer = s; 540 } 541 } 542 dispatchSelector.setExclusiveConsumer(exclusiveConsumer); 543 } 544 ConsumerId consumerId = sub.getConsumerInfo().getConsumerId(); 545 getMessageGroupOwners().removeConsumer(consumerId); 546 547 // redeliver inflight messages 548 549 boolean markAsRedelivered = false; 550 MessageReference lastDeliveredRef = null; 551 List<MessageReference> unAckedMessages = sub.remove(context, this); 552 553 // locate last redelivered in unconsumed list (list in delivery rather than seq order) 554 if (lastDeliveredSequenceId > RemoveInfo.LAST_DELIVERED_UNSET) { 555 for (MessageReference ref : unAckedMessages) { 556 if (ref.getMessageId().getBrokerSequenceId() == lastDeliveredSequenceId) { 557 lastDeliveredRef = ref; 558 markAsRedelivered = true; 559 LOG.debug("found lastDeliveredSeqID: {}, message reference: {}", lastDeliveredSequenceId, ref.getMessageId()); 560 break; 561 } 562 } 563 } 564 565 for (Iterator<MessageReference> unackedListIterator = unAckedMessages.iterator(); unackedListIterator.hasNext(); ) { 566 MessageReference ref = unackedListIterator.next(); 567 // AMQ-5107: don't resend if the broker is shutting down 568 if ( this.brokerService.isStopping() ) { 569 break; 570 } 571 QueueMessageReference qmr = (QueueMessageReference) ref; 572 if (qmr.getLockOwner() == sub) { 573 qmr.unlock(); 574 575 // have no delivery information 576 if (lastDeliveredSequenceId == RemoveInfo.LAST_DELIVERED_UNKNOWN) { 577 qmr.incrementRedeliveryCounter(); 578 } else { 579 if (markAsRedelivered) { 580 qmr.incrementRedeliveryCounter(); 581 } 582 if (ref == lastDeliveredRef) { 583 // all that follow were not redelivered 584 markAsRedelivered = false; 585 } 586 } 587 } 588 if (qmr.isDropped()) { 589 unackedListIterator.remove(); 590 } 591 } 592 dispatchPendingList.addForRedelivery(unAckedMessages, strictOrderDispatch && consumers.isEmpty()); 593 if (sub instanceof QueueBrowserSubscription) { 594 ((QueueBrowserSubscription)sub).decrementQueueRef(); 595 browserDispatches.remove(sub); 596 } 597 // AMQ-5107: don't resend if the broker is shutting down 598 if (dispatchPendingList.hasRedeliveries() && (! this.brokerService.isStopping())) { 599 doDispatch(new OrderedPendingList()); 600 } 601 } finally { 602 consumersLock.writeLock().unlock(); 603 } 604 if (!this.optimizedDispatch) { 605 wakeup(); 606 } 607 } finally { 608 pagedInPendingDispatchLock.writeLock().unlock(); 609 } 610 if (this.optimizedDispatch) { 611 // Outside of dispatchLock() to maintain the lock hierarchy of 612 // iteratingMutex -> dispatchLock. - see 613 // https://issues.apache.org/activemq/browse/AMQ-1878 614 wakeup(); 615 } 616 } 617 618 @Override 619 public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { 620 final ConnectionContext context = producerExchange.getConnectionContext(); 621 // There is delay between the client sending it and it arriving at the 622 // destination.. it may have expired. 623 message.setRegionDestination(this); 624 ProducerState state = producerExchange.getProducerState(); 625 if (state == null) { 626 LOG.warn("Send failed for: {}, missing producer state for: {}", message, producerExchange); 627 throw new JMSException("Cannot send message to " + getActiveMQDestination() + " with invalid (null) producer state"); 628 } 629 final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); 630 final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 631 && !context.isInRecoveryMode(); 632 if (message.isExpired()) { 633 // message not stored - or added to stats yet - so chuck here 634 broker.getRoot().messageExpired(context, message, null); 635 if (sendProducerAck) { 636 ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); 637 context.getConnection().dispatchAsync(ack); 638 } 639 return; 640 } 641 if (memoryUsage.isFull()) { 642 isFull(context, memoryUsage); 643 fastProducer(context, producerInfo); 644 if (isProducerFlowControl() && context.isProducerFlowControl()) { 645 if (isFlowControlLogRequired()) { 646 LOG.info("Usage Manager Memory Limit ({}) reached on {}, size {}. Producers will be throttled to the rate at which messages are removed from this destination to prevent flooding it. See http://activemq.apache.org/producer-flow-control.html for more info.", 647 memoryUsage.getLimit(), getActiveMQDestination().getQualifiedName(), destinationStatistics.getMessages().getCount()); 648 649 } 650 if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) { 651 throw new ResourceAllocationException("Usage Manager Memory Limit reached. Stopping producer (" 652 + message.getProducerId() + ") to prevent flooding " 653 + getActiveMQDestination().getQualifiedName() + "." 654 + " See http://activemq.apache.org/producer-flow-control.html for more info"); 655 } 656 657 // We can avoid blocking due to low usage if the producer is 658 // sending 659 // a sync message or if it is using a producer window 660 if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) { 661 // copy the exchange state since the context will be 662 // modified while we are waiting 663 // for space. 664 final ProducerBrokerExchange producerExchangeCopy = producerExchange.copy(); 665 synchronized (messagesWaitingForSpace) { 666 // Start flow control timeout task 667 // Prevent trying to start it multiple times 668 if (!flowControlTimeoutTask.isAlive()) { 669 flowControlTimeoutTask.setName(getName()+" Producer Flow Control Timeout Task"); 670 flowControlTimeoutTask.start(); 671 } 672 messagesWaitingForSpace.put(message.getMessageId(), new Runnable() { 673 @Override 674 public void run() { 675 676 try { 677 // While waiting for space to free up... the 678 // message may have expired. 679 if (message.isExpired()) { 680 LOG.error("expired waiting for space.."); 681 broker.messageExpired(context, message, null); 682 destinationStatistics.getExpired().increment(); 683 } else { 684 doMessageSend(producerExchangeCopy, message); 685 } 686 687 if (sendProducerAck) { 688 ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message 689 .getSize()); 690 context.getConnection().dispatchAsync(ack); 691 } else { 692 Response response = new Response(); 693 response.setCorrelationId(message.getCommandId()); 694 context.getConnection().dispatchAsync(response); 695 } 696 697 } catch (Exception e) { 698 if (!sendProducerAck && !context.isInRecoveryMode() && !brokerService.isStopping()) { 699 ExceptionResponse response = new ExceptionResponse(e); 700 response.setCorrelationId(message.getCommandId()); 701 context.getConnection().dispatchAsync(response); 702 } else { 703 LOG.debug("unexpected exception on deferred send of: {}", message, e); 704 } 705 } finally { 706 getDestinationStatistics().getBlockedSends().decrement(); 707 producerExchangeCopy.blockingOnFlowControl(false); 708 } 709 } 710 }); 711 712 getDestinationStatistics().getBlockedSends().increment(); 713 producerExchange.blockingOnFlowControl(true); 714 if (!context.isNetworkConnection() && systemUsage.getSendFailIfNoSpaceAfterTimeout() != 0) { 715 flowControlTimeoutMessages.add(new TimeoutMessage(message, context, systemUsage 716 .getSendFailIfNoSpaceAfterTimeout())); 717 } 718 719 registerCallbackForNotFullNotification(); 720 context.setDontSendReponse(true); 721 return; 722 } 723 724 } else { 725 726 if (memoryUsage.isFull()) { 727 waitForSpace(context, producerExchange, memoryUsage, "Usage Manager Memory Limit reached. Producer (" 728 + message.getProducerId() + ") stopped to prevent flooding " 729 + getActiveMQDestination().getQualifiedName() + "." 730 + " See http://activemq.apache.org/producer-flow-control.html for more info"); 731 } 732 733 // The usage manager could have delayed us by the time 734 // we unblock the message could have expired.. 735 if (message.isExpired()) { 736 LOG.debug("Expired message: {}", message); 737 broker.getRoot().messageExpired(context, message, null); 738 return; 739 } 740 } 741 } 742 } 743 doMessageSend(producerExchange, message); 744 if (sendProducerAck) { 745 ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); 746 context.getConnection().dispatchAsync(ack); 747 } 748 } 749 750 private void registerCallbackForNotFullNotification() { 751 // If the usage manager is not full, then the task will not 752 // get called.. 753 if (!memoryUsage.notifyCallbackWhenNotFull(sendMessagesWaitingForSpaceTask)) { 754 // so call it directly here. 755 sendMessagesWaitingForSpaceTask.run(); 756 } 757 } 758 759 private final LinkedList<MessageContext> indexOrderedCursorUpdates = new LinkedList<>(); 760 761 @Override 762 public void onAdd(MessageContext messageContext) { 763 synchronized (indexOrderedCursorUpdates) { 764 indexOrderedCursorUpdates.addLast(messageContext); 765 } 766 } 767 768 private void doPendingCursorAdditions() throws Exception { 769 LinkedList<MessageContext> orderedUpdates = new LinkedList<>(); 770 sendLock.lockInterruptibly(); 771 try { 772 synchronized (indexOrderedCursorUpdates) { 773 MessageContext candidate = indexOrderedCursorUpdates.peek(); 774 while (candidate != null && candidate.message.getMessageId().getFutureOrSequenceLong() != null) { 775 candidate = indexOrderedCursorUpdates.removeFirst(); 776 // check for duplicate adds suppressed by the store 777 if (candidate.message.getMessageId().getFutureOrSequenceLong() instanceof Long && ((Long)candidate.message.getMessageId().getFutureOrSequenceLong()).compareTo(-1l) == 0) { 778 LOG.warn("{} messageStore indicated duplicate add attempt for {}, suppressing duplicate dispatch", this, candidate.message.getMessageId()); 779 } else { 780 orderedUpdates.add(candidate); 781 } 782 candidate = indexOrderedCursorUpdates.peek(); 783 } 784 } 785 messagesLock.writeLock().lock(); 786 try { 787 for (MessageContext messageContext : orderedUpdates) { 788 if (!messages.addMessageLast(messageContext.message)) { 789 // cursor suppressed a duplicate 790 messageContext.duplicate = true; 791 } 792 if (messageContext.onCompletion != null) { 793 messageContext.onCompletion.run(); 794 } 795 } 796 } finally { 797 messagesLock.writeLock().unlock(); 798 } 799 } finally { 800 sendLock.unlock(); 801 } 802 for (MessageContext messageContext : orderedUpdates) { 803 if (!messageContext.duplicate) { 804 messageSent(messageContext.context, messageContext.message); 805 } 806 } 807 orderedUpdates.clear(); 808 } 809 810 final class CursorAddSync extends Synchronization { 811 812 private final MessageContext messageContext; 813 814 CursorAddSync(MessageContext messageContext) { 815 this.messageContext = messageContext; 816 this.messageContext.message.incrementReferenceCount(); 817 } 818 819 @Override 820 public void afterCommit() throws Exception { 821 if (store != null && messageContext.message.isPersistent()) { 822 doPendingCursorAdditions(); 823 } else { 824 cursorAdd(messageContext.message); 825 messageSent(messageContext.context, messageContext.message); 826 } 827 messageContext.message.decrementReferenceCount(); 828 } 829 830 @Override 831 public void afterRollback() throws Exception { 832 messageContext.message.decrementReferenceCount(); 833 } 834 } 835 836 void doMessageSend(final ProducerBrokerExchange producerExchange, final Message message) throws IOException, 837 Exception { 838 final ConnectionContext context = producerExchange.getConnectionContext(); 839 ListenableFuture<Object> result = null; 840 841 producerExchange.incrementSend(); 842 pendingSends.incrementAndGet(); 843 checkUsage(context, producerExchange, message); 844 message.getMessageId().setBrokerSequenceId(getDestinationSequenceId()); 845 if (store != null && message.isPersistent()) { 846 message.getMessageId().setFutureOrSequenceLong(null); 847 try { 848 //AMQ-6133 - don't store async if using persistJMSRedelivered 849 //This flag causes a sync update later on dispatch which can cause a race 850 //condition if the original add is processed after the update, which can cause 851 //a duplicate message to be stored 852 if (messages.isCacheEnabled() && !isPersistJMSRedelivered()) { 853 result = store.asyncAddQueueMessage(context, message, isOptimizeStorage()); 854 result.addListener(new PendingMarshalUsageTracker(message)); 855 } else { 856 store.addMessage(context, message); 857 } 858 if (isReduceMemoryFootprint()) { 859 message.clearMarshalledState(); 860 } 861 } catch (Exception e) { 862 // we may have a store in inconsistent state, so reset the cursor 863 // before restarting normal broker operations 864 resetNeeded = true; 865 pendingSends.decrementAndGet(); 866 throw e; 867 } 868 } 869 orderedCursorAdd(message, context); 870 if (result != null && message.isResponseRequired() && !result.isCancelled()) { 871 try { 872 result.get(); 873 } catch (CancellationException e) { 874 // ignore - the task has been cancelled if the message 875 // has already been deleted 876 } 877 } 878 } 879 880 private void orderedCursorAdd(Message message, ConnectionContext context) throws Exception { 881 if (context.isInTransaction()) { 882 context.getTransaction().addSynchronization(new CursorAddSync(new MessageContext(context, message, null))); 883 } else if (store != null && message.isPersistent()) { 884 doPendingCursorAdditions(); 885 } else { 886 // no ordering issue with non persistent messages 887 cursorAdd(message); 888 messageSent(context, message); 889 } 890 } 891 892 private void checkUsage(ConnectionContext context,ProducerBrokerExchange producerBrokerExchange, Message message) throws ResourceAllocationException, IOException, InterruptedException { 893 if (message.isPersistent()) { 894 if (store != null && systemUsage.getStoreUsage().isFull(getStoreUsageHighWaterMark())) { 895 final String logMessage = "Persistent store is Full, " + getStoreUsageHighWaterMark() + "% of " 896 + systemUsage.getStoreUsage().getLimit() + ". Stopping producer (" 897 + message.getProducerId() + ") to prevent flooding " 898 + getActiveMQDestination().getQualifiedName() + "." 899 + " See http://activemq.apache.org/producer-flow-control.html for more info"; 900 901 waitForSpace(context, producerBrokerExchange, systemUsage.getStoreUsage(), getStoreUsageHighWaterMark(), logMessage); 902 } 903 } else if (messages.getSystemUsage() != null && systemUsage.getTempUsage().isFull()) { 904 final String logMessage = "Temp Store is Full (" 905 + systemUsage.getTempUsage().getPercentUsage() + "% of " + systemUsage.getTempUsage().getLimit() 906 +"). Stopping producer (" + message.getProducerId() 907 + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." 908 + " See http://activemq.apache.org/producer-flow-control.html for more info"; 909 910 waitForSpace(context, producerBrokerExchange, messages.getSystemUsage().getTempUsage(), logMessage); 911 } 912 } 913 914 private void expireMessages() { 915 LOG.debug("{} expiring messages ..", getActiveMQDestination().getQualifiedName()); 916 917 // just track the insertion count 918 List<Message> browsedMessages = new InsertionCountList<Message>(); 919 doBrowse(browsedMessages, this.getMaxExpirePageSize()); 920 asyncWakeup(); 921 LOG.debug("{} expiring messages done.", getActiveMQDestination().getQualifiedName()); 922 } 923 924 @Override 925 public void gc() { 926 } 927 928 @Override 929 public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) 930 throws IOException { 931 messageConsumed(context, node); 932 if (store != null && node.isPersistent()) { 933 store.removeAsyncMessage(context, convertToNonRangedAck(ack, node)); 934 } 935 } 936 937 Message loadMessage(MessageId messageId) throws IOException { 938 Message msg = null; 939 if (store != null) { // can be null for a temp q 940 msg = store.getMessage(messageId); 941 if (msg != null) { 942 msg.setRegionDestination(this); 943 } 944 } 945 return msg; 946 } 947 948 @Override 949 public String toString() { 950 return destination.getQualifiedName() + ", subscriptions=" + consumers.size() 951 + ", memory=" + memoryUsage.getPercentUsage() + "%, size=" + destinationStatistics.getMessages().getCount() + ", pending=" 952 + indexOrderedCursorUpdates.size(); 953 } 954 955 @Override 956 public void start() throws Exception { 957 if (started.compareAndSet(false, true)) { 958 if (memoryUsage != null) { 959 memoryUsage.start(); 960 } 961 if (systemUsage.getStoreUsage() != null) { 962 systemUsage.getStoreUsage().start(); 963 } 964 systemUsage.getMemoryUsage().addUsageListener(this); 965 messages.start(); 966 if (getExpireMessagesPeriod() > 0) { 967 scheduler.executePeriodically(expireMessagesTask, getExpireMessagesPeriod()); 968 } 969 doPageIn(false); 970 } 971 } 972 973 @Override 974 public void stop() throws Exception { 975 if (started.compareAndSet(true, false)) { 976 if (taskRunner != null) { 977 taskRunner.shutdown(); 978 } 979 if (this.executor != null) { 980 ThreadPoolUtils.shutdownNow(executor); 981 executor = null; 982 } 983 984 scheduler.cancel(expireMessagesTask); 985 986 if (flowControlTimeoutTask.isAlive()) { 987 flowControlTimeoutTask.interrupt(); 988 } 989 990 if (messages != null) { 991 messages.stop(); 992 } 993 994 for (MessageReference messageReference : pagedInMessages.values()) { 995 messageReference.decrementReferenceCount(); 996 } 997 pagedInMessages.clear(); 998 999 systemUsage.getMemoryUsage().removeUsageListener(this); 1000 if (memoryUsage != null) { 1001 memoryUsage.stop(); 1002 } 1003 if (store != null) { 1004 store.stop(); 1005 } 1006 } 1007 } 1008 1009 // Properties 1010 // ------------------------------------------------------------------------- 1011 @Override 1012 public ActiveMQDestination getActiveMQDestination() { 1013 return destination; 1014 } 1015 1016 public MessageGroupMap getMessageGroupOwners() { 1017 if (messageGroupOwners == null) { 1018 messageGroupOwners = getMessageGroupMapFactory().createMessageGroupMap(); 1019 messageGroupOwners.setDestination(this); 1020 } 1021 return messageGroupOwners; 1022 } 1023 1024 public DispatchPolicy getDispatchPolicy() { 1025 return dispatchPolicy; 1026 } 1027 1028 public void setDispatchPolicy(DispatchPolicy dispatchPolicy) { 1029 this.dispatchPolicy = dispatchPolicy; 1030 } 1031 1032 public MessageGroupMapFactory getMessageGroupMapFactory() { 1033 return messageGroupMapFactory; 1034 } 1035 1036 public void setMessageGroupMapFactory(MessageGroupMapFactory messageGroupMapFactory) { 1037 this.messageGroupMapFactory = messageGroupMapFactory; 1038 } 1039 1040 public PendingMessageCursor getMessages() { 1041 return this.messages; 1042 } 1043 1044 public void setMessages(PendingMessageCursor messages) { 1045 this.messages = messages; 1046 } 1047 1048 public boolean isUseConsumerPriority() { 1049 return useConsumerPriority; 1050 } 1051 1052 public void setUseConsumerPriority(boolean useConsumerPriority) { 1053 this.useConsumerPriority = useConsumerPriority; 1054 } 1055 1056 public boolean isStrictOrderDispatch() { 1057 return strictOrderDispatch; 1058 } 1059 1060 public void setStrictOrderDispatch(boolean strictOrderDispatch) { 1061 this.strictOrderDispatch = strictOrderDispatch; 1062 } 1063 1064 public boolean isOptimizedDispatch() { 1065 return optimizedDispatch; 1066 } 1067 1068 public void setOptimizedDispatch(boolean optimizedDispatch) { 1069 this.optimizedDispatch = optimizedDispatch; 1070 } 1071 1072 public int getTimeBeforeDispatchStarts() { 1073 return timeBeforeDispatchStarts; 1074 } 1075 1076 public void setTimeBeforeDispatchStarts(int timeBeforeDispatchStarts) { 1077 this.timeBeforeDispatchStarts = timeBeforeDispatchStarts; 1078 } 1079 1080 public int getConsumersBeforeDispatchStarts() { 1081 return consumersBeforeDispatchStarts; 1082 } 1083 1084 public void setConsumersBeforeDispatchStarts(int consumersBeforeDispatchStarts) { 1085 this.consumersBeforeDispatchStarts = consumersBeforeDispatchStarts; 1086 } 1087 1088 public void setAllConsumersExclusiveByDefault(boolean allConsumersExclusiveByDefault) { 1089 this.allConsumersExclusiveByDefault = allConsumersExclusiveByDefault; 1090 } 1091 1092 public boolean isAllConsumersExclusiveByDefault() { 1093 return allConsumersExclusiveByDefault; 1094 } 1095 1096 public boolean isResetNeeded() { 1097 return resetNeeded; 1098 } 1099 1100 // Implementation methods 1101 // ------------------------------------------------------------------------- 1102 private QueueMessageReference createMessageReference(Message message) { 1103 QueueMessageReference result = new IndirectMessageReference(message); 1104 return result; 1105 } 1106 1107 @Override 1108 public Message[] browse() { 1109 List<Message> browseList = new ArrayList<Message>(); 1110 doBrowse(browseList, getMaxBrowsePageSize()); 1111 return browseList.toArray(new Message[browseList.size()]); 1112 } 1113 1114 public void doBrowse(List<Message> browseList, int max) { 1115 final ConnectionContext connectionContext = createConnectionContext(); 1116 try { 1117 int maxPageInAttempts = 1; 1118 if (max > 0) { 1119 messagesLock.readLock().lock(); 1120 try { 1121 maxPageInAttempts += (messages.size() / max); 1122 } finally { 1123 messagesLock.readLock().unlock(); 1124 } 1125 while (shouldPageInMoreForBrowse(max) && maxPageInAttempts-- > 0) { 1126 pageInMessages(!memoryUsage.isFull(110), max); 1127 } 1128 } 1129 doBrowseList(browseList, max, dispatchPendingList, pagedInPendingDispatchLock, connectionContext, "redeliveredWaitingDispatch+pagedInPendingDispatch"); 1130 doBrowseList(browseList, max, pagedInMessages, pagedInMessagesLock, connectionContext, "pagedInMessages"); 1131 1132 // we need a store iterator to walk messages on disk, independent of the cursor which is tracking 1133 // the next message batch 1134 } catch (Exception e) { 1135 LOG.error("Problem retrieving message for browse", e); 1136 } 1137 } 1138 1139 protected void doBrowseList(List<Message> browseList, int max, PendingList list, ReentrantReadWriteLock lock, ConnectionContext connectionContext, String name) throws Exception { 1140 List<MessageReference> toExpire = new ArrayList<MessageReference>(); 1141 lock.readLock().lock(); 1142 try { 1143 addAll(list.values(), browseList, max, toExpire); 1144 } finally { 1145 lock.readLock().unlock(); 1146 } 1147 for (MessageReference ref : toExpire) { 1148 if (broker.isExpired(ref)) { 1149 LOG.debug("expiring from {}: {}", name, ref); 1150 messageExpired(connectionContext, ref); 1151 } else { 1152 lock.writeLock().lock(); 1153 try { 1154 list.remove(ref); 1155 } finally { 1156 lock.writeLock().unlock(); 1157 } 1158 ref.decrementReferenceCount(); 1159 } 1160 } 1161 } 1162 1163 private boolean shouldPageInMoreForBrowse(int max) { 1164 int alreadyPagedIn = 0; 1165 pagedInMessagesLock.readLock().lock(); 1166 try { 1167 alreadyPagedIn = pagedInMessages.size(); 1168 } finally { 1169 pagedInMessagesLock.readLock().unlock(); 1170 } 1171 int messagesInQueue = alreadyPagedIn; 1172 messagesLock.readLock().lock(); 1173 try { 1174 messagesInQueue += messages.size(); 1175 } finally { 1176 messagesLock.readLock().unlock(); 1177 } 1178 1179 LOG.trace("max {}, alreadyPagedIn {}, messagesCount {}, memoryUsage {}%", new Object[]{max, alreadyPagedIn, messagesInQueue, memoryUsage.getPercentUsage()}); 1180 return (alreadyPagedIn < max) 1181 && (alreadyPagedIn < messagesInQueue) 1182 && messages.hasSpace(); 1183 } 1184 1185 private void addAll(Collection<? extends MessageReference> refs, List<Message> l, int max, 1186 List<MessageReference> toExpire) throws Exception { 1187 for (Iterator<? extends MessageReference> i = refs.iterator(); i.hasNext() && l.size() < max;) { 1188 QueueMessageReference ref = (QueueMessageReference) i.next(); 1189 if (ref.isExpired() && (ref.getLockOwner() == null)) { 1190 toExpire.add(ref); 1191 } else if (l.contains(ref.getMessage()) == false) { 1192 l.add(ref.getMessage()); 1193 } 1194 } 1195 } 1196 1197 public QueueMessageReference getMessage(String id) { 1198 MessageId msgId = new MessageId(id); 1199 pagedInMessagesLock.readLock().lock(); 1200 try { 1201 QueueMessageReference ref = (QueueMessageReference)this.pagedInMessages.get(msgId); 1202 if (ref != null) { 1203 return ref; 1204 } 1205 } finally { 1206 pagedInMessagesLock.readLock().unlock(); 1207 } 1208 messagesLock.writeLock().lock(); 1209 try{ 1210 try { 1211 messages.reset(); 1212 while (messages.hasNext()) { 1213 MessageReference mr = messages.next(); 1214 QueueMessageReference qmr = createMessageReference(mr.getMessage()); 1215 qmr.decrementReferenceCount(); 1216 messages.rollback(qmr.getMessageId()); 1217 if (msgId.equals(qmr.getMessageId())) { 1218 return qmr; 1219 } 1220 } 1221 } finally { 1222 messages.release(); 1223 } 1224 }finally { 1225 messagesLock.writeLock().unlock(); 1226 } 1227 return null; 1228 } 1229 1230 public void purge() throws Exception { 1231 ConnectionContext c = createConnectionContext(); 1232 List<MessageReference> list = null; 1233 long originalMessageCount = this.destinationStatistics.getMessages().getCount(); 1234 do { 1235 doPageIn(true, false, getMaxPageSize()); // signal no expiry processing needed. 1236 pagedInMessagesLock.readLock().lock(); 1237 try { 1238 list = new ArrayList<MessageReference>(pagedInMessages.values()); 1239 }finally { 1240 pagedInMessagesLock.readLock().unlock(); 1241 } 1242 1243 for (MessageReference ref : list) { 1244 try { 1245 QueueMessageReference r = (QueueMessageReference) ref; 1246 removeMessage(c, r); 1247 } catch (IOException e) { 1248 } 1249 } 1250 // don't spin/hang if stats are out and there is nothing left in the 1251 // store 1252 } while (!list.isEmpty() && this.destinationStatistics.getMessages().getCount() > 0); 1253 1254 if (this.destinationStatistics.getMessages().getCount() > 0) { 1255 LOG.warn("{} after purge of {} messages, message count stats report: {}", getActiveMQDestination().getQualifiedName(), originalMessageCount, this.destinationStatistics.getMessages().getCount()); 1256 } 1257 gc(); 1258 this.destinationStatistics.getMessages().setCount(0); 1259 getMessages().clear(); 1260 } 1261 1262 @Override 1263 public void clearPendingMessages() { 1264 messagesLock.writeLock().lock(); 1265 try { 1266 if (resetNeeded) { 1267 messages.gc(); 1268 messages.reset(); 1269 resetNeeded = false; 1270 } else { 1271 messages.rebase(); 1272 } 1273 asyncWakeup(); 1274 } finally { 1275 messagesLock.writeLock().unlock(); 1276 } 1277 } 1278 1279 /** 1280 * Removes the message matching the given messageId 1281 */ 1282 public boolean removeMessage(String messageId) throws Exception { 1283 return removeMatchingMessages(createMessageIdFilter(messageId), 1) > 0; 1284 } 1285 1286 /** 1287 * Removes the messages matching the given selector 1288 * 1289 * @return the number of messages removed 1290 */ 1291 public int removeMatchingMessages(String selector) throws Exception { 1292 return removeMatchingMessages(selector, -1); 1293 } 1294 1295 /** 1296 * Removes the messages matching the given selector up to the maximum number 1297 * of matched messages 1298 * 1299 * @return the number of messages removed 1300 */ 1301 public int removeMatchingMessages(String selector, int maximumMessages) throws Exception { 1302 return removeMatchingMessages(createSelectorFilter(selector), maximumMessages); 1303 } 1304 1305 /** 1306 * Removes the messages matching the given filter up to the maximum number 1307 * of matched messages 1308 * 1309 * @return the number of messages removed 1310 */ 1311 public int removeMatchingMessages(MessageReferenceFilter filter, int maximumMessages) throws Exception { 1312 int movedCounter = 0; 1313 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1314 ConnectionContext context = createConnectionContext(); 1315 do { 1316 doPageIn(true); 1317 pagedInMessagesLock.readLock().lock(); 1318 try { 1319 set.addAll(pagedInMessages.values()); 1320 } finally { 1321 pagedInMessagesLock.readLock().unlock(); 1322 } 1323 List<MessageReference> list = new ArrayList<MessageReference>(set); 1324 for (MessageReference ref : list) { 1325 IndirectMessageReference r = (IndirectMessageReference) ref; 1326 if (filter.evaluate(context, r)) { 1327 1328 removeMessage(context, r); 1329 set.remove(r); 1330 if (++movedCounter >= maximumMessages && maximumMessages > 0) { 1331 return movedCounter; 1332 } 1333 } 1334 } 1335 } while (set.size() < this.destinationStatistics.getMessages().getCount()); 1336 return movedCounter; 1337 } 1338 1339 /** 1340 * Copies the message matching the given messageId 1341 */ 1342 public boolean copyMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest) 1343 throws Exception { 1344 return copyMatchingMessages(context, createMessageIdFilter(messageId), dest, 1) > 0; 1345 } 1346 1347 /** 1348 * Copies the messages matching the given selector 1349 * 1350 * @return the number of messages copied 1351 */ 1352 public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest) 1353 throws Exception { 1354 return copyMatchingMessagesTo(context, selector, dest, -1); 1355 } 1356 1357 /** 1358 * Copies the messages matching the given selector up to the maximum number 1359 * of matched messages 1360 * 1361 * @return the number of messages copied 1362 */ 1363 public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest, 1364 int maximumMessages) throws Exception { 1365 return copyMatchingMessages(context, createSelectorFilter(selector), dest, maximumMessages); 1366 } 1367 1368 /** 1369 * Copies the messages matching the given filter up to the maximum number of 1370 * matched messages 1371 * 1372 * @return the number of messages copied 1373 */ 1374 public int copyMatchingMessages(ConnectionContext context, MessageReferenceFilter filter, ActiveMQDestination dest, 1375 int maximumMessages) throws Exception { 1376 int movedCounter = 0; 1377 int count = 0; 1378 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1379 do { 1380 int oldMaxSize = getMaxPageSize(); 1381 setMaxPageSize((int) this.destinationStatistics.getMessages().getCount()); 1382 doPageIn(true); 1383 setMaxPageSize(oldMaxSize); 1384 pagedInMessagesLock.readLock().lock(); 1385 try { 1386 set.addAll(pagedInMessages.values()); 1387 } finally { 1388 pagedInMessagesLock.readLock().unlock(); 1389 } 1390 List<MessageReference> list = new ArrayList<MessageReference>(set); 1391 for (MessageReference ref : list) { 1392 IndirectMessageReference r = (IndirectMessageReference) ref; 1393 if (filter.evaluate(context, r)) { 1394 1395 r.incrementReferenceCount(); 1396 try { 1397 Message m = r.getMessage(); 1398 BrokerSupport.resend(context, m, dest); 1399 if (++movedCounter >= maximumMessages && maximumMessages > 0) { 1400 return movedCounter; 1401 } 1402 } finally { 1403 r.decrementReferenceCount(); 1404 } 1405 } 1406 count++; 1407 } 1408 } while (count < this.destinationStatistics.getMessages().getCount()); 1409 return movedCounter; 1410 } 1411 1412 /** 1413 * Move a message 1414 * 1415 * @param context 1416 * connection context 1417 * @param m 1418 * QueueMessageReference 1419 * @param dest 1420 * ActiveMQDestination 1421 * @throws Exception 1422 */ 1423 public boolean moveMessageTo(ConnectionContext context, QueueMessageReference m, ActiveMQDestination dest) throws Exception { 1424 BrokerSupport.resend(context, m.getMessage(), dest); 1425 removeMessage(context, m); 1426 messagesLock.writeLock().lock(); 1427 try { 1428 messages.rollback(m.getMessageId()); 1429 if (isDLQ()) { 1430 DeadLetterStrategy stratagy = getDeadLetterStrategy(); 1431 stratagy.rollback(m.getMessage()); 1432 } 1433 } finally { 1434 messagesLock.writeLock().unlock(); 1435 } 1436 return true; 1437 } 1438 1439 /** 1440 * Moves the message matching the given messageId 1441 */ 1442 public boolean moveMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest) 1443 throws Exception { 1444 return moveMatchingMessagesTo(context, createMessageIdFilter(messageId), dest, 1) > 0; 1445 } 1446 1447 /** 1448 * Moves the messages matching the given selector 1449 * 1450 * @return the number of messages removed 1451 */ 1452 public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest) 1453 throws Exception { 1454 return moveMatchingMessagesTo(context, selector, dest, Integer.MAX_VALUE); 1455 } 1456 1457 /** 1458 * Moves the messages matching the given selector up to the maximum number 1459 * of matched messages 1460 */ 1461 public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest, 1462 int maximumMessages) throws Exception { 1463 return moveMatchingMessagesTo(context, createSelectorFilter(selector), dest, maximumMessages); 1464 } 1465 1466 /** 1467 * Moves the messages matching the given filter up to the maximum number of 1468 * matched messages 1469 */ 1470 public int moveMatchingMessagesTo(ConnectionContext context, MessageReferenceFilter filter, 1471 ActiveMQDestination dest, int maximumMessages) throws Exception { 1472 int movedCounter = 0; 1473 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1474 do { 1475 doPageIn(true); 1476 pagedInMessagesLock.readLock().lock(); 1477 try { 1478 set.addAll(pagedInMessages.values()); 1479 } finally { 1480 pagedInMessagesLock.readLock().unlock(); 1481 } 1482 List<MessageReference> list = new ArrayList<MessageReference>(set); 1483 for (MessageReference ref : list) { 1484 if (filter.evaluate(context, ref)) { 1485 // We should only move messages that can be locked. 1486 moveMessageTo(context, (QueueMessageReference)ref, dest); 1487 set.remove(ref); 1488 if (++movedCounter >= maximumMessages && maximumMessages > 0) { 1489 return movedCounter; 1490 } 1491 } 1492 } 1493 } while (set.size() < this.destinationStatistics.getMessages().getCount() && set.size() < maximumMessages); 1494 return movedCounter; 1495 } 1496 1497 public int retryMessages(ConnectionContext context, int maximumMessages) throws Exception { 1498 if (!isDLQ()) { 1499 throw new Exception("Retry of message is only possible on Dead Letter Queues!"); 1500 } 1501 int restoredCounter = 0; 1502 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1503 do { 1504 doPageIn(true); 1505 pagedInMessagesLock.readLock().lock(); 1506 try { 1507 set.addAll(pagedInMessages.values()); 1508 } finally { 1509 pagedInMessagesLock.readLock().unlock(); 1510 } 1511 List<MessageReference> list = new ArrayList<MessageReference>(set); 1512 for (MessageReference ref : list) { 1513 if (ref.getMessage().getOriginalDestination() != null) { 1514 1515 moveMessageTo(context, (QueueMessageReference)ref, ref.getMessage().getOriginalDestination()); 1516 set.remove(ref); 1517 if (++restoredCounter >= maximumMessages && maximumMessages > 0) { 1518 return restoredCounter; 1519 } 1520 } 1521 } 1522 } while (set.size() < this.destinationStatistics.getMessages().getCount() && set.size() < maximumMessages); 1523 return restoredCounter; 1524 } 1525 1526 /** 1527 * @return true if we would like to iterate again 1528 * @see org.apache.activemq.thread.Task#iterate() 1529 */ 1530 @Override 1531 public boolean iterate() { 1532 MDC.put("activemq.destination", getName()); 1533 boolean pageInMoreMessages = false; 1534 synchronized (iteratingMutex) { 1535 1536 // If optimize dispatch is on or this is a slave this method could be called recursively 1537 // we set this state value to short-circuit wakeup in those cases to avoid that as it 1538 // could lead to errors. 1539 iterationRunning = true; 1540 1541 // do early to allow dispatch of these waiting messages 1542 synchronized (messagesWaitingForSpace) { 1543 Iterator<Runnable> it = messagesWaitingForSpace.values().iterator(); 1544 while (it.hasNext()) { 1545 if (!memoryUsage.isFull()) { 1546 Runnable op = it.next(); 1547 it.remove(); 1548 op.run(); 1549 } else { 1550 registerCallbackForNotFullNotification(); 1551 break; 1552 } 1553 } 1554 } 1555 1556 if (firstConsumer) { 1557 firstConsumer = false; 1558 try { 1559 if (consumersBeforeDispatchStarts > 0) { 1560 int timeout = 1000; // wait one second by default if 1561 // consumer count isn't reached 1562 if (timeBeforeDispatchStarts > 0) { 1563 timeout = timeBeforeDispatchStarts; 1564 } 1565 if (consumersBeforeStartsLatch.await(timeout, TimeUnit.MILLISECONDS)) { 1566 LOG.debug("{} consumers subscribed. Starting dispatch.", consumers.size()); 1567 } else { 1568 LOG.debug("{} ms elapsed and {} consumers subscribed. Starting dispatch.", timeout, consumers.size()); 1569 } 1570 } 1571 if (timeBeforeDispatchStarts > 0 && consumersBeforeDispatchStarts <= 0) { 1572 iteratingMutex.wait(timeBeforeDispatchStarts); 1573 LOG.debug("{} ms elapsed. Starting dispatch.", timeBeforeDispatchStarts); 1574 } 1575 } catch (Exception e) { 1576 LOG.error(e.toString()); 1577 } 1578 } 1579 1580 messagesLock.readLock().lock(); 1581 try{ 1582 pageInMoreMessages |= !messages.isEmpty(); 1583 } finally { 1584 messagesLock.readLock().unlock(); 1585 } 1586 1587 pagedInPendingDispatchLock.readLock().lock(); 1588 try { 1589 pageInMoreMessages |= !dispatchPendingList.isEmpty(); 1590 } finally { 1591 pagedInPendingDispatchLock.readLock().unlock(); 1592 } 1593 1594 // Perhaps we should page always into the pagedInPendingDispatch 1595 // list if 1596 // !messages.isEmpty(), and then if 1597 // !pagedInPendingDispatch.isEmpty() 1598 // then we do a dispatch. 1599 boolean hasBrowsers = browserDispatches.size() > 0; 1600 1601 if (pageInMoreMessages || hasBrowsers || !dispatchPendingList.hasRedeliveries()) { 1602 try { 1603 pageInMessages(hasBrowsers && getMaxBrowsePageSize() > 0, getMaxPageSize()); 1604 } catch (Throwable e) { 1605 LOG.error("Failed to page in more queue messages ", e); 1606 } 1607 } 1608 1609 if (hasBrowsers) { 1610 PendingList alreadyDispatchedMessages = isPrioritizedMessages() ? 1611 new PrioritizedPendingList() : new OrderedPendingList(); 1612 pagedInMessagesLock.readLock().lock(); 1613 try{ 1614 alreadyDispatchedMessages.addAll(pagedInMessages); 1615 }finally { 1616 pagedInMessagesLock.readLock().unlock(); 1617 } 1618 1619 Iterator<BrowserDispatch> browsers = browserDispatches.iterator(); 1620 while (browsers.hasNext()) { 1621 BrowserDispatch browserDispatch = browsers.next(); 1622 try { 1623 MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext(); 1624 msgContext.setDestination(destination); 1625 1626 QueueBrowserSubscription browser = browserDispatch.getBrowser(); 1627 1628 LOG.debug("dispatch to browser: {}, already dispatched/paged count: {}", browser, alreadyDispatchedMessages.size()); 1629 boolean added = false; 1630 for (MessageReference node : alreadyDispatchedMessages) { 1631 if (!((QueueMessageReference)node).isAcked() && !browser.isDuplicate(node.getMessageId()) && !browser.atMax()) { 1632 msgContext.setMessageReference(node); 1633 if (browser.matches(node, msgContext)) { 1634 browser.add(node); 1635 added = true; 1636 } 1637 } 1638 } 1639 // are we done browsing? no new messages paged 1640 if (!added || browser.atMax()) { 1641 browser.decrementQueueRef(); 1642 browserDispatches.remove(browserDispatch); 1643 } 1644 } catch (Exception e) { 1645 LOG.warn("exception on dispatch to browser: {}", browserDispatch.getBrowser(), e); 1646 } 1647 } 1648 } 1649 1650 if (pendingWakeups.get() > 0) { 1651 pendingWakeups.decrementAndGet(); 1652 } 1653 MDC.remove("activemq.destination"); 1654 iterationRunning = false; 1655 1656 return pendingWakeups.get() > 0; 1657 } 1658 } 1659 1660 public void pauseDispatch() { 1661 dispatchSelector.pause(); 1662 } 1663 1664 public void resumeDispatch() { 1665 dispatchSelector.resume(); 1666 wakeup(); 1667 } 1668 1669 public boolean isDispatchPaused() { 1670 return dispatchSelector.isPaused(); 1671 } 1672 1673 protected MessageReferenceFilter createMessageIdFilter(final String messageId) { 1674 return new MessageReferenceFilter() { 1675 @Override 1676 public boolean evaluate(ConnectionContext context, MessageReference r) { 1677 return messageId.equals(r.getMessageId().toString()); 1678 } 1679 1680 @Override 1681 public String toString() { 1682 return "MessageIdFilter: " + messageId; 1683 } 1684 }; 1685 } 1686 1687 protected MessageReferenceFilter createSelectorFilter(String selector) throws InvalidSelectorException { 1688 1689 if (selector == null || selector.isEmpty()) { 1690 return new MessageReferenceFilter() { 1691 1692 @Override 1693 public boolean evaluate(ConnectionContext context, MessageReference messageReference) throws JMSException { 1694 return true; 1695 } 1696 }; 1697 } 1698 1699 final BooleanExpression selectorExpression = SelectorParser.parse(selector); 1700 1701 return new MessageReferenceFilter() { 1702 @Override 1703 public boolean evaluate(ConnectionContext context, MessageReference r) throws JMSException { 1704 MessageEvaluationContext messageEvaluationContext = context.getMessageEvaluationContext(); 1705 1706 messageEvaluationContext.setMessageReference(r); 1707 if (messageEvaluationContext.getDestination() == null) { 1708 messageEvaluationContext.setDestination(getActiveMQDestination()); 1709 } 1710 1711 return selectorExpression.matches(messageEvaluationContext); 1712 } 1713 }; 1714 } 1715 1716 protected void removeMessage(ConnectionContext c, QueueMessageReference r) throws IOException { 1717 removeMessage(c, null, r); 1718 pagedInPendingDispatchLock.writeLock().lock(); 1719 try { 1720 dispatchPendingList.remove(r); 1721 } finally { 1722 pagedInPendingDispatchLock.writeLock().unlock(); 1723 } 1724 } 1725 1726 protected void removeMessage(ConnectionContext c, Subscription subs, QueueMessageReference r) throws IOException { 1727 MessageAck ack = new MessageAck(); 1728 ack.setAckType(MessageAck.STANDARD_ACK_TYPE); 1729 ack.setDestination(destination); 1730 ack.setMessageID(r.getMessageId()); 1731 removeMessage(c, subs, r, ack); 1732 } 1733 1734 protected void removeMessage(ConnectionContext context, Subscription sub, final QueueMessageReference reference, 1735 MessageAck ack) throws IOException { 1736 LOG.trace("ack of {} with {}", reference.getMessageId(), ack); 1737 // This sends the ack the the journal.. 1738 if (!ack.isInTransaction()) { 1739 acknowledge(context, sub, ack, reference); 1740 getDestinationStatistics().getDequeues().increment(); 1741 dropMessage(reference); 1742 } else { 1743 try { 1744 acknowledge(context, sub, ack, reference); 1745 } finally { 1746 context.getTransaction().addSynchronization(new Synchronization() { 1747 1748 @Override 1749 public void afterCommit() throws Exception { 1750 getDestinationStatistics().getDequeues().increment(); 1751 dropMessage(reference); 1752 wakeup(); 1753 } 1754 1755 @Override 1756 public void afterRollback() throws Exception { 1757 reference.setAcked(false); 1758 wakeup(); 1759 } 1760 }); 1761 } 1762 } 1763 if (ack.isPoisonAck() || (sub != null && sub.getConsumerInfo().isNetworkSubscription())) { 1764 // message gone to DLQ, is ok to allow redelivery 1765 messagesLock.writeLock().lock(); 1766 try { 1767 messages.rollback(reference.getMessageId()); 1768 } finally { 1769 messagesLock.writeLock().unlock(); 1770 } 1771 if (sub != null && sub.getConsumerInfo().isNetworkSubscription()) { 1772 getDestinationStatistics().getForwards().increment(); 1773 } 1774 } 1775 // after successful store update 1776 reference.setAcked(true); 1777 } 1778 1779 private void dropMessage(QueueMessageReference reference) { 1780 if (!reference.isDropped()) { 1781 reference.drop(); 1782 destinationStatistics.getMessages().decrement(); 1783 pagedInMessagesLock.writeLock().lock(); 1784 try { 1785 pagedInMessages.remove(reference); 1786 } finally { 1787 pagedInMessagesLock.writeLock().unlock(); 1788 } 1789 } 1790 } 1791 1792 public void messageExpired(ConnectionContext context, MessageReference reference) { 1793 messageExpired(context, null, reference); 1794 } 1795 1796 @Override 1797 public void messageExpired(ConnectionContext context, Subscription subs, MessageReference reference) { 1798 LOG.debug("message expired: {}", reference); 1799 broker.messageExpired(context, reference, subs); 1800 destinationStatistics.getExpired().increment(); 1801 try { 1802 removeMessage(context, subs, (QueueMessageReference) reference); 1803 messagesLock.writeLock().lock(); 1804 try { 1805 messages.rollback(reference.getMessageId()); 1806 } finally { 1807 messagesLock.writeLock().unlock(); 1808 } 1809 } catch (IOException e) { 1810 LOG.error("Failed to remove expired Message from the store ", e); 1811 } 1812 } 1813 1814 final boolean cursorAdd(final Message msg) throws Exception { 1815 messagesLock.writeLock().lock(); 1816 try { 1817 return messages.addMessageLast(msg); 1818 } finally { 1819 messagesLock.writeLock().unlock(); 1820 } 1821 } 1822 1823 final void messageSent(final ConnectionContext context, final Message msg) throws Exception { 1824 pendingSends.decrementAndGet(); 1825 destinationStatistics.getEnqueues().increment(); 1826 destinationStatistics.getMessages().increment(); 1827 destinationStatistics.getMessageSize().addSize(msg.getSize()); 1828 messageDelivered(context, msg); 1829 consumersLock.readLock().lock(); 1830 try { 1831 if (consumers.isEmpty()) { 1832 onMessageWithNoConsumers(context, msg); 1833 } 1834 }finally { 1835 consumersLock.readLock().unlock(); 1836 } 1837 LOG.debug("{} Message {} sent to {}", new Object[]{ broker.getBrokerName(), msg.getMessageId(), this.destination }); 1838 wakeup(); 1839 } 1840 1841 @Override 1842 public void wakeup() { 1843 if (optimizedDispatch && !iterationRunning) { 1844 iterate(); 1845 pendingWakeups.incrementAndGet(); 1846 } else { 1847 asyncWakeup(); 1848 } 1849 } 1850 1851 private void asyncWakeup() { 1852 try { 1853 pendingWakeups.incrementAndGet(); 1854 this.taskRunner.wakeup(); 1855 } catch (InterruptedException e) { 1856 LOG.warn("Async task runner failed to wakeup ", e); 1857 } 1858 } 1859 1860 private void doPageIn(boolean force) throws Exception { 1861 doPageIn(force, true, getMaxPageSize()); 1862 } 1863 1864 private void doPageIn(boolean force, boolean processExpired, int maxPageSize) throws Exception { 1865 PendingList newlyPaged = doPageInForDispatch(force, processExpired, maxPageSize); 1866 pagedInPendingDispatchLock.writeLock().lock(); 1867 try { 1868 if (dispatchPendingList.isEmpty()) { 1869 dispatchPendingList.addAll(newlyPaged); 1870 1871 } else { 1872 for (MessageReference qmr : newlyPaged) { 1873 if (!dispatchPendingList.contains(qmr)) { 1874 dispatchPendingList.addMessageLast(qmr); 1875 } 1876 } 1877 } 1878 } finally { 1879 pagedInPendingDispatchLock.writeLock().unlock(); 1880 } 1881 } 1882 1883 private PendingList doPageInForDispatch(boolean force, boolean processExpired, int maxPageSize) throws Exception { 1884 List<QueueMessageReference> result = null; 1885 PendingList resultList = null; 1886 1887 int toPageIn = Math.min(maxPageSize, messages.size()); 1888 int pagedInPendingSize = 0; 1889 pagedInPendingDispatchLock.readLock().lock(); 1890 try { 1891 pagedInPendingSize = dispatchPendingList.size(); 1892 } finally { 1893 pagedInPendingDispatchLock.readLock().unlock(); 1894 } 1895 if (isLazyDispatch() && !force) { 1896 // Only page in the minimum number of messages which can be 1897 // dispatched immediately. 1898 toPageIn = Math.min(getConsumerMessageCountBeforeFull(), toPageIn); 1899 } 1900 1901 if (LOG.isDebugEnabled()) { 1902 LOG.debug("{} toPageIn: {}, force:{}, Inflight: {}, pagedInMessages.size {}, pagedInPendingDispatch.size {}, enqueueCount: {}, dequeueCount: {}, memUsage:{}, maxPageSize:{}", 1903 new Object[]{ 1904 this, 1905 toPageIn, 1906 force, 1907 destinationStatistics.getInflight().getCount(), 1908 pagedInMessages.size(), 1909 pagedInPendingSize, 1910 destinationStatistics.getEnqueues().getCount(), 1911 destinationStatistics.getDequeues().getCount(), 1912 getMemoryUsage().getUsage(), 1913 maxPageSize 1914 }); 1915 } 1916 1917 if (toPageIn > 0 && (force || (haveRealConsumer() && pagedInPendingSize < maxPageSize))) { 1918 int count = 0; 1919 result = new ArrayList<QueueMessageReference>(toPageIn); 1920 messagesLock.writeLock().lock(); 1921 try { 1922 try { 1923 messages.setMaxBatchSize(toPageIn); 1924 messages.reset(); 1925 while (count < toPageIn && messages.hasNext()) { 1926 MessageReference node = messages.next(); 1927 messages.remove(); 1928 1929 QueueMessageReference ref = createMessageReference(node.getMessage()); 1930 if (processExpired && ref.isExpired()) { 1931 if (broker.isExpired(ref)) { 1932 messageExpired(createConnectionContext(), ref); 1933 } else { 1934 ref.decrementReferenceCount(); 1935 } 1936 } else { 1937 result.add(ref); 1938 count++; 1939 } 1940 } 1941 } finally { 1942 messages.release(); 1943 } 1944 } finally { 1945 messagesLock.writeLock().unlock(); 1946 } 1947 // Only add new messages, not already pagedIn to avoid multiple 1948 // dispatch attempts 1949 pagedInMessagesLock.writeLock().lock(); 1950 try { 1951 if(isPrioritizedMessages()) { 1952 resultList = new PrioritizedPendingList(); 1953 } else { 1954 resultList = new OrderedPendingList(); 1955 } 1956 for (QueueMessageReference ref : result) { 1957 if (!pagedInMessages.contains(ref)) { 1958 pagedInMessages.addMessageLast(ref); 1959 resultList.addMessageLast(ref); 1960 } else { 1961 ref.decrementReferenceCount(); 1962 // store should have trapped duplicate in it's index, or cursor audit trapped insert 1963 // or producerBrokerExchange suppressed send. 1964 // note: jdbc store will not trap unacked messages as a duplicate b/c it gives each message a unique sequence id 1965 LOG.warn("{}, duplicate message {} - {} from cursor, is cursor audit disabled or too constrained? Redirecting to dlq", this, ref.getMessageId(), ref.getMessage().getMessageId().getFutureOrSequenceLong()); 1966 if (store != null) { 1967 ConnectionContext connectionContext = createConnectionContext(); 1968 dropMessage(ref); 1969 if (gotToTheStore(ref.getMessage())) { 1970 LOG.debug("Duplicate message {} from cursor, removing from store", this, ref.getMessage()); 1971 store.removeMessage(connectionContext, new MessageAck(ref.getMessage(), MessageAck.POSION_ACK_TYPE, 1)); 1972 } 1973 broker.getRoot().sendToDeadLetterQueue(connectionContext, ref.getMessage(), null, new Throwable("duplicate paged in from cursor for " + destination)); 1974 } 1975 } 1976 } 1977 } finally { 1978 pagedInMessagesLock.writeLock().unlock(); 1979 } 1980 } else { 1981 // Avoid return null list, if condition is not validated 1982 resultList = new OrderedPendingList(); 1983 } 1984 1985 return resultList; 1986 } 1987 1988 private final boolean haveRealConsumer() { 1989 return consumers.size() - browserDispatches.size() > 0; 1990 } 1991 1992 private void doDispatch(PendingList list) throws Exception { 1993 boolean doWakeUp = false; 1994 1995 pagedInPendingDispatchLock.writeLock().lock(); 1996 try { 1997 if (isPrioritizedMessages() && !dispatchPendingList.isEmpty() && list != null && !list.isEmpty()) { 1998 // merge all to select priority order 1999 for (MessageReference qmr : list) { 2000 if (!dispatchPendingList.contains(qmr)) { 2001 dispatchPendingList.addMessageLast(qmr); 2002 } 2003 } 2004 list = null; 2005 } 2006 2007 doActualDispatch(dispatchPendingList); 2008 // and now see if we can dispatch the new stuff.. and append to the pending 2009 // list anything that does not actually get dispatched. 2010 if (list != null && !list.isEmpty()) { 2011 if (dispatchPendingList.isEmpty()) { 2012 dispatchPendingList.addAll(doActualDispatch(list)); 2013 } else { 2014 for (MessageReference qmr : list) { 2015 if (!dispatchPendingList.contains(qmr)) { 2016 dispatchPendingList.addMessageLast(qmr); 2017 } 2018 } 2019 doWakeUp = true; 2020 } 2021 } 2022 } finally { 2023 pagedInPendingDispatchLock.writeLock().unlock(); 2024 } 2025 2026 if (doWakeUp) { 2027 // avoid lock order contention 2028 asyncWakeup(); 2029 } 2030 } 2031 2032 /** 2033 * @return list of messages that could get dispatched to consumers if they 2034 * were not full. 2035 */ 2036 private PendingList doActualDispatch(PendingList list) throws Exception { 2037 List<Subscription> consumers; 2038 consumersLock.readLock().lock(); 2039 2040 try { 2041 if (this.consumers.isEmpty()) { 2042 // slave dispatch happens in processDispatchNotification 2043 return list; 2044 } 2045 consumers = new ArrayList<Subscription>(this.consumers); 2046 } finally { 2047 consumersLock.readLock().unlock(); 2048 } 2049 2050 Set<Subscription> fullConsumers = new HashSet<Subscription>(this.consumers.size()); 2051 2052 for (Iterator<MessageReference> iterator = list.iterator(); iterator.hasNext();) { 2053 2054 MessageReference node = iterator.next(); 2055 Subscription target = null; 2056 for (Subscription s : consumers) { 2057 if (s instanceof QueueBrowserSubscription) { 2058 continue; 2059 } 2060 if (!fullConsumers.contains(s)) { 2061 if (!s.isFull()) { 2062 if (dispatchSelector.canSelect(s, node) && assignMessageGroup(s, (QueueMessageReference)node) && !((QueueMessageReference) node).isAcked() ) { 2063 // Dispatch it. 2064 s.add(node); 2065 LOG.trace("assigned {} to consumer {}", node.getMessageId(), s.getConsumerInfo().getConsumerId()); 2066 iterator.remove(); 2067 target = s; 2068 break; 2069 } 2070 } else { 2071 // no further dispatch of list to a full consumer to 2072 // avoid out of order message receipt 2073 fullConsumers.add(s); 2074 LOG.trace("Subscription full {}", s); 2075 } 2076 } 2077 } 2078 2079 if (target == null && node.isDropped()) { 2080 iterator.remove(); 2081 } 2082 2083 // return if there are no consumers or all consumers are full 2084 if (target == null && consumers.size() == fullConsumers.size()) { 2085 return list; 2086 } 2087 2088 // If it got dispatched, rotate the consumer list to get round robin 2089 // distribution. 2090 if (target != null && !strictOrderDispatch && consumers.size() > 1 2091 && !dispatchSelector.isExclusiveConsumer(target)) { 2092 consumersLock.writeLock().lock(); 2093 try { 2094 if (removeFromConsumerList(target)) { 2095 addToConsumerList(target); 2096 consumers = new ArrayList<Subscription>(this.consumers); 2097 } 2098 } finally { 2099 consumersLock.writeLock().unlock(); 2100 } 2101 } 2102 } 2103 2104 return list; 2105 } 2106 2107 protected boolean assignMessageGroup(Subscription subscription, QueueMessageReference node) throws Exception { 2108 boolean result = true; 2109 // Keep message groups together. 2110 String groupId = node.getGroupID(); 2111 int sequence = node.getGroupSequence(); 2112 if (groupId != null) { 2113 2114 MessageGroupMap messageGroupOwners = getMessageGroupOwners(); 2115 // If we can own the first, then no-one else should own the 2116 // rest. 2117 if (sequence == 1) { 2118 assignGroup(subscription, messageGroupOwners, node, groupId); 2119 } else { 2120 2121 // Make sure that the previous owner is still valid, we may 2122 // need to become the new owner. 2123 ConsumerId groupOwner; 2124 2125 groupOwner = messageGroupOwners.get(groupId); 2126 if (groupOwner == null) { 2127 assignGroup(subscription, messageGroupOwners, node, groupId); 2128 } else { 2129 if (groupOwner.equals(subscription.getConsumerInfo().getConsumerId())) { 2130 // A group sequence < 1 is an end of group signal. 2131 if (sequence < 0) { 2132 messageGroupOwners.removeGroup(groupId); 2133 subscription.getConsumerInfo().decrementAssignedGroupCount(destination); 2134 } 2135 } else { 2136 result = false; 2137 } 2138 } 2139 } 2140 } 2141 2142 return result; 2143 } 2144 2145 protected void assignGroup(Subscription subs, MessageGroupMap messageGroupOwners, MessageReference n, String groupId) throws IOException { 2146 messageGroupOwners.put(groupId, subs.getConsumerInfo().getConsumerId()); 2147 Message message = n.getMessage(); 2148 message.setJMSXGroupFirstForConsumer(true); 2149 subs.getConsumerInfo().incrementAssignedGroupCount(destination); 2150 } 2151 2152 protected void pageInMessages(boolean force, int maxPageSize) throws Exception { 2153 doDispatch(doPageInForDispatch(force, true, maxPageSize)); 2154 } 2155 2156 private void addToConsumerList(Subscription sub) { 2157 if (useConsumerPriority) { 2158 consumers.add(sub); 2159 Collections.sort(consumers, orderedCompare); 2160 } else { 2161 consumers.add(sub); 2162 } 2163 } 2164 2165 private boolean removeFromConsumerList(Subscription sub) { 2166 return consumers.remove(sub); 2167 } 2168 2169 private int getConsumerMessageCountBeforeFull() throws Exception { 2170 int total = 0; 2171 consumersLock.readLock().lock(); 2172 try { 2173 for (Subscription s : consumers) { 2174 if (s.isBrowser()) { 2175 continue; 2176 } 2177 int countBeforeFull = s.countBeforeFull(); 2178 total += countBeforeFull; 2179 } 2180 } finally { 2181 consumersLock.readLock().unlock(); 2182 } 2183 return total; 2184 } 2185 2186 /* 2187 * In slave mode, dispatch is ignored till we get this notification as the 2188 * dispatch process is non deterministic between master and slave. On a 2189 * notification, the actual dispatch to the subscription (as chosen by the 2190 * master) is completed. (non-Javadoc) 2191 * @see 2192 * org.apache.activemq.broker.region.BaseDestination#processDispatchNotification 2193 * (org.apache.activemq.command.MessageDispatchNotification) 2194 */ 2195 @Override 2196 public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception { 2197 // do dispatch 2198 Subscription sub = getMatchingSubscription(messageDispatchNotification); 2199 if (sub != null) { 2200 MessageReference message = getMatchingMessage(messageDispatchNotification); 2201 sub.add(message); 2202 sub.processMessageDispatchNotification(messageDispatchNotification); 2203 } 2204 } 2205 2206 private QueueMessageReference getMatchingMessage(MessageDispatchNotification messageDispatchNotification) 2207 throws Exception { 2208 QueueMessageReference message = null; 2209 MessageId messageId = messageDispatchNotification.getMessageId(); 2210 2211 pagedInPendingDispatchLock.writeLock().lock(); 2212 try { 2213 for (MessageReference ref : dispatchPendingList) { 2214 if (messageId.equals(ref.getMessageId())) { 2215 message = (QueueMessageReference)ref; 2216 dispatchPendingList.remove(ref); 2217 break; 2218 } 2219 } 2220 } finally { 2221 pagedInPendingDispatchLock.writeLock().unlock(); 2222 } 2223 2224 if (message == null) { 2225 pagedInMessagesLock.readLock().lock(); 2226 try { 2227 message = (QueueMessageReference)pagedInMessages.get(messageId); 2228 } finally { 2229 pagedInMessagesLock.readLock().unlock(); 2230 } 2231 } 2232 2233 if (message == null) { 2234 messagesLock.writeLock().lock(); 2235 try { 2236 try { 2237 messages.setMaxBatchSize(getMaxPageSize()); 2238 messages.reset(); 2239 while (messages.hasNext()) { 2240 MessageReference node = messages.next(); 2241 messages.remove(); 2242 if (messageId.equals(node.getMessageId())) { 2243 message = this.createMessageReference(node.getMessage()); 2244 break; 2245 } 2246 } 2247 } finally { 2248 messages.release(); 2249 } 2250 } finally { 2251 messagesLock.writeLock().unlock(); 2252 } 2253 } 2254 2255 if (message == null) { 2256 Message msg = loadMessage(messageId); 2257 if (msg != null) { 2258 message = this.createMessageReference(msg); 2259 } 2260 } 2261 2262 if (message == null) { 2263 throw new JMSException("Slave broker out of sync with master - Message: " 2264 + messageDispatchNotification.getMessageId() + " on " 2265 + messageDispatchNotification.getDestination() + " does not exist among pending(" 2266 + dispatchPendingList.size() + ") for subscription: " 2267 + messageDispatchNotification.getConsumerId()); 2268 } 2269 return message; 2270 } 2271 2272 /** 2273 * Find a consumer that matches the id in the message dispatch notification 2274 * 2275 * @param messageDispatchNotification 2276 * @return sub or null if the subscription has been removed before dispatch 2277 * @throws JMSException 2278 */ 2279 private Subscription getMatchingSubscription(MessageDispatchNotification messageDispatchNotification) 2280 throws JMSException { 2281 Subscription sub = null; 2282 consumersLock.readLock().lock(); 2283 try { 2284 for (Subscription s : consumers) { 2285 if (messageDispatchNotification.getConsumerId().equals(s.getConsumerInfo().getConsumerId())) { 2286 sub = s; 2287 break; 2288 } 2289 } 2290 } finally { 2291 consumersLock.readLock().unlock(); 2292 } 2293 return sub; 2294 } 2295 2296 @Override 2297 public void onUsageChanged(@SuppressWarnings("rawtypes") Usage usage, int oldPercentUsage, int newPercentUsage) { 2298 if (oldPercentUsage > newPercentUsage) { 2299 asyncWakeup(); 2300 } 2301 } 2302 2303 @Override 2304 protected Logger getLog() { 2305 return LOG; 2306 } 2307 2308 protected boolean isOptimizeStorage(){ 2309 boolean result = false; 2310 if (isDoOptimzeMessageStorage()){ 2311 consumersLock.readLock().lock(); 2312 try{ 2313 if (consumers.isEmpty()==false){ 2314 result = true; 2315 for (Subscription s : consumers) { 2316 if (s.getPrefetchSize()==0){ 2317 result = false; 2318 break; 2319 } 2320 if (s.isSlowConsumer()){ 2321 result = false; 2322 break; 2323 } 2324 if (s.getInFlightUsage() > getOptimizeMessageStoreInFlightLimit()){ 2325 result = false; 2326 break; 2327 } 2328 } 2329 } 2330 } finally { 2331 consumersLock.readLock().unlock(); 2332 } 2333 } 2334 return result; 2335 } 2336}