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 static org.apache.activemq.broker.region.cursors.AbstractStoreCursor.gotToTheStore; 020import static org.apache.activemq.transaction.Transaction.IN_USE_STATE; 021 022import java.io.IOException; 023import java.util.ArrayList; 024import java.util.Collection; 025import java.util.Collections; 026import java.util.Comparator; 027import java.util.HashSet; 028import java.util.Iterator; 029import java.util.LinkedHashMap; 030import java.util.LinkedHashSet; 031import java.util.LinkedList; 032import java.util.List; 033import java.util.Map; 034import java.util.Set; 035import java.util.concurrent.CancellationException; 036import java.util.concurrent.ConcurrentLinkedQueue; 037import java.util.concurrent.CountDownLatch; 038import java.util.concurrent.DelayQueue; 039import java.util.concurrent.Delayed; 040import java.util.concurrent.ExecutorService; 041import java.util.concurrent.TimeUnit; 042import java.util.concurrent.atomic.AtomicInteger; 043import java.util.concurrent.atomic.AtomicLong; 044import java.util.concurrent.locks.Lock; 045import java.util.concurrent.locks.ReentrantLock; 046import java.util.concurrent.locks.ReentrantReadWriteLock; 047 048import javax.jms.InvalidSelectorException; 049import javax.jms.JMSException; 050import javax.jms.ResourceAllocationException; 051 052import org.apache.activemq.broker.BrokerService; 053import org.apache.activemq.broker.BrokerStoppedException; 054import org.apache.activemq.broker.ConnectionContext; 055import org.apache.activemq.broker.ProducerBrokerExchange; 056import org.apache.activemq.broker.region.cursors.OrderedPendingList; 057import org.apache.activemq.broker.region.cursors.PendingList; 058import org.apache.activemq.broker.region.cursors.PendingMessageCursor; 059import org.apache.activemq.broker.region.cursors.PrioritizedPendingList; 060import org.apache.activemq.broker.region.cursors.QueueDispatchPendingList; 061import org.apache.activemq.broker.region.cursors.StoreQueueCursor; 062import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor; 063import org.apache.activemq.broker.region.group.CachedMessageGroupMapFactory; 064import org.apache.activemq.broker.region.group.MessageGroupMap; 065import org.apache.activemq.broker.region.group.MessageGroupMapFactory; 066import org.apache.activemq.broker.region.policy.DeadLetterStrategy; 067import org.apache.activemq.broker.region.policy.DispatchPolicy; 068import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy; 069import org.apache.activemq.broker.util.InsertionCountList; 070import org.apache.activemq.command.ActiveMQDestination; 071import org.apache.activemq.command.ConsumerId; 072import org.apache.activemq.command.ExceptionResponse; 073import org.apache.activemq.command.Message; 074import org.apache.activemq.command.MessageAck; 075import org.apache.activemq.command.MessageDispatchNotification; 076import org.apache.activemq.command.MessageId; 077import org.apache.activemq.command.ProducerAck; 078import org.apache.activemq.command.ProducerInfo; 079import org.apache.activemq.command.RemoveInfo; 080import org.apache.activemq.command.Response; 081import org.apache.activemq.filter.BooleanExpression; 082import org.apache.activemq.filter.MessageEvaluationContext; 083import org.apache.activemq.filter.NonCachedMessageEvaluationContext; 084import org.apache.activemq.selector.SelectorParser; 085import org.apache.activemq.state.ProducerState; 086import org.apache.activemq.store.IndexListener; 087import org.apache.activemq.store.ListenableFuture; 088import org.apache.activemq.store.MessageRecoveryListener; 089import org.apache.activemq.store.MessageStore; 090import org.apache.activemq.thread.Task; 091import org.apache.activemq.thread.TaskRunner; 092import org.apache.activemq.thread.TaskRunnerFactory; 093import org.apache.activemq.transaction.Synchronization; 094import org.apache.activemq.usage.Usage; 095import org.apache.activemq.usage.UsageListener; 096import org.apache.activemq.util.BrokerSupport; 097import org.apache.activemq.util.ThreadPoolUtils; 098import org.slf4j.Logger; 099import org.slf4j.LoggerFactory; 100import org.slf4j.MDC; 101 102/** 103 * The Queue is a List of MessageEntry objects that are dispatched to matching 104 * subscriptions. 105 */ 106public class Queue extends BaseDestination implements Task, UsageListener, IndexListener { 107 protected static final Logger LOG = LoggerFactory.getLogger(Queue.class); 108 protected final TaskRunnerFactory taskFactory; 109 protected TaskRunner taskRunner; 110 private final ReentrantReadWriteLock consumersLock = new ReentrantReadWriteLock(); 111 protected final List<Subscription> consumers = new ArrayList<Subscription>(50); 112 private final ReentrantReadWriteLock messagesLock = new ReentrantReadWriteLock(); 113 protected PendingMessageCursor messages; 114 private final ReentrantReadWriteLock pagedInMessagesLock = new ReentrantReadWriteLock(); 115 private final PendingList pagedInMessages = new OrderedPendingList(); 116 // Messages that are paged in but have not yet been targeted at a subscription 117 private final ReentrantReadWriteLock pagedInPendingDispatchLock = new ReentrantReadWriteLock(); 118 protected QueueDispatchPendingList dispatchPendingList = new QueueDispatchPendingList(); 119 private AtomicInteger pendingSends = new AtomicInteger(0); 120 private MessageGroupMap messageGroupOwners; 121 private DispatchPolicy dispatchPolicy = new RoundRobinDispatchPolicy(); 122 private MessageGroupMapFactory messageGroupMapFactory = new CachedMessageGroupMapFactory(); 123 final Lock sendLock = new ReentrantLock(); 124 private ExecutorService executor; 125 private final Map<MessageId, Runnable> messagesWaitingForSpace = new LinkedHashMap<MessageId, Runnable>(); 126 private boolean useConsumerPriority = true; 127 private boolean strictOrderDispatch = false; 128 private final QueueDispatchSelector dispatchSelector; 129 private boolean optimizedDispatch = false; 130 private boolean iterationRunning = false; 131 private boolean firstConsumer = false; 132 private int timeBeforeDispatchStarts = 0; 133 private int consumersBeforeDispatchStarts = 0; 134 private CountDownLatch consumersBeforeStartsLatch; 135 private final AtomicLong pendingWakeups = new AtomicLong(); 136 private boolean allConsumersExclusiveByDefault = false; 137 138 private volatile 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 store.start(); 393 final int messageCount = store.getMessageCount(); 394 if (messageCount > 0 && messages.isRecoveryRequired()) { 395 BatchMessageRecoveryListener listener = new BatchMessageRecoveryListener(messageCount); 396 do { 397 listener.reset(); 398 store.recoverNextMessages(getMaxPageSize(), listener); 399 listener.processExpired(); 400 } while (!listener.done()); 401 } else { 402 destinationStatistics.getMessages().add(messageCount); 403 } 404 } 405 } 406 407 /* 408 * Holder for subscription that needs attention on next iterate browser 409 * needs access to existing messages in the queue that have already been 410 * dispatched 411 */ 412 class BrowserDispatch { 413 QueueBrowserSubscription browser; 414 415 public BrowserDispatch(QueueBrowserSubscription browserSubscription) { 416 browser = browserSubscription; 417 browser.incrementQueueRef(); 418 } 419 420 public QueueBrowserSubscription getBrowser() { 421 return browser; 422 } 423 } 424 425 ConcurrentLinkedQueue<BrowserDispatch> browserDispatches = new ConcurrentLinkedQueue<BrowserDispatch>(); 426 427 @Override 428 public void addSubscription(ConnectionContext context, Subscription sub) throws Exception { 429 LOG.debug("{} add sub: {}, dequeues: {}, dispatched: {}, inflight: {}", new Object[]{ getActiveMQDestination().getQualifiedName(), sub, getDestinationStatistics().getDequeues().getCount(), getDestinationStatistics().getDispatched().getCount(), getDestinationStatistics().getInflight().getCount() }); 430 431 super.addSubscription(context, sub); 432 // synchronize with dispatch method so that no new messages are sent 433 // while setting up a subscription. avoid out of order messages, 434 // duplicates, etc. 435 pagedInPendingDispatchLock.writeLock().lock(); 436 try { 437 438 sub.add(context, this); 439 440 // needs to be synchronized - so no contention with dispatching 441 // consumersLock. 442 consumersLock.writeLock().lock(); 443 try { 444 // set a flag if this is a first consumer 445 if (consumers.size() == 0) { 446 firstConsumer = true; 447 if (consumersBeforeDispatchStarts != 0) { 448 consumersBeforeStartsLatch = new CountDownLatch(consumersBeforeDispatchStarts - 1); 449 } 450 } else { 451 if (consumersBeforeStartsLatch != null) { 452 consumersBeforeStartsLatch.countDown(); 453 } 454 } 455 456 addToConsumerList(sub); 457 if (sub.getConsumerInfo().isExclusive() || isAllConsumersExclusiveByDefault()) { 458 Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer(); 459 if (exclusiveConsumer == null) { 460 exclusiveConsumer = sub; 461 } else if (sub.getConsumerInfo().getPriority() == Byte.MAX_VALUE || 462 sub.getConsumerInfo().getPriority() > exclusiveConsumer.getConsumerInfo().getPriority()) { 463 exclusiveConsumer = sub; 464 } 465 dispatchSelector.setExclusiveConsumer(exclusiveConsumer); 466 } 467 } finally { 468 consumersLock.writeLock().unlock(); 469 } 470 471 if (sub instanceof QueueBrowserSubscription) { 472 // tee up for dispatch in next iterate 473 QueueBrowserSubscription browserSubscription = (QueueBrowserSubscription) sub; 474 BrowserDispatch browserDispatch = new BrowserDispatch(browserSubscription); 475 browserDispatches.add(browserDispatch); 476 } 477 478 if (!this.optimizedDispatch) { 479 wakeup(); 480 } 481 } finally { 482 pagedInPendingDispatchLock.writeLock().unlock(); 483 } 484 if (this.optimizedDispatch) { 485 // Outside of dispatchLock() to maintain the lock hierarchy of 486 // iteratingMutex -> dispatchLock. - see 487 // https://issues.apache.org/activemq/browse/AMQ-1878 488 wakeup(); 489 } 490 } 491 492 @Override 493 public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId) 494 throws Exception { 495 super.removeSubscription(context, sub, lastDeliveredSequenceId); 496 // synchronize with dispatch method so that no new messages are sent 497 // while removing up a subscription. 498 pagedInPendingDispatchLock.writeLock().lock(); 499 try { 500 LOG.debug("{} remove sub: {}, lastDeliveredSeqId: {}, dequeues: {}, dispatched: {}, inflight: {}, groups: {}", new Object[]{ 501 getActiveMQDestination().getQualifiedName(), 502 sub, 503 lastDeliveredSequenceId, 504 getDestinationStatistics().getDequeues().getCount(), 505 getDestinationStatistics().getDispatched().getCount(), 506 getDestinationStatistics().getInflight().getCount(), 507 sub.getConsumerInfo().getAssignedGroupCount(destination) 508 }); 509 consumersLock.writeLock().lock(); 510 try { 511 removeFromConsumerList(sub); 512 if (sub.getConsumerInfo().isExclusive()) { 513 Subscription exclusiveConsumer = dispatchSelector.getExclusiveConsumer(); 514 if (exclusiveConsumer == sub) { 515 exclusiveConsumer = null; 516 for (Subscription s : consumers) { 517 if (s.getConsumerInfo().isExclusive() 518 && (exclusiveConsumer == null || s.getConsumerInfo().getPriority() > exclusiveConsumer 519 .getConsumerInfo().getPriority())) { 520 exclusiveConsumer = s; 521 522 } 523 } 524 dispatchSelector.setExclusiveConsumer(exclusiveConsumer); 525 } 526 } else if (isAllConsumersExclusiveByDefault()) { 527 Subscription exclusiveConsumer = null; 528 for (Subscription s : consumers) { 529 if (exclusiveConsumer == null 530 || s.getConsumerInfo().getPriority() > exclusiveConsumer 531 .getConsumerInfo().getPriority()) { 532 exclusiveConsumer = s; 533 } 534 } 535 dispatchSelector.setExclusiveConsumer(exclusiveConsumer); 536 } 537 ConsumerId consumerId = sub.getConsumerInfo().getConsumerId(); 538 getMessageGroupOwners().removeConsumer(consumerId); 539 540 // redeliver inflight messages 541 542 boolean markAsRedelivered = false; 543 MessageReference lastDeliveredRef = null; 544 List<MessageReference> unAckedMessages = sub.remove(context, this); 545 546 // locate last redelivered in unconsumed list (list in delivery rather than seq order) 547 if (lastDeliveredSequenceId > RemoveInfo.LAST_DELIVERED_UNSET) { 548 for (MessageReference ref : unAckedMessages) { 549 if (ref.getMessageId().getBrokerSequenceId() == lastDeliveredSequenceId) { 550 lastDeliveredRef = ref; 551 markAsRedelivered = true; 552 LOG.debug("found lastDeliveredSeqID: {}, message reference: {}", lastDeliveredSequenceId, ref.getMessageId()); 553 break; 554 } 555 } 556 } 557 558 for (Iterator<MessageReference> unackedListIterator = unAckedMessages.iterator(); unackedListIterator.hasNext(); ) { 559 MessageReference ref = unackedListIterator.next(); 560 // AMQ-5107: don't resend if the broker is shutting down 561 if ( this.brokerService.isStopping() ) { 562 break; 563 } 564 QueueMessageReference qmr = (QueueMessageReference) ref; 565 if (qmr.getLockOwner() == sub) { 566 qmr.unlock(); 567 568 // have no delivery information 569 if (lastDeliveredSequenceId == RemoveInfo.LAST_DELIVERED_UNKNOWN) { 570 qmr.incrementRedeliveryCounter(); 571 } else { 572 if (markAsRedelivered) { 573 qmr.incrementRedeliveryCounter(); 574 } 575 if (ref == lastDeliveredRef) { 576 // all that follow were not redelivered 577 markAsRedelivered = false; 578 } 579 } 580 } 581 if (qmr.isDropped()) { 582 unackedListIterator.remove(); 583 } 584 } 585 dispatchPendingList.addForRedelivery(unAckedMessages, strictOrderDispatch && consumers.isEmpty()); 586 if (sub instanceof QueueBrowserSubscription) { 587 ((QueueBrowserSubscription)sub).decrementQueueRef(); 588 browserDispatches.remove(sub); 589 } 590 // AMQ-5107: don't resend if the broker is shutting down 591 if (dispatchPendingList.hasRedeliveries() && (! this.brokerService.isStopping())) { 592 doDispatch(new OrderedPendingList()); 593 } 594 } finally { 595 consumersLock.writeLock().unlock(); 596 } 597 if (!this.optimizedDispatch) { 598 wakeup(); 599 } 600 } finally { 601 pagedInPendingDispatchLock.writeLock().unlock(); 602 } 603 if (this.optimizedDispatch) { 604 // Outside of dispatchLock() to maintain the lock hierarchy of 605 // iteratingMutex -> dispatchLock. - see 606 // https://issues.apache.org/activemq/browse/AMQ-1878 607 wakeup(); 608 } 609 } 610 611 @Override 612 public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { 613 final ConnectionContext context = producerExchange.getConnectionContext(); 614 // There is delay between the client sending it and it arriving at the 615 // destination.. it may have expired. 616 message.setRegionDestination(this); 617 ProducerState state = producerExchange.getProducerState(); 618 if (state == null) { 619 LOG.warn("Send failed for: {}, missing producer state for: {}", message, producerExchange); 620 throw new JMSException("Cannot send message to " + getActiveMQDestination() + " with invalid (null) producer state"); 621 } 622 final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); 623 final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 624 && !context.isInRecoveryMode(); 625 if (message.isExpired()) { 626 // message not stored - or added to stats yet - so chuck here 627 broker.getRoot().messageExpired(context, message, null); 628 if (sendProducerAck) { 629 ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); 630 context.getConnection().dispatchAsync(ack); 631 } 632 return; 633 } 634 if (memoryUsage.isFull()) { 635 isFull(context, memoryUsage); 636 fastProducer(context, producerInfo); 637 if (isProducerFlowControl() && context.isProducerFlowControl()) { 638 if (isFlowControlLogRequired()) { 639 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.", 640 memoryUsage.getLimit(), getActiveMQDestination().getQualifiedName(), destinationStatistics.getMessages().getCount()); 641 642 } 643 if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) { 644 throw new ResourceAllocationException("Usage Manager Memory Limit reached. Stopping producer (" 645 + message.getProducerId() + ") to prevent flooding " 646 + getActiveMQDestination().getQualifiedName() + "." 647 + " See http://activemq.apache.org/producer-flow-control.html for more info"); 648 } 649 650 // We can avoid blocking due to low usage if the producer is 651 // sending 652 // a sync message or if it is using a producer window 653 if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) { 654 // copy the exchange state since the context will be 655 // modified while we are waiting 656 // for space. 657 final ProducerBrokerExchange producerExchangeCopy = producerExchange.copy(); 658 synchronized (messagesWaitingForSpace) { 659 // Start flow control timeout task 660 // Prevent trying to start it multiple times 661 if (!flowControlTimeoutTask.isAlive()) { 662 flowControlTimeoutTask.setName(getName()+" Producer Flow Control Timeout Task"); 663 flowControlTimeoutTask.start(); 664 } 665 messagesWaitingForSpace.put(message.getMessageId(), new Runnable() { 666 @Override 667 public void run() { 668 669 try { 670 // While waiting for space to free up... the 671 // transaction may be done 672 if (message.isInTransaction()) { 673 if (context.getTransaction() == null || context.getTransaction().getState() > IN_USE_STATE) { 674 throw new JMSException("Send transaction completed while waiting for space"); 675 } 676 } 677 678 // the message may have expired. 679 if (message.isExpired()) { 680 LOG.error("message 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 do { 844 checkUsage(context, producerExchange, message); 845 message.getMessageId().setBrokerSequenceId(getDestinationSequenceId()); 846 if (store != null && message.isPersistent()) { 847 message.getMessageId().setFutureOrSequenceLong(null); 848 try { 849 //AMQ-6133 - don't store async if using persistJMSRedelivered 850 //This flag causes a sync update later on dispatch which can cause a race 851 //condition if the original add is processed after the update, which can cause 852 //a duplicate message to be stored 853 if (messages.isCacheEnabled() && !isPersistJMSRedelivered()) { 854 result = store.asyncAddQueueMessage(context, message, isOptimizeStorage()); 855 result.addListener(new PendingMarshalUsageTracker(message)); 856 } else { 857 store.addMessage(context, message); 858 } 859 } catch (Exception e) { 860 // we may have a store in inconsistent state, so reset the cursor 861 // before restarting normal broker operations 862 resetNeeded = true; 863 pendingSends.decrementAndGet(); 864 throw e; 865 } 866 } 867 868 //Clear the unmarshalled state if the message is marshalled 869 //Persistent messages will always be marshalled but non-persistent may not be 870 //Specially non-persistent messages over the VM transport won't be 871 if (isReduceMemoryFootprint() && message.isMarshalled()) { 872 message.clearUnMarshalledState(); 873 } 874 if(tryOrderedCursorAdd(message, context)) { 875 break; 876 } 877 } while (started.get()); 878 879 if (result != null && message.isResponseRequired() && !result.isCancelled()) { 880 try { 881 result.get(); 882 } catch (CancellationException e) { 883 // ignore - the task has been cancelled if the message 884 // has already been deleted 885 } 886 } 887 } 888 889 private boolean tryOrderedCursorAdd(Message message, ConnectionContext context) throws Exception { 890 boolean result = true; 891 892 if (context.isInTransaction()) { 893 context.getTransaction().addSynchronization(new CursorAddSync(new MessageContext(context, message, null))); 894 } else if (store != null && message.isPersistent()) { 895 doPendingCursorAdditions(); 896 } else { 897 // no ordering issue with non persistent messages 898 result = tryCursorAdd(message); 899 messageSent(context, message); 900 } 901 902 return result; 903 } 904 905 private void checkUsage(ConnectionContext context,ProducerBrokerExchange producerBrokerExchange, Message message) throws ResourceAllocationException, IOException, InterruptedException { 906 if (message.isPersistent()) { 907 if (store != null && systemUsage.getStoreUsage().isFull(getStoreUsageHighWaterMark())) { 908 final String logMessage = "Persistent store is Full, " + getStoreUsageHighWaterMark() + "% of " 909 + systemUsage.getStoreUsage().getLimit() + ". Stopping producer (" 910 + message.getProducerId() + ") to prevent flooding " 911 + getActiveMQDestination().getQualifiedName() + "." 912 + " See http://activemq.apache.org/producer-flow-control.html for more info"; 913 914 waitForSpace(context, producerBrokerExchange, systemUsage.getStoreUsage(), getStoreUsageHighWaterMark(), logMessage); 915 } 916 } else if (messages.getSystemUsage() != null && systemUsage.getTempUsage().isFull()) { 917 final String logMessage = "Temp Store is Full (" 918 + systemUsage.getTempUsage().getPercentUsage() + "% of " + systemUsage.getTempUsage().getLimit() 919 +"). Stopping producer (" + message.getProducerId() 920 + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." 921 + " See http://activemq.apache.org/producer-flow-control.html for more info"; 922 923 waitForSpace(context, producerBrokerExchange, messages.getSystemUsage().getTempUsage(), logMessage); 924 } 925 } 926 927 private void expireMessages() { 928 LOG.debug("{} expiring messages ..", getActiveMQDestination().getQualifiedName()); 929 930 // just track the insertion count 931 List<Message> browsedMessages = new InsertionCountList<Message>(); 932 doBrowse(browsedMessages, this.getMaxExpirePageSize()); 933 asyncWakeup(); 934 LOG.debug("{} expiring messages done.", getActiveMQDestination().getQualifiedName()); 935 } 936 937 @Override 938 public void gc() { 939 } 940 941 @Override 942 public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) 943 throws IOException { 944 messageConsumed(context, node); 945 if (store != null && node.isPersistent()) { 946 store.removeAsyncMessage(context, convertToNonRangedAck(ack, node)); 947 } 948 } 949 950 Message loadMessage(MessageId messageId) throws IOException { 951 Message msg = null; 952 if (store != null) { // can be null for a temp q 953 msg = store.getMessage(messageId); 954 if (msg != null) { 955 msg.setRegionDestination(this); 956 } 957 } 958 return msg; 959 } 960 961 public long getPendingMessageSize() { 962 messagesLock.readLock().lock(); 963 try{ 964 return messages.messageSize(); 965 } finally { 966 messagesLock.readLock().unlock(); 967 } 968 } 969 970 public long getPendingMessageCount() { 971 return this.destinationStatistics.getMessages().getCount(); 972 } 973 974 @Override 975 public String toString() { 976 return destination.getQualifiedName() + ", subscriptions=" + consumers.size() 977 + ", memory=" + memoryUsage.getPercentUsage() + "%, size=" + destinationStatistics.getMessages().getCount() + ", pending=" 978 + indexOrderedCursorUpdates.size(); 979 } 980 981 @Override 982 public void start() throws Exception { 983 if (started.compareAndSet(false, true)) { 984 if (memoryUsage != null) { 985 memoryUsage.start(); 986 } 987 if (systemUsage.getStoreUsage() != null) { 988 systemUsage.getStoreUsage().start(); 989 } 990 if (systemUsage.getTempUsage() != null) { 991 systemUsage.getTempUsage().start(); 992 } 993 systemUsage.getMemoryUsage().addUsageListener(this); 994 messages.start(); 995 if (getExpireMessagesPeriod() > 0) { 996 scheduler.executePeriodically(expireMessagesTask, getExpireMessagesPeriod()); 997 } 998 doPageIn(false); 999 } 1000 } 1001 1002 @Override 1003 public void stop() throws Exception { 1004 if (started.compareAndSet(true, false)) { 1005 if (taskRunner != null) { 1006 taskRunner.shutdown(); 1007 } 1008 if (this.executor != null) { 1009 ThreadPoolUtils.shutdownNow(executor); 1010 executor = null; 1011 } 1012 1013 scheduler.cancel(expireMessagesTask); 1014 1015 if (flowControlTimeoutTask.isAlive()) { 1016 flowControlTimeoutTask.interrupt(); 1017 } 1018 1019 if (messages != null) { 1020 messages.stop(); 1021 } 1022 1023 for (MessageReference messageReference : pagedInMessages.values()) { 1024 messageReference.decrementReferenceCount(); 1025 } 1026 pagedInMessages.clear(); 1027 1028 systemUsage.getMemoryUsage().removeUsageListener(this); 1029 if (memoryUsage != null) { 1030 memoryUsage.stop(); 1031 } 1032 if (systemUsage.getStoreUsage() != null) { 1033 systemUsage.getStoreUsage().stop(); 1034 } 1035 if (store != null) { 1036 store.stop(); 1037 } 1038 } 1039 } 1040 1041 // Properties 1042 // ------------------------------------------------------------------------- 1043 @Override 1044 public ActiveMQDestination getActiveMQDestination() { 1045 return destination; 1046 } 1047 1048 public MessageGroupMap getMessageGroupOwners() { 1049 if (messageGroupOwners == null) { 1050 messageGroupOwners = getMessageGroupMapFactory().createMessageGroupMap(); 1051 messageGroupOwners.setDestination(this); 1052 } 1053 return messageGroupOwners; 1054 } 1055 1056 public DispatchPolicy getDispatchPolicy() { 1057 return dispatchPolicy; 1058 } 1059 1060 public void setDispatchPolicy(DispatchPolicy dispatchPolicy) { 1061 this.dispatchPolicy = dispatchPolicy; 1062 } 1063 1064 public MessageGroupMapFactory getMessageGroupMapFactory() { 1065 return messageGroupMapFactory; 1066 } 1067 1068 public void setMessageGroupMapFactory(MessageGroupMapFactory messageGroupMapFactory) { 1069 this.messageGroupMapFactory = messageGroupMapFactory; 1070 } 1071 1072 public PendingMessageCursor getMessages() { 1073 return this.messages; 1074 } 1075 1076 public void setMessages(PendingMessageCursor messages) { 1077 this.messages = messages; 1078 } 1079 1080 public boolean isUseConsumerPriority() { 1081 return useConsumerPriority; 1082 } 1083 1084 public void setUseConsumerPriority(boolean useConsumerPriority) { 1085 this.useConsumerPriority = useConsumerPriority; 1086 } 1087 1088 public boolean isStrictOrderDispatch() { 1089 return strictOrderDispatch; 1090 } 1091 1092 public void setStrictOrderDispatch(boolean strictOrderDispatch) { 1093 this.strictOrderDispatch = strictOrderDispatch; 1094 } 1095 1096 public boolean isOptimizedDispatch() { 1097 return optimizedDispatch; 1098 } 1099 1100 public void setOptimizedDispatch(boolean optimizedDispatch) { 1101 this.optimizedDispatch = optimizedDispatch; 1102 } 1103 1104 public int getTimeBeforeDispatchStarts() { 1105 return timeBeforeDispatchStarts; 1106 } 1107 1108 public void setTimeBeforeDispatchStarts(int timeBeforeDispatchStarts) { 1109 this.timeBeforeDispatchStarts = timeBeforeDispatchStarts; 1110 } 1111 1112 public int getConsumersBeforeDispatchStarts() { 1113 return consumersBeforeDispatchStarts; 1114 } 1115 1116 public void setConsumersBeforeDispatchStarts(int consumersBeforeDispatchStarts) { 1117 this.consumersBeforeDispatchStarts = consumersBeforeDispatchStarts; 1118 } 1119 1120 public void setAllConsumersExclusiveByDefault(boolean allConsumersExclusiveByDefault) { 1121 this.allConsumersExclusiveByDefault = allConsumersExclusiveByDefault; 1122 } 1123 1124 public boolean isAllConsumersExclusiveByDefault() { 1125 return allConsumersExclusiveByDefault; 1126 } 1127 1128 public boolean isResetNeeded() { 1129 return resetNeeded; 1130 } 1131 1132 // Implementation methods 1133 // ------------------------------------------------------------------------- 1134 private QueueMessageReference createMessageReference(Message message) { 1135 QueueMessageReference result = new IndirectMessageReference(message); 1136 return result; 1137 } 1138 1139 @Override 1140 public Message[] browse() { 1141 List<Message> browseList = new ArrayList<Message>(); 1142 doBrowse(browseList, getMaxBrowsePageSize()); 1143 return browseList.toArray(new Message[browseList.size()]); 1144 } 1145 1146 public void doBrowse(List<Message> browseList, int max) { 1147 final ConnectionContext connectionContext = createConnectionContext(); 1148 try { 1149 int maxPageInAttempts = 1; 1150 if (max > 0) { 1151 messagesLock.readLock().lock(); 1152 try { 1153 maxPageInAttempts += (messages.size() / max); 1154 } finally { 1155 messagesLock.readLock().unlock(); 1156 } 1157 while (shouldPageInMoreForBrowse(max) && maxPageInAttempts-- > 0) { 1158 pageInMessages(!memoryUsage.isFull(110), max); 1159 } 1160 } 1161 doBrowseList(browseList, max, dispatchPendingList, pagedInPendingDispatchLock, connectionContext, "redeliveredWaitingDispatch+pagedInPendingDispatch"); 1162 doBrowseList(browseList, max, pagedInMessages, pagedInMessagesLock, connectionContext, "pagedInMessages"); 1163 1164 // we need a store iterator to walk messages on disk, independent of the cursor which is tracking 1165 // the next message batch 1166 } catch (BrokerStoppedException ignored) { 1167 } catch (Exception e) { 1168 LOG.error("Problem retrieving message for browse", e); 1169 } 1170 } 1171 1172 protected void doBrowseList(List<Message> browseList, int max, PendingList list, ReentrantReadWriteLock lock, ConnectionContext connectionContext, String name) throws Exception { 1173 List<MessageReference> toExpire = new ArrayList<MessageReference>(); 1174 lock.readLock().lock(); 1175 try { 1176 addAll(list.values(), browseList, max, toExpire); 1177 } finally { 1178 lock.readLock().unlock(); 1179 } 1180 for (MessageReference ref : toExpire) { 1181 if (broker.isExpired(ref)) { 1182 LOG.debug("expiring from {}: {}", name, ref); 1183 messageExpired(connectionContext, ref); 1184 } else { 1185 lock.writeLock().lock(); 1186 try { 1187 list.remove(ref); 1188 } finally { 1189 lock.writeLock().unlock(); 1190 } 1191 ref.decrementReferenceCount(); 1192 } 1193 } 1194 } 1195 1196 private boolean shouldPageInMoreForBrowse(int max) { 1197 int alreadyPagedIn = 0; 1198 pagedInMessagesLock.readLock().lock(); 1199 try { 1200 alreadyPagedIn = pagedInMessages.size(); 1201 } finally { 1202 pagedInMessagesLock.readLock().unlock(); 1203 } 1204 int messagesInQueue = alreadyPagedIn; 1205 messagesLock.readLock().lock(); 1206 try { 1207 messagesInQueue += messages.size(); 1208 } finally { 1209 messagesLock.readLock().unlock(); 1210 } 1211 1212 LOG.trace("max {}, alreadyPagedIn {}, messagesCount {}, memoryUsage {}%", new Object[]{max, alreadyPagedIn, messagesInQueue, memoryUsage.getPercentUsage()}); 1213 return (alreadyPagedIn == 0 || (alreadyPagedIn < max) 1214 && (alreadyPagedIn < messagesInQueue) 1215 && messages.hasSpace()); 1216 } 1217 1218 private void addAll(Collection<? extends MessageReference> refs, List<Message> l, int max, 1219 List<MessageReference> toExpire) throws Exception { 1220 for (Iterator<? extends MessageReference> i = refs.iterator(); i.hasNext() && l.size() < max;) { 1221 QueueMessageReference ref = (QueueMessageReference) i.next(); 1222 if (ref.isExpired() && (ref.getLockOwner() == null)) { 1223 toExpire.add(ref); 1224 } else if (l.contains(ref.getMessage()) == false) { 1225 l.add(ref.getMessage()); 1226 } 1227 } 1228 } 1229 1230 public QueueMessageReference getMessage(String id) { 1231 MessageId msgId = new MessageId(id); 1232 pagedInMessagesLock.readLock().lock(); 1233 try { 1234 QueueMessageReference ref = (QueueMessageReference)this.pagedInMessages.get(msgId); 1235 if (ref != null) { 1236 return ref; 1237 } 1238 } finally { 1239 pagedInMessagesLock.readLock().unlock(); 1240 } 1241 messagesLock.writeLock().lock(); 1242 try{ 1243 try { 1244 messages.reset(); 1245 while (messages.hasNext()) { 1246 MessageReference mr = messages.next(); 1247 QueueMessageReference qmr = createMessageReference(mr.getMessage()); 1248 qmr.decrementReferenceCount(); 1249 messages.rollback(qmr.getMessageId()); 1250 if (msgId.equals(qmr.getMessageId())) { 1251 return qmr; 1252 } 1253 } 1254 } finally { 1255 messages.release(); 1256 } 1257 }finally { 1258 messagesLock.writeLock().unlock(); 1259 } 1260 return null; 1261 } 1262 1263 public void purge() throws Exception { 1264 ConnectionContext c = createConnectionContext(); 1265 List<MessageReference> list = null; 1266 try { 1267 sendLock.lock(); 1268 long originalMessageCount = this.destinationStatistics.getMessages().getCount(); 1269 do { 1270 doPageIn(true, false, getMaxPageSize()); // signal no expiry processing needed. 1271 pagedInMessagesLock.readLock().lock(); 1272 try { 1273 list = new ArrayList<MessageReference>(pagedInMessages.values()); 1274 }finally { 1275 pagedInMessagesLock.readLock().unlock(); 1276 } 1277 1278 for (MessageReference ref : list) { 1279 try { 1280 QueueMessageReference r = (QueueMessageReference) ref; 1281 removeMessage(c, r); 1282 } catch (IOException e) { 1283 } 1284 } 1285 // don't spin/hang if stats are out and there is nothing left in the 1286 // store 1287 } while (!list.isEmpty() && this.destinationStatistics.getMessages().getCount() > 0); 1288 1289 if (getMessages().getMessageAudit() != null) { 1290 getMessages().getMessageAudit().clear(); 1291 } 1292 1293 if (this.destinationStatistics.getMessages().getCount() > 0) { 1294 LOG.warn("{} after purge of {} messages, message count stats report: {}", getActiveMQDestination().getQualifiedName(), originalMessageCount, this.destinationStatistics.getMessages().getCount()); 1295 } 1296 } finally { 1297 sendLock.unlock(); 1298 } 1299 } 1300 1301 @Override 1302 public void clearPendingMessages() { 1303 messagesLock.writeLock().lock(); 1304 try { 1305 if (resetNeeded) { 1306 messages.gc(); 1307 messages.reset(); 1308 resetNeeded = false; 1309 } else { 1310 messages.rebase(); 1311 } 1312 asyncWakeup(); 1313 } finally { 1314 messagesLock.writeLock().unlock(); 1315 } 1316 } 1317 1318 /** 1319 * Removes the message matching the given messageId 1320 */ 1321 public boolean removeMessage(String messageId) throws Exception { 1322 return removeMatchingMessages(createMessageIdFilter(messageId), 1) > 0; 1323 } 1324 1325 /** 1326 * Removes the messages matching the given selector 1327 * 1328 * @return the number of messages removed 1329 */ 1330 public int removeMatchingMessages(String selector) throws Exception { 1331 return removeMatchingMessages(selector, -1); 1332 } 1333 1334 /** 1335 * Removes the messages matching the given selector up to the maximum number 1336 * of matched messages 1337 * 1338 * @return the number of messages removed 1339 */ 1340 public int removeMatchingMessages(String selector, int maximumMessages) throws Exception { 1341 return removeMatchingMessages(createSelectorFilter(selector), maximumMessages); 1342 } 1343 1344 /** 1345 * Removes the messages matching the given filter up to the maximum number 1346 * of matched messages 1347 * 1348 * @return the number of messages removed 1349 */ 1350 public int removeMatchingMessages(MessageReferenceFilter filter, int maximumMessages) throws Exception { 1351 int movedCounter = 0; 1352 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1353 ConnectionContext context = createConnectionContext(); 1354 do { 1355 doPageIn(true); 1356 pagedInMessagesLock.readLock().lock(); 1357 try { 1358 set.addAll(pagedInMessages.values()); 1359 } finally { 1360 pagedInMessagesLock.readLock().unlock(); 1361 } 1362 List<MessageReference> list = new ArrayList<MessageReference>(set); 1363 for (MessageReference ref : list) { 1364 IndirectMessageReference r = (IndirectMessageReference) ref; 1365 if (filter.evaluate(context, r)) { 1366 1367 removeMessage(context, r); 1368 set.remove(r); 1369 if (++movedCounter >= maximumMessages && maximumMessages > 0) { 1370 return movedCounter; 1371 } 1372 } 1373 } 1374 } while (set.size() < this.destinationStatistics.getMessages().getCount()); 1375 return movedCounter; 1376 } 1377 1378 /** 1379 * Copies the message matching the given messageId 1380 */ 1381 public boolean copyMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest) 1382 throws Exception { 1383 return copyMatchingMessages(context, createMessageIdFilter(messageId), dest, 1) > 0; 1384 } 1385 1386 /** 1387 * Copies the messages matching the given selector 1388 * 1389 * @return the number of messages copied 1390 */ 1391 public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest) 1392 throws Exception { 1393 return copyMatchingMessagesTo(context, selector, dest, -1); 1394 } 1395 1396 /** 1397 * Copies the messages matching the given selector up to the maximum number 1398 * of matched messages 1399 * 1400 * @return the number of messages copied 1401 */ 1402 public int copyMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest, 1403 int maximumMessages) throws Exception { 1404 return copyMatchingMessages(context, createSelectorFilter(selector), dest, maximumMessages); 1405 } 1406 1407 /** 1408 * Copies the messages matching the given filter up to the maximum number of 1409 * matched messages 1410 * 1411 * @return the number of messages copied 1412 */ 1413 public int copyMatchingMessages(ConnectionContext context, MessageReferenceFilter filter, ActiveMQDestination dest, 1414 int maximumMessages) throws Exception { 1415 1416 if (destination.equals(dest)) { 1417 return 0; 1418 } 1419 1420 int movedCounter = 0; 1421 int count = 0; 1422 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1423 do { 1424 int oldMaxSize = getMaxPageSize(); 1425 setMaxPageSize((int) this.destinationStatistics.getMessages().getCount()); 1426 doPageIn(true); 1427 setMaxPageSize(oldMaxSize); 1428 pagedInMessagesLock.readLock().lock(); 1429 try { 1430 set.addAll(pagedInMessages.values()); 1431 } finally { 1432 pagedInMessagesLock.readLock().unlock(); 1433 } 1434 List<MessageReference> list = new ArrayList<MessageReference>(set); 1435 for (MessageReference ref : list) { 1436 IndirectMessageReference r = (IndirectMessageReference) ref; 1437 if (filter.evaluate(context, r)) { 1438 1439 r.incrementReferenceCount(); 1440 try { 1441 Message m = r.getMessage(); 1442 BrokerSupport.resend(context, m, dest); 1443 if (++movedCounter >= maximumMessages && maximumMessages > 0) { 1444 return movedCounter; 1445 } 1446 } finally { 1447 r.decrementReferenceCount(); 1448 } 1449 } 1450 count++; 1451 } 1452 } while (count < this.destinationStatistics.getMessages().getCount()); 1453 return movedCounter; 1454 } 1455 1456 /** 1457 * Move a message 1458 * 1459 * @param context 1460 * connection context 1461 * @param m 1462 * QueueMessageReference 1463 * @param dest 1464 * ActiveMQDestination 1465 * @throws Exception 1466 */ 1467 public boolean moveMessageTo(ConnectionContext context, QueueMessageReference m, ActiveMQDestination dest) throws Exception { 1468 Set<Destination> destsToPause = regionBroker.getDestinations(dest); 1469 try { 1470 for (Destination d: destsToPause) { 1471 if (d instanceof Queue) { 1472 ((Queue)d).pauseDispatch(); 1473 } 1474 } 1475 BrokerSupport.resend(context, m.getMessage(), dest); 1476 removeMessage(context, m); 1477 messagesLock.writeLock().lock(); 1478 try { 1479 messages.rollback(m.getMessageId()); 1480 if (isDLQ()) { 1481 ActiveMQDestination originalDestination = m.getMessage().getOriginalDestination(); 1482 if (originalDestination != null) { 1483 for (Destination destination : regionBroker.getDestinations(originalDestination)) { 1484 DeadLetterStrategy strategy = destination.getDeadLetterStrategy(); 1485 strategy.rollback(m.getMessage()); 1486 } 1487 } 1488 } 1489 } finally { 1490 messagesLock.writeLock().unlock(); 1491 } 1492 } finally { 1493 for (Destination d: destsToPause) { 1494 if (d instanceof Queue) { 1495 ((Queue)d).resumeDispatch(); 1496 } 1497 } 1498 } 1499 1500 return true; 1501 } 1502 1503 /** 1504 * Moves the message matching the given messageId 1505 */ 1506 public boolean moveMessageTo(ConnectionContext context, String messageId, ActiveMQDestination dest) 1507 throws Exception { 1508 return moveMatchingMessagesTo(context, createMessageIdFilter(messageId), dest, 1) > 0; 1509 } 1510 1511 /** 1512 * Moves the messages matching the given selector 1513 * 1514 * @return the number of messages removed 1515 */ 1516 public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest) 1517 throws Exception { 1518 return moveMatchingMessagesTo(context, selector, dest, Integer.MAX_VALUE); 1519 } 1520 1521 /** 1522 * Moves the messages matching the given selector up to the maximum number 1523 * of matched messages 1524 */ 1525 public int moveMatchingMessagesTo(ConnectionContext context, String selector, ActiveMQDestination dest, 1526 int maximumMessages) throws Exception { 1527 return moveMatchingMessagesTo(context, createSelectorFilter(selector), dest, maximumMessages); 1528 } 1529 1530 /** 1531 * Moves the messages matching the given filter up to the maximum number of 1532 * matched messages 1533 */ 1534 public int moveMatchingMessagesTo(ConnectionContext context, MessageReferenceFilter filter, 1535 ActiveMQDestination dest, int maximumMessages) throws Exception { 1536 1537 if (destination.equals(dest)) { 1538 return 0; 1539 } 1540 1541 int movedCounter = 0; 1542 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1543 do { 1544 doPageIn(true); 1545 pagedInMessagesLock.readLock().lock(); 1546 try { 1547 set.addAll(pagedInMessages.values()); 1548 } finally { 1549 pagedInMessagesLock.readLock().unlock(); 1550 } 1551 List<MessageReference> list = new ArrayList<MessageReference>(set); 1552 for (MessageReference ref : list) { 1553 if (filter.evaluate(context, ref)) { 1554 // We should only move messages that can be locked. 1555 moveMessageTo(context, (QueueMessageReference)ref, dest); 1556 set.remove(ref); 1557 if (++movedCounter >= maximumMessages && maximumMessages > 0) { 1558 return movedCounter; 1559 } 1560 } 1561 } 1562 } while (set.size() < this.destinationStatistics.getMessages().getCount() && set.size() < maximumMessages); 1563 return movedCounter; 1564 } 1565 1566 public int retryMessages(ConnectionContext context, int maximumMessages) throws Exception { 1567 if (!isDLQ()) { 1568 throw new Exception("Retry of message is only possible on Dead Letter Queues!"); 1569 } 1570 int restoredCounter = 0; 1571 // ensure we deal with a snapshot to avoid potential duplicates in the event of messages 1572 // getting immediate dlq'ed 1573 long numberOfRetryAttemptsToCheckAllMessagesOnce = this.destinationStatistics.getMessages().getCount(); 1574 Set<MessageReference> set = new LinkedHashSet<MessageReference>(); 1575 do { 1576 doPageIn(true); 1577 pagedInMessagesLock.readLock().lock(); 1578 try { 1579 set.addAll(pagedInMessages.values()); 1580 } finally { 1581 pagedInMessagesLock.readLock().unlock(); 1582 } 1583 List<MessageReference> list = new ArrayList<MessageReference>(set); 1584 for (MessageReference ref : list) { 1585 numberOfRetryAttemptsToCheckAllMessagesOnce--; 1586 if (ref.getMessage().getOriginalDestination() != null) { 1587 1588 moveMessageTo(context, (QueueMessageReference)ref, ref.getMessage().getOriginalDestination()); 1589 set.remove(ref); 1590 if (++restoredCounter >= maximumMessages && maximumMessages > 0) { 1591 return restoredCounter; 1592 } 1593 } 1594 } 1595 } while (numberOfRetryAttemptsToCheckAllMessagesOnce > 0 && set.size() < this.destinationStatistics.getMessages().getCount()); 1596 return restoredCounter; 1597 } 1598 1599 /** 1600 * @return true if we would like to iterate again 1601 * @see org.apache.activemq.thread.Task#iterate() 1602 */ 1603 @Override 1604 public boolean iterate() { 1605 MDC.put("activemq.destination", getName()); 1606 boolean pageInMoreMessages = false; 1607 synchronized (iteratingMutex) { 1608 1609 // If optimize dispatch is on or this is a slave this method could be called recursively 1610 // we set this state value to short-circuit wakeup in those cases to avoid that as it 1611 // could lead to errors. 1612 iterationRunning = true; 1613 1614 // do early to allow dispatch of these waiting messages 1615 synchronized (messagesWaitingForSpace) { 1616 Iterator<Runnable> it = messagesWaitingForSpace.values().iterator(); 1617 while (it.hasNext()) { 1618 if (!memoryUsage.isFull()) { 1619 Runnable op = it.next(); 1620 it.remove(); 1621 op.run(); 1622 } else { 1623 registerCallbackForNotFullNotification(); 1624 break; 1625 } 1626 } 1627 } 1628 1629 if (firstConsumer) { 1630 firstConsumer = false; 1631 try { 1632 if (consumersBeforeDispatchStarts > 0) { 1633 int timeout = 1000; // wait one second by default if 1634 // consumer count isn't reached 1635 if (timeBeforeDispatchStarts > 0) { 1636 timeout = timeBeforeDispatchStarts; 1637 } 1638 if (consumersBeforeStartsLatch.await(timeout, TimeUnit.MILLISECONDS)) { 1639 LOG.debug("{} consumers subscribed. Starting dispatch.", consumers.size()); 1640 } else { 1641 LOG.debug("{} ms elapsed and {} consumers subscribed. Starting dispatch.", timeout, consumers.size()); 1642 } 1643 } 1644 if (timeBeforeDispatchStarts > 0 && consumersBeforeDispatchStarts <= 0) { 1645 iteratingMutex.wait(timeBeforeDispatchStarts); 1646 LOG.debug("{} ms elapsed. Starting dispatch.", timeBeforeDispatchStarts); 1647 } 1648 } catch (Exception e) { 1649 LOG.error(e.toString()); 1650 } 1651 } 1652 1653 messagesLock.readLock().lock(); 1654 try{ 1655 pageInMoreMessages |= !messages.isEmpty(); 1656 } finally { 1657 messagesLock.readLock().unlock(); 1658 } 1659 1660 pagedInPendingDispatchLock.readLock().lock(); 1661 try { 1662 pageInMoreMessages |= !dispatchPendingList.isEmpty(); 1663 } finally { 1664 pagedInPendingDispatchLock.readLock().unlock(); 1665 } 1666 1667 boolean hasBrowsers = !browserDispatches.isEmpty(); 1668 1669 if (pageInMoreMessages || hasBrowsers || !dispatchPendingList.hasRedeliveries()) { 1670 try { 1671 pageInMessages(hasBrowsers && getMaxBrowsePageSize() > 0, getMaxPageSize()); 1672 } catch (Throwable e) { 1673 LOG.error("Failed to page in more queue messages ", e); 1674 } 1675 } 1676 1677 if (hasBrowsers) { 1678 PendingList messagesInMemory = isPrioritizedMessages() ? 1679 new PrioritizedPendingList() : new OrderedPendingList(); 1680 pagedInMessagesLock.readLock().lock(); 1681 try { 1682 messagesInMemory.addAll(pagedInMessages); 1683 } finally { 1684 pagedInMessagesLock.readLock().unlock(); 1685 } 1686 1687 Iterator<BrowserDispatch> browsers = browserDispatches.iterator(); 1688 while (browsers.hasNext()) { 1689 BrowserDispatch browserDispatch = browsers.next(); 1690 try { 1691 MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext(); 1692 msgContext.setDestination(destination); 1693 1694 QueueBrowserSubscription browser = browserDispatch.getBrowser(); 1695 1696 LOG.debug("dispatch to browser: {}, already dispatched/paged count: {}", browser, messagesInMemory.size()); 1697 boolean added = false; 1698 for (MessageReference node : messagesInMemory) { 1699 if (!((QueueMessageReference)node).isAcked() && !browser.isDuplicate(node.getMessageId()) && !browser.atMax()) { 1700 msgContext.setMessageReference(node); 1701 if (browser.matches(node, msgContext)) { 1702 browser.add(node); 1703 added = true; 1704 } 1705 } 1706 } 1707 // are we done browsing? no new messages paged 1708 if (!added || browser.atMax()) { 1709 browser.decrementQueueRef(); 1710 browserDispatches.remove(browserDispatch); 1711 } else { 1712 wakeup(); 1713 } 1714 } catch (Exception e) { 1715 LOG.warn("exception on dispatch to browser: {}", browserDispatch.getBrowser(), e); 1716 } 1717 } 1718 } 1719 1720 if (pendingWakeups.get() > 0) { 1721 pendingWakeups.decrementAndGet(); 1722 } 1723 MDC.remove("activemq.destination"); 1724 iterationRunning = false; 1725 1726 return pendingWakeups.get() > 0; 1727 } 1728 } 1729 1730 public void pauseDispatch() { 1731 dispatchSelector.pause(); 1732 } 1733 1734 public void resumeDispatch() { 1735 dispatchSelector.resume(); 1736 wakeup(); 1737 } 1738 1739 public boolean isDispatchPaused() { 1740 return dispatchSelector.isPaused(); 1741 } 1742 1743 protected MessageReferenceFilter createMessageIdFilter(final String messageId) { 1744 return new MessageReferenceFilter() { 1745 @Override 1746 public boolean evaluate(ConnectionContext context, MessageReference r) { 1747 return messageId.equals(r.getMessageId().toString()); 1748 } 1749 1750 @Override 1751 public String toString() { 1752 return "MessageIdFilter: " + messageId; 1753 } 1754 }; 1755 } 1756 1757 protected MessageReferenceFilter createSelectorFilter(String selector) throws InvalidSelectorException { 1758 1759 if (selector == null || selector.isEmpty()) { 1760 return new MessageReferenceFilter() { 1761 1762 @Override 1763 public boolean evaluate(ConnectionContext context, MessageReference messageReference) throws JMSException { 1764 return true; 1765 } 1766 }; 1767 } 1768 1769 final BooleanExpression selectorExpression = SelectorParser.parse(selector); 1770 1771 return new MessageReferenceFilter() { 1772 @Override 1773 public boolean evaluate(ConnectionContext context, MessageReference r) throws JMSException { 1774 MessageEvaluationContext messageEvaluationContext = context.getMessageEvaluationContext(); 1775 1776 messageEvaluationContext.setMessageReference(r); 1777 if (messageEvaluationContext.getDestination() == null) { 1778 messageEvaluationContext.setDestination(getActiveMQDestination()); 1779 } 1780 1781 return selectorExpression.matches(messageEvaluationContext); 1782 } 1783 }; 1784 } 1785 1786 protected void removeMessage(ConnectionContext c, QueueMessageReference r) throws IOException { 1787 removeMessage(c, null, r); 1788 pagedInPendingDispatchLock.writeLock().lock(); 1789 try { 1790 dispatchPendingList.remove(r); 1791 } finally { 1792 pagedInPendingDispatchLock.writeLock().unlock(); 1793 } 1794 } 1795 1796 protected void removeMessage(ConnectionContext c, Subscription subs, QueueMessageReference r) throws IOException { 1797 MessageAck ack = new MessageAck(); 1798 ack.setAckType(MessageAck.STANDARD_ACK_TYPE); 1799 ack.setDestination(destination); 1800 ack.setMessageID(r.getMessageId()); 1801 removeMessage(c, subs, r, ack); 1802 } 1803 1804 protected void removeMessage(ConnectionContext context, Subscription sub, final QueueMessageReference reference, 1805 MessageAck ack) throws IOException { 1806 LOG.trace("ack of {} with {}", reference.getMessageId(), ack); 1807 // This sends the ack the the journal.. 1808 if (!ack.isInTransaction()) { 1809 acknowledge(context, sub, ack, reference); 1810 dropMessage(reference); 1811 } else { 1812 try { 1813 acknowledge(context, sub, ack, reference); 1814 } finally { 1815 context.getTransaction().addSynchronization(new Synchronization() { 1816 1817 @Override 1818 public void afterCommit() throws Exception { 1819 dropMessage(reference); 1820 wakeup(); 1821 } 1822 1823 @Override 1824 public void afterRollback() throws Exception { 1825 reference.setAcked(false); 1826 wakeup(); 1827 } 1828 }); 1829 } 1830 } 1831 if (ack.isPoisonAck() || (sub != null && sub.getConsumerInfo().isNetworkSubscription())) { 1832 // message gone to DLQ, is ok to allow redelivery 1833 messagesLock.writeLock().lock(); 1834 try { 1835 messages.rollback(reference.getMessageId()); 1836 } finally { 1837 messagesLock.writeLock().unlock(); 1838 } 1839 if (sub != null && sub.getConsumerInfo().isNetworkSubscription()) { 1840 getDestinationStatistics().getForwards().increment(); 1841 } 1842 } 1843 // after successful store update 1844 reference.setAcked(true); 1845 } 1846 1847 private void dropMessage(QueueMessageReference reference) { 1848 //use dropIfLive so we only process the statistics at most one time 1849 if (reference.dropIfLive()) { 1850 getDestinationStatistics().getDequeues().increment(); 1851 getDestinationStatistics().getMessages().decrement(); 1852 pagedInMessagesLock.writeLock().lock(); 1853 try { 1854 pagedInMessages.remove(reference); 1855 } finally { 1856 pagedInMessagesLock.writeLock().unlock(); 1857 } 1858 } 1859 } 1860 1861 public void messageExpired(ConnectionContext context, MessageReference reference) { 1862 messageExpired(context, null, reference); 1863 } 1864 1865 @Override 1866 public void messageExpired(ConnectionContext context, Subscription subs, MessageReference reference) { 1867 LOG.debug("message expired: {}", reference); 1868 broker.messageExpired(context, reference, subs); 1869 destinationStatistics.getExpired().increment(); 1870 try { 1871 removeMessage(context, subs, (QueueMessageReference) reference); 1872 messagesLock.writeLock().lock(); 1873 try { 1874 messages.rollback(reference.getMessageId()); 1875 } finally { 1876 messagesLock.writeLock().unlock(); 1877 } 1878 } catch (IOException e) { 1879 LOG.error("Failed to remove expired Message from the store ", e); 1880 } 1881 } 1882 1883 private final boolean cursorAdd(final Message msg) throws Exception { 1884 messagesLock.writeLock().lock(); 1885 try { 1886 return messages.addMessageLast(msg); 1887 } finally { 1888 messagesLock.writeLock().unlock(); 1889 } 1890 } 1891 1892 private final boolean tryCursorAdd(final Message msg) throws Exception { 1893 messagesLock.writeLock().lock(); 1894 try { 1895 return messages.tryAddMessageLast(msg, 50); 1896 } finally { 1897 messagesLock.writeLock().unlock(); 1898 } 1899 } 1900 1901 final void messageSent(final ConnectionContext context, final Message msg) throws Exception { 1902 pendingSends.decrementAndGet(); 1903 destinationStatistics.getEnqueues().increment(); 1904 destinationStatistics.getMessages().increment(); 1905 destinationStatistics.getMessageSize().addSize(msg.getSize()); 1906 messageDelivered(context, msg); 1907 consumersLock.readLock().lock(); 1908 try { 1909 if (consumers.isEmpty()) { 1910 onMessageWithNoConsumers(context, msg); 1911 } 1912 }finally { 1913 consumersLock.readLock().unlock(); 1914 } 1915 LOG.debug("{} Message {} sent to {}", new Object[]{ broker.getBrokerName(), msg.getMessageId(), this.destination }); 1916 wakeup(); 1917 } 1918 1919 @Override 1920 public void wakeup() { 1921 if (optimizedDispatch && !iterationRunning) { 1922 iterate(); 1923 pendingWakeups.incrementAndGet(); 1924 } else { 1925 asyncWakeup(); 1926 } 1927 } 1928 1929 private void asyncWakeup() { 1930 try { 1931 pendingWakeups.incrementAndGet(); 1932 this.taskRunner.wakeup(); 1933 } catch (InterruptedException e) { 1934 LOG.warn("Async task runner failed to wakeup ", e); 1935 } 1936 } 1937 1938 private void doPageIn(boolean force) throws Exception { 1939 doPageIn(force, true, getMaxPageSize()); 1940 } 1941 1942 private void doPageIn(boolean force, boolean processExpired, int maxPageSize) throws Exception { 1943 PendingList newlyPaged = doPageInForDispatch(force, processExpired, maxPageSize); 1944 pagedInPendingDispatchLock.writeLock().lock(); 1945 try { 1946 if (dispatchPendingList.isEmpty()) { 1947 dispatchPendingList.addAll(newlyPaged); 1948 1949 } else { 1950 for (MessageReference qmr : newlyPaged) { 1951 if (!dispatchPendingList.contains(qmr)) { 1952 dispatchPendingList.addMessageLast(qmr); 1953 } 1954 } 1955 } 1956 } finally { 1957 pagedInPendingDispatchLock.writeLock().unlock(); 1958 } 1959 } 1960 1961 private PendingList doPageInForDispatch(boolean force, boolean processExpired, int maxPageSize) throws Exception { 1962 List<QueueMessageReference> result = null; 1963 PendingList resultList = null; 1964 1965 int toPageIn = maxPageSize; 1966 messagesLock.readLock().lock(); 1967 try { 1968 toPageIn = Math.min(toPageIn, messages.size()); 1969 } finally { 1970 messagesLock.readLock().unlock(); 1971 } 1972 int pagedInPendingSize = 0; 1973 pagedInPendingDispatchLock.readLock().lock(); 1974 try { 1975 pagedInPendingSize = dispatchPendingList.size(); 1976 } finally { 1977 pagedInPendingDispatchLock.readLock().unlock(); 1978 } 1979 if (isLazyDispatch() && !force) { 1980 // Only page in the minimum number of messages which can be 1981 // dispatched immediately. 1982 toPageIn = Math.min(toPageIn, getConsumerMessageCountBeforeFull()); 1983 } 1984 1985 if (LOG.isDebugEnabled()) { 1986 LOG.debug("{} toPageIn: {}, force:{}, Inflight: {}, pagedInMessages.size {}, pagedInPendingDispatch.size {}, enqueueCount: {}, dequeueCount: {}, memUsage:{}, maxPageSize:{}", 1987 new Object[]{ 1988 this, 1989 toPageIn, 1990 force, 1991 destinationStatistics.getInflight().getCount(), 1992 pagedInMessages.size(), 1993 pagedInPendingSize, 1994 destinationStatistics.getEnqueues().getCount(), 1995 destinationStatistics.getDequeues().getCount(), 1996 getMemoryUsage().getUsage(), 1997 maxPageSize 1998 }); 1999 } 2000 2001 if (toPageIn > 0 && (force || (haveRealConsumer() && pagedInPendingSize < maxPageSize))) { 2002 int count = 0; 2003 result = new ArrayList<QueueMessageReference>(toPageIn); 2004 messagesLock.writeLock().lock(); 2005 try { 2006 try { 2007 messages.setMaxBatchSize(toPageIn); 2008 messages.reset(); 2009 while (count < toPageIn && messages.hasNext()) { 2010 MessageReference node = messages.next(); 2011 messages.remove(); 2012 2013 QueueMessageReference ref = createMessageReference(node.getMessage()); 2014 if (processExpired && ref.isExpired()) { 2015 if (broker.isExpired(ref)) { 2016 messageExpired(createConnectionContext(), ref); 2017 } else { 2018 ref.decrementReferenceCount(); 2019 } 2020 } else { 2021 result.add(ref); 2022 count++; 2023 } 2024 } 2025 } finally { 2026 messages.release(); 2027 } 2028 } finally { 2029 messagesLock.writeLock().unlock(); 2030 } 2031 // Only add new messages, not already pagedIn to avoid multiple 2032 // dispatch attempts 2033 pagedInMessagesLock.writeLock().lock(); 2034 try { 2035 if(isPrioritizedMessages()) { 2036 resultList = new PrioritizedPendingList(); 2037 } else { 2038 resultList = new OrderedPendingList(); 2039 } 2040 for (QueueMessageReference ref : result) { 2041 if (!pagedInMessages.contains(ref)) { 2042 pagedInMessages.addMessageLast(ref); 2043 resultList.addMessageLast(ref); 2044 } else { 2045 ref.decrementReferenceCount(); 2046 // store should have trapped duplicate in it's index, or cursor audit trapped insert 2047 // or producerBrokerExchange suppressed send. 2048 // note: jdbc store will not trap unacked messages as a duplicate b/c it gives each message a unique sequence id 2049 LOG.warn("{}, duplicate message {} - {} from cursor, is cursor audit disabled or too constrained? Redirecting to dlq", this, ref.getMessageId(), ref.getMessage().getMessageId().getFutureOrSequenceLong()); 2050 if (store != null) { 2051 ConnectionContext connectionContext = createConnectionContext(); 2052 dropMessage(ref); 2053 if (gotToTheStore(ref.getMessage())) { 2054 LOG.debug("Duplicate message {} from cursor, removing from store", this, ref.getMessage()); 2055 store.removeMessage(connectionContext, new MessageAck(ref.getMessage(), MessageAck.POSION_ACK_TYPE, 1)); 2056 } 2057 broker.getRoot().sendToDeadLetterQueue(connectionContext, ref.getMessage(), null, new Throwable("duplicate paged in from cursor for " + destination)); 2058 } 2059 } 2060 } 2061 } finally { 2062 pagedInMessagesLock.writeLock().unlock(); 2063 } 2064 } else { 2065 // Avoid return null list, if condition is not validated 2066 resultList = new OrderedPendingList(); 2067 } 2068 2069 return resultList; 2070 } 2071 2072 private final boolean haveRealConsumer() { 2073 return consumers.size() - browserDispatches.size() > 0; 2074 } 2075 2076 private void doDispatch(PendingList list) throws Exception { 2077 boolean doWakeUp = false; 2078 2079 pagedInPendingDispatchLock.writeLock().lock(); 2080 try { 2081 if (isPrioritizedMessages() && !dispatchPendingList.isEmpty() && list != null && !list.isEmpty()) { 2082 // merge all to select priority order 2083 for (MessageReference qmr : list) { 2084 if (!dispatchPendingList.contains(qmr)) { 2085 dispatchPendingList.addMessageLast(qmr); 2086 } 2087 } 2088 list = null; 2089 } 2090 2091 doActualDispatch(dispatchPendingList); 2092 // and now see if we can dispatch the new stuff.. and append to the pending 2093 // list anything that does not actually get dispatched. 2094 if (list != null && !list.isEmpty()) { 2095 if (dispatchPendingList.isEmpty()) { 2096 dispatchPendingList.addAll(doActualDispatch(list)); 2097 } else { 2098 for (MessageReference qmr : list) { 2099 if (!dispatchPendingList.contains(qmr)) { 2100 dispatchPendingList.addMessageLast(qmr); 2101 } 2102 } 2103 doWakeUp = true; 2104 } 2105 } 2106 } finally { 2107 pagedInPendingDispatchLock.writeLock().unlock(); 2108 } 2109 2110 if (doWakeUp) { 2111 // avoid lock order contention 2112 asyncWakeup(); 2113 } 2114 } 2115 2116 /** 2117 * @return list of messages that could get dispatched to consumers if they 2118 * were not full. 2119 */ 2120 private PendingList doActualDispatch(PendingList list) throws Exception { 2121 List<Subscription> consumers; 2122 consumersLock.readLock().lock(); 2123 2124 try { 2125 if (this.consumers.isEmpty()) { 2126 // slave dispatch happens in processDispatchNotification 2127 return list; 2128 } 2129 consumers = new ArrayList<Subscription>(this.consumers); 2130 } finally { 2131 consumersLock.readLock().unlock(); 2132 } 2133 2134 Set<Subscription> fullConsumers = new HashSet<Subscription>(this.consumers.size()); 2135 2136 for (Iterator<MessageReference> iterator = list.iterator(); iterator.hasNext();) { 2137 2138 MessageReference node = iterator.next(); 2139 Subscription target = null; 2140 for (Subscription s : consumers) { 2141 if (s instanceof QueueBrowserSubscription) { 2142 continue; 2143 } 2144 if (!fullConsumers.contains(s)) { 2145 if (!s.isFull()) { 2146 if (dispatchSelector.canSelect(s, node) && assignMessageGroup(s, (QueueMessageReference)node) && !((QueueMessageReference) node).isAcked() ) { 2147 // Dispatch it. 2148 s.add(node); 2149 LOG.trace("assigned {} to consumer {}", node.getMessageId(), s.getConsumerInfo().getConsumerId()); 2150 iterator.remove(); 2151 target = s; 2152 break; 2153 } 2154 } else { 2155 // no further dispatch of list to a full consumer to 2156 // avoid out of order message receipt 2157 fullConsumers.add(s); 2158 LOG.trace("Subscription full {}", s); 2159 } 2160 } 2161 } 2162 2163 if (target == null && node.isDropped()) { 2164 iterator.remove(); 2165 } 2166 2167 // return if there are no consumers or all consumers are full 2168 if (target == null && consumers.size() == fullConsumers.size()) { 2169 return list; 2170 } 2171 2172 // If it got dispatched, rotate the consumer list to get round robin 2173 // distribution. 2174 if (target != null && !strictOrderDispatch && consumers.size() > 1 2175 && !dispatchSelector.isExclusiveConsumer(target)) { 2176 consumersLock.writeLock().lock(); 2177 try { 2178 if (removeFromConsumerList(target)) { 2179 addToConsumerList(target); 2180 consumers = new ArrayList<Subscription>(this.consumers); 2181 } 2182 } finally { 2183 consumersLock.writeLock().unlock(); 2184 } 2185 } 2186 } 2187 2188 return list; 2189 } 2190 2191 protected boolean assignMessageGroup(Subscription subscription, QueueMessageReference node) throws Exception { 2192 boolean result = true; 2193 // Keep message groups together. 2194 String groupId = node.getGroupID(); 2195 int sequence = node.getGroupSequence(); 2196 if (groupId != null) { 2197 2198 MessageGroupMap messageGroupOwners = getMessageGroupOwners(); 2199 // If we can own the first, then no-one else should own the 2200 // rest. 2201 if (sequence == 1) { 2202 assignGroup(subscription, messageGroupOwners, node, groupId); 2203 } else { 2204 2205 // Make sure that the previous owner is still valid, we may 2206 // need to become the new owner. 2207 ConsumerId groupOwner; 2208 2209 groupOwner = messageGroupOwners.get(groupId); 2210 if (groupOwner == null) { 2211 assignGroup(subscription, messageGroupOwners, node, groupId); 2212 } else { 2213 if (groupOwner.equals(subscription.getConsumerInfo().getConsumerId())) { 2214 // A group sequence < 1 is an end of group signal. 2215 if (sequence < 0) { 2216 messageGroupOwners.removeGroup(groupId); 2217 subscription.getConsumerInfo().decrementAssignedGroupCount(destination); 2218 } 2219 } else { 2220 result = false; 2221 } 2222 } 2223 } 2224 } 2225 2226 return result; 2227 } 2228 2229 protected void assignGroup(Subscription subs, MessageGroupMap messageGroupOwners, MessageReference n, String groupId) throws IOException { 2230 messageGroupOwners.put(groupId, subs.getConsumerInfo().getConsumerId()); 2231 Message message = n.getMessage(); 2232 message.setJMSXGroupFirstForConsumer(true); 2233 subs.getConsumerInfo().incrementAssignedGroupCount(destination); 2234 } 2235 2236 protected void pageInMessages(boolean force, int maxPageSize) throws Exception { 2237 doDispatch(doPageInForDispatch(force, true, maxPageSize)); 2238 } 2239 2240 private void addToConsumerList(Subscription sub) { 2241 if (useConsumerPriority) { 2242 consumers.add(sub); 2243 Collections.sort(consumers, orderedCompare); 2244 } else { 2245 consumers.add(sub); 2246 } 2247 } 2248 2249 private boolean removeFromConsumerList(Subscription sub) { 2250 return consumers.remove(sub); 2251 } 2252 2253 private int getConsumerMessageCountBeforeFull() throws Exception { 2254 int total = 0; 2255 consumersLock.readLock().lock(); 2256 try { 2257 for (Subscription s : consumers) { 2258 if (s.isBrowser()) { 2259 continue; 2260 } 2261 int countBeforeFull = s.countBeforeFull(); 2262 total += countBeforeFull; 2263 } 2264 } finally { 2265 consumersLock.readLock().unlock(); 2266 } 2267 return total; 2268 } 2269 2270 /* 2271 * In slave mode, dispatch is ignored till we get this notification as the 2272 * dispatch process is non deterministic between master and slave. On a 2273 * notification, the actual dispatch to the subscription (as chosen by the 2274 * master) is completed. (non-Javadoc) 2275 * @see 2276 * org.apache.activemq.broker.region.BaseDestination#processDispatchNotification 2277 * (org.apache.activemq.command.MessageDispatchNotification) 2278 */ 2279 @Override 2280 public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception { 2281 // do dispatch 2282 Subscription sub = getMatchingSubscription(messageDispatchNotification); 2283 if (sub != null) { 2284 MessageReference message = getMatchingMessage(messageDispatchNotification); 2285 sub.add(message); 2286 sub.processMessageDispatchNotification(messageDispatchNotification); 2287 } 2288 } 2289 2290 private QueueMessageReference getMatchingMessage(MessageDispatchNotification messageDispatchNotification) 2291 throws Exception { 2292 QueueMessageReference message = null; 2293 MessageId messageId = messageDispatchNotification.getMessageId(); 2294 2295 pagedInPendingDispatchLock.writeLock().lock(); 2296 try { 2297 for (MessageReference ref : dispatchPendingList) { 2298 if (messageId.equals(ref.getMessageId())) { 2299 message = (QueueMessageReference)ref; 2300 dispatchPendingList.remove(ref); 2301 break; 2302 } 2303 } 2304 } finally { 2305 pagedInPendingDispatchLock.writeLock().unlock(); 2306 } 2307 2308 if (message == null) { 2309 pagedInMessagesLock.readLock().lock(); 2310 try { 2311 message = (QueueMessageReference)pagedInMessages.get(messageId); 2312 } finally { 2313 pagedInMessagesLock.readLock().unlock(); 2314 } 2315 } 2316 2317 if (message == null) { 2318 messagesLock.writeLock().lock(); 2319 try { 2320 try { 2321 messages.setMaxBatchSize(getMaxPageSize()); 2322 messages.reset(); 2323 while (messages.hasNext()) { 2324 MessageReference node = messages.next(); 2325 messages.remove(); 2326 if (messageId.equals(node.getMessageId())) { 2327 message = this.createMessageReference(node.getMessage()); 2328 break; 2329 } 2330 } 2331 } finally { 2332 messages.release(); 2333 } 2334 } finally { 2335 messagesLock.writeLock().unlock(); 2336 } 2337 } 2338 2339 if (message == null) { 2340 Message msg = loadMessage(messageId); 2341 if (msg != null) { 2342 message = this.createMessageReference(msg); 2343 } 2344 } 2345 2346 if (message == null) { 2347 throw new JMSException("Slave broker out of sync with master - Message: " 2348 + messageDispatchNotification.getMessageId() + " on " 2349 + messageDispatchNotification.getDestination() + " does not exist among pending(" 2350 + dispatchPendingList.size() + ") for subscription: " 2351 + messageDispatchNotification.getConsumerId()); 2352 } 2353 return message; 2354 } 2355 2356 /** 2357 * Find a consumer that matches the id in the message dispatch notification 2358 * 2359 * @param messageDispatchNotification 2360 * @return sub or null if the subscription has been removed before dispatch 2361 * @throws JMSException 2362 */ 2363 private Subscription getMatchingSubscription(MessageDispatchNotification messageDispatchNotification) 2364 throws JMSException { 2365 Subscription sub = null; 2366 consumersLock.readLock().lock(); 2367 try { 2368 for (Subscription s : consumers) { 2369 if (messageDispatchNotification.getConsumerId().equals(s.getConsumerInfo().getConsumerId())) { 2370 sub = s; 2371 break; 2372 } 2373 } 2374 } finally { 2375 consumersLock.readLock().unlock(); 2376 } 2377 return sub; 2378 } 2379 2380 @Override 2381 public void onUsageChanged(@SuppressWarnings("rawtypes") Usage usage, int oldPercentUsage, int newPercentUsage) { 2382 if (oldPercentUsage > newPercentUsage) { 2383 asyncWakeup(); 2384 } 2385 } 2386 2387 @Override 2388 protected Logger getLog() { 2389 return LOG; 2390 } 2391 2392 protected boolean isOptimizeStorage(){ 2393 boolean result = false; 2394 if (isDoOptimzeMessageStorage()){ 2395 consumersLock.readLock().lock(); 2396 try{ 2397 if (consumers.isEmpty()==false){ 2398 result = true; 2399 for (Subscription s : consumers) { 2400 if (s.getPrefetchSize()==0){ 2401 result = false; 2402 break; 2403 } 2404 if (s.isSlowConsumer()){ 2405 result = false; 2406 break; 2407 } 2408 if (s.getInFlightUsage() > getOptimizeMessageStoreInFlightLimit()){ 2409 result = false; 2410 break; 2411 } 2412 } 2413 } 2414 } finally { 2415 consumersLock.readLock().unlock(); 2416 } 2417 } 2418 return result; 2419 } 2420}