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.List;
021
022import javax.jms.ResourceAllocationException;
023
024import org.apache.activemq.advisory.AdvisorySupport;
025import org.apache.activemq.broker.Broker;
026import org.apache.activemq.broker.BrokerService;
027import org.apache.activemq.broker.ConnectionContext;
028import org.apache.activemq.broker.ProducerBrokerExchange;
029import org.apache.activemq.broker.region.policy.DeadLetterStrategy;
030import org.apache.activemq.broker.region.policy.SlowConsumerStrategy;
031import org.apache.activemq.command.ActiveMQDestination;
032import org.apache.activemq.command.ActiveMQTopic;
033import org.apache.activemq.command.Message;
034import org.apache.activemq.command.MessageAck;
035import org.apache.activemq.command.MessageDispatchNotification;
036import org.apache.activemq.command.ProducerInfo;
037import org.apache.activemq.filter.NonCachedMessageEvaluationContext;
038import org.apache.activemq.security.SecurityContext;
039import org.apache.activemq.state.ProducerState;
040import org.apache.activemq.store.MessageStore;
041import org.apache.activemq.thread.Scheduler;
042import org.apache.activemq.usage.MemoryUsage;
043import org.apache.activemq.usage.SystemUsage;
044import org.apache.activemq.usage.Usage;
045import org.slf4j.Logger;
046
047/**
048 *
049 */
050public abstract class BaseDestination implements Destination {
051    /**
052     * The maximum number of messages to page in to the destination from
053     * persistent storage
054     */
055    public static final int MAX_PAGE_SIZE = 200;
056    public static final int MAX_BROWSE_PAGE_SIZE = MAX_PAGE_SIZE * 2;
057    public static final long EXPIRE_MESSAGE_PERIOD = 30 * 1000;
058    public static final long DEFAULT_INACTIVE_TIMEOUT_BEFORE_GC = 60 * 1000;
059    public static final int MAX_PRODUCERS_TO_AUDIT = 64;
060    public static final int MAX_AUDIT_DEPTH = 10000;
061
062    protected final ActiveMQDestination destination;
063    protected final Broker broker;
064    protected final MessageStore store;
065    protected SystemUsage systemUsage;
066    protected MemoryUsage memoryUsage;
067    private boolean producerFlowControl = true;
068    private boolean alwaysRetroactive = false;
069    protected long lastBlockedProducerWarnTime = 0l;
070    protected long blockedProducerWarningInterval = DEFAULT_BLOCKED_PRODUCER_WARNING_INTERVAL;
071
072    private int maxProducersToAudit = 1024;
073    private int maxAuditDepth = 2048;
074    private boolean enableAudit = true;
075    private int maxPageSize = MAX_PAGE_SIZE;
076    private int maxBrowsePageSize = MAX_BROWSE_PAGE_SIZE;
077    private boolean useCache = true;
078    private int minimumMessageSize = 1024;
079    private boolean lazyDispatch = false;
080    private boolean advisoryForSlowConsumers;
081    private boolean advisoryForFastProducers;
082    private boolean advisoryForDiscardingMessages;
083    private boolean advisoryWhenFull;
084    private boolean advisoryForDelivery;
085    private boolean advisoryForConsumed;
086    private boolean sendAdvisoryIfNoConsumers;
087    protected final DestinationStatistics destinationStatistics = new DestinationStatistics();
088    protected final BrokerService brokerService;
089    protected final Broker regionBroker;
090    protected DeadLetterStrategy deadLetterStrategy = DEFAULT_DEAD_LETTER_STRATEGY;
091    protected long expireMessagesPeriod = EXPIRE_MESSAGE_PERIOD;
092    private int maxExpirePageSize = MAX_BROWSE_PAGE_SIZE;
093    protected int cursorMemoryHighWaterMark = 70;
094    protected int storeUsageHighWaterMark = 100;
095    private SlowConsumerStrategy slowConsumerStrategy;
096    private boolean prioritizedMessages;
097    private long inactiveTimeoutBeforeGC = DEFAULT_INACTIVE_TIMEOUT_BEFORE_GC;
098    private boolean gcIfInactive;
099    private boolean gcWithNetworkConsumers;
100    private long lastActiveTime=0l;
101    private boolean reduceMemoryFootprint = false;
102    protected final Scheduler scheduler;
103    private boolean disposed = false;
104    private boolean doOptimzeMessageStorage = true;
105    /*
106     * percentage of in-flight messages above which optimize message store is disabled
107     */
108    private int optimizeMessageStoreInFlightLimit = 10;
109    private boolean persistJMSRedelivered;
110
111    /**
112     * @param brokerService
113     * @param store
114     * @param destination
115     * @param parentStats
116     * @throws Exception
117     */
118    public BaseDestination(BrokerService brokerService, MessageStore store, ActiveMQDestination destination, DestinationStatistics parentStats) throws Exception {
119        this.brokerService = brokerService;
120        this.broker = brokerService.getBroker();
121        this.store = store;
122        this.destination = destination;
123        // let's copy the enabled property from the parent DestinationStatistics
124        this.destinationStatistics.setEnabled(parentStats.isEnabled());
125        this.destinationStatistics.setParent(parentStats);
126        this.systemUsage = new SystemUsage(brokerService.getProducerSystemUsage(), destination.toString());
127        this.memoryUsage = this.systemUsage.getMemoryUsage();
128        this.memoryUsage.setUsagePortion(1.0f);
129        this.regionBroker = brokerService.getRegionBroker();
130        this.scheduler = brokerService.getBroker().getScheduler();
131    }
132
133    /**
134     * initialize the destination
135     *
136     * @throws Exception
137     */
138    public void initialize() throws Exception {
139        // Let the store know what usage manager we are using so that he can
140        // flush messages to disk when usage gets high.
141        if (store != null) {
142            store.setMemoryUsage(this.memoryUsage);
143        }
144    }
145
146    /**
147     * @return the producerFlowControl
148     */
149    @Override
150    public boolean isProducerFlowControl() {
151        return producerFlowControl;
152    }
153
154    /**
155     * @param producerFlowControl the producerFlowControl to set
156     */
157    @Override
158    public void setProducerFlowControl(boolean producerFlowControl) {
159        this.producerFlowControl = producerFlowControl;
160    }
161
162    @Override
163    public boolean isAlwaysRetroactive() {
164        return alwaysRetroactive;
165    }
166
167    @Override
168    public void setAlwaysRetroactive(boolean alwaysRetroactive) {
169        this.alwaysRetroactive = alwaysRetroactive;
170    }
171
172    /**
173     * Set's the interval at which warnings about producers being blocked by
174     * resource usage will be triggered. Values of 0 or less will disable
175     * warnings
176     *
177     * @param blockedProducerWarningInterval the interval at which warning about
178     *            blocked producers will be triggered.
179     */
180    @Override
181    public void setBlockedProducerWarningInterval(long blockedProducerWarningInterval) {
182        this.blockedProducerWarningInterval = blockedProducerWarningInterval;
183    }
184
185    /**
186     *
187     * @return the interval at which warning about blocked producers will be
188     *         triggered.
189     */
190    @Override
191    public long getBlockedProducerWarningInterval() {
192        return blockedProducerWarningInterval;
193    }
194
195    /**
196     * @return the maxProducersToAudit
197     */
198    @Override
199    public int getMaxProducersToAudit() {
200        return maxProducersToAudit;
201    }
202
203    /**
204     * @param maxProducersToAudit the maxProducersToAudit to set
205     */
206    @Override
207    public void setMaxProducersToAudit(int maxProducersToAudit) {
208        this.maxProducersToAudit = maxProducersToAudit;
209    }
210
211    /**
212     * @return the maxAuditDepth
213     */
214    @Override
215    public int getMaxAuditDepth() {
216        return maxAuditDepth;
217    }
218
219    /**
220     * @param maxAuditDepth the maxAuditDepth to set
221     */
222    @Override
223    public void setMaxAuditDepth(int maxAuditDepth) {
224        this.maxAuditDepth = maxAuditDepth;
225    }
226
227    /**
228     * @return the enableAudit
229     */
230    @Override
231    public boolean isEnableAudit() {
232        return enableAudit;
233    }
234
235    /**
236     * @param enableAudit the enableAudit to set
237     */
238    @Override
239    public void setEnableAudit(boolean enableAudit) {
240        this.enableAudit = enableAudit;
241    }
242
243    @Override
244    public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
245        destinationStatistics.getProducers().increment();
246        this.lastActiveTime=0l;
247    }
248
249    @Override
250    public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
251        destinationStatistics.getProducers().decrement();
252    }
253
254    @Override
255    public void addSubscription(ConnectionContext context, Subscription sub) throws Exception{
256        destinationStatistics.getConsumers().increment();
257        this.lastActiveTime=0l;
258    }
259
260    @Override
261    public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId) throws Exception{
262        destinationStatistics.getConsumers().decrement();
263        this.lastActiveTime=0l;
264    }
265
266
267    @Override
268    public final MemoryUsage getMemoryUsage() {
269        return memoryUsage;
270    }
271
272    @Override
273    public void setMemoryUsage(MemoryUsage memoryUsage) {
274        this.memoryUsage = memoryUsage;
275    }
276
277    @Override
278    public DestinationStatistics getDestinationStatistics() {
279        return destinationStatistics;
280    }
281
282    @Override
283    public ActiveMQDestination getActiveMQDestination() {
284        return destination;
285    }
286
287    @Override
288    public final String getName() {
289        return getActiveMQDestination().getPhysicalName();
290    }
291
292    @Override
293    public final MessageStore getMessageStore() {
294        return store;
295    }
296
297    @Override
298    public boolean isActive() {
299        boolean isActive = destinationStatistics.getConsumers().getCount() > 0 ||
300                           destinationStatistics.getProducers().getCount() > 0;
301        if (isActive && isGcWithNetworkConsumers() && destinationStatistics.getConsumers().getCount() > 0) {
302            isActive = hasRegularConsumers(getConsumers());
303        }
304        return isActive;
305    }
306
307    @Override
308    public int getMaxPageSize() {
309        return maxPageSize;
310    }
311
312    @Override
313    public void setMaxPageSize(int maxPageSize) {
314        this.maxPageSize = maxPageSize;
315    }
316
317    @Override
318    public int getMaxBrowsePageSize() {
319        return this.maxBrowsePageSize;
320    }
321
322    @Override
323    public void setMaxBrowsePageSize(int maxPageSize) {
324        this.maxBrowsePageSize = maxPageSize;
325    }
326
327    public int getMaxExpirePageSize() {
328        return this.maxExpirePageSize;
329    }
330
331    public void setMaxExpirePageSize(int maxPageSize) {
332        this.maxExpirePageSize = maxPageSize;
333    }
334
335    public void setExpireMessagesPeriod(long expireMessagesPeriod) {
336        this.expireMessagesPeriod = expireMessagesPeriod;
337    }
338
339    public long getExpireMessagesPeriod() {
340        return expireMessagesPeriod;
341    }
342
343    @Override
344    public boolean isUseCache() {
345        return useCache;
346    }
347
348    @Override
349    public void setUseCache(boolean useCache) {
350        this.useCache = useCache;
351    }
352
353    @Override
354    public int getMinimumMessageSize() {
355        return minimumMessageSize;
356    }
357
358    @Override
359    public void setMinimumMessageSize(int minimumMessageSize) {
360        this.minimumMessageSize = minimumMessageSize;
361    }
362
363    @Override
364    public boolean isLazyDispatch() {
365        return lazyDispatch;
366    }
367
368    @Override
369    public void setLazyDispatch(boolean lazyDispatch) {
370        this.lazyDispatch = lazyDispatch;
371    }
372
373    protected long getDestinationSequenceId() {
374        return regionBroker.getBrokerSequenceId();
375    }
376
377    /**
378     * @return the advisoryForSlowConsumers
379     */
380    public boolean isAdvisoryForSlowConsumers() {
381        return advisoryForSlowConsumers;
382    }
383
384    /**
385     * @param advisoryForSlowConsumers the advisoryForSlowConsumers to set
386     */
387    public void setAdvisoryForSlowConsumers(boolean advisoryForSlowConsumers) {
388        this.advisoryForSlowConsumers = advisoryForSlowConsumers;
389    }
390
391    /**
392     * @return the advisoryForDiscardingMessages
393     */
394    public boolean isAdvisoryForDiscardingMessages() {
395        return advisoryForDiscardingMessages;
396    }
397
398    /**
399     * @param advisoryForDiscardingMessages the advisoryForDiscardingMessages to
400     *            set
401     */
402    public void setAdvisoryForDiscardingMessages(boolean advisoryForDiscardingMessages) {
403        this.advisoryForDiscardingMessages = advisoryForDiscardingMessages;
404    }
405
406    /**
407     * @return the advisoryWhenFull
408     */
409    public boolean isAdvisoryWhenFull() {
410        return advisoryWhenFull;
411    }
412
413    /**
414     * @param advisoryWhenFull the advisoryWhenFull to set
415     */
416    public void setAdvisoryWhenFull(boolean advisoryWhenFull) {
417        this.advisoryWhenFull = advisoryWhenFull;
418    }
419
420    /**
421     * @return the advisoryForDelivery
422     */
423    public boolean isAdvisoryForDelivery() {
424        return advisoryForDelivery;
425    }
426
427    /**
428     * @param advisoryForDelivery the advisoryForDelivery to set
429     */
430    public void setAdvisoryForDelivery(boolean advisoryForDelivery) {
431        this.advisoryForDelivery = advisoryForDelivery;
432    }
433
434    /**
435     * @return the advisoryForConsumed
436     */
437    public boolean isAdvisoryForConsumed() {
438        return advisoryForConsumed;
439    }
440
441    /**
442     * @param advisoryForConsumed the advisoryForConsumed to set
443     */
444    public void setAdvisoryForConsumed(boolean advisoryForConsumed) {
445        this.advisoryForConsumed = advisoryForConsumed;
446    }
447
448    /**
449     * @return the advisdoryForFastProducers
450     */
451    public boolean isAdvisoryForFastProducers() {
452        return advisoryForFastProducers;
453    }
454
455    /**
456     * @param advisoryForFastProducers the advisdoryForFastProducers to set
457     */
458    public void setAdvisoryForFastProducers(boolean advisoryForFastProducers) {
459        this.advisoryForFastProducers = advisoryForFastProducers;
460    }
461
462    public boolean isSendAdvisoryIfNoConsumers() {
463        return sendAdvisoryIfNoConsumers;
464    }
465
466    public void setSendAdvisoryIfNoConsumers(boolean sendAdvisoryIfNoConsumers) {
467        this.sendAdvisoryIfNoConsumers = sendAdvisoryIfNoConsumers;
468    }
469
470    /**
471     * @return the dead letter strategy
472     */
473    @Override
474    public DeadLetterStrategy getDeadLetterStrategy() {
475        return deadLetterStrategy;
476    }
477
478    /**
479     * set the dead letter strategy
480     *
481     * @param deadLetterStrategy
482     */
483    public void setDeadLetterStrategy(DeadLetterStrategy deadLetterStrategy) {
484        this.deadLetterStrategy = deadLetterStrategy;
485    }
486
487    @Override
488    public int getCursorMemoryHighWaterMark() {
489        return this.cursorMemoryHighWaterMark;
490    }
491
492    @Override
493    public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) {
494        this.cursorMemoryHighWaterMark = cursorMemoryHighWaterMark;
495    }
496
497    /**
498     * called when message is consumed
499     *
500     * @param context
501     * @param messageReference
502     */
503    @Override
504    public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
505        if (advisoryForConsumed) {
506            broker.messageConsumed(context, messageReference);
507        }
508    }
509
510    /**
511     * Called when message is delivered to the broker
512     *
513     * @param context
514     * @param messageReference
515     */
516    @Override
517    public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
518        this.lastActiveTime = 0L;
519        if (advisoryForDelivery) {
520            broker.messageDelivered(context, messageReference);
521        }
522    }
523
524    /**
525     * Called when a message is discarded - e.g. running low on memory This will
526     * happen only if the policy is enabled - e.g. non durable topics
527     *
528     * @param context
529     * @param messageReference
530     */
531    @Override
532    public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
533        if (advisoryForDiscardingMessages) {
534            broker.messageDiscarded(context, sub, messageReference);
535        }
536    }
537
538    /**
539     * Called when there is a slow consumer
540     *
541     * @param context
542     * @param subs
543     */
544    @Override
545    public void slowConsumer(ConnectionContext context, Subscription subs) {
546        if (advisoryForSlowConsumers) {
547            broker.slowConsumer(context, this, subs);
548        }
549        if (slowConsumerStrategy != null) {
550            slowConsumerStrategy.slowConsumer(context, subs);
551        }
552    }
553
554    /**
555     * Called to notify a producer is too fast
556     *
557     * @param context
558     * @param producerInfo
559     */
560    @Override
561    public void fastProducer(ConnectionContext context, ProducerInfo producerInfo) {
562        if (advisoryForFastProducers) {
563            broker.fastProducer(context, producerInfo, getActiveMQDestination());
564        }
565    }
566
567    /**
568     * Called when a Usage reaches a limit
569     *
570     * @param context
571     * @param usage
572     */
573    @Override
574    public void isFull(ConnectionContext context, Usage<?> usage) {
575        if (advisoryWhenFull) {
576            broker.isFull(context, this, usage);
577        }
578    }
579
580    @Override
581    public void dispose(ConnectionContext context) throws IOException {
582        if (this.store != null) {
583            this.store.removeAllMessages(context);
584            this.store.dispose(context);
585        }
586        this.destinationStatistics.setParent(null);
587        this.memoryUsage.stop();
588        this.disposed = true;
589    }
590
591    @Override
592    public boolean isDisposed() {
593        return this.disposed;
594    }
595
596    /**
597     * Provides a hook to allow messages with no consumer to be processed in
598     * some way - such as to send to a dead letter queue or something..
599     */
600    protected void onMessageWithNoConsumers(ConnectionContext context, Message msg) throws Exception {
601        if (!msg.isPersistent()) {
602            if (isSendAdvisoryIfNoConsumers()) {
603                // allow messages with no consumers to be dispatched to a dead
604                // letter queue
605                if (destination.isQueue() || !AdvisorySupport.isAdvisoryTopic(destination)) {
606
607                    Message message = msg.copy();
608                    // The original destination and transaction id do not get
609                    // filled when the message is first sent,
610                    // it is only populated if the message is routed to another
611                    // destination like the DLQ
612                    if (message.getOriginalDestination() != null) {
613                        message.setOriginalDestination(message.getDestination());
614                    }
615                    if (message.getOriginalTransactionId() != null) {
616                        message.setOriginalTransactionId(message.getTransactionId());
617                    }
618
619                    ActiveMQTopic advisoryTopic;
620                    if (destination.isQueue()) {
621                        advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(destination);
622                    } else {
623                        advisoryTopic = AdvisorySupport.getNoTopicConsumersAdvisoryTopic(destination);
624                    }
625                    message.setDestination(advisoryTopic);
626                    message.setTransactionId(null);
627
628                    // Disable flow control for this since since we don't want
629                    // to block.
630                    boolean originalFlowControl = context.isProducerFlowControl();
631                    try {
632                        context.setProducerFlowControl(false);
633                        ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
634                        producerExchange.setMutable(false);
635                        producerExchange.setConnectionContext(context);
636                        producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
637                        context.getBroker().send(producerExchange, message);
638                    } finally {
639                        context.setProducerFlowControl(originalFlowControl);
640                    }
641
642                }
643            }
644        }
645    }
646
647    @Override
648    public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception {
649    }
650
651    public final int getStoreUsageHighWaterMark() {
652        return this.storeUsageHighWaterMark;
653    }
654
655    public void setStoreUsageHighWaterMark(int storeUsageHighWaterMark) {
656        this.storeUsageHighWaterMark = storeUsageHighWaterMark;
657    }
658
659    protected final void waitForSpace(ConnectionContext context,ProducerBrokerExchange producerBrokerExchange, Usage<?> usage, String warning) throws IOException, InterruptedException, ResourceAllocationException {
660        waitForSpace(context, producerBrokerExchange, usage, 100, warning);
661    }
662
663    protected final void waitForSpace(ConnectionContext context, ProducerBrokerExchange producerBrokerExchange, Usage<?> usage, int highWaterMark, String warning) throws IOException, InterruptedException, ResourceAllocationException {
664        if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) {
665            getLog().debug("sendFailIfNoSpace, forcing exception on send, usage: {}: {}", usage, warning);
666            throw new ResourceAllocationException(warning);
667        }
668        if (!context.isNetworkConnection() && systemUsage.getSendFailIfNoSpaceAfterTimeout() != 0) {
669            if (!usage.waitForSpace(systemUsage.getSendFailIfNoSpaceAfterTimeout(), highWaterMark)) {
670                getLog().debug("sendFailIfNoSpaceAfterTimeout expired, forcing exception on send, usage: {}: {}", usage, warning);
671                throw new ResourceAllocationException(warning);
672            }
673        } else {
674            long start = System.currentTimeMillis();
675            producerBrokerExchange.blockingOnFlowControl(true);
676            destinationStatistics.getBlockedSends().increment();
677            while (!usage.waitForSpace(1000, highWaterMark)) {
678                if (context.getStopping().get()) {
679                    throw new IOException("Connection closed, send aborted.");
680                }
681
682                if (isFlowControlLogRequired()) {
683                    getLog().warn("{}: {} (blocking for: {}s)", new Object[]{ usage, warning, new Long(((System.currentTimeMillis() - start) / 1000))});
684                } else {
685                    getLog().debug("{}: {} (blocking for: {}s)", new Object[]{ usage, warning, new Long(((System.currentTimeMillis() - start) / 1000))});
686                }
687            }
688            long finish = System.currentTimeMillis();
689            long totalTimeBlocked = finish - start;
690            destinationStatistics.getBlockedTime().addTime(totalTimeBlocked);
691            producerBrokerExchange.incrementTimeBlocked(this,totalTimeBlocked);
692            producerBrokerExchange.blockingOnFlowControl(false);
693        }
694    }
695
696    protected boolean isFlowControlLogRequired() {
697        boolean answer = false;
698        if (blockedProducerWarningInterval > 0) {
699            long now = System.currentTimeMillis();
700            if (lastBlockedProducerWarnTime + blockedProducerWarningInterval <= now) {
701                lastBlockedProducerWarnTime = now;
702                answer = true;
703            }
704        }
705        return answer;
706    }
707
708    protected abstract Logger getLog();
709
710    public void setSlowConsumerStrategy(SlowConsumerStrategy slowConsumerStrategy) {
711        this.slowConsumerStrategy = slowConsumerStrategy;
712    }
713
714    @Override
715    public SlowConsumerStrategy getSlowConsumerStrategy() {
716        return this.slowConsumerStrategy;
717    }
718
719
720    @Override
721    public boolean isPrioritizedMessages() {
722        return this.prioritizedMessages;
723    }
724
725    public void setPrioritizedMessages(boolean prioritizedMessages) {
726        this.prioritizedMessages = prioritizedMessages;
727        if (store != null) {
728            store.setPrioritizedMessages(prioritizedMessages);
729        }
730    }
731
732    /**
733     * @return the inactiveTimeoutBeforeGC
734     */
735    @Override
736    public long getInactiveTimeoutBeforeGC() {
737        return this.inactiveTimeoutBeforeGC;
738    }
739
740    /**
741     * @param inactiveTimeoutBeforeGC the inactiveTimeoutBeforeGC to set
742     */
743    public void setInactiveTimeoutBeforeGC(long inactiveTimeoutBeforeGC) {
744        this.inactiveTimeoutBeforeGC = inactiveTimeoutBeforeGC;
745    }
746
747    /**
748     * @return the gcIfInactive
749     */
750    public boolean isGcIfInactive() {
751        return this.gcIfInactive;
752    }
753
754    /**
755     * @param gcIfInactive the gcIfInactive to set
756     */
757    public void setGcIfInactive(boolean gcIfInactive) {
758        this.gcIfInactive = gcIfInactive;
759    }
760
761    /**
762     * Indicate if it is ok to gc destinations that have only network consumers
763     * @param gcWithNetworkConsumers
764     */
765    public void setGcWithNetworkConsumers(boolean gcWithNetworkConsumers) {
766        this.gcWithNetworkConsumers = gcWithNetworkConsumers;
767    }
768
769    public boolean isGcWithNetworkConsumers() {
770        return gcWithNetworkConsumers;
771    }
772
773    @Override
774    public void markForGC(long timeStamp) {
775        if (isGcIfInactive() && this.lastActiveTime == 0 && isActive() == false
776                && destinationStatistics.messages.getCount() == 0 && getInactiveTimeoutBeforeGC() > 0l) {
777            this.lastActiveTime = timeStamp;
778        }
779    }
780
781    @Override
782    public boolean canGC() {
783        boolean result = false;
784        final long currentLastActiveTime = this.lastActiveTime;
785        if (isGcIfInactive() && currentLastActiveTime != 0l && destinationStatistics.messages.getCount() == 0L ) {
786            if ((System.currentTimeMillis() - currentLastActiveTime) >= getInactiveTimeoutBeforeGC()) {
787                result = true;
788            }
789        }
790        return result;
791    }
792
793    public void setReduceMemoryFootprint(boolean reduceMemoryFootprint) {
794        this.reduceMemoryFootprint = reduceMemoryFootprint;
795    }
796
797    protected boolean isReduceMemoryFootprint() {
798        return this.reduceMemoryFootprint;
799    }
800
801    @Override
802    public boolean isDoOptimzeMessageStorage() {
803        return doOptimzeMessageStorage;
804    }
805
806    @Override
807    public void setDoOptimzeMessageStorage(boolean doOptimzeMessageStorage) {
808        this.doOptimzeMessageStorage = doOptimzeMessageStorage;
809    }
810
811    public int getOptimizeMessageStoreInFlightLimit() {
812        return optimizeMessageStoreInFlightLimit;
813    }
814
815    public void setOptimizeMessageStoreInFlightLimit(int optimizeMessageStoreInFlightLimit) {
816        this.optimizeMessageStoreInFlightLimit = optimizeMessageStoreInFlightLimit;
817    }
818
819
820    @Override
821    public abstract List<Subscription> getConsumers();
822
823    protected boolean hasRegularConsumers(List<Subscription> consumers) {
824        boolean hasRegularConsumers = false;
825        for (Subscription subscription: consumers) {
826            if (!subscription.getConsumerInfo().isNetworkSubscription()) {
827                hasRegularConsumers = true;
828                break;
829            }
830        }
831        return hasRegularConsumers;
832    }
833
834    public ConnectionContext createConnectionContext() {
835        ConnectionContext answer = new ConnectionContext(new NonCachedMessageEvaluationContext());
836        answer.setBroker(this.broker);
837        answer.getMessageEvaluationContext().setDestination(getActiveMQDestination());
838        answer.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
839        return answer;
840    }
841
842    protected MessageAck convertToNonRangedAck(MessageAck ack, MessageReference node) {
843        // the original ack may be a ranged ack, but we are trying to delete
844        // a specific
845        // message store here so we need to convert to a non ranged ack.
846        if (ack.getMessageCount() > 0) {
847            // Dup the ack
848            MessageAck a = new MessageAck();
849            ack.copy(a);
850            ack = a;
851            // Convert to non-ranged.
852            ack.setMessageCount(1);
853        }
854        // always use node messageId so we can access entry/data Location
855        ack.setFirstMessageId(node.getMessageId());
856        ack.setLastMessageId(node.getMessageId());
857        return ack;
858    }
859
860    protected boolean isDLQ() {
861        return destination.isDLQ();
862    }
863
864    @Override
865    public void duplicateFromStore(Message message, Subscription durableSub) {
866        ConnectionContext connectionContext = createConnectionContext();
867        getLog().warn("duplicate message from store {}, redirecting for dlq processing", message.getMessageId());
868        Throwable cause = new Throwable("duplicate from store for " + destination);
869        message.setRegionDestination(this);
870        broker.getRoot().sendToDeadLetterQueue(connectionContext, message, null, cause);
871        MessageAck messageAck = new MessageAck(message, MessageAck.POSION_ACK_TYPE, 1);
872        messageAck.setPoisonCause(cause);
873        try {
874            acknowledge(connectionContext, durableSub, messageAck, message);
875        } catch (IOException e) {
876            getLog().error("Failed to acknowledge duplicate message {} from {} with {}", message.getMessageId(), destination, messageAck);
877        }
878    }
879
880    public void setPersistJMSRedelivered(boolean persistJMSRedelivered) {
881        this.persistJMSRedelivered = persistJMSRedelivered;
882    }
883
884    public boolean isPersistJMSRedelivered() {
885        return persistJMSRedelivered;
886    }
887}