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.network;
018
019import java.io.IOException;
020import java.security.GeneralSecurityException;
021import java.security.cert.X509Certificate;
022import java.util.Arrays;
023import java.util.Collection;
024import java.util.Iterator;
025import java.util.List;
026import java.util.Properties;
027import java.util.concurrent.ConcurrentHashMap;
028import java.util.concurrent.ConcurrentMap;
029import java.util.concurrent.CountDownLatch;
030import java.util.concurrent.ExecutionException;
031import java.util.concurrent.ExecutorService;
032import java.util.concurrent.Executors;
033import java.util.concurrent.Future;
034import java.util.concurrent.TimeUnit;
035import java.util.concurrent.TimeoutException;
036import java.util.concurrent.atomic.AtomicBoolean;
037import java.util.concurrent.atomic.AtomicLong;
038
039import javax.management.ObjectName;
040
041import org.apache.activemq.DestinationDoesNotExistException;
042import org.apache.activemq.Service;
043import org.apache.activemq.advisory.AdvisoryBroker;
044import org.apache.activemq.advisory.AdvisorySupport;
045import org.apache.activemq.broker.BrokerService;
046import org.apache.activemq.broker.BrokerServiceAware;
047import org.apache.activemq.broker.ConnectionContext;
048import org.apache.activemq.broker.TransportConnection;
049import org.apache.activemq.broker.region.AbstractRegion;
050import org.apache.activemq.broker.region.DurableTopicSubscription;
051import org.apache.activemq.broker.region.Region;
052import org.apache.activemq.broker.region.RegionBroker;
053import org.apache.activemq.broker.region.Subscription;
054import org.apache.activemq.broker.region.policy.PolicyEntry;
055import org.apache.activemq.command.ActiveMQDestination;
056import org.apache.activemq.command.ActiveMQMessage;
057import org.apache.activemq.command.ActiveMQTempDestination;
058import org.apache.activemq.command.ActiveMQTopic;
059import org.apache.activemq.command.BrokerId;
060import org.apache.activemq.command.BrokerInfo;
061import org.apache.activemq.command.Command;
062import org.apache.activemq.command.ConnectionError;
063import org.apache.activemq.command.ConnectionId;
064import org.apache.activemq.command.ConnectionInfo;
065import org.apache.activemq.command.ConsumerId;
066import org.apache.activemq.command.ConsumerInfo;
067import org.apache.activemq.command.DataStructure;
068import org.apache.activemq.command.DestinationInfo;
069import org.apache.activemq.command.ExceptionResponse;
070import org.apache.activemq.command.KeepAliveInfo;
071import org.apache.activemq.command.Message;
072import org.apache.activemq.command.MessageAck;
073import org.apache.activemq.command.MessageDispatch;
074import org.apache.activemq.command.MessageId;
075import org.apache.activemq.command.NetworkBridgeFilter;
076import org.apache.activemq.command.ProducerInfo;
077import org.apache.activemq.command.RemoveInfo;
078import org.apache.activemq.command.RemoveSubscriptionInfo;
079import org.apache.activemq.command.Response;
080import org.apache.activemq.command.SessionInfo;
081import org.apache.activemq.command.ShutdownInfo;
082import org.apache.activemq.command.SubscriptionInfo;
083import org.apache.activemq.command.WireFormatInfo;
084import org.apache.activemq.filter.DestinationFilter;
085import org.apache.activemq.filter.MessageEvaluationContext;
086import org.apache.activemq.security.SecurityContext;
087import org.apache.activemq.transport.DefaultTransportListener;
088import org.apache.activemq.transport.FutureResponse;
089import org.apache.activemq.transport.ResponseCallback;
090import org.apache.activemq.transport.Transport;
091import org.apache.activemq.transport.TransportDisposedIOException;
092import org.apache.activemq.transport.TransportFilter;
093import org.apache.activemq.transport.tcp.SslTransport;
094import org.apache.activemq.util.IdGenerator;
095import org.apache.activemq.util.IntrospectionSupport;
096import org.apache.activemq.util.LongSequenceGenerator;
097import org.apache.activemq.util.MarshallingSupport;
098import org.apache.activemq.util.ServiceStopper;
099import org.apache.activemq.util.ServiceSupport;
100import org.slf4j.Logger;
101import org.slf4j.LoggerFactory;
102
103/**
104 * A useful base class for implementing demand forwarding bridges.
105 */
106public abstract class DemandForwardingBridgeSupport implements NetworkBridge, BrokerServiceAware {
107    private static final Logger LOG = LoggerFactory.getLogger(DemandForwardingBridgeSupport.class);
108    protected static final String DURABLE_SUB_PREFIX = "NC-DS_";
109    protected final Transport localBroker;
110    protected final Transport remoteBroker;
111    protected IdGenerator idGenerator = new IdGenerator();
112    protected final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator();
113    protected ConnectionInfo localConnectionInfo;
114    protected ConnectionInfo remoteConnectionInfo;
115    protected SessionInfo localSessionInfo;
116    protected ProducerInfo producerInfo;
117    protected String remoteBrokerName = "Unknown";
118    protected String localClientId;
119    protected ConsumerInfo demandConsumerInfo;
120    protected int demandConsumerDispatched;
121    protected final AtomicBoolean localBridgeStarted = new AtomicBoolean(false);
122    protected final AtomicBoolean remoteBridgeStarted = new AtomicBoolean(false);
123    protected final AtomicBoolean bridgeFailed = new AtomicBoolean();
124    protected final AtomicBoolean disposed = new AtomicBoolean();
125    protected BrokerId localBrokerId;
126    protected ActiveMQDestination[] excludedDestinations;
127    protected ActiveMQDestination[] dynamicallyIncludedDestinations;
128    protected ActiveMQDestination[] staticallyIncludedDestinations;
129    protected ActiveMQDestination[] durableDestinations;
130    protected final ConcurrentMap<ConsumerId, DemandSubscription> subscriptionMapByLocalId = new ConcurrentHashMap<ConsumerId, DemandSubscription>();
131    protected final ConcurrentMap<ConsumerId, DemandSubscription> subscriptionMapByRemoteId = new ConcurrentHashMap<ConsumerId, DemandSubscription>();
132    protected final BrokerId localBrokerPath[] = new BrokerId[]{null};
133    protected final CountDownLatch startedLatch = new CountDownLatch(2);
134    protected final CountDownLatch localStartedLatch = new CountDownLatch(1);
135    protected final AtomicBoolean lastConnectSucceeded = new AtomicBoolean(false);
136    protected NetworkBridgeConfiguration configuration;
137    protected final NetworkBridgeFilterFactory defaultFilterFactory = new DefaultNetworkBridgeFilterFactory();
138
139    protected final BrokerId remoteBrokerPath[] = new BrokerId[]{null};
140    protected BrokerId remoteBrokerId;
141
142    final AtomicLong enqueueCounter = new AtomicLong();
143    final AtomicLong dequeueCounter = new AtomicLong();
144
145    private NetworkBridgeListener networkBridgeListener;
146    private boolean createdByDuplex;
147    private BrokerInfo localBrokerInfo;
148    private BrokerInfo remoteBrokerInfo;
149
150    private final FutureBrokerInfo futureRemoteBrokerInfo = new FutureBrokerInfo(remoteBrokerInfo, disposed);
151    private final FutureBrokerInfo futureLocalBrokerInfo = new FutureBrokerInfo(localBrokerInfo, disposed);
152
153    private final AtomicBoolean started = new AtomicBoolean();
154    private TransportConnection duplexInitiatingConnection;
155    private final AtomicBoolean duplexInitiatingConnectionInfoReceived = new AtomicBoolean();
156    protected BrokerService brokerService = null;
157    private ObjectName mbeanObjectName;
158    private final ExecutorService serialExecutor = Executors.newSingleThreadExecutor();
159    private Transport duplexInboundLocalBroker = null;
160    private ProducerInfo duplexInboundLocalProducerInfo;
161
162    public DemandForwardingBridgeSupport(NetworkBridgeConfiguration configuration, Transport localBroker, Transport remoteBroker) {
163        this.configuration = configuration;
164        this.localBroker = localBroker;
165        this.remoteBroker = remoteBroker;
166    }
167
168    public void duplexStart(TransportConnection connection, BrokerInfo localBrokerInfo, BrokerInfo remoteBrokerInfo) throws Exception {
169        this.localBrokerInfo = localBrokerInfo;
170        this.remoteBrokerInfo = remoteBrokerInfo;
171        this.duplexInitiatingConnection = connection;
172        start();
173        serviceRemoteCommand(remoteBrokerInfo);
174    }
175
176    @Override
177    public void start() throws Exception {
178        if (started.compareAndSet(false, true)) {
179
180            if (brokerService == null) {
181                throw new IllegalArgumentException("BrokerService is null on " + this);
182            }
183
184            if (isDuplex()) {
185                duplexInboundLocalBroker = NetworkBridgeFactory.createLocalTransport(brokerService.getBroker());
186                duplexInboundLocalBroker.setTransportListener(new DefaultTransportListener() {
187
188                    @Override
189                    public void onCommand(Object o) {
190                        Command command = (Command) o;
191                        serviceLocalCommand(command);
192                    }
193
194                    @Override
195                    public void onException(IOException error) {
196                        serviceLocalException(error);
197                    }
198                });
199                duplexInboundLocalBroker.start();
200            }
201
202            localBroker.setTransportListener(new DefaultTransportListener() {
203
204                @Override
205                public void onCommand(Object o) {
206                    Command command = (Command) o;
207                    serviceLocalCommand(command);
208                }
209
210                @Override
211                public void onException(IOException error) {
212                    if (!futureLocalBrokerInfo.isDone()) {
213                        futureLocalBrokerInfo.cancel(true);
214                        return;
215                    }
216                    serviceLocalException(error);
217                }
218            });
219
220            remoteBroker.setTransportListener(new DefaultTransportListener() {
221
222                @Override
223                public void onCommand(Object o) {
224                    Command command = (Command) o;
225                    serviceRemoteCommand(command);
226                }
227
228                @Override
229                public void onException(IOException error) {
230                    if (!futureRemoteBrokerInfo.isDone()) {
231                        futureRemoteBrokerInfo.cancel(true);
232                        return;
233                    }
234                    serviceRemoteException(error);
235                }
236            });
237
238            remoteBroker.start();
239            localBroker.start();
240
241            if (!disposed.get()) {
242                try {
243                    triggerStartAsyncNetworkBridgeCreation();
244                } catch (IOException e) {
245                    LOG.warn("Caught exception from remote start", e);
246                }
247            } else {
248                LOG.warn("Bridge was disposed before the start() method was fully executed.");
249                throw new TransportDisposedIOException();
250            }
251        }
252    }
253
254    @Override
255    public void stop() throws Exception {
256        if (started.compareAndSet(true, false)) {
257            if (disposed.compareAndSet(false, true)) {
258                LOG.debug(" stopping {} bridge to {}", configuration.getBrokerName(), remoteBrokerName);
259
260                futureRemoteBrokerInfo.cancel(true);
261                futureLocalBrokerInfo.cancel(true);
262
263                NetworkBridgeListener l = this.networkBridgeListener;
264                if (l != null) {
265                    l.onStop(this);
266                }
267                try {
268                    // local start complete
269                    if (startedLatch.getCount() < 2) {
270                        LOG.trace("{} unregister bridge ({}) to {}", new Object[]{
271                                configuration.getBrokerName(), this, remoteBrokerName
272                        });
273                        brokerService.getBroker().removeBroker(null, remoteBrokerInfo);
274                        brokerService.getBroker().networkBridgeStopped(remoteBrokerInfo);
275                    }
276
277                    remoteBridgeStarted.set(false);
278                    final CountDownLatch sendShutdown = new CountDownLatch(1);
279
280                    brokerService.getTaskRunnerFactory().execute(new Runnable() {
281                        @Override
282                        public void run() {
283                            try {
284                                serialExecutor.shutdown();
285                                if (!serialExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
286                                    List<Runnable> pendingTasks = serialExecutor.shutdownNow();
287                                    LOG.info("pending tasks on stop {}", pendingTasks);
288                                }
289                                localBroker.oneway(new ShutdownInfo());
290                                remoteBroker.oneway(new ShutdownInfo());
291                            } catch (Throwable e) {
292                                LOG.debug("Caught exception sending shutdown", e);
293                            } finally {
294                                sendShutdown.countDown();
295                            }
296
297                        }
298                    }, "ActiveMQ ForwardingBridge StopTask");
299
300                    if (!sendShutdown.await(10, TimeUnit.SECONDS)) {
301                        LOG.info("Network Could not shutdown in a timely manner");
302                    }
303                } finally {
304                    ServiceStopper ss = new ServiceStopper();
305                    ss.stop(remoteBroker);
306                    ss.stop(localBroker);
307                    ss.stop(duplexInboundLocalBroker);
308                    // Release the started Latch since another thread could be
309                    // stuck waiting for it to start up.
310                    startedLatch.countDown();
311                    startedLatch.countDown();
312                    localStartedLatch.countDown();
313
314                    ss.throwFirstException();
315                }
316            }
317
318            LOG.info("{} bridge to {} stopped", configuration.getBrokerName(), remoteBrokerName);
319        }
320    }
321
322    protected void triggerStartAsyncNetworkBridgeCreation() throws IOException {
323        brokerService.getTaskRunnerFactory().execute(new Runnable() {
324            @Override
325            public void run() {
326                final String originalName = Thread.currentThread().getName();
327                Thread.currentThread().setName("triggerStartAsyncNetworkBridgeCreation: " +
328                        "remoteBroker=" + remoteBroker + ", localBroker= " + localBroker);
329
330                try {
331                    // First we collect the info data from both the local and remote ends
332                    collectBrokerInfos();
333
334                    // Once we have all required broker info we can attempt to start
335                    // the local and then remote sides of the bridge.
336                    doStartLocalAndRemoteBridges();
337                } finally {
338                    Thread.currentThread().setName(originalName);
339                }
340            }
341        });
342    }
343
344    private void collectBrokerInfos() {
345
346        // First wait for the remote to feed us its BrokerInfo, then we can check on
347        // the LocalBrokerInfo and decide is this is a loop.
348        try {
349            remoteBrokerInfo = futureRemoteBrokerInfo.get();
350            if (remoteBrokerInfo == null) {
351                serviceLocalException(new Throwable("remoteBrokerInfo is null"));
352                return;
353            }
354        } catch (Exception e) {
355            serviceRemoteException(e);
356            return;
357        }
358
359        try {
360            localBrokerInfo = futureLocalBrokerInfo.get();
361            if (localBrokerInfo == null) {
362                serviceLocalException(new Throwable("localBrokerInfo is null"));
363                return;
364            }
365
366            // Before we try and build the bridge lets check if we are in a loop
367            // and if so just stop now before registering anything.
368            remoteBrokerId = remoteBrokerInfo.getBrokerId();
369            if (localBrokerId.equals(remoteBrokerId)) {
370                LOG.trace("{} disconnecting remote loop back connector for: {}, with id: {}", new Object[]{
371                        configuration.getBrokerName(), remoteBrokerName, remoteBrokerId
372                });
373                ServiceSupport.dispose(localBroker);
374                ServiceSupport.dispose(remoteBroker);
375                // the bridge is left in a bit of limbo, but it won't get retried
376                // in this state.
377                return;
378            }
379
380            // Fill in the remote broker's information now.
381            remoteBrokerPath[0] = remoteBrokerId;
382            remoteBrokerName = remoteBrokerInfo.getBrokerName();
383            if (configuration.isUseBrokerNamesAsIdSeed()) {
384                idGenerator = new IdGenerator(brokerService.getBrokerName() + "->" + remoteBrokerName);
385            }
386        } catch (Throwable e) {
387            serviceLocalException(e);
388        }
389    }
390
391    private void doStartLocalAndRemoteBridges() {
392
393        if (disposed.get()) {
394            return;
395        }
396
397        if (isCreatedByDuplex()) {
398            // apply remote (propagated) configuration to local duplex bridge before start
399            Properties props = null;
400            try {
401                props = MarshallingSupport.stringToProperties(remoteBrokerInfo.getNetworkProperties());
402                IntrospectionSupport.getProperties(configuration, props, null);
403                if (configuration.getExcludedDestinations() != null) {
404                    excludedDestinations = configuration.getExcludedDestinations().toArray(
405                            new ActiveMQDestination[configuration.getExcludedDestinations().size()]);
406                }
407                if (configuration.getStaticallyIncludedDestinations() != null) {
408                    staticallyIncludedDestinations = configuration.getStaticallyIncludedDestinations().toArray(
409                            new ActiveMQDestination[configuration.getStaticallyIncludedDestinations().size()]);
410                }
411                if (configuration.getDynamicallyIncludedDestinations() != null) {
412                    dynamicallyIncludedDestinations = configuration.getDynamicallyIncludedDestinations().toArray(
413                            new ActiveMQDestination[configuration.getDynamicallyIncludedDestinations().size()]);
414                }
415            } catch (Throwable t) {
416                LOG.error("Error mapping remote configuration: {}", props, t);
417            }
418        }
419
420        try {
421            startLocalBridge();
422        } catch (Throwable e) {
423            serviceLocalException(e);
424            return;
425        }
426
427        try {
428            startRemoteBridge();
429        } catch (Throwable e) {
430            serviceRemoteException(e);
431            return;
432        }
433
434        try {
435            if (safeWaitUntilStarted()) {
436                setupStaticDestinations();
437            }
438        } catch (Throwable e) {
439            serviceLocalException(e);
440        }
441    }
442
443    private void startLocalBridge() throws Throwable {
444        if (!bridgeFailed.get() && localBridgeStarted.compareAndSet(false, true)) {
445            synchronized (this) {
446                LOG.trace("{} starting local Bridge, localBroker={}", configuration.getBrokerName(), localBroker);
447                if (!disposed.get()) {
448
449                    if (idGenerator == null) {
450                        throw new IllegalStateException("Id Generator cannot be null");
451                    }
452
453                    localConnectionInfo = new ConnectionInfo();
454                    localConnectionInfo.setConnectionId(new ConnectionId(idGenerator.generateId()));
455                    localClientId = configuration.getName() + "_" + remoteBrokerName + "_inbound_" + configuration.getBrokerName();
456                    localConnectionInfo.setClientId(localClientId);
457                    localConnectionInfo.setUserName(configuration.getUserName());
458                    localConnectionInfo.setPassword(configuration.getPassword());
459                    Transport originalTransport = remoteBroker;
460                    while (originalTransport instanceof TransportFilter) {
461                        originalTransport = ((TransportFilter) originalTransport).getNext();
462                    }
463                    if (originalTransport instanceof SslTransport) {
464                        X509Certificate[] peerCerts = ((SslTransport) originalTransport).getPeerCertificates();
465                        localConnectionInfo.setTransportContext(peerCerts);
466                    }
467                    // sync requests that may fail
468                    Object resp = localBroker.request(localConnectionInfo);
469                    if (resp instanceof ExceptionResponse) {
470                        throw ((ExceptionResponse) resp).getException();
471                    }
472                    localSessionInfo = new SessionInfo(localConnectionInfo, 1);
473                    localBroker.oneway(localSessionInfo);
474
475                    if (configuration.isDuplex()) {
476                        // separate in-bound channel for forwards so we don't
477                        // contend with out-bound dispatch on same connection
478                        remoteBrokerInfo.setNetworkConnection(true);
479                        duplexInboundLocalBroker.oneway(remoteBrokerInfo);
480
481                        ConnectionInfo duplexLocalConnectionInfo = new ConnectionInfo();
482                        duplexLocalConnectionInfo.setConnectionId(new ConnectionId(idGenerator.generateId()));
483                        duplexLocalConnectionInfo.setClientId(configuration.getName() + "_" + remoteBrokerName + "_inbound_duplex_"
484                                + configuration.getBrokerName());
485                        duplexLocalConnectionInfo.setUserName(configuration.getUserName());
486                        duplexLocalConnectionInfo.setPassword(configuration.getPassword());
487
488                        if (originalTransport instanceof SslTransport) {
489                            X509Certificate[] peerCerts = ((SslTransport) originalTransport).getPeerCertificates();
490                            duplexLocalConnectionInfo.setTransportContext(peerCerts);
491                        }
492                        // sync requests that may fail
493                        resp = duplexInboundLocalBroker.request(duplexLocalConnectionInfo);
494                        if (resp instanceof ExceptionResponse) {
495                            throw ((ExceptionResponse) resp).getException();
496                        }
497                        SessionInfo duplexInboundSession = new SessionInfo(duplexLocalConnectionInfo, 1);
498                        duplexInboundLocalProducerInfo = new ProducerInfo(duplexInboundSession, 1);
499                        duplexInboundLocalBroker.oneway(duplexInboundSession);
500                        duplexInboundLocalBroker.oneway(duplexInboundLocalProducerInfo);
501                    }
502                    brokerService.getBroker().networkBridgeStarted(remoteBrokerInfo, this.createdByDuplex, remoteBroker.toString());
503                    NetworkBridgeListener l = this.networkBridgeListener;
504                    if (l != null) {
505                        l.onStart(this);
506                    }
507
508                    // Let the local broker know the remote broker's ID.
509                    localBroker.oneway(remoteBrokerInfo);
510                    // new peer broker (a consumer can work with remote broker also)
511                    brokerService.getBroker().addBroker(null, remoteBrokerInfo);
512
513                    LOG.info("Network connection between {} and {} ({}) has been established.", new Object[]{
514                            localBroker, remoteBroker, remoteBrokerName
515                    });
516                    LOG.trace("{} register bridge ({}) to {}", new Object[]{
517                            configuration.getBrokerName(), this, remoteBrokerName
518                    });
519                } else {
520                    LOG.warn("Bridge was disposed before the startLocalBridge() method was fully executed.");
521                }
522                startedLatch.countDown();
523                localStartedLatch.countDown();
524            }
525        }
526    }
527
528    protected void startRemoteBridge() throws Exception {
529        if (!bridgeFailed.get() && remoteBridgeStarted.compareAndSet(false, true)) {
530            LOG.trace("{} starting remote Bridge, remoteBroker={}", configuration.getBrokerName(), remoteBroker);
531            synchronized (this) {
532                if (!isCreatedByDuplex()) {
533                    BrokerInfo brokerInfo = new BrokerInfo();
534                    brokerInfo.setBrokerName(configuration.getBrokerName());
535                    brokerInfo.setBrokerURL(configuration.getBrokerURL());
536                    brokerInfo.setNetworkConnection(true);
537                    brokerInfo.setDuplexConnection(configuration.isDuplex());
538                    // set our properties
539                    Properties props = new Properties();
540                    IntrospectionSupport.getProperties(configuration, props, null);
541                    props.remove("networkTTL");
542                    String str = MarshallingSupport.propertiesToString(props);
543                    brokerInfo.setNetworkProperties(str);
544                    brokerInfo.setBrokerId(this.localBrokerId);
545                    remoteBroker.oneway(brokerInfo);
546                }
547                if (remoteConnectionInfo != null) {
548                    remoteBroker.oneway(remoteConnectionInfo.createRemoveCommand());
549                }
550                remoteConnectionInfo = new ConnectionInfo();
551                remoteConnectionInfo.setConnectionId(new ConnectionId(idGenerator.generateId()));
552                remoteConnectionInfo.setClientId(configuration.getName() + "_" + configuration.getBrokerName() + "_outbound");
553                remoteConnectionInfo.setUserName(configuration.getUserName());
554                remoteConnectionInfo.setPassword(configuration.getPassword());
555                remoteBroker.oneway(remoteConnectionInfo);
556
557                SessionInfo remoteSessionInfo = new SessionInfo(remoteConnectionInfo, 1);
558                remoteBroker.oneway(remoteSessionInfo);
559                producerInfo = new ProducerInfo(remoteSessionInfo, 1);
560                producerInfo.setResponseRequired(false);
561                remoteBroker.oneway(producerInfo);
562                // Listen to consumer advisory messages on the remote broker to determine demand.
563                if (!configuration.isStaticBridge()) {
564                    demandConsumerInfo = new ConsumerInfo(remoteSessionInfo, 1);
565                    // always dispatch advisory message asynchronously so that
566                    // we never block the producer broker if we are slow
567                    demandConsumerInfo.setDispatchAsync(true);
568                    String advisoryTopic = configuration.getDestinationFilter();
569                    if (configuration.isBridgeTempDestinations()) {
570                        advisoryTopic += "," + AdvisorySupport.TEMP_DESTINATION_COMPOSITE_ADVISORY_TOPIC;
571                    }
572                    demandConsumerInfo.setDestination(new ActiveMQTopic(advisoryTopic));
573                    demandConsumerInfo.setPrefetchSize(configuration.getPrefetchSize());
574                    remoteBroker.oneway(demandConsumerInfo);
575                }
576                startedLatch.countDown();
577            }
578        }
579    }
580
581    @Override
582    public void serviceRemoteException(Throwable error) {
583        if (!disposed.get()) {
584            if (error instanceof SecurityException || error instanceof GeneralSecurityException) {
585                LOG.error("Network connection between {} and {} shutdown due to a remote error: {}", new Object[]{
586                        localBroker, remoteBroker, error
587                });
588            } else {
589                LOG.warn("Network connection between {} and {} shutdown due to a remote error: {}", new Object[]{
590                        localBroker, remoteBroker, error
591                });
592            }
593            LOG.debug("The remote Exception was: {}", error, error);
594            brokerService.getTaskRunnerFactory().execute(new Runnable() {
595                @Override
596                public void run() {
597                    ServiceSupport.dispose(getControllingService());
598                }
599            });
600            fireBridgeFailed(error);
601        }
602    }
603
604    protected void serviceRemoteCommand(Command command) {
605        if (!disposed.get()) {
606            try {
607                if (command.isMessageDispatch()) {
608                    safeWaitUntilStarted();
609                    MessageDispatch md = (MessageDispatch) command;
610                    serviceRemoteConsumerAdvisory(md.getMessage().getDataStructure());
611                    ackAdvisory(md.getMessage());
612                } else if (command.isBrokerInfo()) {
613                    futureRemoteBrokerInfo.set((BrokerInfo) command);
614                } else if (command.getClass() == ConnectionError.class) {
615                    ConnectionError ce = (ConnectionError) command;
616                    serviceRemoteException(ce.getException());
617                } else {
618                    if (isDuplex()) {
619                        LOG.trace("{} duplex command type: {}", configuration.getBrokerName(), command.getDataStructureType());
620                        if (command.isMessage()) {
621                            final ActiveMQMessage message = (ActiveMQMessage) command;
622                            if (NetworkBridgeFilter.isAdvisoryInterpretedByNetworkBridge(message)) {
623                                serviceRemoteConsumerAdvisory(message.getDataStructure());
624                                ackAdvisory(message);
625                            } else {
626                                if (!isPermissableDestination(message.getDestination(), true)) {
627                                    return;
628                                }
629                                // message being forwarded - we need to
630                                // propagate the response to our local send
631                                if (canDuplexDispatch(message)) {
632                                    message.setProducerId(duplexInboundLocalProducerInfo.getProducerId());
633                                    if (message.isResponseRequired() || configuration.isAlwaysSyncSend()) {
634                                        duplexInboundLocalBroker.asyncRequest(message, new ResponseCallback() {
635                                            final int correlationId = message.getCommandId();
636
637                                            @Override
638                                            public void onCompletion(FutureResponse resp) {
639                                                try {
640                                                    Response reply = resp.getResult();
641                                                    reply.setCorrelationId(correlationId);
642                                                    remoteBroker.oneway(reply);
643                                                } catch (IOException error) {
644                                                    LOG.error("Exception: {} on duplex forward of: {}", error, message);
645                                                    serviceRemoteException(error);
646                                                }
647                                            }
648                                        });
649                                    } else {
650                                        duplexInboundLocalBroker.oneway(message);
651                                    }
652                                    serviceInboundMessage(message);
653                                } else {
654                                    if (message.isResponseRequired() || configuration.isAlwaysSyncSend()) {
655                                        Response reply = new Response();
656                                        reply.setCorrelationId(message.getCommandId());
657                                        remoteBroker.oneway(reply);
658                                    }
659                                }
660                            }
661                        } else {
662                            switch (command.getDataStructureType()) {
663                                case ConnectionInfo.DATA_STRUCTURE_TYPE:
664                                    if (duplexInitiatingConnection != null && duplexInitiatingConnectionInfoReceived.compareAndSet(false, true)) {
665                                        // end of initiating connection setup - propogate to initial connection to get mbean by clientid
666                                        duplexInitiatingConnection.processAddConnection((ConnectionInfo) command);
667                                    } else {
668                                        localBroker.oneway(command);
669                                    }
670                                    break;
671                                case SessionInfo.DATA_STRUCTURE_TYPE:
672                                    localBroker.oneway(command);
673                                    break;
674                                case ProducerInfo.DATA_STRUCTURE_TYPE:
675                                    // using duplexInboundLocalProducerInfo
676                                    break;
677                                case MessageAck.DATA_STRUCTURE_TYPE:
678                                    MessageAck ack = (MessageAck) command;
679                                    DemandSubscription localSub = subscriptionMapByRemoteId.get(ack.getConsumerId());
680                                    if (localSub != null) {
681                                        ack.setConsumerId(localSub.getLocalInfo().getConsumerId());
682                                        localBroker.oneway(ack);
683                                    } else {
684                                        LOG.warn("Matching local subscription not found for ack: {}", ack);
685                                    }
686                                    break;
687                                case ConsumerInfo.DATA_STRUCTURE_TYPE:
688                                    localStartedLatch.await();
689                                    if (started.get()) {
690                                        addConsumerInfo((ConsumerInfo) command);
691                                    } else {
692                                        // received a subscription whilst stopping
693                                        LOG.warn("Stopping - ignoring ConsumerInfo: {}", command);
694                                    }
695                                    break;
696                                case ShutdownInfo.DATA_STRUCTURE_TYPE:
697                                    // initiator is shutting down, controlled case
698                                    // abortive close dealt with by inactivity monitor
699                                    LOG.info("Stopping network bridge on shutdown of remote broker");
700                                    serviceRemoteException(new IOException(command.toString()));
701                                    break;
702                                default:
703                                    LOG.debug("Ignoring remote command: {}", command);
704                            }
705                        }
706                    } else {
707                        switch (command.getDataStructureType()) {
708                            case KeepAliveInfo.DATA_STRUCTURE_TYPE:
709                            case WireFormatInfo.DATA_STRUCTURE_TYPE:
710                            case ShutdownInfo.DATA_STRUCTURE_TYPE:
711                                break;
712                            default:
713                                LOG.warn("Unexpected remote command: {}", command);
714                        }
715                    }
716                }
717            } catch (Throwable e) {
718                LOG.debug("Exception processing remote command: {}", command, e);
719                serviceRemoteException(e);
720            }
721        }
722    }
723
724    private void ackAdvisory(Message message) throws IOException {
725        demandConsumerDispatched++;
726        if (demandConsumerDispatched > (demandConsumerInfo.getPrefetchSize() * .75)) {
727            MessageAck ack = new MessageAck(message, MessageAck.STANDARD_ACK_TYPE, demandConsumerDispatched);
728            ack.setConsumerId(demandConsumerInfo.getConsumerId());
729            remoteBroker.oneway(ack);
730            demandConsumerDispatched = 0;
731        }
732    }
733
734    private void serviceRemoteConsumerAdvisory(DataStructure data) throws IOException {
735        final int networkTTL = configuration.getConsumerTTL();
736        if (data.getClass() == ConsumerInfo.class) {
737            // Create a new local subscription
738            ConsumerInfo info = (ConsumerInfo) data;
739            BrokerId[] path = info.getBrokerPath();
740
741            if (info.isBrowser()) {
742                LOG.debug("{} Ignoring sub from {}, browsers explicitly suppressed", configuration.getBrokerName(), remoteBrokerName);
743                return;
744            }
745
746            if (path != null && networkTTL > -1 && path.length >= networkTTL) {
747                LOG.debug("{} Ignoring sub from {}, restricted to {} network hops only: {}", new Object[]{
748                        configuration.getBrokerName(), remoteBrokerName, networkTTL, info
749                });
750                return;
751            }
752
753            if (contains(path, localBrokerPath[0])) {
754                // Ignore this consumer as it's a consumer we locally sent to the broker.
755                LOG.debug("{} Ignoring sub from {}, already routed through this broker once: {}", new Object[]{
756                        configuration.getBrokerName(), remoteBrokerName, info
757                });
758                return;
759            }
760
761            if (!isPermissableDestination(info.getDestination())) {
762                // ignore if not in the permitted or in the excluded list
763                LOG.debug("{} Ignoring sub from {}, destination {} is not permitted: {}", new Object[]{
764                        configuration.getBrokerName(), remoteBrokerName, info.getDestination(), info
765                });
766                return;
767            }
768
769            // in a cyclic network there can be multiple bridges per broker that can propagate
770            // a network subscription so there is a need to synchronize on a shared entity
771            synchronized (brokerService.getVmConnectorURI()) {
772                addConsumerInfo(info);
773            }
774        } else if (data.getClass() == DestinationInfo.class) {
775            // It's a destination info - we want to pass up information about temporary destinations
776            final DestinationInfo destInfo = (DestinationInfo) data;
777            BrokerId[] path = destInfo.getBrokerPath();
778            if (path != null && networkTTL > -1 && path.length >= networkTTL) {
779                LOG.debug("{} Ignoring destination {} restricted to {} network hops only", new Object[]{
780                        configuration.getBrokerName(), destInfo, networkTTL
781                });
782                return;
783            }
784            if (contains(destInfo.getBrokerPath(), localBrokerPath[0])) {
785                LOG.debug("{} Ignoring destination {} already routed through this broker once", configuration.getBrokerName(), destInfo);
786                return;
787            }
788            destInfo.setConnectionId(localConnectionInfo.getConnectionId());
789            if (destInfo.getDestination() instanceof ActiveMQTempDestination) {
790                // re-set connection id so comes from here
791                ActiveMQTempDestination tempDest = (ActiveMQTempDestination) destInfo.getDestination();
792                tempDest.setConnectionId(localSessionInfo.getSessionId().getConnectionId());
793            }
794            destInfo.setBrokerPath(appendToBrokerPath(destInfo.getBrokerPath(), getRemoteBrokerPath()));
795            LOG.trace("{} bridging {} destination on {} from {}, destination: {}", new Object[]{
796                    configuration.getBrokerName(), (destInfo.isAddOperation() ? "add" : "remove"), localBroker, remoteBrokerName, destInfo
797            });
798            if (destInfo.isRemoveOperation()) {
799                // Serialize with removeSub operations such that all removeSub advisories
800                // are generated
801                serialExecutor.execute(new Runnable() {
802                    @Override
803                    public void run() {
804                        try {
805                            localBroker.oneway(destInfo);
806                        } catch (IOException e) {
807                            LOG.warn("failed to deliver remove command for destination: {}", destInfo.getDestination(), e);
808                        }
809                    }
810                });
811            } else {
812                localBroker.oneway(destInfo);
813            }
814        } else if (data.getClass() == RemoveInfo.class) {
815            ConsumerId id = (ConsumerId) ((RemoveInfo) data).getObjectId();
816            removeDemandSubscription(id);
817        } else if (data.getClass() == RemoveSubscriptionInfo.class) {
818            RemoveSubscriptionInfo info = ((RemoveSubscriptionInfo) data);
819            SubscriptionInfo subscriptionInfo = new SubscriptionInfo(info.getClientId(), info.getSubscriptionName());
820            for (Iterator<DemandSubscription> i = subscriptionMapByLocalId.values().iterator(); i.hasNext(); ) {
821                DemandSubscription ds = i.next();
822                boolean removed = ds.getDurableRemoteSubs().remove(subscriptionInfo);
823                if (removed) {
824                    if (ds.getDurableRemoteSubs().isEmpty()) {
825
826                        // deactivate subscriber
827                        RemoveInfo removeInfo = new RemoveInfo(ds.getLocalInfo().getConsumerId());
828                        localBroker.oneway(removeInfo);
829
830                        // remove subscriber
831                        RemoveSubscriptionInfo sending = new RemoveSubscriptionInfo();
832                        sending.setClientId(localClientId);
833                        sending.setSubscriptionName(ds.getLocalDurableSubscriber().getSubscriptionName());
834                        sending.setConnectionId(this.localConnectionInfo.getConnectionId());
835                        localBroker.oneway(sending);
836
837                        //remove subscriber from map
838                        i.remove();
839                    }
840                }
841            }
842        }
843    }
844
845    @Override
846    public void serviceLocalException(Throwable error) {
847        serviceLocalException(null, error);
848    }
849
850    public void serviceLocalException(MessageDispatch messageDispatch, Throwable error) {
851        LOG.trace("serviceLocalException: disposed {} ex", disposed.get(), error);
852        if (!disposed.get()) {
853            if (error instanceof DestinationDoesNotExistException && ((DestinationDoesNotExistException) error).isTemporary()) {
854                // not a reason to terminate the bridge - temps can disappear with
855                // pending sends as the demand sub may outlive the remote dest
856                if (messageDispatch != null) {
857                    LOG.warn("PoisonAck of {} on forwarding error: {}", messageDispatch.getMessage().getMessageId(), error);
858                    try {
859                        MessageAck poisonAck = new MessageAck(messageDispatch, MessageAck.POSION_ACK_TYPE, 1);
860                        poisonAck.setPoisonCause(error);
861                        localBroker.oneway(poisonAck);
862                    } catch (IOException ioe) {
863                        LOG.error("Failed to posion ack message following forward failure: ", ioe);
864                    }
865                    fireFailedForwardAdvisory(messageDispatch, error);
866                } else {
867                    LOG.warn("Ignoring exception on forwarding to non existent temp dest: ", error);
868                }
869                return;
870            }
871
872            LOG.info("Network connection between {} and {} shutdown due to a local error: {}", new Object[]{localBroker, remoteBroker, error});
873            LOG.debug("The local Exception was: {}", error, error);
874
875            brokerService.getTaskRunnerFactory().execute(new Runnable() {
876                @Override
877                public void run() {
878                    ServiceSupport.dispose(getControllingService());
879                }
880            });
881            fireBridgeFailed(error);
882        }
883    }
884
885    private void fireFailedForwardAdvisory(MessageDispatch messageDispatch, Throwable error) {
886        if (configuration.isAdvisoryForFailedForward()) {
887            AdvisoryBroker advisoryBroker = null;
888            try {
889                advisoryBroker = (AdvisoryBroker) brokerService.getBroker().getAdaptor(AdvisoryBroker.class);
890
891                if (advisoryBroker != null) {
892                    ConnectionContext context = new ConnectionContext();
893                    context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
894                    context.setBroker(brokerService.getBroker());
895
896                    ActiveMQMessage advisoryMessage = new ActiveMQMessage();
897                    advisoryMessage.setStringProperty("cause", error.getLocalizedMessage());
898                    advisoryBroker.fireAdvisory(context, AdvisorySupport.getNetworkBridgeForwardFailureAdvisoryTopic(), messageDispatch.getMessage(), null,
899                            advisoryMessage);
900
901                }
902            } catch (Exception e) {
903                LOG.warn("failed to fire forward failure advisory, cause: {}", e);
904                LOG.debug("detail", e);
905            }
906        }
907    }
908
909    protected Service getControllingService() {
910        return duplexInitiatingConnection != null ? duplexInitiatingConnection : DemandForwardingBridgeSupport.this;
911    }
912
913    protected void addSubscription(DemandSubscription sub) throws IOException {
914        if (sub != null) {
915            if (isDuplex()) {
916                // async vm transport, need to wait for completion
917                localBroker.request(sub.getLocalInfo());
918            } else {
919                localBroker.oneway(sub.getLocalInfo());
920            }
921        }
922    }
923
924    protected void removeSubscription(final DemandSubscription sub) throws IOException {
925        if (sub != null) {
926            LOG.trace("{} remove local subscription: {} for remote {}", new Object[]{configuration.getBrokerName(), sub.getLocalInfo().getConsumerId(), sub.getRemoteInfo().getConsumerId()});
927
928            // ensure not available for conduit subs pending removal
929            subscriptionMapByLocalId.remove(sub.getLocalInfo().getConsumerId());
930            subscriptionMapByRemoteId.remove(sub.getRemoteInfo().getConsumerId());
931
932            // continue removal in separate thread to free up this thread for outstanding responses
933            // Serialize with removeDestination operations so that removeSubs are serialized with
934            // removeDestinations such that all removeSub advisories are generated
935            serialExecutor.execute(new Runnable() {
936                @Override
937                public void run() {
938                    sub.waitForCompletion();
939                    try {
940                        localBroker.oneway(sub.getLocalInfo().createRemoveCommand());
941                    } catch (IOException e) {
942                        LOG.warn("failed to deliver remove command for local subscription, for remote {}", sub.getRemoteInfo().getConsumerId(), e);
943                    }
944                }
945            });
946        }
947    }
948
949    protected Message configureMessage(MessageDispatch md) throws IOException {
950        Message message = md.getMessage().copy();
951        // Update the packet to show where it came from.
952        message.setBrokerPath(appendToBrokerPath(message.getBrokerPath(), localBrokerPath));
953        message.setProducerId(producerInfo.getProducerId());
954        message.setDestination(md.getDestination());
955        message.setMemoryUsage(null);
956        if (message.getOriginalTransactionId() == null) {
957            message.setOriginalTransactionId(message.getTransactionId());
958        }
959        message.setTransactionId(null);
960        if (configuration.isUseCompression()) {
961            message.compress();
962        }
963        return message;
964    }
965
966    protected void serviceLocalCommand(Command command) {
967        if (!disposed.get()) {
968            try {
969                if (command.isMessageDispatch()) {
970                    safeWaitUntilStarted();
971                    enqueueCounter.incrementAndGet();
972                    final MessageDispatch md = (MessageDispatch) command;
973                    final DemandSubscription sub = subscriptionMapByLocalId.get(md.getConsumerId());
974                    if (sub != null && md.getMessage() != null && sub.incrementOutstandingResponses()) {
975
976                        if (suppressMessageDispatch(md, sub)) {
977                            LOG.debug("{} message not forwarded to {} because message came from there or fails TTL, brokerPath: {}, message: {}", new Object[]{
978                                    configuration.getBrokerName(), remoteBrokerName, Arrays.toString(md.getMessage().getBrokerPath()), md.getMessage()
979                            });
980                            // still ack as it may be durable
981                            try {
982                                localBroker.oneway(new MessageAck(md, MessageAck.INDIVIDUAL_ACK_TYPE, 1));
983                            } finally {
984                                sub.decrementOutstandingResponses();
985                            }
986                            return;
987                        }
988
989                        Message message = configureMessage(md);
990                        LOG.debug("bridging ({} -> {}), consumer: {}, destination: {}, brokerPath: {}, message: {}", new Object[]{
991                                configuration.getBrokerName(), remoteBrokerName, (LOG.isTraceEnabled() ? message : message.getMessageId()), md.getConsumerId(), message.getDestination(), Arrays.toString(message.getBrokerPath()), message
992                        });
993
994                        if (isDuplex() && NetworkBridgeFilter.isAdvisoryInterpretedByNetworkBridge(message)) {
995                            try {
996                                // never request b/c they are eventually acked async
997                                remoteBroker.oneway(message);
998                            } finally {
999                                sub.decrementOutstandingResponses();
1000                            }
1001                            return;
1002                        }
1003
1004                        if (message.isPersistent() || configuration.isAlwaysSyncSend()) {
1005
1006                            // The message was not sent using async send, so we should only
1007                            // ack the local broker when we get confirmation that the remote
1008                            // broker has received the message.
1009                            remoteBroker.asyncRequest(message, new ResponseCallback() {
1010                                @Override
1011                                public void onCompletion(FutureResponse future) {
1012                                    try {
1013                                        Response response = future.getResult();
1014                                        if (response.isException()) {
1015                                            ExceptionResponse er = (ExceptionResponse) response;
1016                                            serviceLocalException(md, er.getException());
1017                                        } else {
1018                                            localBroker.oneway(new MessageAck(md, MessageAck.INDIVIDUAL_ACK_TYPE, 1));
1019                                            dequeueCounter.incrementAndGet();
1020                                        }
1021                                    } catch (IOException e) {
1022                                        serviceLocalException(md, e);
1023                                    } finally {
1024                                        sub.decrementOutstandingResponses();
1025                                    }
1026                                }
1027                            });
1028
1029                        } else {
1030                            // If the message was originally sent using async send, we will
1031                            // preserve that QOS by bridging it using an async send (small chance
1032                            // of message loss).
1033                            try {
1034                                remoteBroker.oneway(message);
1035                                localBroker.oneway(new MessageAck(md, MessageAck.INDIVIDUAL_ACK_TYPE, 1));
1036                                dequeueCounter.incrementAndGet();
1037                            } finally {
1038                                sub.decrementOutstandingResponses();
1039                            }
1040                        }
1041                        serviceOutbound(message);
1042                    } else {
1043                        LOG.debug("No subscription registered with this network bridge for consumerId: {} for message: {}", md.getConsumerId(), md.getMessage());
1044                    }
1045                } else if (command.isBrokerInfo()) {
1046                    futureLocalBrokerInfo.set((BrokerInfo) command);
1047                } else if (command.isShutdownInfo()) {
1048                    LOG.info("{} Shutting down {}", configuration.getBrokerName(), configuration.getName());
1049                    stop();
1050                } else if (command.getClass() == ConnectionError.class) {
1051                    ConnectionError ce = (ConnectionError) command;
1052                    serviceLocalException(ce.getException());
1053                } else {
1054                    switch (command.getDataStructureType()) {
1055                        case WireFormatInfo.DATA_STRUCTURE_TYPE:
1056                            break;
1057                        default:
1058                            LOG.warn("Unexpected local command: {}", command);
1059                    }
1060                }
1061            } catch (Throwable e) {
1062                LOG.warn("Caught an exception processing local command", e);
1063                serviceLocalException(e);
1064            }
1065        }
1066    }
1067
1068    private boolean suppressMessageDispatch(MessageDispatch md, DemandSubscription sub) throws Exception {
1069        boolean suppress = false;
1070        // for durable subs, suppression via filter leaves dangling acks so we
1071        // need to check here and allow the ack irrespective
1072        if (sub.getLocalInfo().isDurable()) {
1073            MessageEvaluationContext messageEvalContext = new MessageEvaluationContext();
1074            messageEvalContext.setMessageReference(md.getMessage());
1075            messageEvalContext.setDestination(md.getDestination());
1076            suppress = !sub.getNetworkBridgeFilter().matches(messageEvalContext);
1077        }
1078        return suppress;
1079    }
1080
1081    public static boolean contains(BrokerId[] brokerPath, BrokerId brokerId) {
1082        if (brokerPath != null) {
1083            for (BrokerId id : brokerPath) {
1084                if (brokerId.equals(id)) {
1085                    return true;
1086                }
1087            }
1088        }
1089        return false;
1090    }
1091
1092    protected BrokerId[] appendToBrokerPath(BrokerId[] brokerPath, BrokerId[] pathsToAppend) {
1093        if (brokerPath == null || brokerPath.length == 0) {
1094            return pathsToAppend;
1095        }
1096        BrokerId rc[] = new BrokerId[brokerPath.length + pathsToAppend.length];
1097        System.arraycopy(brokerPath, 0, rc, 0, brokerPath.length);
1098        System.arraycopy(pathsToAppend, 0, rc, brokerPath.length, pathsToAppend.length);
1099        return rc;
1100    }
1101
1102    protected BrokerId[] appendToBrokerPath(BrokerId[] brokerPath, BrokerId idToAppend) {
1103        if (brokerPath == null || brokerPath.length == 0) {
1104            return new BrokerId[]{idToAppend};
1105        }
1106        BrokerId rc[] = new BrokerId[brokerPath.length + 1];
1107        System.arraycopy(brokerPath, 0, rc, 0, brokerPath.length);
1108        rc[brokerPath.length] = idToAppend;
1109        return rc;
1110    }
1111
1112    protected boolean isPermissableDestination(ActiveMQDestination destination) {
1113        return isPermissableDestination(destination, false);
1114    }
1115
1116    protected boolean isPermissableDestination(ActiveMQDestination destination, boolean allowTemporary) {
1117        // Are we not bridging temporary destinations?
1118        if (destination.isTemporary()) {
1119            if (allowTemporary) {
1120                return true;
1121            } else {
1122                return configuration.isBridgeTempDestinations();
1123            }
1124        }
1125
1126        ActiveMQDestination[] dests = staticallyIncludedDestinations;
1127        if (dests != null && dests.length > 0) {
1128            for (ActiveMQDestination dest : dests) {
1129                DestinationFilter inclusionFilter = DestinationFilter.parseFilter(dest);
1130                if (dest != null && inclusionFilter.matches(destination) && dest.getDestinationType() == destination.getDestinationType()) {
1131                    return true;
1132                }
1133            }
1134        }
1135
1136        dests = excludedDestinations;
1137        if (dests != null && dests.length > 0) {
1138            for (ActiveMQDestination dest : dests) {
1139                DestinationFilter exclusionFilter = DestinationFilter.parseFilter(dest);
1140                if (dest != null && exclusionFilter.matches(destination) && dest.getDestinationType() == destination.getDestinationType()) {
1141                    return false;
1142                }
1143            }
1144        }
1145
1146        dests = dynamicallyIncludedDestinations;
1147        if (dests != null && dests.length > 0) {
1148            for (ActiveMQDestination dest : dests) {
1149                DestinationFilter inclusionFilter = DestinationFilter.parseFilter(dest);
1150                if (dest != null && inclusionFilter.matches(destination) && dest.getDestinationType() == destination.getDestinationType()) {
1151                    return true;
1152                }
1153            }
1154
1155            return false;
1156        }
1157        return true;
1158    }
1159
1160    /**
1161     * Subscriptions for these destinations are always created
1162     */
1163    protected void setupStaticDestinations() {
1164        ActiveMQDestination[] dests = staticallyIncludedDestinations;
1165        if (dests != null) {
1166            for (ActiveMQDestination dest : dests) {
1167                DemandSubscription sub = createDemandSubscription(dest);
1168                sub.setStaticallyIncluded(true);
1169                try {
1170                    addSubscription(sub);
1171                } catch (IOException e) {
1172                    LOG.error("Failed to add static destination {}", dest, e);
1173                }
1174                LOG.trace("{}, bridging messages for static destination: {}", configuration.getBrokerName(), dest);
1175            }
1176        }
1177    }
1178
1179    protected void addConsumerInfo(final ConsumerInfo consumerInfo) throws IOException {
1180        ConsumerInfo info = consumerInfo.copy();
1181        addRemoteBrokerToBrokerPath(info);
1182        DemandSubscription sub = createDemandSubscription(info);
1183        if (sub != null) {
1184            if (duplicateSuppressionIsRequired(sub)) {
1185                undoMapRegistration(sub);
1186            } else {
1187                if (consumerInfo.isDurable()) {
1188                    sub.getDurableRemoteSubs().add(new SubscriptionInfo(sub.getRemoteInfo().getClientId(), consumerInfo.getSubscriptionName()));
1189                }
1190                addSubscription(sub);
1191                LOG.debug("{} new demand subscription: {}", configuration.getBrokerName(), sub);
1192            }
1193        }
1194    }
1195
1196    private void undoMapRegistration(DemandSubscription sub) {
1197        subscriptionMapByLocalId.remove(sub.getLocalInfo().getConsumerId());
1198        subscriptionMapByRemoteId.remove(sub.getRemoteInfo().getConsumerId());
1199    }
1200
1201    /*
1202     * check our existing subs networkConsumerIds against the list of network
1203     * ids in this subscription A match means a duplicate which we suppress for
1204     * topics and maybe for queues
1205     */
1206    private boolean duplicateSuppressionIsRequired(DemandSubscription candidate) {
1207        final ConsumerInfo consumerInfo = candidate.getRemoteInfo();
1208        boolean suppress = false;
1209
1210        if (consumerInfo.getDestination().isQueue() && !configuration.isSuppressDuplicateQueueSubscriptions() || consumerInfo.getDestination().isTopic()
1211                && !configuration.isSuppressDuplicateTopicSubscriptions()) {
1212            return suppress;
1213        }
1214
1215        List<ConsumerId> candidateConsumers = consumerInfo.getNetworkConsumerIds();
1216        Collection<Subscription> currentSubs = getRegionSubscriptions(consumerInfo.getDestination());
1217        for (Subscription sub : currentSubs) {
1218            List<ConsumerId> networkConsumers = sub.getConsumerInfo().getNetworkConsumerIds();
1219            if (!networkConsumers.isEmpty()) {
1220                if (matchFound(candidateConsumers, networkConsumers)) {
1221                    if (isInActiveDurableSub(sub)) {
1222                        suppress = false;
1223                    } else {
1224                        suppress = hasLowerPriority(sub, candidate.getLocalInfo());
1225                    }
1226                    break;
1227                }
1228            }
1229        }
1230        return suppress;
1231    }
1232
1233    private boolean isInActiveDurableSub(Subscription sub) {
1234        return (sub.getConsumerInfo().isDurable() && sub instanceof DurableTopicSubscription && !((DurableTopicSubscription) sub).isActive());
1235    }
1236
1237    private boolean hasLowerPriority(Subscription existingSub, ConsumerInfo candidateInfo) {
1238        boolean suppress = false;
1239
1240        if (existingSub.getConsumerInfo().getPriority() >= candidateInfo.getPriority()) {
1241            LOG.debug("{} Ignoring duplicate subscription from {}, sub: {} is duplicate by network subscription with equal or higher network priority: {}, networkConsumerIds: {}", new Object[]{
1242                    configuration.getBrokerName(), remoteBrokerName, candidateInfo, existingSub, existingSub.getConsumerInfo().getNetworkConsumerIds()
1243            });
1244            suppress = true;
1245        } else {
1246            // remove the existing lower priority duplicate and allow this candidate
1247            try {
1248                removeDuplicateSubscription(existingSub);
1249
1250                LOG.debug("{} Replacing duplicate subscription {} with sub from {}, which has a higher priority, new sub: {}, networkConsumerIds: {}", new Object[]{
1251                        configuration.getBrokerName(), existingSub.getConsumerInfo(), remoteBrokerName, candidateInfo, candidateInfo.getNetworkConsumerIds()
1252                });
1253            } catch (IOException e) {
1254                LOG.error("Failed to remove duplicated sub as a result of sub with higher priority, sub: {}", existingSub, e);
1255            }
1256        }
1257        return suppress;
1258    }
1259
1260    private void removeDuplicateSubscription(Subscription existingSub) throws IOException {
1261        for (NetworkConnector connector : brokerService.getNetworkConnectors()) {
1262            if (connector.removeDemandSubscription(existingSub.getConsumerInfo().getConsumerId())) {
1263                break;
1264            }
1265        }
1266    }
1267
1268    private boolean matchFound(List<ConsumerId> candidateConsumers, List<ConsumerId> networkConsumers) {
1269        boolean found = false;
1270        for (ConsumerId aliasConsumer : networkConsumers) {
1271            if (candidateConsumers.contains(aliasConsumer)) {
1272                found = true;
1273                break;
1274            }
1275        }
1276        return found;
1277    }
1278
1279    protected final Collection<Subscription> getRegionSubscriptions(ActiveMQDestination dest) {
1280        RegionBroker region_broker = (RegionBroker) brokerService.getRegionBroker();
1281        Region region;
1282        Collection<Subscription> subs;
1283
1284        region = null;
1285        switch (dest.getDestinationType()) {
1286            case ActiveMQDestination.QUEUE_TYPE:
1287                region = region_broker.getQueueRegion();
1288                break;
1289            case ActiveMQDestination.TOPIC_TYPE:
1290                region = region_broker.getTopicRegion();
1291                break;
1292            case ActiveMQDestination.TEMP_QUEUE_TYPE:
1293                region = region_broker.getTempQueueRegion();
1294                break;
1295            case ActiveMQDestination.TEMP_TOPIC_TYPE:
1296                region = region_broker.getTempTopicRegion();
1297                break;
1298        }
1299
1300        if (region instanceof AbstractRegion) {
1301            subs = ((AbstractRegion) region).getSubscriptions().values();
1302        } else {
1303            subs = null;
1304        }
1305
1306        return subs;
1307    }
1308
1309    protected DemandSubscription createDemandSubscription(ConsumerInfo info) throws IOException {
1310        // add our original id to ourselves
1311        info.addNetworkConsumerId(info.getConsumerId());
1312        return doCreateDemandSubscription(info);
1313    }
1314
1315    protected DemandSubscription doCreateDemandSubscription(ConsumerInfo info) throws IOException {
1316        DemandSubscription result = new DemandSubscription(info);
1317        result.getLocalInfo().setConsumerId(new ConsumerId(localSessionInfo.getSessionId(), consumerIdGenerator.getNextSequenceId()));
1318        if (info.getDestination().isTemporary()) {
1319            // reset the local connection Id
1320            ActiveMQTempDestination dest = (ActiveMQTempDestination) result.getLocalInfo().getDestination();
1321            dest.setConnectionId(localConnectionInfo.getConnectionId().toString());
1322        }
1323
1324        if (configuration.isDecreaseNetworkConsumerPriority()) {
1325            byte priority = (byte) configuration.getConsumerPriorityBase();
1326            if (info.getBrokerPath() != null && info.getBrokerPath().length > 1) {
1327                // The longer the path to the consumer, the less it's consumer priority.
1328                priority -= info.getBrokerPath().length + 1;
1329            }
1330            result.getLocalInfo().setPriority(priority);
1331            LOG.debug("{} using priority: {} for subscription: {}", new Object[]{configuration.getBrokerName(), priority, info});
1332        }
1333        configureDemandSubscription(info, result);
1334        return result;
1335    }
1336
1337    final protected DemandSubscription createDemandSubscription(ActiveMQDestination destination) {
1338        ConsumerInfo info = new ConsumerInfo();
1339        info.setNetworkSubscription(true);
1340        info.setDestination(destination);
1341
1342        // Indicate that this subscription is being made on behalf of the remote broker.
1343        info.setBrokerPath(new BrokerId[]{remoteBrokerId});
1344
1345        // the remote info held by the DemandSubscription holds the original
1346        // consumerId, the local info get's overwritten
1347        info.setConsumerId(new ConsumerId(localSessionInfo.getSessionId(), consumerIdGenerator.getNextSequenceId()));
1348        DemandSubscription result = null;
1349        try {
1350            result = createDemandSubscription(info);
1351        } catch (IOException e) {
1352            LOG.error("Failed to create DemandSubscription ", e);
1353        }
1354        return result;
1355    }
1356
1357    protected void configureDemandSubscription(ConsumerInfo info, DemandSubscription sub) throws IOException {
1358        if (AdvisorySupport.isConsumerAdvisoryTopic(info.getDestination()) ||
1359                AdvisorySupport.isVirtualDestinationConsumerAdvisoryTopic(info.getDestination())) {
1360            sub.getLocalInfo().setDispatchAsync(true);
1361        } else {
1362            sub.getLocalInfo().setDispatchAsync(configuration.isDispatchAsync());
1363        }
1364        sub.getLocalInfo().setPrefetchSize(configuration.getPrefetchSize());
1365        subscriptionMapByLocalId.put(sub.getLocalInfo().getConsumerId(), sub);
1366        subscriptionMapByRemoteId.put(sub.getRemoteInfo().getConsumerId(), sub);
1367
1368        sub.setNetworkBridgeFilter(createNetworkBridgeFilter(info));
1369        if (!info.isDurable()) {
1370            // This works for now since we use a VM connection to the local broker.
1371            // may need to change if we ever subscribe to a remote broker.
1372            sub.getLocalInfo().setAdditionalPredicate(sub.getNetworkBridgeFilter());
1373        } else {
1374            sub.setLocalDurableSubscriber(new SubscriptionInfo(info.getClientId(), info.getSubscriptionName()));
1375        }
1376    }
1377
1378    protected void removeDemandSubscription(ConsumerId id) throws IOException {
1379        DemandSubscription sub = subscriptionMapByRemoteId.remove(id);
1380        LOG.debug("{} remove request on {} from {}, consumer id: {}, matching sub: {}", new Object[]{
1381                configuration.getBrokerName(), localBroker, remoteBrokerName, id, sub
1382        });
1383        if (sub != null) {
1384            removeSubscription(sub);
1385            LOG.debug("{} removed sub on {} from {}: {}", new Object[]{
1386                    configuration.getBrokerName(), localBroker, remoteBrokerName, sub.getRemoteInfo()
1387            });
1388        }
1389    }
1390
1391    protected boolean removeDemandSubscriptionByLocalId(ConsumerId consumerId) {
1392        boolean removeDone = false;
1393        DemandSubscription sub = subscriptionMapByLocalId.get(consumerId);
1394        if (sub != null) {
1395            try {
1396                removeDemandSubscription(sub.getRemoteInfo().getConsumerId());
1397                removeDone = true;
1398            } catch (IOException e) {
1399                LOG.debug("removeDemandSubscriptionByLocalId failed for localId: {}", consumerId, e);
1400            }
1401        }
1402        return removeDone;
1403    }
1404
1405    /**
1406     * Performs a timed wait on the started latch and then checks for disposed
1407     * before performing another wait each time the the started wait times out.
1408     */
1409    protected boolean safeWaitUntilStarted() throws InterruptedException {
1410        while (!disposed.get()) {
1411            if (startedLatch.await(1, TimeUnit.SECONDS)) {
1412                break;
1413            }
1414        }
1415        return !disposed.get();
1416    }
1417
1418    protected NetworkBridgeFilter createNetworkBridgeFilter(ConsumerInfo info) throws IOException {
1419        NetworkBridgeFilterFactory filterFactory = defaultFilterFactory;
1420        if (brokerService != null && brokerService.getDestinationPolicy() != null) {
1421            PolicyEntry entry = brokerService.getDestinationPolicy().getEntryFor(info.getDestination());
1422            if (entry != null && entry.getNetworkBridgeFilterFactory() != null) {
1423                filterFactory = entry.getNetworkBridgeFilterFactory();
1424            }
1425        }
1426        return filterFactory.create(info, getRemoteBrokerPath(), configuration.getMessageTTL(), configuration.getConsumerTTL());
1427    }
1428
1429    protected void addRemoteBrokerToBrokerPath(ConsumerInfo info) throws IOException {
1430        info.setBrokerPath(appendToBrokerPath(info.getBrokerPath(), getRemoteBrokerPath()));
1431    }
1432
1433    protected BrokerId[] getRemoteBrokerPath() {
1434        return remoteBrokerPath;
1435    }
1436
1437    @Override
1438    public void setNetworkBridgeListener(NetworkBridgeListener listener) {
1439        this.networkBridgeListener = listener;
1440    }
1441
1442    private void fireBridgeFailed(Throwable reason) {
1443        LOG.trace("fire bridge failed, listener: {}", this.networkBridgeListener, reason);
1444        NetworkBridgeListener l = this.networkBridgeListener;
1445        if (l != null && this.bridgeFailed.compareAndSet(false, true)) {
1446            l.bridgeFailed();
1447        }
1448    }
1449
1450    /**
1451     * @return Returns the dynamicallyIncludedDestinations.
1452     */
1453    public ActiveMQDestination[] getDynamicallyIncludedDestinations() {
1454        return dynamicallyIncludedDestinations;
1455    }
1456
1457    /**
1458     * @param dynamicallyIncludedDestinations
1459     *         The dynamicallyIncludedDestinations to set.
1460     */
1461    public void setDynamicallyIncludedDestinations(ActiveMQDestination[] dynamicallyIncludedDestinations) {
1462        this.dynamicallyIncludedDestinations = dynamicallyIncludedDestinations;
1463    }
1464
1465    /**
1466     * @return Returns the excludedDestinations.
1467     */
1468    public ActiveMQDestination[] getExcludedDestinations() {
1469        return excludedDestinations;
1470    }
1471
1472    /**
1473     * @param excludedDestinations The excludedDestinations to set.
1474     */
1475    public void setExcludedDestinations(ActiveMQDestination[] excludedDestinations) {
1476        this.excludedDestinations = excludedDestinations;
1477    }
1478
1479    /**
1480     * @return Returns the staticallyIncludedDestinations.
1481     */
1482    public ActiveMQDestination[] getStaticallyIncludedDestinations() {
1483        return staticallyIncludedDestinations;
1484    }
1485
1486    /**
1487     * @param staticallyIncludedDestinations The staticallyIncludedDestinations to set.
1488     */
1489    public void setStaticallyIncludedDestinations(ActiveMQDestination[] staticallyIncludedDestinations) {
1490        this.staticallyIncludedDestinations = staticallyIncludedDestinations;
1491    }
1492
1493    /**
1494     * @return Returns the durableDestinations.
1495     */
1496    public ActiveMQDestination[] getDurableDestinations() {
1497        return durableDestinations;
1498    }
1499
1500    /**
1501     * @param durableDestinations The durableDestinations to set.
1502     */
1503    public void setDurableDestinations(ActiveMQDestination[] durableDestinations) {
1504        this.durableDestinations = durableDestinations;
1505    }
1506
1507    /**
1508     * @return Returns the localBroker.
1509     */
1510    public Transport getLocalBroker() {
1511        return localBroker;
1512    }
1513
1514    /**
1515     * @return Returns the remoteBroker.
1516     */
1517    public Transport getRemoteBroker() {
1518        return remoteBroker;
1519    }
1520
1521    /**
1522     * @return the createdByDuplex
1523     */
1524    public boolean isCreatedByDuplex() {
1525        return this.createdByDuplex;
1526    }
1527
1528    /**
1529     * @param createdByDuplex the createdByDuplex to set
1530     */
1531    public void setCreatedByDuplex(boolean createdByDuplex) {
1532        this.createdByDuplex = createdByDuplex;
1533    }
1534
1535    @Override
1536    public String getRemoteAddress() {
1537        return remoteBroker.getRemoteAddress();
1538    }
1539
1540    @Override
1541    public String getLocalAddress() {
1542        return localBroker.getRemoteAddress();
1543    }
1544
1545    @Override
1546    public String getRemoteBrokerName() {
1547        return remoteBrokerInfo == null ? null : remoteBrokerInfo.getBrokerName();
1548    }
1549
1550    @Override
1551    public String getRemoteBrokerId() {
1552        return (remoteBrokerInfo == null || remoteBrokerInfo.getBrokerId() == null) ? null : remoteBrokerInfo.getBrokerId().toString();
1553    }
1554
1555    @Override
1556    public String getLocalBrokerName() {
1557        return localBrokerInfo == null ? null : localBrokerInfo.getBrokerName();
1558    }
1559
1560    @Override
1561    public long getDequeueCounter() {
1562        return dequeueCounter.get();
1563    }
1564
1565    @Override
1566    public long getEnqueueCounter() {
1567        return enqueueCounter.get();
1568    }
1569
1570    protected boolean isDuplex() {
1571        return configuration.isDuplex() || createdByDuplex;
1572    }
1573
1574    public ConcurrentMap<ConsumerId, DemandSubscription> getLocalSubscriptionMap() {
1575        return subscriptionMapByRemoteId;
1576    }
1577
1578    @Override
1579    public void setBrokerService(BrokerService brokerService) {
1580        this.brokerService = brokerService;
1581        this.localBrokerId = brokerService.getRegionBroker().getBrokerId();
1582        localBrokerPath[0] = localBrokerId;
1583    }
1584
1585    @Override
1586    public void setMbeanObjectName(ObjectName objectName) {
1587        this.mbeanObjectName = objectName;
1588    }
1589
1590    @Override
1591    public ObjectName getMbeanObjectName() {
1592        return mbeanObjectName;
1593    }
1594
1595    @Override
1596    public void resetStats() {
1597        enqueueCounter.set(0);
1598        dequeueCounter.set(0);
1599    }
1600
1601    /*
1602     * Used to allow for async tasks to await receipt of the BrokerInfo from the local and
1603     * remote sides of the network bridge.
1604     */
1605    private static class FutureBrokerInfo implements Future<BrokerInfo> {
1606
1607        private final CountDownLatch slot = new CountDownLatch(1);
1608        private final AtomicBoolean disposed;
1609        private volatile BrokerInfo info = null;
1610
1611        public FutureBrokerInfo(BrokerInfo info, AtomicBoolean disposed) {
1612            this.info = info;
1613            this.disposed = disposed;
1614        }
1615
1616        @Override
1617        public boolean cancel(boolean mayInterruptIfRunning) {
1618            slot.countDown();
1619            return true;
1620        }
1621
1622        @Override
1623        public boolean isCancelled() {
1624            return slot.getCount() == 0 && info == null;
1625        }
1626
1627        @Override
1628        public boolean isDone() {
1629            return info != null;
1630        }
1631
1632        @Override
1633        public BrokerInfo get() throws InterruptedException, ExecutionException {
1634            try {
1635                if (info == null) {
1636                    while (!disposed.get()) {
1637                        if (slot.await(1, TimeUnit.SECONDS)) {
1638                            break;
1639                        }
1640                    }
1641                }
1642                return info;
1643            } catch (InterruptedException e) {
1644                Thread.currentThread().interrupt();
1645                LOG.debug("Operation interrupted: {}", e, e);
1646                throw new InterruptedException("Interrupted.");
1647            }
1648        }
1649
1650        @Override
1651        public BrokerInfo get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
1652            try {
1653                if (info == null) {
1654                    long deadline = System.currentTimeMillis() + unit.toMillis(timeout);
1655
1656                    while (!disposed.get() || System.currentTimeMillis() < deadline) {
1657                        if (slot.await(1, TimeUnit.MILLISECONDS)) {
1658                            break;
1659                        }
1660                    }
1661                    if (info == null) {
1662                        throw new TimeoutException();
1663                    }
1664                }
1665                return info;
1666            } catch (InterruptedException e) {
1667                throw new InterruptedException("Interrupted.");
1668            }
1669        }
1670
1671        public void set(BrokerInfo info) {
1672            this.info = info;
1673            this.slot.countDown();
1674        }
1675    }
1676
1677    protected void serviceOutbound(Message message) {
1678        NetworkBridgeListener l = this.networkBridgeListener;
1679        if (l != null) {
1680            l.onOutboundMessage(this, message);
1681        }
1682    }
1683
1684    protected void serviceInboundMessage(Message message) {
1685        NetworkBridgeListener l = this.networkBridgeListener;
1686        if (l != null) {
1687            l.onInboundMessage(this, message);
1688        }
1689    }
1690
1691    protected boolean canDuplexDispatch(Message message) {
1692        boolean result = true;
1693        if (configuration.isCheckDuplicateMessagesOnDuplex()){
1694            final long producerSequenceId = message.getMessageId().getProducerSequenceId();
1695            //  messages are multiplexed on this producer so we need to query the persistenceAdapter
1696            long lastStoredForMessageProducer = getStoredSequenceIdForMessage(message.getMessageId());
1697            if (producerSequenceId <= lastStoredForMessageProducer) {
1698                result = false;
1699                LOG.debug("suppressing duplicate message send [{}] from network producer with producerSequence [{}] less than last stored: {}", new Object[]{
1700                        (LOG.isTraceEnabled() ? message : message.getMessageId()), producerSequenceId, lastStoredForMessageProducer
1701                });
1702            }
1703        }
1704        return result;
1705    }
1706
1707    protected long getStoredSequenceIdForMessage(MessageId messageId) {
1708        try {
1709            return brokerService.getPersistenceAdapter().getLastProducerSequenceId(messageId.getProducerId());
1710        } catch (IOException ignored) {
1711            LOG.debug("Failed to determine last producer sequence id for: {}", messageId, ignored);
1712        }
1713        return -1;
1714    }
1715
1716}