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.advisory;
018
019import java.util.ArrayList;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.Iterator;
023import java.util.LinkedHashMap;
024import java.util.Map;
025import java.util.Set;
026import java.util.concurrent.ConcurrentHashMap;
027import java.util.concurrent.ConcurrentMap;
028import java.util.concurrent.locks.ReentrantReadWriteLock;
029
030import org.apache.activemq.broker.Broker;
031import org.apache.activemq.broker.BrokerFilter;
032import org.apache.activemq.broker.BrokerService;
033import org.apache.activemq.broker.ConnectionContext;
034import org.apache.activemq.broker.ProducerBrokerExchange;
035import org.apache.activemq.broker.TransportConnector;
036import org.apache.activemq.broker.region.BaseDestination;
037import org.apache.activemq.broker.region.Destination;
038import org.apache.activemq.broker.region.DurableTopicSubscription;
039import org.apache.activemq.broker.region.MessageReference;
040import org.apache.activemq.broker.region.RegionBroker;
041import org.apache.activemq.broker.region.Subscription;
042import org.apache.activemq.broker.region.TopicRegion;
043import org.apache.activemq.broker.region.TopicSubscription;
044import org.apache.activemq.broker.region.virtual.VirtualDestination;
045import org.apache.activemq.command.ActiveMQDestination;
046import org.apache.activemq.command.ActiveMQMessage;
047import org.apache.activemq.command.ActiveMQTopic;
048import org.apache.activemq.command.BrokerInfo;
049import org.apache.activemq.command.Command;
050import org.apache.activemq.command.ConnectionId;
051import org.apache.activemq.command.ConnectionInfo;
052import org.apache.activemq.command.ConsumerId;
053import org.apache.activemq.command.ConsumerInfo;
054import org.apache.activemq.command.DestinationInfo;
055import org.apache.activemq.command.Message;
056import org.apache.activemq.command.MessageId;
057import org.apache.activemq.command.ProducerId;
058import org.apache.activemq.command.ProducerInfo;
059import org.apache.activemq.command.RemoveSubscriptionInfo;
060import org.apache.activemq.command.SessionId;
061import org.apache.activemq.security.SecurityContext;
062import org.apache.activemq.state.ProducerState;
063import org.apache.activemq.usage.Usage;
064import org.apache.activemq.util.IdGenerator;
065import org.apache.activemq.util.LongSequenceGenerator;
066import org.apache.activemq.util.SubscriptionKey;
067import org.slf4j.Logger;
068import org.slf4j.LoggerFactory;
069
070/**
071 * This broker filter handles tracking the state of the broker for purposes of
072 * publishing advisory messages to advisory consumers.
073 */
074public class AdvisoryBroker extends BrokerFilter {
075
076    private static final Logger LOG = LoggerFactory.getLogger(AdvisoryBroker.class);
077    private static final IdGenerator ID_GENERATOR = new IdGenerator();
078
079    protected final ConcurrentMap<ConnectionId, ConnectionInfo> connections = new ConcurrentHashMap<ConnectionId, ConnectionInfo>();
080
081    private final ReentrantReadWriteLock consumersLock = new ReentrantReadWriteLock();
082    protected final Map<ConsumerId, ConsumerInfo> consumers = new LinkedHashMap<ConsumerId, ConsumerInfo>();
083
084    /**
085     * This is a set to track all of the virtual destinations that have been added to the broker so
086     * they can be easily referenced later.
087     */
088    protected final Set<VirtualDestination> virtualDestinations = Collections.newSetFromMap(new ConcurrentHashMap<VirtualDestination, Boolean>());
089    /**
090     * This is a map to track all consumers that exist on the virtual destination so that we can fire
091     * an advisory later when they go away to remove the demand.
092     */
093    protected final ConcurrentMap<ConsumerInfo, VirtualDestination> virtualDestinationConsumers = new ConcurrentHashMap<>();
094    /**
095     * This is a map to track unique demand for the existence of a virtual destination so we make sure
096     * we don't send duplicate advisories.
097     */
098    protected final ConcurrentMap<VirtualConsumerPair, ConsumerInfo> brokerConsumerDests = new ConcurrentHashMap<>();
099
100    protected final ConcurrentMap<ProducerId, ProducerInfo> producers = new ConcurrentHashMap<ProducerId, ProducerInfo>();
101    protected final ConcurrentMap<ActiveMQDestination, DestinationInfo> destinations = new ConcurrentHashMap<ActiveMQDestination, DestinationInfo>();
102    protected final ConcurrentMap<BrokerInfo, ActiveMQMessage> networkBridges = new ConcurrentHashMap<BrokerInfo, ActiveMQMessage>();
103    protected final ProducerId advisoryProducerId = new ProducerId();
104
105    private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator();
106
107    private VirtualDestinationMatcher virtualDestinationMatcher = new DestinationFilterVirtualDestinationMatcher();
108
109    public AdvisoryBroker(Broker next) {
110        super(next);
111        advisoryProducerId.setConnectionId(ID_GENERATOR.generateId());
112    }
113
114    @Override
115    public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
116        super.addConnection(context, info);
117
118        ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
119        // do not distribute passwords in advisory messages. usernames okay
120        ConnectionInfo copy = info.copy();
121        copy.setPassword("");
122        fireAdvisory(context, topic, copy);
123        connections.put(copy.getConnectionId(), copy);
124    }
125
126    @Override
127    public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
128        Subscription answer = super.addConsumer(context, info);
129
130        // Don't advise advisory topics.
131        if (!AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
132            ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(info.getDestination());
133            consumersLock.writeLock().lock();
134            try {
135                consumers.put(info.getConsumerId(), info);
136
137                //check if this is a consumer on a destination that matches a virtual destination
138                if (getBrokerService().isUseVirtualDestSubs()) {
139                    for (VirtualDestination virtualDestination : virtualDestinations) {
140                        if (virtualDestinationMatcher.matches(virtualDestination, info.getDestination())) {
141                            fireVirtualDestinationAddAdvisory(context, info, info.getDestination(), virtualDestination);
142                        }
143                    }
144                }
145            } finally {
146                consumersLock.writeLock().unlock();
147            }
148            fireConsumerAdvisory(context, info.getDestination(), topic, info);
149        } else {
150            // We need to replay all the previously collected state objects
151            // for this newly added consumer.
152            if (AdvisorySupport.isConnectionAdvisoryTopic(info.getDestination())) {
153                // Replay the connections.
154                for (Iterator<ConnectionInfo> iter = connections.values().iterator(); iter.hasNext(); ) {
155                    ConnectionInfo value = iter.next();
156                    ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
157                    fireAdvisory(context, topic, value, info.getConsumerId());
158                }
159            }
160
161            // We check here whether the Destination is Temporary Destination specific or not since we
162            // can avoid sending advisory messages to the consumer if it only wants Temporary Destination
163            // notifications.  If its not just temporary destination related destinations then we have
164            // to send them all, a composite destination could want both.
165            if (AdvisorySupport.isTempDestinationAdvisoryTopic(info.getDestination())) {
166                // Replay the temporary destinations.
167                for (DestinationInfo destination : destinations.values()) {
168                    if (destination.getDestination().isTemporary()) {
169                        ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
170                        fireAdvisory(context, topic, destination, info.getConsumerId());
171                    }
172                }
173            } else if (AdvisorySupport.isDestinationAdvisoryTopic(info.getDestination())) {
174                // Replay all the destinations.
175                for (DestinationInfo destination : destinations.values()) {
176                    ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
177                    fireAdvisory(context, topic, destination, info.getConsumerId());
178                }
179            }
180
181            // Replay the producers.
182            if (AdvisorySupport.isProducerAdvisoryTopic(info.getDestination())) {
183                for (Iterator<ProducerInfo> iter = producers.values().iterator(); iter.hasNext(); ) {
184                    ProducerInfo value = iter.next();
185                    ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(value.getDestination());
186                    fireProducerAdvisory(context, value.getDestination(), topic, value, info.getConsumerId());
187                }
188            }
189
190            // Replay the consumers.
191            if (AdvisorySupport.isConsumerAdvisoryTopic(info.getDestination())) {
192                consumersLock.readLock().lock();
193                try {
194                    for (Iterator<ConsumerInfo> iter = consumers.values().iterator(); iter.hasNext(); ) {
195                        ConsumerInfo value = iter.next();
196                        ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(value.getDestination());
197                        fireConsumerAdvisory(context, value.getDestination(), topic, value, info.getConsumerId());
198                    }
199                } finally {
200                    consumersLock.readLock().unlock();
201                }
202            }
203
204            // Replay the virtual destination consumers.
205            if (AdvisorySupport.isVirtualDestinationConsumerAdvisoryTopic(info.getDestination())) {
206                for (Iterator<ConsumerInfo> iter = virtualDestinationConsumers.keySet().iterator(); iter.hasNext(); ) {
207                    ConsumerInfo key = iter.next();
208                    ActiveMQTopic topic = AdvisorySupport.getVirtualDestinationConsumerAdvisoryTopic(key.getDestination());
209                    fireConsumerAdvisory(context, key.getDestination(), topic, key);
210              }
211            }
212
213            // Replay network bridges
214            if (AdvisorySupport.isNetworkBridgeAdvisoryTopic(info.getDestination())) {
215                for (Iterator<BrokerInfo> iter = networkBridges.keySet().iterator(); iter.hasNext(); ) {
216                    BrokerInfo key = iter.next();
217                    ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
218                    fireAdvisory(context, topic, key, null, networkBridges.get(key));
219                }
220            }
221        }
222        return answer;
223    }
224
225    @Override
226    public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
227        super.addProducer(context, info);
228
229        // Don't advise advisory topics.
230        if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
231            ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(info.getDestination());
232            fireProducerAdvisory(context, info.getDestination(), topic, info);
233            producers.put(info.getProducerId(), info);
234        }
235    }
236
237    @Override
238    public Destination addDestination(ConnectionContext context, ActiveMQDestination destination, boolean create) throws Exception {
239        Destination answer = super.addDestination(context, destination, create);
240        if (!AdvisorySupport.isAdvisoryTopic(destination)) {
241            //for queues, create demand if isUseVirtualDestSubsOnCreation is true
242            if (getBrokerService().isUseVirtualDestSubsOnCreation() && destination.isQueue()) {
243                //check if this new destination matches a virtual destination that exists
244                for (VirtualDestination virtualDestination : virtualDestinations) {
245                    if (virtualDestinationMatcher.matches(virtualDestination, destination)) {
246                        fireVirtualDestinationAddAdvisory(context, null, destination, virtualDestination);
247                    }
248                }
249            }
250
251            DestinationInfo info = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, destination);
252            DestinationInfo previous = destinations.putIfAbsent(destination, info);
253            if (previous == null) {
254                ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
255                fireAdvisory(context, topic, info);
256            }
257        }
258        return answer;
259    }
260
261    @Override
262    public void addDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception {
263        ActiveMQDestination destination = info.getDestination();
264        next.addDestinationInfo(context, info);
265
266        if (!AdvisorySupport.isAdvisoryTopic(destination)) {
267            DestinationInfo previous = destinations.putIfAbsent(destination, info);
268            if (previous == null) {
269                ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
270                fireAdvisory(context, topic, info);
271            }
272        }
273    }
274
275    @Override
276    public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
277        super.removeDestination(context, destination, timeout);
278        DestinationInfo info = destinations.remove(destination);
279        if (info != null) {
280
281            //on destination removal, remove all demand if using virtual dest subs
282            if (getBrokerService().isUseVirtualDestSubs()) {
283                for (ConsumerInfo consumerInfo : virtualDestinationConsumers.keySet()) {
284                    //find all consumers for this virtual destination
285                    VirtualDestination virtualDestination = virtualDestinationConsumers.get(consumerInfo);
286
287                    //find a consumer that matches this virtualDest and destination
288                    if (virtualDestinationMatcher.matches(virtualDestination, destination)) {
289                        //in case of multiple matches
290                        VirtualConsumerPair key = new VirtualConsumerPair(virtualDestination, destination);
291                        ConsumerInfo i = brokerConsumerDests.get(key);
292                        if (consumerInfo.equals(i)) {
293                            if (brokerConsumerDests.remove(key) != null) {
294                                fireVirtualDestinationRemoveAdvisory(context, consumerInfo);
295                                break;
296                            }
297                        }
298                    }
299                }
300            }
301
302            // ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
303            info = info.copy();
304            info.setDestination(destination);
305            info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
306            ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
307            fireAdvisory(context, topic, info);
308            ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destination);
309            for (ActiveMQTopic advisoryDestination : advisoryDestinations) {
310                try {
311                    next.removeDestination(context, advisoryDestination, -1);
312                } catch (Exception expectedIfDestinationDidNotExistYet) {
313                }
314            }
315        }
316    }
317
318    @Override
319    public void removeDestinationInfo(ConnectionContext context, DestinationInfo destInfo) throws Exception {
320        super.removeDestinationInfo(context, destInfo);
321        DestinationInfo info = destinations.remove(destInfo.getDestination());
322        if (info != null) {
323            // ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
324            info = info.copy();
325            info.setDestination(destInfo.getDestination());
326            info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
327            ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destInfo.getDestination());
328            fireAdvisory(context, topic, info);
329            ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destInfo.getDestination());
330            for (ActiveMQTopic advisoryDestination : advisoryDestinations) {
331                try {
332                    next.removeDestination(context, advisoryDestination, -1);
333                } catch (Exception expectedIfDestinationDidNotExistYet) {
334                }
335            }
336        }
337    }
338
339    @Override
340    public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
341        super.removeConnection(context, info, error);
342
343        ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
344        fireAdvisory(context, topic, info.createRemoveCommand());
345        connections.remove(info.getConnectionId());
346    }
347
348    @Override
349    public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
350        super.removeConsumer(context, info);
351
352        // Don't advise advisory topics.
353        ActiveMQDestination dest = info.getDestination();
354        if (!AdvisorySupport.isAdvisoryTopic(dest)) {
355            ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(dest);
356            consumersLock.writeLock().lock();
357            try {
358                consumers.remove(info.getConsumerId());
359
360                //remove the demand for this consumer if it matches a virtual destination
361                if(getBrokerService().isUseVirtualDestSubs()) {
362                    fireVirtualDestinationRemoveAdvisory(context, info);
363                }
364            } finally {
365                consumersLock.writeLock().unlock();
366            }
367            if (!dest.isTemporary() || destinations.containsKey(dest)) {
368                fireConsumerAdvisory(context, dest, topic, info.createRemoveCommand());
369            }
370        }
371    }
372
373    @Override
374    public void removeSubscription(ConnectionContext context, RemoveSubscriptionInfo info) throws Exception {
375        SubscriptionKey key = new SubscriptionKey(context.getClientId(), info.getSubscriptionName());
376
377        RegionBroker regionBroker = null;
378        if (next instanceof RegionBroker) {
379            regionBroker = (RegionBroker) next;
380        } else {
381            BrokerService service = next.getBrokerService();
382            regionBroker = (RegionBroker) service.getRegionBroker();
383        }
384
385        if (regionBroker == null) {
386            LOG.warn("Cannot locate a RegionBroker instance to pass along the removeSubscription call");
387            throw new IllegalStateException("No RegionBroker found.");
388        }
389
390        DurableTopicSubscription sub = ((TopicRegion) regionBroker.getTopicRegion()).getDurableSubscription(key);
391
392        super.removeSubscription(context, info);
393
394        if (sub == null) {
395            LOG.warn("We cannot send an advisory message for a durable sub removal when we don't know about the durable sub");
396            return;
397        }
398
399        ActiveMQDestination dest = sub.getConsumerInfo().getDestination();
400
401        // Don't advise advisory topics.
402        if (!AdvisorySupport.isAdvisoryTopic(dest)) {
403            ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(dest);
404            fireConsumerAdvisory(context, dest, topic, info);
405        }
406
407    }
408
409    @Override
410    public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
411        super.removeProducer(context, info);
412
413        // Don't advise advisory topics.
414        ActiveMQDestination dest = info.getDestination();
415        if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(dest)) {
416            ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(dest);
417            producers.remove(info.getProducerId());
418            if (!dest.isTemporary() || destinations.containsKey(dest)) {
419                fireProducerAdvisory(context, dest, topic, info.createRemoveCommand());
420            }
421        }
422    }
423
424    @Override
425    public void messageExpired(ConnectionContext context, MessageReference messageReference, Subscription subscription) {
426        super.messageExpired(context, messageReference, subscription);
427        try {
428            if (!messageReference.isAdvisory()) {
429                ActiveMQTopic topic = AdvisorySupport.getExpiredMessageTopic(messageReference.getMessage().getDestination());
430                Message payload = messageReference.getMessage().copy();
431                if (!isIncludeBodyForAdvisory(messageReference.getMessage().getDestination())) {
432                    payload.clearBody();
433                }
434                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
435                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
436                fireAdvisory(context, topic, payload, null, advisoryMessage);
437            }
438        } catch (Exception e) {
439            handleFireFailure("expired", e);
440        }
441    }
442
443    @Override
444    public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
445        super.messageConsumed(context, messageReference);
446        try {
447            if (!messageReference.isAdvisory()) {
448                ActiveMQTopic topic = AdvisorySupport.getMessageConsumedAdvisoryTopic(messageReference.getMessage().getDestination());
449                Message payload = messageReference.getMessage().copy();
450                if (!isIncludeBodyForAdvisory(messageReference.getMessage().getDestination())) {
451                    payload.clearBody();
452                }
453                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
454                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
455                ActiveMQDestination destination = payload.getDestination();
456                if (destination != null) {
457                    advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_DESTINATION, payload.getMessageId().toString());
458                }
459                fireAdvisory(context, topic, payload, null, advisoryMessage);
460            }
461        } catch (Exception e) {
462            handleFireFailure("consumed", e);
463        }
464    }
465
466    @Override
467    public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
468        super.messageDelivered(context, messageReference);
469        try {
470            if (!messageReference.isAdvisory()) {
471                ActiveMQTopic topic = AdvisorySupport.getMessageDeliveredAdvisoryTopic(messageReference.getMessage().getDestination());
472                Message payload = messageReference.getMessage().copy();
473                if (!isIncludeBodyForAdvisory(messageReference.getMessage().getDestination())) {
474                    payload.clearBody();
475                }
476                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
477                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
478                ActiveMQDestination destination = payload.getDestination();
479                if (destination != null) {
480                    advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_DESTINATION, payload.getMessageId().toString());
481                }
482                fireAdvisory(context, topic, payload, null, advisoryMessage);
483            }
484        } catch (Exception e) {
485            handleFireFailure("delivered", e);
486        }
487    }
488
489    @Override
490    public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
491        super.messageDiscarded(context, sub, messageReference);
492        try {
493            if (!messageReference.isAdvisory()) {
494                ActiveMQTopic topic = AdvisorySupport.getMessageDiscardedAdvisoryTopic(messageReference.getMessage().getDestination());
495                Message payload = messageReference.getMessage().copy();
496                if (!isIncludeBodyForAdvisory(messageReference.getMessage().getDestination())) {
497                    payload.clearBody();
498                }
499                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
500                if (sub instanceof TopicSubscription) {
501                    advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_DISCARDED_COUNT, ((TopicSubscription) sub).discarded());
502                }
503                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
504                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, sub.getConsumerInfo().getConsumerId().toString());
505                ActiveMQDestination destination = payload.getDestination();
506                if (destination != null) {
507                    advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_DESTINATION, payload.getMessageId().toString());
508                }
509                fireAdvisory(context, topic, payload, null, advisoryMessage);
510            }
511        } catch (Exception e) {
512            handleFireFailure("discarded", e);
513        }
514    }
515
516    @Override
517    public void slowConsumer(ConnectionContext context, Destination destination, Subscription subs) {
518        super.slowConsumer(context, destination, subs);
519        try {
520            if (!AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination())) {
521                ActiveMQTopic topic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination.getActiveMQDestination());
522                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
523                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, subs.getConsumerInfo().getConsumerId().toString());
524                fireAdvisory(context, topic, subs.getConsumerInfo(), null, advisoryMessage);
525            }
526        } catch (Exception e) {
527            handleFireFailure("slow consumer", e);
528        }
529    }
530
531    @Override
532    public void fastProducer(ConnectionContext context, ProducerInfo producerInfo, ActiveMQDestination destination) {
533        super.fastProducer(context, producerInfo, destination);
534        try {
535            if (!AdvisorySupport.isAdvisoryTopic(destination)) {
536                ActiveMQTopic topic = AdvisorySupport.getFastProducerAdvisoryTopic(destination);
537                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
538                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_PRODUCER_ID, producerInfo.getProducerId().toString());
539                fireAdvisory(context, topic, producerInfo, null, advisoryMessage);
540            }
541        } catch (Exception e) {
542            handleFireFailure("fast producer", e);
543        }
544    }
545
546    private final IdGenerator connectionIdGenerator = new IdGenerator("advisory");
547    private final LongSequenceGenerator sessionIdGenerator = new LongSequenceGenerator();
548    private final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator();
549
550    @Override
551    public void virtualDestinationAdded(ConnectionContext context,
552            VirtualDestination virtualDestination) {
553        super.virtualDestinationAdded(context, virtualDestination);
554
555        if (virtualDestinations.add(virtualDestination)) {
556            try {
557                // Don't advise advisory topics.
558                if (!AdvisorySupport.isAdvisoryTopic(virtualDestination.getVirtualDestination())) {
559
560                    //create demand for consumers on virtual destinations
561                    consumersLock.readLock().lock();
562                    try {
563                        //loop through existing destinations to see if any match this newly
564                        //created virtual destination
565                        if (getBrokerService().isUseVirtualDestSubsOnCreation()) {
566                            //for matches that are a queue, fire an advisory for demand
567                            for (ActiveMQDestination destination : destinations.keySet()) {
568                                if(destination.isQueue()) {
569                                    if (virtualDestinationMatcher.matches(virtualDestination, destination)) {
570                                        fireVirtualDestinationAddAdvisory(context, null, destination, virtualDestination);
571                                    }
572                                }
573                            }
574                        }
575
576                        //loop through existing consumers to see if any of them are consuming on a destination
577                        //that matches the new virtual destination
578                        for (Iterator<ConsumerInfo> iter = consumers.values().iterator(); iter.hasNext(); ) {
579                            ConsumerInfo info = iter.next();
580                            if (virtualDestinationMatcher.matches(virtualDestination, info.getDestination())) {
581                                fireVirtualDestinationAddAdvisory(context, info, info.getDestination(), virtualDestination);
582                            }
583                        }
584                    } finally {
585                        consumersLock.readLock().unlock();
586                    }
587                }
588            } catch (Exception e) {
589                handleFireFailure("virtualDestinationAdded", e);
590            }
591        }
592    }
593
594    private void fireVirtualDestinationAddAdvisory(ConnectionContext context, ConsumerInfo info, ActiveMQDestination activeMQDest,
595            VirtualDestination virtualDestination) throws Exception {
596        //if no consumer info, we need to create one - this is the case when an advisory is fired
597        //because of the existence of a destination matching a virtual destination
598        if (info == null) {
599            ConnectionId connectionId = new ConnectionId(connectionIdGenerator.generateId());
600            SessionId sessionId = new SessionId(connectionId, sessionIdGenerator.getNextSequenceId());
601            ConsumerId consumerId = new ConsumerId(sessionId, consumerIdGenerator.getNextSequenceId());
602
603            info = new ConsumerInfo(consumerId);
604
605            //store the virtual destination and the activeMQDestination as a pair so that we can keep track
606            //of all matching forwarded destinations that caused demand
607            if(brokerConsumerDests.putIfAbsent(new VirtualConsumerPair(virtualDestination, activeMQDest), info) == null) {
608                info.setDestination(virtualDestination.getVirtualDestination());
609                ActiveMQTopic topic = AdvisorySupport.getVirtualDestinationConsumerAdvisoryTopic(info.getDestination());
610
611                if (virtualDestinationConsumers.putIfAbsent(info, virtualDestination) == null) {
612                    fireConsumerAdvisory(context, info.getDestination(), topic, info);
613                }
614            }
615        //this is the case of a real consumer coming online
616        } else {
617            info = info.copy();
618            info.setDestination(virtualDestination.getVirtualDestination());
619            ActiveMQTopic topic = AdvisorySupport.getVirtualDestinationConsumerAdvisoryTopic(info.getDestination());
620
621            if (virtualDestinationConsumers.putIfAbsent(info, virtualDestination) == null) {
622                fireConsumerAdvisory(context, info.getDestination(), topic, info);
623            }
624        }
625    }
626
627    @Override
628    public void virtualDestinationRemoved(ConnectionContext context,
629            VirtualDestination virtualDestination) {
630        super.virtualDestinationRemoved(context, virtualDestination);
631
632        if (virtualDestinations.remove(virtualDestination)) {
633            try {
634                consumersLock.readLock().lock();
635                try {
636                    // remove the demand created by the addition of the virtual destination
637                    if (getBrokerService().isUseVirtualDestSubsOnCreation()) {
638                        if (!AdvisorySupport.isAdvisoryTopic(virtualDestination.getVirtualDestination())) {
639                            for (ConsumerInfo info : virtualDestinationConsumers.keySet()) {
640                                //find all consumers for this virtual destination
641                                if (virtualDestinationConsumers.get(info).equals(virtualDestination)) {
642                                    fireVirtualDestinationRemoveAdvisory(context, info);
643                                }
644
645                                //check consumers created for the existence of a destination to see if they
646                                //match the consumerinfo and clean up
647                                for (VirtualConsumerPair activeMQDest : brokerConsumerDests.keySet()) {
648                                    ConsumerInfo i = brokerConsumerDests.get(activeMQDest);
649                                    if (info.equals(i)) {
650                                        brokerConsumerDests.remove(activeMQDest);
651                                    }
652                                }
653                            }
654                        }
655                    }
656                } finally {
657                    consumersLock.readLock().unlock();
658                }
659            } catch (Exception e) {
660                handleFireFailure("virtualDestinationAdded", e);
661            }
662        }
663    }
664
665    private void fireVirtualDestinationRemoveAdvisory(ConnectionContext context,
666            ConsumerInfo info) throws Exception {
667
668        VirtualDestination virtualDestination = virtualDestinationConsumers.remove(info);
669        if (virtualDestination != null) {
670            ActiveMQTopic topic = AdvisorySupport.getVirtualDestinationConsumerAdvisoryTopic(virtualDestination.getVirtualDestination());
671
672            ActiveMQDestination dest = info.getDestination();
673
674            if (!dest.isTemporary() || destinations.containsKey(dest)) {
675                fireConsumerAdvisory(context, dest, topic, info.createRemoveCommand());
676            }
677        }
678    }
679
680    @Override
681    public void isFull(ConnectionContext context, Destination destination, Usage usage) {
682        super.isFull(context, destination, usage);
683        if (AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination()) == false) {
684            try {
685
686                ActiveMQTopic topic = AdvisorySupport.getFullAdvisoryTopic(destination.getActiveMQDestination());
687                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
688                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_USAGE_NAME, usage.getName());
689                fireAdvisory(context, topic, null, null, advisoryMessage);
690
691            } catch (Exception e) {
692                handleFireFailure("is full", e);
693            }
694        }
695    }
696
697    @Override
698    public void nowMasterBroker() {
699        super.nowMasterBroker();
700        try {
701            ActiveMQTopic topic = AdvisorySupport.getMasterBrokerAdvisoryTopic();
702            ActiveMQMessage advisoryMessage = new ActiveMQMessage();
703            ConnectionContext context = new ConnectionContext();
704            context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
705            context.setBroker(getBrokerService().getBroker());
706            fireAdvisory(context, topic, null, null, advisoryMessage);
707        } catch (Exception e) {
708            handleFireFailure("now master broker", e);
709        }
710    }
711
712    @Override
713    public boolean sendToDeadLetterQueue(ConnectionContext context, MessageReference messageReference,
714                                         Subscription subscription, Throwable poisonCause) {
715        boolean wasDLQd = super.sendToDeadLetterQueue(context, messageReference, subscription, poisonCause);
716        if (wasDLQd) {
717            try {
718                if (!messageReference.isAdvisory()) {
719                    ActiveMQTopic topic = AdvisorySupport.getMessageDLQdAdvisoryTopic(messageReference.getMessage().getDestination());
720                    Message payload = messageReference.getMessage().copy();
721                    if (!isIncludeBodyForAdvisory(messageReference.getMessage().getDestination())) {
722                        payload.clearBody();
723                    }
724                    fireAdvisory(context, topic, payload);
725                }
726            } catch (Exception e) {
727                handleFireFailure("add to DLQ", e);
728            }
729        }
730
731        return wasDLQd;
732    }
733
734    @Override
735    public void networkBridgeStarted(BrokerInfo brokerInfo, boolean createdByDuplex, String remoteIp) {
736        try {
737            if (brokerInfo != null) {
738                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
739                advisoryMessage.setBooleanProperty("started", true);
740                advisoryMessage.setBooleanProperty("createdByDuplex", createdByDuplex);
741                advisoryMessage.setStringProperty("remoteIp", remoteIp);
742                networkBridges.putIfAbsent(brokerInfo, advisoryMessage);
743
744                ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
745
746                ConnectionContext context = new ConnectionContext();
747                context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
748                context.setBroker(getBrokerService().getBroker());
749                fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
750            }
751        } catch (Exception e) {
752            handleFireFailure("network bridge started", e);
753        }
754    }
755
756    @Override
757    public void networkBridgeStopped(BrokerInfo brokerInfo) {
758        try {
759            if (brokerInfo != null) {
760                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
761                advisoryMessage.setBooleanProperty("started", false);
762                networkBridges.remove(brokerInfo);
763
764                ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
765
766                ConnectionContext context = new ConnectionContext();
767                context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
768                context.setBroker(getBrokerService().getBroker());
769                fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
770            }
771        } catch (Exception e) {
772            handleFireFailure("network bridge stopped", e);
773        }
774    }
775
776    protected boolean isIncludeBodyForAdvisory(ActiveMQDestination activemqDestination) {
777        Destination destination = next.getDestinationMap(activemqDestination).get(activemqDestination);
778        return (destination instanceof BaseDestination &&
779                ((BaseDestination) destination).isIncludeBodyForAdvisory()) ? true : false;
780    }
781
782    private void handleFireFailure(String message, Throwable cause) {
783        LOG.warn("Failed to fire {} advisory, reason: {}", message, cause);
784        LOG.debug("{} detail: {}", message, cause);
785    }
786
787    protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command) throws Exception {
788        fireAdvisory(context, topic, command, null);
789    }
790
791    protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
792        ActiveMQMessage advisoryMessage = new ActiveMQMessage();
793        fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
794    }
795
796    protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination, ActiveMQTopic topic, Command command) throws Exception {
797        fireConsumerAdvisory(context, consumerDestination, topic, command, null);
798    }
799
800    protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
801        ActiveMQMessage advisoryMessage = new ActiveMQMessage();
802        int count = 0;
803        Set<Destination> set = getDestinations(consumerDestination);
804        if (set != null) {
805            for (Destination dest : set) {
806                count += dest.getDestinationStatistics().getConsumers().getCount();
807            }
808        }
809        advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_COUNT, count);
810
811        fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
812    }
813
814    protected void fireProducerAdvisory(ConnectionContext context, ActiveMQDestination producerDestination, ActiveMQTopic topic, Command command) throws Exception {
815        fireProducerAdvisory(context, producerDestination, topic, command, null);
816    }
817
818    protected void fireProducerAdvisory(ConnectionContext context, ActiveMQDestination producerDestination, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
819        ActiveMQMessage advisoryMessage = new ActiveMQMessage();
820        int count = 0;
821        if (producerDestination != null) {
822            Set<Destination> set = getDestinations(producerDestination);
823            if (set != null) {
824                for (Destination dest : set) {
825                    count += dest.getDestinationStatistics().getProducers().getCount();
826                }
827            }
828        }
829        advisoryMessage.setIntProperty("producerCount", count);
830        fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
831    }
832
833    public void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId, ActiveMQMessage advisoryMessage) throws Exception {
834        if (getBrokerService().isStarted()) {
835            //set properties
836            advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName());
837            String id = getBrokerId() != null ? getBrokerId().getValue() : "NOT_SET";
838            advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id);
839
840            String url = getBrokerService().getVmConnectorURI().toString();
841            //try and find the URL on the transport connector and use if it exists else
842            //try and find a default URL
843            if (context.getConnector() instanceof TransportConnector
844                    && ((TransportConnector) context.getConnector()).getPublishableConnectString() != null) {
845                url = ((TransportConnector) context.getConnector()).getPublishableConnectString();
846            } else if (getBrokerService().getDefaultSocketURIString() != null) {
847                url = getBrokerService().getDefaultSocketURIString();
848            }
849            advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url);
850
851            //set the data structure
852            advisoryMessage.setDataStructure(command);
853            advisoryMessage.setPersistent(false);
854            advisoryMessage.setType(AdvisorySupport.ADIVSORY_MESSAGE_TYPE);
855            advisoryMessage.setMessageId(new MessageId(advisoryProducerId, messageIdGenerator.getNextSequenceId()));
856            advisoryMessage.setTargetConsumerId(targetConsumerId);
857            advisoryMessage.setDestination(topic);
858            advisoryMessage.setResponseRequired(false);
859            advisoryMessage.setProducerId(advisoryProducerId);
860            boolean originalFlowControl = context.isProducerFlowControl();
861            final ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
862            producerExchange.setConnectionContext(context);
863            producerExchange.setMutable(true);
864            producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
865            try {
866                context.setProducerFlowControl(false);
867                next.send(producerExchange, advisoryMessage);
868            } finally {
869                context.setProducerFlowControl(originalFlowControl);
870            }
871        }
872    }
873
874    public Map<ConnectionId, ConnectionInfo> getAdvisoryConnections() {
875        return connections;
876    }
877
878    public Collection<ConsumerInfo> getAdvisoryConsumers() {
879        consumersLock.readLock().lock();
880        try {
881            return new ArrayList<ConsumerInfo>(consumers.values());
882        } finally {
883            consumersLock.readLock().unlock();
884        }
885    }
886
887    public Map<ProducerId, ProducerInfo> getAdvisoryProducers() {
888        return producers;
889    }
890
891    public Map<ActiveMQDestination, DestinationInfo> getAdvisoryDestinations() {
892        return destinations;
893    }
894
895    private class VirtualConsumerPair {
896        private final VirtualDestination virtualDestination;
897
898        //destination that matches this virtualDestination as part target
899        //this is so we can keep track of more than one destination that might
900        //match the virtualDestination and cause demand
901        private final ActiveMQDestination activeMQDestination;
902
903        public VirtualConsumerPair(VirtualDestination virtualDestination,
904                ActiveMQDestination activeMQDestination) {
905            super();
906            this.virtualDestination = virtualDestination;
907            this.activeMQDestination = activeMQDestination;
908        }
909        @Override
910        public int hashCode() {
911            final int prime = 31;
912            int result = 1;
913            result = prime * result + getOuterType().hashCode();
914            result = prime
915                    * result
916                    + ((activeMQDestination == null) ? 0 : activeMQDestination
917                            .hashCode());
918            result = prime
919                    * result
920                    + ((virtualDestination == null) ? 0 : virtualDestination
921                            .hashCode());
922            return result;
923        }
924        @Override
925        public boolean equals(Object obj) {
926            if (this == obj)
927                return true;
928            if (obj == null)
929                return false;
930            if (getClass() != obj.getClass())
931                return false;
932            VirtualConsumerPair other = (VirtualConsumerPair) obj;
933            if (!getOuterType().equals(other.getOuterType()))
934                return false;
935            if (activeMQDestination == null) {
936                if (other.activeMQDestination != null)
937                    return false;
938            } else if (!activeMQDestination.equals(other.activeMQDestination))
939                return false;
940            if (virtualDestination == null) {
941                if (other.virtualDestination != null)
942                    return false;
943            } else if (!virtualDestination.equals(other.virtualDestination))
944                return false;
945            return true;
946        }
947        private AdvisoryBroker getOuterType() {
948            return AdvisoryBroker.this;
949        }
950    }
951}