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.Iterator;
022import java.util.LinkedHashMap;
023import java.util.Map;
024import java.util.Set;
025import java.util.concurrent.ConcurrentHashMap;
026import java.util.concurrent.ConcurrentMap;
027import java.util.concurrent.locks.ReentrantReadWriteLock;
028
029import org.apache.activemq.broker.Broker;
030import org.apache.activemq.broker.BrokerFilter;
031import org.apache.activemq.broker.BrokerService;
032import org.apache.activemq.broker.ConnectionContext;
033import org.apache.activemq.broker.ProducerBrokerExchange;
034import org.apache.activemq.broker.region.Destination;
035import org.apache.activemq.broker.region.DurableTopicSubscription;
036import org.apache.activemq.broker.region.MessageReference;
037import org.apache.activemq.broker.region.RegionBroker;
038import org.apache.activemq.broker.region.Subscription;
039import org.apache.activemq.broker.region.TopicRegion;
040import org.apache.activemq.broker.region.TopicSubscription;
041import org.apache.activemq.command.ActiveMQDestination;
042import org.apache.activemq.command.ActiveMQMessage;
043import org.apache.activemq.command.ActiveMQTopic;
044import org.apache.activemq.command.BrokerInfo;
045import org.apache.activemq.command.Command;
046import org.apache.activemq.command.ConnectionId;
047import org.apache.activemq.command.ConnectionInfo;
048import org.apache.activemq.command.ConsumerId;
049import org.apache.activemq.command.ConsumerInfo;
050import org.apache.activemq.command.DestinationInfo;
051import org.apache.activemq.command.Message;
052import org.apache.activemq.command.MessageId;
053import org.apache.activemq.command.ProducerId;
054import org.apache.activemq.command.ProducerInfo;
055import org.apache.activemq.command.RemoveSubscriptionInfo;
056import org.apache.activemq.security.SecurityContext;
057import org.apache.activemq.state.ProducerState;
058import org.apache.activemq.usage.Usage;
059import org.apache.activemq.util.IdGenerator;
060import org.apache.activemq.util.LongSequenceGenerator;
061import org.apache.activemq.util.SubscriptionKey;
062import org.slf4j.Logger;
063import org.slf4j.LoggerFactory;
064
065/**
066 * This broker filter handles tracking the state of the broker for purposes of
067 * publishing advisory messages to advisory consumers.
068 */
069public class AdvisoryBroker extends BrokerFilter {
070
071    private static final Logger LOG = LoggerFactory.getLogger(AdvisoryBroker.class);
072    private static final IdGenerator ID_GENERATOR = new IdGenerator();
073
074    protected final ConcurrentMap<ConnectionId, ConnectionInfo> connections = new ConcurrentHashMap<ConnectionId, ConnectionInfo>();
075
076    private final ReentrantReadWriteLock consumersLock = new ReentrantReadWriteLock();
077    protected final Map<ConsumerId, ConsumerInfo> consumers = new LinkedHashMap<ConsumerId, ConsumerInfo>();
078
079    protected final ConcurrentMap<ProducerId, ProducerInfo> producers = new ConcurrentHashMap<ProducerId, ProducerInfo>();
080    protected final ConcurrentMap<ActiveMQDestination, DestinationInfo> destinations = new ConcurrentHashMap<ActiveMQDestination, DestinationInfo>();
081    protected final ConcurrentMap<BrokerInfo, ActiveMQMessage> networkBridges = new ConcurrentHashMap<BrokerInfo, ActiveMQMessage>();
082    protected final ProducerId advisoryProducerId = new ProducerId();
083
084    private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator();
085
086    public AdvisoryBroker(Broker next) {
087        super(next);
088        advisoryProducerId.setConnectionId(ID_GENERATOR.generateId());
089    }
090
091    @Override
092    public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
093        super.addConnection(context, info);
094
095        ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
096        // do not distribute passwords in advisory messages. usernames okay
097        ConnectionInfo copy = info.copy();
098        copy.setPassword("");
099        fireAdvisory(context, topic, copy);
100        connections.put(copy.getConnectionId(), copy);
101    }
102
103    @Override
104    public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
105        Subscription answer = super.addConsumer(context, info);
106
107        // Don't advise advisory topics.
108        if (!AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
109            ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(info.getDestination());
110            consumersLock.writeLock().lock();
111            try {
112                consumers.put(info.getConsumerId(), info);
113            } finally {
114                consumersLock.writeLock().unlock();
115            }
116            fireConsumerAdvisory(context, info.getDestination(), topic, info);
117        } else {
118            // We need to replay all the previously collected state objects
119            // for this newly added consumer.
120            if (AdvisorySupport.isConnectionAdvisoryTopic(info.getDestination())) {
121                // Replay the connections.
122                for (Iterator<ConnectionInfo> iter = connections.values().iterator(); iter.hasNext(); ) {
123                    ConnectionInfo value = iter.next();
124                    ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
125                    fireAdvisory(context, topic, value, info.getConsumerId());
126                }
127            }
128
129            // We check here whether the Destination is Temporary Destination specific or not since we
130            // can avoid sending advisory messages to the consumer if it only wants Temporary Destination
131            // notifications.  If its not just temporary destination related destinations then we have
132            // to send them all, a composite destination could want both.
133            if (AdvisorySupport.isTempDestinationAdvisoryTopic(info.getDestination())) {
134                // Replay the temporary destinations.
135                for (DestinationInfo destination : destinations.values()) {
136                    if (destination.getDestination().isTemporary()) {
137                        ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
138                        fireAdvisory(context, topic, destination, info.getConsumerId());
139                    }
140                }
141            } else if (AdvisorySupport.isDestinationAdvisoryTopic(info.getDestination())) {
142                // Replay all the destinations.
143                for (DestinationInfo destination : destinations.values()) {
144                    ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
145                    fireAdvisory(context, topic, destination, info.getConsumerId());
146                }
147            }
148
149            // Replay the producers.
150            if (AdvisorySupport.isProducerAdvisoryTopic(info.getDestination())) {
151                for (Iterator<ProducerInfo> iter = producers.values().iterator(); iter.hasNext(); ) {
152                    ProducerInfo value = iter.next();
153                    ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(value.getDestination());
154                    fireProducerAdvisory(context, value.getDestination(), topic, value, info.getConsumerId());
155                }
156            }
157
158            // Replay the consumers.
159            if (AdvisorySupport.isConsumerAdvisoryTopic(info.getDestination())) {
160                consumersLock.readLock().lock();
161                try {
162                    for (Iterator<ConsumerInfo> iter = consumers.values().iterator(); iter.hasNext(); ) {
163                        ConsumerInfo value = iter.next();
164                        ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(value.getDestination());
165                        fireConsumerAdvisory(context, value.getDestination(), topic, value, info.getConsumerId());
166                    }
167                } finally {
168                    consumersLock.readLock().unlock();
169                }
170            }
171
172            // Replay network bridges
173            if (AdvisorySupport.isNetworkBridgeAdvisoryTopic(info.getDestination())) {
174                for (Iterator<BrokerInfo> iter = networkBridges.keySet().iterator(); iter.hasNext(); ) {
175                    BrokerInfo key = iter.next();
176                    ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
177                    fireAdvisory(context, topic, key, null, networkBridges.get(key));
178                }
179            }
180        }
181        return answer;
182    }
183
184    @Override
185    public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
186        super.addProducer(context, info);
187
188        // Don't advise advisory topics.
189        if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
190            ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(info.getDestination());
191            fireProducerAdvisory(context, info.getDestination(), topic, info);
192            producers.put(info.getProducerId(), info);
193        }
194    }
195
196    @Override
197    public Destination addDestination(ConnectionContext context, ActiveMQDestination destination, boolean create) throws Exception {
198        Destination answer = super.addDestination(context, destination, create);
199        if (!AdvisorySupport.isAdvisoryTopic(destination)) {
200            DestinationInfo info = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, destination);
201            DestinationInfo previous = destinations.putIfAbsent(destination, info);
202            if (previous == null) {
203                ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
204                fireAdvisory(context, topic, info);
205            }
206        }
207        return answer;
208    }
209
210    @Override
211    public void addDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception {
212        ActiveMQDestination destination = info.getDestination();
213        next.addDestinationInfo(context, info);
214
215        if (!AdvisorySupport.isAdvisoryTopic(destination)) {
216            DestinationInfo previous = destinations.putIfAbsent(destination, info);
217            if (previous == null) {
218                ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
219                fireAdvisory(context, topic, info);
220            }
221        }
222    }
223
224    @Override
225    public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
226        super.removeDestination(context, destination, timeout);
227        DestinationInfo info = destinations.remove(destination);
228        if (info != null) {
229            // ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
230            info = info.copy();
231            info.setDestination(destination);
232            info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
233            ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
234            fireAdvisory(context, topic, info);
235            ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destination);
236            for (ActiveMQTopic advisoryDestination : advisoryDestinations) {
237                try {
238                    next.removeDestination(context, advisoryDestination, -1);
239                } catch (Exception expectedIfDestinationDidNotExistYet) {
240                }
241            }
242        }
243    }
244
245    @Override
246    public void removeDestinationInfo(ConnectionContext context, DestinationInfo destInfo) throws Exception {
247        super.removeDestinationInfo(context, destInfo);
248        DestinationInfo info = destinations.remove(destInfo.getDestination());
249        if (info != null) {
250            // ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
251            info = info.copy();
252            info.setDestination(destInfo.getDestination());
253            info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
254            ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destInfo.getDestination());
255            fireAdvisory(context, topic, info);
256            ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destInfo.getDestination());
257            for (ActiveMQTopic advisoryDestination : advisoryDestinations) {
258                try {
259                    next.removeDestination(context, advisoryDestination, -1);
260                } catch (Exception expectedIfDestinationDidNotExistYet) {
261                }
262            }
263        }
264    }
265
266    @Override
267    public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
268        super.removeConnection(context, info, error);
269
270        ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
271        fireAdvisory(context, topic, info.createRemoveCommand());
272        connections.remove(info.getConnectionId());
273    }
274
275    @Override
276    public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
277        super.removeConsumer(context, info);
278
279        // Don't advise advisory topics.
280        ActiveMQDestination dest = info.getDestination();
281        if (!AdvisorySupport.isAdvisoryTopic(dest)) {
282            ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(dest);
283            consumersLock.writeLock().lock();
284            try {
285                consumers.remove(info.getConsumerId());
286            } finally {
287                consumersLock.writeLock().unlock();
288            }
289            if (!dest.isTemporary() || destinations.containsKey(dest)) {
290                fireConsumerAdvisory(context, dest, topic, info.createRemoveCommand());
291            }
292        }
293    }
294
295    @Override
296    public void removeSubscription(ConnectionContext context, RemoveSubscriptionInfo info) throws Exception {
297        SubscriptionKey key = new SubscriptionKey(context.getClientId(), info.getSubscriptionName());
298
299        RegionBroker regionBroker = null;
300        if (next instanceof RegionBroker) {
301            regionBroker = (RegionBroker) next;
302        } else {
303            BrokerService service = next.getBrokerService();
304            regionBroker = (RegionBroker) service.getRegionBroker();
305        }
306
307        if (regionBroker == null) {
308            LOG.warn("Cannot locate a RegionBroker instance to pass along the removeSubscription call");
309            throw new IllegalStateException("No RegionBroker found.");
310        }
311
312        DurableTopicSubscription sub = ((TopicRegion) regionBroker.getTopicRegion()).getDurableSubscription(key);
313
314        super.removeSubscription(context, info);
315
316        if (sub == null) {
317            LOG.warn("We cannot send an advisory message for a durable sub removal when we don't know about the durable sub");
318            return;
319        }
320
321        ActiveMQDestination dest = sub.getConsumerInfo().getDestination();
322
323        // Don't advise advisory topics.
324        if (!AdvisorySupport.isAdvisoryTopic(dest)) {
325            ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(dest);
326            fireConsumerAdvisory(context, dest, topic, info);
327        }
328
329    }
330
331    @Override
332    public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
333        super.removeProducer(context, info);
334
335        // Don't advise advisory topics.
336        ActiveMQDestination dest = info.getDestination();
337        if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(dest)) {
338            ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(dest);
339            producers.remove(info.getProducerId());
340            if (!dest.isTemporary() || destinations.containsKey(dest)) {
341                fireProducerAdvisory(context, dest, topic, info.createRemoveCommand());
342            }
343        }
344    }
345
346    @Override
347    public void messageExpired(ConnectionContext context, MessageReference messageReference, Subscription subscription) {
348        super.messageExpired(context, messageReference, subscription);
349        try {
350            if (!messageReference.isAdvisory()) {
351                ActiveMQTopic topic = AdvisorySupport.getExpiredMessageTopic(messageReference.getMessage().getDestination());
352                Message payload = messageReference.getMessage().copy();
353                payload.clearBody();
354                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
355                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
356                fireAdvisory(context, topic, payload, null, advisoryMessage);
357            }
358        } catch (Exception e) {
359            handleFireFailure("expired", e);
360        }
361    }
362
363    @Override
364    public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
365        super.messageConsumed(context, messageReference);
366        try {
367            if (!messageReference.isAdvisory()) {
368                ActiveMQTopic topic = AdvisorySupport.getMessageConsumedAdvisoryTopic(messageReference.getMessage().getDestination());
369                Message payload = messageReference.getMessage().copy();
370                payload.clearBody();
371                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
372                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
373                ActiveMQDestination destination = payload.getDestination();
374                if (destination != null) {
375                    advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_DESTINATION, payload.getMessageId().toString());
376                }
377                fireAdvisory(context, topic, payload, null, advisoryMessage);
378            }
379        } catch (Exception e) {
380            handleFireFailure("consumed", e);
381        }
382    }
383
384    @Override
385    public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
386        super.messageDelivered(context, messageReference);
387        try {
388            if (!messageReference.isAdvisory()) {
389                ActiveMQTopic topic = AdvisorySupport.getMessageDeliveredAdvisoryTopic(messageReference.getMessage().getDestination());
390                Message payload = messageReference.getMessage().copy();
391                payload.clearBody();
392                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
393                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
394                ActiveMQDestination destination = payload.getDestination();
395                if (destination != null) {
396                    advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_DESTINATION, payload.getMessageId().toString());
397                }
398                fireAdvisory(context, topic, payload, null, advisoryMessage);
399            }
400        } catch (Exception e) {
401            handleFireFailure("delivered", e);
402        }
403    }
404
405    @Override
406    public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
407        super.messageDiscarded(context, sub, messageReference);
408        try {
409            if (!messageReference.isAdvisory()) {
410                ActiveMQTopic topic = AdvisorySupport.getMessageDiscardedAdvisoryTopic(messageReference.getMessage().getDestination());
411                Message payload = messageReference.getMessage().copy();
412                payload.clearBody();
413                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
414                if (sub instanceof TopicSubscription) {
415                    advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_DISCARDED_COUNT, ((TopicSubscription) sub).discarded());
416                }
417                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
418                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, sub.getConsumerInfo().getConsumerId().toString());
419                ActiveMQDestination destination = payload.getDestination();
420                if (destination != null) {
421                    advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_DESTINATION, payload.getMessageId().toString());
422                }
423                fireAdvisory(context, topic, payload, null, advisoryMessage);
424            }
425        } catch (Exception e) {
426            handleFireFailure("discarded", e);
427        }
428    }
429
430    @Override
431    public void slowConsumer(ConnectionContext context, Destination destination, Subscription subs) {
432        super.slowConsumer(context, destination, subs);
433        try {
434            if (!AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination())) {
435                ActiveMQTopic topic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination.getActiveMQDestination());
436                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
437                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, subs.getConsumerInfo().getConsumerId().toString());
438                fireAdvisory(context, topic, subs.getConsumerInfo(), null, advisoryMessage);
439            }
440        } catch (Exception e) {
441            handleFireFailure("slow consumer", e);
442        }
443    }
444
445    @Override
446    public void fastProducer(ConnectionContext context, ProducerInfo producerInfo, ActiveMQDestination destination) {
447        super.fastProducer(context, producerInfo, destination);
448        try {
449            if (!AdvisorySupport.isAdvisoryTopic(destination)) {
450                ActiveMQTopic topic = AdvisorySupport.getFastProducerAdvisoryTopic(destination);
451                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
452                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_PRODUCER_ID, producerInfo.getProducerId().toString());
453                fireAdvisory(context, topic, producerInfo, null, advisoryMessage);
454            }
455        } catch (Exception e) {
456            handleFireFailure("fast producer", e);
457        }
458    }
459
460    @Override
461    public void isFull(ConnectionContext context, Destination destination, Usage usage) {
462        super.isFull(context, destination, usage);
463        if (AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination()) == false) {
464            try {
465
466                ActiveMQTopic topic = AdvisorySupport.getFullAdvisoryTopic(destination.getActiveMQDestination());
467                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
468                advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_USAGE_NAME, usage.getName());
469                fireAdvisory(context, topic, null, null, advisoryMessage);
470
471            } catch (Exception e) {
472                handleFireFailure("is full", e);
473            }
474        }
475    }
476
477    @Override
478    public void nowMasterBroker() {
479        super.nowMasterBroker();
480        try {
481            ActiveMQTopic topic = AdvisorySupport.getMasterBrokerAdvisoryTopic();
482            ActiveMQMessage advisoryMessage = new ActiveMQMessage();
483            ConnectionContext context = new ConnectionContext();
484            context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
485            context.setBroker(getBrokerService().getBroker());
486            fireAdvisory(context, topic, null, null, advisoryMessage);
487        } catch (Exception e) {
488            handleFireFailure("now master broker", e);
489        }
490    }
491
492    @Override
493    public boolean sendToDeadLetterQueue(ConnectionContext context, MessageReference messageReference,
494                                         Subscription subscription, Throwable poisonCause) {
495        boolean wasDLQd = super.sendToDeadLetterQueue(context, messageReference, subscription, poisonCause);
496        if (wasDLQd) {
497            try {
498                if (!messageReference.isAdvisory()) {
499                    ActiveMQTopic topic = AdvisorySupport.getMessageDLQdAdvisoryTopic(messageReference.getMessage().getDestination());
500                    Message payload = messageReference.getMessage().copy();
501                    payload.clearBody();
502                    fireAdvisory(context, topic, payload);
503                }
504            } catch (Exception e) {
505                handleFireFailure("add to DLQ", e);
506            }
507        }
508
509        return wasDLQd;
510    }
511
512    @Override
513    public void networkBridgeStarted(BrokerInfo brokerInfo, boolean createdByDuplex, String remoteIp) {
514        try {
515            if (brokerInfo != null) {
516                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
517                advisoryMessage.setBooleanProperty("started", true);
518                advisoryMessage.setBooleanProperty("createdByDuplex", createdByDuplex);
519                advisoryMessage.setStringProperty("remoteIp", remoteIp);
520                networkBridges.putIfAbsent(brokerInfo, advisoryMessage);
521
522                ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
523
524                ConnectionContext context = new ConnectionContext();
525                context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
526                context.setBroker(getBrokerService().getBroker());
527                fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
528            }
529        } catch (Exception e) {
530            handleFireFailure("network bridge started", e);
531        }
532    }
533
534    @Override
535    public void networkBridgeStopped(BrokerInfo brokerInfo) {
536        try {
537            if (brokerInfo != null) {
538                ActiveMQMessage advisoryMessage = new ActiveMQMessage();
539                advisoryMessage.setBooleanProperty("started", false);
540                networkBridges.remove(brokerInfo);
541
542                ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
543
544                ConnectionContext context = new ConnectionContext();
545                context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
546                context.setBroker(getBrokerService().getBroker());
547                fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
548            }
549        } catch (Exception e) {
550            handleFireFailure("network bridge stopped", e);
551        }
552    }
553
554    private void handleFireFailure(String message, Throwable cause) {
555        LOG.warn("Failed to fire {} advisory, reason: {}", message, cause);
556        LOG.debug("{} detail: {}", message, cause);
557    }
558
559    protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command) throws Exception {
560        fireAdvisory(context, topic, command, null);
561    }
562
563    protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
564        ActiveMQMessage advisoryMessage = new ActiveMQMessage();
565        fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
566    }
567
568    protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination, ActiveMQTopic topic, Command command) throws Exception {
569        fireConsumerAdvisory(context, consumerDestination, topic, command, null);
570    }
571
572    protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
573        ActiveMQMessage advisoryMessage = new ActiveMQMessage();
574        int count = 0;
575        Set<Destination> set = getDestinations(consumerDestination);
576        if (set != null) {
577            for (Destination dest : set) {
578                count += dest.getDestinationStatistics().getConsumers().getCount();
579            }
580        }
581        advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_COUNT, count);
582
583        fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
584    }
585
586    protected void fireProducerAdvisory(ConnectionContext context, ActiveMQDestination producerDestination, ActiveMQTopic topic, Command command) throws Exception {
587        fireProducerAdvisory(context, producerDestination, topic, command, null);
588    }
589
590    protected void fireProducerAdvisory(ConnectionContext context, ActiveMQDestination producerDestination, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
591        ActiveMQMessage advisoryMessage = new ActiveMQMessage();
592        int count = 0;
593        if (producerDestination != null) {
594            Set<Destination> set = getDestinations(producerDestination);
595            if (set != null) {
596                for (Destination dest : set) {
597                    count += dest.getDestinationStatistics().getProducers().getCount();
598                }
599            }
600        }
601        advisoryMessage.setIntProperty("producerCount", count);
602        fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
603    }
604
605    public void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId, ActiveMQMessage advisoryMessage) throws Exception {
606        if (getBrokerService().isStarted()) {
607            //set properties
608            advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName());
609            String id = getBrokerId() != null ? getBrokerId().getValue() : "NOT_SET";
610            advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id);
611
612            String url = getBrokerService().getVmConnectorURI().toString();
613            if (getBrokerService().getDefaultSocketURIString() != null) {
614                url = getBrokerService().getDefaultSocketURIString();
615            }
616            advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url);
617
618            //set the data structure
619            advisoryMessage.setDataStructure(command);
620            advisoryMessage.setPersistent(false);
621            advisoryMessage.setType(AdvisorySupport.ADIVSORY_MESSAGE_TYPE);
622            advisoryMessage.setMessageId(new MessageId(advisoryProducerId, messageIdGenerator.getNextSequenceId()));
623            advisoryMessage.setTargetConsumerId(targetConsumerId);
624            advisoryMessage.setDestination(topic);
625            advisoryMessage.setResponseRequired(false);
626            advisoryMessage.setProducerId(advisoryProducerId);
627            boolean originalFlowControl = context.isProducerFlowControl();
628            final ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
629            producerExchange.setConnectionContext(context);
630            producerExchange.setMutable(true);
631            producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
632            try {
633                context.setProducerFlowControl(false);
634                next.send(producerExchange, advisoryMessage);
635            } finally {
636                context.setProducerFlowControl(originalFlowControl);
637            }
638        }
639    }
640
641    public Map<ConnectionId, ConnectionInfo> getAdvisoryConnections() {
642        return connections;
643    }
644
645    public Collection<ConsumerInfo> getAdvisoryConsumers() {
646        consumersLock.readLock().lock();
647        try {
648            return new ArrayList<ConsumerInfo>(consumers.values());
649        } finally {
650            consumersLock.readLock().unlock();
651        }
652    }
653
654    public Map<ProducerId, ProducerInfo> getAdvisoryProducers() {
655        return producers;
656    }
657
658    public Map<ActiveMQDestination, DestinationInfo> getAdvisoryDestinations() {
659        return destinations;
660    }
661}