001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.broker;
018
019import java.io.EOFException;
020import java.io.IOException;
021import java.net.SocketException;
022import java.net.URI;
023import java.util.Collection;
024import java.util.HashMap;
025import java.util.Iterator;
026import java.util.LinkedList;
027import java.util.List;
028import java.util.Map;
029import java.util.Properties;
030import java.util.concurrent.ConcurrentHashMap;
031import java.util.concurrent.CopyOnWriteArrayList;
032import java.util.concurrent.CountDownLatch;
033import java.util.concurrent.TimeUnit;
034import java.util.concurrent.atomic.AtomicBoolean;
035import java.util.concurrent.atomic.AtomicInteger;
036import java.util.concurrent.atomic.AtomicReference;
037import java.util.concurrent.locks.ReentrantReadWriteLock;
038
039import javax.transaction.xa.XAResource;
040
041import org.apache.activemq.advisory.AdvisorySupport;
042import org.apache.activemq.broker.region.ConnectionStatistics;
043import org.apache.activemq.broker.region.RegionBroker;
044import org.apache.activemq.command.ActiveMQDestination;
045import org.apache.activemq.command.BrokerInfo;
046import org.apache.activemq.command.BrokerSubscriptionInfo;
047import org.apache.activemq.command.Command;
048import org.apache.activemq.command.CommandTypes;
049import org.apache.activemq.command.ConnectionControl;
050import org.apache.activemq.command.ConnectionError;
051import org.apache.activemq.command.ConnectionId;
052import org.apache.activemq.command.ConnectionInfo;
053import org.apache.activemq.command.ConsumerControl;
054import org.apache.activemq.command.ConsumerId;
055import org.apache.activemq.command.ConsumerInfo;
056import org.apache.activemq.command.ControlCommand;
057import org.apache.activemq.command.DataArrayResponse;
058import org.apache.activemq.command.DestinationInfo;
059import org.apache.activemq.command.ExceptionResponse;
060import org.apache.activemq.command.FlushCommand;
061import org.apache.activemq.command.IntegerResponse;
062import org.apache.activemq.command.KeepAliveInfo;
063import org.apache.activemq.command.Message;
064import org.apache.activemq.command.MessageAck;
065import org.apache.activemq.command.MessageDispatch;
066import org.apache.activemq.command.MessageDispatchNotification;
067import org.apache.activemq.command.MessagePull;
068import org.apache.activemq.command.ProducerAck;
069import org.apache.activemq.command.ProducerId;
070import org.apache.activemq.command.ProducerInfo;
071import org.apache.activemq.command.RemoveInfo;
072import org.apache.activemq.command.RemoveSubscriptionInfo;
073import org.apache.activemq.command.Response;
074import org.apache.activemq.command.SessionId;
075import org.apache.activemq.command.SessionInfo;
076import org.apache.activemq.command.ShutdownInfo;
077import org.apache.activemq.command.TransactionId;
078import org.apache.activemq.command.TransactionInfo;
079import org.apache.activemq.command.WireFormatInfo;
080import org.apache.activemq.network.DemandForwardingBridge;
081import org.apache.activemq.network.MBeanNetworkListener;
082import org.apache.activemq.network.NetworkBridgeConfiguration;
083import org.apache.activemq.network.NetworkBridgeFactory;
084import org.apache.activemq.network.NetworkConnector;
085import org.apache.activemq.security.MessageAuthorizationPolicy;
086import org.apache.activemq.state.CommandVisitor;
087import org.apache.activemq.state.ConnectionState;
088import org.apache.activemq.state.ConsumerState;
089import org.apache.activemq.state.ProducerState;
090import org.apache.activemq.state.SessionState;
091import org.apache.activemq.state.TransactionState;
092import org.apache.activemq.thread.Task;
093import org.apache.activemq.thread.TaskRunner;
094import org.apache.activemq.thread.TaskRunnerFactory;
095import org.apache.activemq.transaction.Transaction;
096import org.apache.activemq.transport.DefaultTransportListener;
097import org.apache.activemq.transport.ResponseCorrelator;
098import org.apache.activemq.transport.TransmitCallback;
099import org.apache.activemq.transport.Transport;
100import org.apache.activemq.transport.TransportDisposedIOException;
101import org.apache.activemq.util.IntrospectionSupport;
102import org.apache.activemq.util.MarshallingSupport;
103import org.apache.activemq.util.NetworkBridgeUtils;
104import org.apache.activemq.util.SubscriptionKey;
105import org.slf4j.Logger;
106import org.slf4j.LoggerFactory;
107import org.slf4j.MDC;
108
109public class TransportConnection implements Connection, Task, CommandVisitor {
110    private static final Logger LOG = LoggerFactory.getLogger(TransportConnection.class);
111    private static final Logger TRANSPORTLOG = LoggerFactory.getLogger(TransportConnection.class.getName() + ".Transport");
112    private static final Logger SERVICELOG = LoggerFactory.getLogger(TransportConnection.class.getName() + ".Service");
113    // Keeps track of the broker and connector that created this connection.
114    protected final Broker broker;
115    protected final BrokerService brokerService;
116    protected final TransportConnector connector;
117    // Keeps track of the state of the connections.
118    // protected final ConcurrentHashMap localConnectionStates=new
119    // ConcurrentHashMap();
120    protected final Map<ConnectionId, ConnectionState> brokerConnectionStates;
121    // The broker and wireformat info that was exchanged.
122    protected BrokerInfo brokerInfo;
123    protected final List<Command> dispatchQueue = new LinkedList<>();
124    protected TaskRunner taskRunner;
125    protected final AtomicReference<Throwable> transportException = new AtomicReference<>();
126    protected AtomicBoolean dispatchStopped = new AtomicBoolean(false);
127    private final Transport transport;
128    private MessageAuthorizationPolicy messageAuthorizationPolicy;
129    private WireFormatInfo wireFormatInfo;
130    // Used to do async dispatch.. this should perhaps be pushed down into the
131    // transport layer..
132    private boolean inServiceException;
133    private final ConnectionStatistics statistics = new ConnectionStatistics();
134    private boolean manageable;
135    private boolean slow;
136    private boolean markedCandidate;
137    private boolean blockedCandidate;
138    private boolean blocked;
139    private boolean connected;
140    private boolean active;
141
142    // state management around pending stop
143    private static final int NEW           = 0;
144    private static final int STARTING      = 1;
145    private static final int STARTED       = 2;
146    private static final int PENDING_STOP  = 3;
147    private final AtomicInteger status = new AtomicInteger(NEW);
148
149    private long timeStamp;
150    private final AtomicBoolean stopping = new AtomicBoolean(false);
151    private final CountDownLatch stopped = new CountDownLatch(1);
152    private final AtomicBoolean asyncException = new AtomicBoolean(false);
153    private final Map<ProducerId, ProducerBrokerExchange> producerExchanges = new HashMap<>();
154    private final Map<ConsumerId, ConsumerBrokerExchange> consumerExchanges = new HashMap<>();
155    private final CountDownLatch dispatchStoppedLatch = new CountDownLatch(1);
156    private ConnectionContext context;
157    private boolean networkConnection;
158    private boolean faultTolerantConnection;
159    private final AtomicInteger protocolVersion = new AtomicInteger(CommandTypes.PROTOCOL_VERSION);
160    private DemandForwardingBridge duplexBridge;
161    private final TaskRunnerFactory taskRunnerFactory;
162    private final TaskRunnerFactory stopTaskRunnerFactory;
163    private TransportConnectionStateRegister connectionStateRegister = new SingleTransportConnectionStateRegister();
164    private final ReentrantReadWriteLock serviceLock = new ReentrantReadWriteLock();
165    private String duplexNetworkConnectorId;
166
167    /**
168     * @param taskRunnerFactory - can be null if you want direct dispatch to the transport
169     *                          else commands are sent async.
170     * @param stopTaskRunnerFactory - can <b>not</b> be null, used for stopping this connection.
171     */
172    public TransportConnection(TransportConnector connector, final Transport transport, Broker broker,
173                               TaskRunnerFactory taskRunnerFactory, TaskRunnerFactory stopTaskRunnerFactory) {
174        this.connector = connector;
175        this.broker = broker;
176        this.brokerService = broker.getBrokerService();
177
178        RegionBroker rb = (RegionBroker) broker.getAdaptor(RegionBroker.class);
179        brokerConnectionStates = rb.getConnectionStates();
180        if (connector != null) {
181            this.statistics.setParent(connector.getStatistics());
182            this.messageAuthorizationPolicy = connector.getMessageAuthorizationPolicy();
183        }
184        this.taskRunnerFactory = taskRunnerFactory;
185        this.stopTaskRunnerFactory = stopTaskRunnerFactory;
186        this.transport = transport;
187        if( this.transport instanceof BrokerServiceAware ) {
188            ((BrokerServiceAware)this.transport).setBrokerService(brokerService);
189        }
190        this.transport.setTransportListener(new DefaultTransportListener() {
191            @Override
192            public void onCommand(Object o) {
193                serviceLock.readLock().lock();
194                try {
195                    if (!(o instanceof Command)) {
196                        throw new RuntimeException("Protocol violation - Command corrupted: " + o.toString());
197                    }
198                    Command command = (Command) o;
199                    if (!brokerService.isStopping()) {
200                        Response response = service(command);
201                        if (response != null && !brokerService.isStopping()) {
202                            dispatchSync(response);
203                        }
204                    } else {
205                        throw new BrokerStoppedException("Broker " + brokerService + " is being stopped");
206                    }
207                } finally {
208                    serviceLock.readLock().unlock();
209                }
210            }
211
212            @Override
213            public void onException(IOException exception) {
214                serviceLock.readLock().lock();
215                try {
216                    serviceTransportException(exception);
217                } finally {
218                    serviceLock.readLock().unlock();
219                }
220            }
221        });
222        connected = true;
223    }
224
225    /**
226     * Returns the number of messages to be dispatched to this connection
227     *
228     * @return size of dispatch queue
229     */
230    @Override
231    public int getDispatchQueueSize() {
232        synchronized (dispatchQueue) {
233            return dispatchQueue.size();
234        }
235    }
236
237    public void serviceTransportException(IOException e) {
238        if (!stopping.get() && status.get() != PENDING_STOP) {
239            transportException.set(e);
240            if (TRANSPORTLOG.isDebugEnabled()) {
241                TRANSPORTLOG.debug("{} failed: {}", this, e.getMessage(), e);
242            } else if (TRANSPORTLOG.isWarnEnabled() && !expected(e)) {
243                TRANSPORTLOG.warn("{} failed", this, e);
244            }
245            stopAsync(e);
246        }
247    }
248
249    private boolean expected(IOException e) {
250        return isStomp() && ((e instanceof SocketException && e.getMessage().indexOf("reset") != -1) || e instanceof EOFException);
251    }
252
253    private boolean isStomp() {
254        URI uri = connector.getUri();
255        return uri != null && uri.getScheme() != null && uri.getScheme().indexOf("stomp") != -1;
256    }
257
258    /**
259     * Calls the serviceException method in an async thread. Since handling a
260     * service exception closes a socket, we should not tie up broker threads
261     * since client sockets may hang or cause deadlocks.
262     */
263    @Override
264    public void serviceExceptionAsync(final IOException e) {
265        if (asyncException.compareAndSet(false, true)) {
266            new Thread("Async Exception Handler") {
267                @Override
268                public void run() {
269                    serviceException(e);
270                }
271            }.start();
272        }
273    }
274
275    /**
276     * Closes a clients connection due to a detected error. Errors are ignored
277     * if: the client is closing or broker is closing. Otherwise, the connection
278     * error transmitted to the client before stopping it's transport.
279     */
280    @Override
281    public void serviceException(Throwable e) {
282        // are we a transport exception such as not being able to dispatch
283        // synchronously to a transport
284        if (e instanceof IOException) {
285            serviceTransportException((IOException) e);
286        } else if (e.getClass() == BrokerStoppedException.class) {
287            // Handle the case where the broker is stopped
288            // But the client is still connected.
289            if (!stopping.get()) {
290                SERVICELOG.debug("Broker has been stopped.  Notifying client and closing his connection.");
291                ConnectionError ce = new ConnectionError();
292                ce.setException(e);
293                dispatchSync(ce);
294                // Record the error that caused the transport to stop
295                transportException.set(e);
296                // Wait a little bit to try to get the output buffer to flush
297                // the exception notification to the client.
298                try {
299                    Thread.sleep(500);
300                } catch (InterruptedException ie) {
301                    Thread.currentThread().interrupt();
302                }
303                // Worst case is we just kill the connection before the
304                // notification gets to him.
305                stopAsync();
306            }
307        } else if (!stopping.get() && !inServiceException) {
308            inServiceException = true;
309            try {
310                if (SERVICELOG.isDebugEnabled()) {
311                    SERVICELOG.debug("Async error occurred: {}", e.getMessage(), e);
312                } else {
313                    SERVICELOG.warn("Async error occurred", e);
314                }
315                ConnectionError ce = new ConnectionError();
316                ce.setException(e);
317                if (status.get() == PENDING_STOP) {
318                    dispatchSync(ce);
319                } else {
320                    dispatchAsync(ce);
321                }
322            } finally {
323                inServiceException = false;
324            }
325        }
326    }
327
328    @Override
329    public Response service(Command command) {
330        MDC.put("activemq.connector", connector.getUri().toString());
331        Response response = null;
332        boolean responseRequired = command.isResponseRequired();
333        int commandId = command.getCommandId();
334        try {
335            if (status.get() != PENDING_STOP) {
336                response = command.visit(this);
337            } else {
338                response = new ExceptionResponse(transportException.get());
339            }
340        } catch (Throwable e) {
341            if (SERVICELOG.isDebugEnabled() && e.getClass() != BrokerStoppedException.class) {
342                SERVICELOG.debug("Error occurred while processing {} command: {}, exception: {}",
343                        (responseRequired ? "sync" : "async"),
344                        command,
345                        e.getMessage(),
346                        e);
347            }
348
349            if (e instanceof SuppressReplyException || (e.getCause() instanceof SuppressReplyException)) {
350                LOG.info("Suppressing reply to: {} on: {}, cause: {}", command, e, e.getCause());
351                responseRequired = false;
352            }
353
354            if (responseRequired) {
355                if (e instanceof SecurityException || e.getCause() instanceof SecurityException) {
356                    SERVICELOG.warn("Security Error occurred on connection to: {}, {}",
357                            transport.getRemoteAddress(), e.getMessage());
358                }
359                response = new ExceptionResponse(e);
360            } else {
361                forceRollbackOnlyOnFailedAsyncTransactionOp(e, command);
362                serviceException(e);
363            }
364        }
365        if (responseRequired) {
366            if (response == null) {
367                response = new Response();
368            }
369            response.setCorrelationId(commandId);
370        }
371        // The context may have been flagged so that the response is not
372        // sent.
373        if (context != null) {
374            if (context.isDontSendReponse()) {
375                context.setDontSendReponse(false);
376                response = null;
377            }
378            context = null;
379        }
380        MDC.remove("activemq.connector");
381        return response;
382    }
383
384    private void forceRollbackOnlyOnFailedAsyncTransactionOp(Throwable e, Command command) {
385        if (brokerService.isRollbackOnlyOnAsyncException() && !(e instanceof IOException) && isInTransaction(command)) {
386            Transaction transaction = getActiveTransaction(command);
387            if (transaction != null && !transaction.isRollbackOnly()) {
388                LOG.debug("on async exception, force rollback of transaction for: {}", command, e);
389                transaction.setRollbackOnly(e);
390            }
391        }
392    }
393
394    private Transaction getActiveTransaction(Command command) {
395        Transaction transaction = null;
396        try {
397            if (command instanceof Message) {
398                Message messageSend = (Message) command;
399                ProducerId producerId = messageSend.getProducerId();
400                ProducerBrokerExchange producerExchange = getProducerBrokerExchange(producerId);
401                transaction = producerExchange.getConnectionContext().getTransactions().get(messageSend.getTransactionId());
402            } else if (command instanceof  MessageAck) {
403                MessageAck messageAck = (MessageAck) command;
404                ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(messageAck.getConsumerId());
405                if (consumerExchange != null) {
406                    transaction = consumerExchange.getConnectionContext().getTransactions().get(messageAck.getTransactionId());
407                }
408            }
409        } catch(Exception ignored){
410            LOG.trace("failed to find active transaction for command: {}", command, ignored);
411        }
412        return transaction;
413    }
414
415    private boolean isInTransaction(Command command) {
416        return command instanceof Message && ((Message)command).isInTransaction()
417                || command instanceof MessageAck && ((MessageAck)command).isInTransaction();
418    }
419
420    @Override
421    public Response processKeepAlive(KeepAliveInfo info) throws Exception {
422        return null;
423    }
424
425    @Override
426    public Response processRemoveSubscription(RemoveSubscriptionInfo info) throws Exception {
427        broker.removeSubscription(lookupConnectionState(info.getConnectionId()).getContext(), info);
428        return null;
429    }
430
431    @Override
432    public Response processWireFormat(WireFormatInfo info) throws Exception {
433        wireFormatInfo = info;
434        protocolVersion.set(info.getVersion());
435        return null;
436    }
437
438    @Override
439    public Response processShutdown(ShutdownInfo info) throws Exception {
440        stopAsync();
441        return null;
442    }
443
444    @Override
445    public Response processFlush(FlushCommand command) throws Exception {
446        return null;
447    }
448
449    @Override
450    public Response processBeginTransaction(TransactionInfo info) throws Exception {
451        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
452        context = null;
453        if (cs != null) {
454            context = cs.getContext();
455        }
456        if (cs == null) {
457            throw new NullPointerException("Context is null");
458        }
459        // Avoid replaying dup commands
460        if (cs.getTransactionState(info.getTransactionId()) == null) {
461            cs.addTransactionState(info.getTransactionId());
462            broker.beginTransaction(context, info.getTransactionId());
463        }
464        return null;
465    }
466
467    @Override
468    public int getActiveTransactionCount() {
469        int rc = 0;
470        for (TransportConnectionState cs : connectionStateRegister.listConnectionStates()) {
471            rc += cs.getTransactionStates().size();
472        }
473        return rc;
474    }
475
476    @Override
477    public Long getOldestActiveTransactionDuration() {
478        TransactionState oldestTX = null;
479        for (TransportConnectionState cs : connectionStateRegister.listConnectionStates()) {
480            Collection<TransactionState> transactions = cs.getTransactionStates();
481            for (TransactionState transaction : transactions) {
482                if( oldestTX ==null || oldestTX.getCreatedAt() < transaction.getCreatedAt() ) {
483                    oldestTX = transaction;
484                }
485            }
486        }
487        if( oldestTX == null ) {
488            return null;
489        }
490        return System.currentTimeMillis() - oldestTX.getCreatedAt();
491    }
492
493    @Override
494    public Response processEndTransaction(TransactionInfo info) throws Exception {
495        // No need to do anything. This packet is just sent by the client
496        // make sure he is synced with the server as commit command could
497        // come from a different connection.
498        return null;
499    }
500
501    @Override
502    public Response processPrepareTransaction(TransactionInfo info) throws Exception {
503        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
504        context = null;
505        if (cs != null) {
506            context = cs.getContext();
507        }
508        if (cs == null) {
509            throw new NullPointerException("Context is null");
510        }
511        TransactionState transactionState = cs.getTransactionState(info.getTransactionId());
512        if (transactionState == null) {
513            throw new IllegalStateException("Cannot prepare a transaction that had not been started or previously returned XA_RDONLY: "
514                    + info.getTransactionId());
515        }
516        // Avoid dups.
517        if (!transactionState.isPrepared()) {
518            transactionState.setPrepared(true);
519            int result = broker.prepareTransaction(context, info.getTransactionId());
520            transactionState.setPreparedResult(result);
521            if (result == XAResource.XA_RDONLY) {
522                // we are done, no further rollback or commit from TM
523                cs.removeTransactionState(info.getTransactionId());
524            }
525            IntegerResponse response = new IntegerResponse(result);
526            return response;
527        } else {
528            IntegerResponse response = new IntegerResponse(transactionState.getPreparedResult());
529            return response;
530        }
531    }
532
533    @Override
534    public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception {
535        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
536        context = cs.getContext();
537        cs.removeTransactionState(info.getTransactionId());
538        broker.commitTransaction(context, info.getTransactionId(), true);
539        return null;
540    }
541
542    @Override
543    public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception {
544        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
545        context = cs.getContext();
546        cs.removeTransactionState(info.getTransactionId());
547        broker.commitTransaction(context, info.getTransactionId(), false);
548        return null;
549    }
550
551    @Override
552    public Response processRollbackTransaction(TransactionInfo info) throws Exception {
553        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
554        context = cs.getContext();
555        cs.removeTransactionState(info.getTransactionId());
556        broker.rollbackTransaction(context, info.getTransactionId());
557        return null;
558    }
559
560    @Override
561    public Response processForgetTransaction(TransactionInfo info) throws Exception {
562        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
563        context = cs.getContext();
564        broker.forgetTransaction(context, info.getTransactionId());
565        return null;
566    }
567
568    @Override
569    public Response processRecoverTransactions(TransactionInfo info) throws Exception {
570        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
571        context = cs.getContext();
572        TransactionId[] preparedTransactions = broker.getPreparedTransactions(context);
573        return new DataArrayResponse(preparedTransactions);
574    }
575
576    @Override
577    public Response processMessage(Message messageSend) throws Exception {
578        ProducerId producerId = messageSend.getProducerId();
579        ProducerBrokerExchange producerExchange = getProducerBrokerExchange(producerId);
580        if (producerExchange.canDispatch(messageSend)) {
581            broker.send(producerExchange, messageSend);
582        }
583        return null;
584    }
585
586    @Override
587    public Response processMessageAck(MessageAck ack) throws Exception {
588        ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(ack.getConsumerId());
589        if (consumerExchange != null) {
590            broker.acknowledge(consumerExchange, ack);
591        } else if (ack.isInTransaction()) {
592            LOG.warn("no matching consumer {}, ignoring ack {}", consumerExchange, ack);
593        }
594        return null;
595    }
596
597    @Override
598    public Response processMessagePull(MessagePull pull) throws Exception {
599        return broker.messagePull(lookupConnectionState(pull.getConsumerId()).getContext(), pull);
600    }
601
602    @Override
603    public Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception {
604        broker.processDispatchNotification(notification);
605        return null;
606    }
607
608    @Override
609    public Response processAddDestination(DestinationInfo info) throws Exception {
610        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
611        broker.addDestinationInfo(cs.getContext(), info);
612        if (info.getDestination().isTemporary()) {
613            cs.addTempDestination(info);
614        }
615        return null;
616    }
617
618    @Override
619    public Response processRemoveDestination(DestinationInfo info) throws Exception {
620        TransportConnectionState cs = lookupConnectionState(info.getConnectionId());
621        broker.removeDestinationInfo(cs.getContext(), info);
622        if (info.getDestination().isTemporary()) {
623            cs.removeTempDestination(info.getDestination());
624        }
625        return null;
626    }
627
628    @Override
629    public Response processAddProducer(ProducerInfo info) throws Exception {
630        SessionId sessionId = info.getProducerId().getParentId();
631        ConnectionId connectionId = sessionId.getParentId();
632        TransportConnectionState cs = lookupConnectionState(connectionId);
633        if (cs == null) {
634            throw new IllegalStateException("Cannot add a producer to a connection that had not been registered: "
635                    + connectionId);
636        }
637        SessionState ss = cs.getSessionState(sessionId);
638        if (ss == null) {
639            throw new IllegalStateException("Cannot add a producer to a session that had not been registered: "
640                    + sessionId);
641        }
642        // Avoid replaying dup commands
643        if (!ss.getProducerIds().contains(info.getProducerId())) {
644            ActiveMQDestination destination = info.getDestination();
645            // Do not check for null here as it would cause the count of max producers to exclude
646            // anonymous producers.  The isAdvisoryTopic method checks for null so it is safe to
647            // call it from here with a null Destination value.
648            if (!AdvisorySupport.isAdvisoryTopic(destination)) {
649                if (getProducerCount(connectionId) >= connector.getMaximumProducersAllowedPerConnection()){
650                    throw new IllegalStateException("Can't add producer on connection " + connectionId + ": at maximum limit: " + connector.getMaximumProducersAllowedPerConnection());
651                }
652            }
653            broker.addProducer(cs.getContext(), info);
654            try {
655                ss.addProducer(info);
656            } catch (IllegalStateException e) {
657                broker.removeProducer(cs.getContext(), info);
658            }
659
660        }
661        return null;
662    }
663
664    @Override
665    public Response processRemoveProducer(ProducerId id) throws Exception {
666        SessionId sessionId = id.getParentId();
667        ConnectionId connectionId = sessionId.getParentId();
668        TransportConnectionState cs = lookupConnectionState(connectionId);
669        SessionState ss = cs.getSessionState(sessionId);
670        if (ss == null) {
671            throw new IllegalStateException("Cannot remove a producer from a session that had not been registered: "
672                    + sessionId);
673        }
674        ProducerState ps = ss.removeProducer(id);
675        if (ps == null) {
676            throw new IllegalStateException("Cannot remove a producer that had not been registered: " + id);
677        }
678        removeProducerBrokerExchange(id);
679        broker.removeProducer(cs.getContext(), ps.getInfo());
680        return null;
681    }
682
683    @Override
684    public Response processAddConsumer(ConsumerInfo info) throws Exception {
685        SessionId sessionId = info.getConsumerId().getParentId();
686        ConnectionId connectionId = sessionId.getParentId();
687        TransportConnectionState cs = lookupConnectionState(connectionId);
688        if (cs == null) {
689            throw new IllegalStateException("Cannot add a consumer to a connection that had not been registered: "
690                    + connectionId);
691        }
692        SessionState ss = cs.getSessionState(sessionId);
693        if (ss == null) {
694            throw new IllegalStateException(broker.getBrokerName()
695                    + " Cannot add a consumer to a session that had not been registered: " + sessionId);
696        }
697        // Avoid replaying dup commands
698        if (!ss.getConsumerIds().contains(info.getConsumerId())) {
699            ActiveMQDestination destination = info.getDestination();
700            if (destination != null && !AdvisorySupport.isAdvisoryTopic(destination)) {
701                if (getConsumerCount(connectionId) >= connector.getMaximumConsumersAllowedPerConnection()){
702                    throw new IllegalStateException("Can't add consumer on connection " + connectionId + ": at maximum limit: " + connector.getMaximumConsumersAllowedPerConnection());
703                }
704            }
705
706            broker.addConsumer(cs.getContext(), info);
707            try {
708                ss.addConsumer(info);
709                addConsumerBrokerExchange(cs, info.getConsumerId());
710            } catch (IllegalStateException e) {
711                broker.removeConsumer(cs.getContext(), info);
712            }
713
714        }
715        return null;
716    }
717
718    @Override
719    public Response processRemoveConsumer(ConsumerId id, long lastDeliveredSequenceId) throws Exception {
720        SessionId sessionId = id.getParentId();
721        ConnectionId connectionId = sessionId.getParentId();
722        TransportConnectionState cs = lookupConnectionState(connectionId);
723        if (cs == null) {
724            throw new IllegalStateException("Cannot remove a consumer from a connection that had not been registered: "
725                    + connectionId);
726        }
727        SessionState ss = cs.getSessionState(sessionId);
728        if (ss == null) {
729            throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: "
730                    + sessionId);
731        }
732        ConsumerState consumerState = ss.removeConsumer(id);
733        if (consumerState == null) {
734            throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id);
735        }
736        ConsumerInfo info = consumerState.getInfo();
737        info.setLastDeliveredSequenceId(lastDeliveredSequenceId);
738        broker.removeConsumer(cs.getContext(), consumerState.getInfo());
739        removeConsumerBrokerExchange(id);
740        return null;
741    }
742
743    @Override
744    public Response processAddSession(SessionInfo info) throws Exception {
745        ConnectionId connectionId = info.getSessionId().getParentId();
746        TransportConnectionState cs = lookupConnectionState(connectionId);
747        // Avoid replaying dup commands
748        if (cs != null && !cs.getSessionIds().contains(info.getSessionId())) {
749            broker.addSession(cs.getContext(), info);
750            try {
751                cs.addSession(info);
752            } catch (IllegalStateException e) {
753                LOG.warn("Failed to add session: {}", info.getSessionId(), e);
754                broker.removeSession(cs.getContext(), info);
755            }
756        }
757        return null;
758    }
759
760    @Override
761    public Response processRemoveSession(SessionId id, long lastDeliveredSequenceId) throws Exception {
762        ConnectionId connectionId = id.getParentId();
763        TransportConnectionState cs = lookupConnectionState(connectionId);
764        if (cs == null) {
765            throw new IllegalStateException("Cannot remove session from connection that had not been registered: " + connectionId);
766        }
767        SessionState session = cs.getSessionState(id);
768        if (session == null) {
769            throw new IllegalStateException("Cannot remove session that had not been registered: " + id);
770        }
771        // Don't let new consumers or producers get added while we are closing
772        // this down.
773        session.shutdown();
774        // Cascade the connection stop to the consumers and producers.
775        for (ConsumerId consumerId : session.getConsumerIds()) {
776            try {
777                processRemoveConsumer(consumerId, lastDeliveredSequenceId);
778            } catch (Throwable e) {
779                LOG.warn("Failed to remove consumer: {}", consumerId, e);
780            }
781        }
782        for (ProducerId producerId : session.getProducerIds()) {
783            try {
784                processRemoveProducer(producerId);
785            } catch (Throwable e) {
786                LOG.warn("Failed to remove producer: {}", producerId, e);
787            }
788        }
789        cs.removeSession(id);
790        broker.removeSession(cs.getContext(), session.getInfo());
791        return null;
792    }
793
794    @Override
795    public Response processAddConnection(ConnectionInfo info) throws Exception {
796        // Older clients should have been defaulting this field to true.. but
797        // they were not.
798        if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2) {
799            info.setClientMaster(true);
800        }
801        TransportConnectionState state;
802        // Make sure 2 concurrent connections by the same ID only generate 1
803        // TransportConnectionState object.
804        synchronized (brokerConnectionStates) {
805            state = (TransportConnectionState) brokerConnectionStates.get(info.getConnectionId());
806            if (state == null) {
807                state = new TransportConnectionState(info, this);
808                brokerConnectionStates.put(info.getConnectionId(), state);
809            }
810            state.incrementReference();
811        }
812        // If there are 2 concurrent connections for the same connection id,
813        // then last one in wins, we need to sync here
814        // to figure out the winner.
815        synchronized (state.getConnectionMutex()) {
816            if (state.getConnection() != this) {
817                LOG.debug("Killing previous stale connection: {}", state.getConnection().getRemoteAddress());
818                state.getConnection().stop();
819                LOG.debug("Connection {} taking over previous connection: {}", getRemoteAddress(), state.getConnection().getRemoteAddress());
820                state.setConnection(this);
821                state.reset(info);
822            }
823        }
824        registerConnectionState(info.getConnectionId(), state);
825        LOG.debug("Setting up new connection id: {}, address: {}, info: {}",
826                info.getConnectionId(), getRemoteAddress(), info);
827        this.faultTolerantConnection = info.isFaultTolerant();
828        // Setup the context.
829        String clientId = info.getClientId();
830        context = new ConnectionContext();
831        context.setBroker(broker);
832        context.setClientId(clientId);
833        context.setClientMaster(info.isClientMaster());
834        context.setConnection(this);
835        context.setConnectionId(info.getConnectionId());
836        context.setConnector(connector);
837        context.setMessageAuthorizationPolicy(getMessageAuthorizationPolicy());
838        context.setNetworkConnection(networkConnection);
839        context.setFaultTolerant(faultTolerantConnection);
840        context.setTransactions(new ConcurrentHashMap<TransactionId, Transaction>());
841        context.setUserName(info.getUserName());
842        context.setWireFormatInfo(wireFormatInfo);
843        context.setReconnect(info.isFailoverReconnect());
844        this.manageable = info.isManageable();
845        context.setConnectionState(state);
846        state.setContext(context);
847        state.setConnection(this);
848        if (info.getClientIp() == null) {
849            info.setClientIp(getRemoteAddress());
850        }
851
852        try {
853            broker.addConnection(context, info);
854        } catch (Exception e) {
855            synchronized (brokerConnectionStates) {
856                brokerConnectionStates.remove(info.getConnectionId());
857            }
858            unregisterConnectionState(info.getConnectionId());
859            LOG.warn("Failed to add Connection id={}, clientId={}, clientIP={} due to {}",
860                    info.getConnectionId(), clientId, info.getClientIp(), e.getLocalizedMessage());
861            //AMQ-6561 - stop for all exceptions on addConnection
862            // close this down - in case the peer of this transport doesn't play nice
863            delayedStop(2000, "Failed with SecurityException: " + e.getLocalizedMessage(), e);
864            throw e;
865        }
866        if (info.isManageable()) {
867            // send ConnectionCommand
868            ConnectionControl command = this.connector.getConnectionControl();
869            command.setFaultTolerant(broker.isFaultTolerantConfiguration());
870            if (info.isFailoverReconnect()) {
871                command.setRebalanceConnection(false);
872            }
873            dispatchAsync(command);
874        }
875        return null;
876    }
877
878    @Override
879    public synchronized Response processRemoveConnection(ConnectionId id, long lastDeliveredSequenceId)
880            throws InterruptedException {
881        LOG.debug("remove connection id: {}", id);
882        TransportConnectionState cs = lookupConnectionState(id);
883        if (cs != null) {
884            // Don't allow things to be added to the connection state while we
885            // are shutting down.
886            cs.shutdown();
887            // Cascade the connection stop to the sessions.
888            for (SessionId sessionId : cs.getSessionIds()) {
889                try {
890                    processRemoveSession(sessionId, lastDeliveredSequenceId);
891                } catch (Throwable e) {
892                    SERVICELOG.warn("Failed to remove session {}", sessionId, e);
893                }
894            }
895            // Cascade the connection stop to temp destinations.
896            for (Iterator<DestinationInfo> iter = cs.getTempDestinations().iterator(); iter.hasNext(); ) {
897                DestinationInfo di = iter.next();
898                try {
899                    broker.removeDestination(cs.getContext(), di.getDestination(), 0);
900                } catch (Throwable e) {
901                    SERVICELOG.warn("Failed to remove tmp destination {}", di.getDestination(), e);
902                }
903                iter.remove();
904            }
905            try {
906                broker.removeConnection(cs.getContext(), cs.getInfo(), transportException.get());
907            } catch (Throwable e) {
908                SERVICELOG.warn("Failed to remove connection {}", cs.getInfo(), e);
909            }
910            TransportConnectionState state = unregisterConnectionState(id);
911            if (state != null) {
912                synchronized (brokerConnectionStates) {
913                    // If we are the last reference, we should remove the state
914                    // from the broker.
915                    if (state.decrementReference() == 0) {
916                        brokerConnectionStates.remove(id);
917                    }
918                }
919            }
920        }
921        return null;
922    }
923
924    @Override
925    public Response processProducerAck(ProducerAck ack) throws Exception {
926        // A broker should not get ProducerAck messages.
927        return null;
928    }
929
930    @Override
931    public Connector getConnector() {
932        return connector;
933    }
934
935    @Override
936    public void dispatchSync(Command message) {
937        try {
938            processDispatch(message);
939        } catch (IOException e) {
940            serviceExceptionAsync(e);
941        }
942    }
943
944    @Override
945    public void dispatchAsync(Command message) {
946        if (!stopping.get()) {
947            if (taskRunner == null) {
948                dispatchSync(message);
949            } else {
950                synchronized (dispatchQueue) {
951                    dispatchQueue.add(message);
952                }
953                try {
954                    taskRunner.wakeup();
955                } catch (InterruptedException e) {
956                    Thread.currentThread().interrupt();
957                }
958            }
959        } else {
960            if (message.isMessageDispatch()) {
961                MessageDispatch md = (MessageDispatch) message;
962                TransmitCallback sub = md.getTransmitCallback();
963                broker.postProcessDispatch(md);
964                if (sub != null) {
965                    sub.onFailure();
966                }
967            }
968        }
969    }
970
971    protected void processDispatch(Command command) throws IOException {
972        MessageDispatch messageDispatch = (MessageDispatch) (command.isMessageDispatch() ? command : null);
973        try {
974            if (!stopping.get()) {
975                if (messageDispatch != null) {
976                    try {
977                        broker.preProcessDispatch(messageDispatch);
978                    } catch (RuntimeException convertToIO) {
979                        throw new IOException(convertToIO);
980                    }
981                }
982                dispatch(command);
983            }
984        } catch (IOException e) {
985            if (messageDispatch != null) {
986                TransmitCallback sub = messageDispatch.getTransmitCallback();
987                broker.postProcessDispatch(messageDispatch);
988                if (sub != null) {
989                    sub.onFailure();
990                }
991                messageDispatch = null;
992                throw e;
993            } else {
994                if (TRANSPORTLOG.isDebugEnabled()) {
995                    TRANSPORTLOG.debug("Unexpected exception on asyncDispatch, command of type: {}",
996                            command.getDataStructureType(), e);
997                }
998            }
999        } finally {
1000            if (messageDispatch != null) {
1001                TransmitCallback sub = messageDispatch.getTransmitCallback();
1002                broker.postProcessDispatch(messageDispatch);
1003                if (sub != null) {
1004                    sub.onSuccess();
1005                }
1006            }
1007        }
1008    }
1009
1010    @Override
1011    public boolean iterate() {
1012        try {
1013            if (status.get() == PENDING_STOP || stopping.get()) {
1014                if (dispatchStopped.compareAndSet(false, true)) {
1015                    if (transportException.get() == null) {
1016                        try {
1017                            dispatch(new ShutdownInfo());
1018                        } catch (Throwable ignore) {
1019                        }
1020                    }
1021                    dispatchStoppedLatch.countDown();
1022                }
1023                return false;
1024            }
1025            if (!dispatchStopped.get()) {
1026                Command command = null;
1027                synchronized (dispatchQueue) {
1028                    if (dispatchQueue.isEmpty()) {
1029                        return false;
1030                    }
1031                    command = dispatchQueue.remove(0);
1032                }
1033                processDispatch(command);
1034                return true;
1035            }
1036            return false;
1037        } catch (IOException e) {
1038            if (dispatchStopped.compareAndSet(false, true)) {
1039                dispatchStoppedLatch.countDown();
1040            }
1041            serviceExceptionAsync(e);
1042            return false;
1043        }
1044    }
1045
1046    /**
1047     * Returns the statistics for this connection
1048     */
1049    @Override
1050    public ConnectionStatistics getStatistics() {
1051        return statistics;
1052    }
1053
1054    public MessageAuthorizationPolicy getMessageAuthorizationPolicy() {
1055        return messageAuthorizationPolicy;
1056    }
1057
1058    public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) {
1059        this.messageAuthorizationPolicy = messageAuthorizationPolicy;
1060    }
1061
1062    @Override
1063    public boolean isManageable() {
1064        return manageable;
1065    }
1066
1067    @Override
1068    public void start() throws Exception {
1069        if (status.compareAndSet(NEW, STARTING)) {
1070            try {
1071                synchronized (this) {
1072                    if (taskRunnerFactory != null) {
1073                        taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: "
1074                                + getRemoteAddress());
1075                    } else {
1076                        taskRunner = null;
1077                    }
1078                    transport.start();
1079                    active = true;
1080                    BrokerInfo info = connector.getBrokerInfo().copy();
1081                    if (connector.isUpdateClusterClients()) {
1082                        info.setPeerBrokerInfos(this.broker.getPeerBrokerInfos());
1083                    } else {
1084                        info.setPeerBrokerInfos(null);
1085                    }
1086                    dispatchAsync(info);
1087
1088                    connector.onStarted(this);
1089                }
1090            } catch (Exception e) {
1091                // Force clean up on an error starting up.
1092                status.set(PENDING_STOP);
1093                throw e;
1094            } finally {
1095                // stop() can be called from within the above block,
1096                // but we want to be sure start() completes before
1097                // stop() runs, so queue the stop until right now:
1098                if (!status.compareAndSet(STARTING, STARTED)) {
1099                    LOG.debug("Calling the delayed stop() after start() {}", this);
1100                    stop();
1101                }
1102            }
1103        }
1104    }
1105
1106    @Override
1107    public void stop() throws Exception {
1108        // do not stop task the task runner factories (taskRunnerFactory, stopTaskRunnerFactory)
1109        // as their lifecycle is handled elsewhere
1110
1111        stopAsync();
1112        while (!stopped.await(5, TimeUnit.SECONDS)) {
1113            LOG.info("The connection to '{}' is taking a long time to shutdown.", transport.getRemoteAddress());
1114        }
1115    }
1116
1117    public void delayedStop(final int waitTime, final String reason, Throwable cause) {
1118        if (waitTime > 0) {
1119            status.compareAndSet(STARTING, PENDING_STOP);
1120            transportException.set(cause);
1121            try {
1122                stopTaskRunnerFactory.execute(new Runnable() {
1123                    @Override
1124                    public void run() {
1125                        try {
1126                            Thread.sleep(waitTime);
1127                            stopAsync();
1128                            LOG.info("Stopping {} because {}", transport.getRemoteAddress(), reason);
1129                        } catch (InterruptedException e) {
1130                        }
1131                    }
1132                });
1133            } catch (Throwable t) {
1134                LOG.warn("Cannot create stopAsync. This exception will be ignored.", t);
1135            }
1136        }
1137    }
1138
1139    public void stopAsync(Throwable cause) {
1140        transportException.set(cause);
1141        stopAsync();
1142    }
1143
1144    public void stopAsync() {
1145        // If we're in the middle of starting then go no further... for now.
1146        if (status.compareAndSet(STARTING, PENDING_STOP)) {
1147            LOG.debug("stopAsync() called in the middle of start(). Delaying till start completes..");
1148            return;
1149        }
1150        if (stopping.compareAndSet(false, true)) {
1151            // Let all the connection contexts know we are shutting down
1152            // so that in progress operations can notice and unblock.
1153            List<TransportConnectionState> connectionStates = listConnectionStates();
1154            for (TransportConnectionState cs : connectionStates) {
1155                ConnectionContext connectionContext = cs.getContext();
1156                if (connectionContext != null) {
1157                    connectionContext.getStopping().set(true);
1158                }
1159            }
1160            try {
1161                stopTaskRunnerFactory.execute(new Runnable() {
1162                    @Override
1163                    public void run() {
1164                        serviceLock.writeLock().lock();
1165                        try {
1166                            doStop();
1167                        } catch (Throwable e) {
1168                            LOG.debug("Error occurred while shutting down a connection {}", this, e);
1169                        } finally {
1170                            stopped.countDown();
1171                            serviceLock.writeLock().unlock();
1172                        }
1173                    }
1174                });
1175            } catch (Throwable t) {
1176                LOG.warn("Cannot create async transport stopper thread. This exception is ignored. Not waiting for stop to complete", t);
1177                stopped.countDown();
1178            }
1179        }
1180    }
1181
1182    @Override
1183    public String toString() {
1184        return "Transport Connection to: " + transport.getRemoteAddress();
1185    }
1186
1187    protected void doStop() throws Exception {
1188        LOG.debug("Stopping connection: {}", transport.getRemoteAddress());
1189        connector.onStopped(this);
1190        try {
1191            synchronized (this) {
1192                if (duplexBridge != null) {
1193                    duplexBridge.stop();
1194                }
1195            }
1196        } catch (Exception ignore) {
1197            LOG.trace("Exception caught stopping. This exception is ignored.", ignore);
1198        }
1199        try {
1200            transport.stop();
1201            LOG.debug("Stopped transport: {}", transport.getRemoteAddress());
1202        } catch (Exception e) {
1203            LOG.debug("Could not stop transport to {}. This exception is ignored.", transport.getRemoteAddress(), e);
1204        }
1205        if (taskRunner != null) {
1206            taskRunner.shutdown(1);
1207            taskRunner = null;
1208        }
1209        active = false;
1210        // Run the MessageDispatch callbacks so that message references get
1211        // cleaned up.
1212        synchronized (dispatchQueue) {
1213            for (Iterator<Command> iter = dispatchQueue.iterator(); iter.hasNext(); ) {
1214                Command command = iter.next();
1215                if (command.isMessageDispatch()) {
1216                    MessageDispatch md = (MessageDispatch) command;
1217                    TransmitCallback sub = md.getTransmitCallback();
1218                    broker.postProcessDispatch(md);
1219                    if (sub != null) {
1220                        sub.onFailure();
1221                    }
1222                }
1223            }
1224            dispatchQueue.clear();
1225        }
1226        //
1227        // Remove all logical connection associated with this connection
1228        // from the broker.
1229        if (!broker.isStopped()) {
1230            List<TransportConnectionState> connectionStates = listConnectionStates();
1231            connectionStates = listConnectionStates();
1232            for (TransportConnectionState cs : connectionStates) {
1233                cs.getContext().getStopping().set(true);
1234                try {
1235                    LOG.debug("Cleaning up connection resources: {}", getRemoteAddress());
1236                    processRemoveConnection(cs.getInfo().getConnectionId(), RemoveInfo.LAST_DELIVERED_UNKNOWN);
1237                } catch (Throwable ignore) {
1238                    LOG.debug("Exception caught removing connection {}. This exception is ignored.", cs.getInfo().getConnectionId(), ignore);
1239                }
1240            }
1241        }
1242        LOG.debug("Connection Stopped: {}", getRemoteAddress());
1243    }
1244
1245    /**
1246     * @return Returns the blockedCandidate.
1247     */
1248    public boolean isBlockedCandidate() {
1249        return blockedCandidate;
1250    }
1251
1252    /**
1253     * @param blockedCandidate The blockedCandidate to set.
1254     */
1255    public void setBlockedCandidate(boolean blockedCandidate) {
1256        this.blockedCandidate = blockedCandidate;
1257    }
1258
1259    /**
1260     * @return Returns the markedCandidate.
1261     */
1262    public boolean isMarkedCandidate() {
1263        return markedCandidate;
1264    }
1265
1266    /**
1267     * @param markedCandidate The markedCandidate to set.
1268     */
1269    public void setMarkedCandidate(boolean markedCandidate) {
1270        this.markedCandidate = markedCandidate;
1271        if (!markedCandidate) {
1272            timeStamp = 0;
1273            blockedCandidate = false;
1274        }
1275    }
1276
1277    /**
1278     * @param slow The slow to set.
1279     */
1280    public void setSlow(boolean slow) {
1281        this.slow = slow;
1282    }
1283
1284    /**
1285     * @return true if the Connection is slow
1286     */
1287    @Override
1288    public boolean isSlow() {
1289        return slow;
1290    }
1291
1292    /**
1293     * @return true if the Connection is potentially blocked
1294     */
1295    public boolean isMarkedBlockedCandidate() {
1296        return markedCandidate;
1297    }
1298
1299    /**
1300     * Mark the Connection, so we can deem if it's collectable on the next sweep
1301     */
1302    public void doMark() {
1303        if (timeStamp == 0) {
1304            timeStamp = System.currentTimeMillis();
1305        }
1306    }
1307
1308    /**
1309     * @return if after being marked, the Connection is still writing
1310     */
1311    @Override
1312    public boolean isBlocked() {
1313        return blocked;
1314    }
1315
1316    /**
1317     * @return true if the Connection is connected
1318     */
1319    @Override
1320    public boolean isConnected() {
1321        return connected;
1322    }
1323
1324    /**
1325     * @param blocked The blocked to set.
1326     */
1327    public void setBlocked(boolean blocked) {
1328        this.blocked = blocked;
1329    }
1330
1331    /**
1332     * @param connected The connected to set.
1333     */
1334    public void setConnected(boolean connected) {
1335        this.connected = connected;
1336    }
1337
1338    /**
1339     * @return true if the Connection is active
1340     */
1341    @Override
1342    public boolean isActive() {
1343        return active;
1344    }
1345
1346    /**
1347     * @param active The active to set.
1348     */
1349    public void setActive(boolean active) {
1350        this.active = active;
1351    }
1352
1353    /**
1354     * @return true if the Connection is starting
1355     */
1356    public boolean isStarting() {
1357        return status.get() == STARTING;
1358    }
1359
1360    @Override
1361    public synchronized boolean isNetworkConnection() {
1362        return networkConnection;
1363    }
1364
1365    @Override
1366    public boolean isFaultTolerantConnection() {
1367        return this.faultTolerantConnection;
1368    }
1369
1370    /**
1371     * @return true if the Connection needs to stop
1372     */
1373    public boolean isPendingStop() {
1374        return status.get() == PENDING_STOP;
1375    }
1376
1377    private NetworkBridgeConfiguration getNetworkConfiguration(final BrokerInfo info) throws IOException {
1378        Properties properties = MarshallingSupport.stringToProperties(info.getNetworkProperties());
1379        Map<String, String> props = createMap(properties);
1380        NetworkBridgeConfiguration config = new NetworkBridgeConfiguration();
1381        IntrospectionSupport.setProperties(config, props, "");
1382        return config;
1383    }
1384
1385    @Override
1386    public Response processBrokerInfo(BrokerInfo info) {
1387        if (info.isSlaveBroker()) {
1388            LOG.error(" Slave Brokers are no longer supported - slave trying to attach is: {}", info.getBrokerName());
1389        } else if (info.isNetworkConnection() && !info.isDuplexConnection()) {
1390            try {
1391                NetworkBridgeConfiguration config = getNetworkConfiguration(info);
1392                if (config.isSyncDurableSubs() && protocolVersion.get() >= CommandTypes.PROTOCOL_VERSION_DURABLE_SYNC) {
1393                    LOG.debug("SyncDurableSubs is enabled, Sending BrokerSubscriptionInfo");
1394                    dispatchSync(NetworkBridgeUtils.getBrokerSubscriptionInfo(this.broker.getBrokerService(), config));
1395                }
1396            } catch (Exception e) {
1397                LOG.error("Failed to respond to network bridge creation from broker {}", info.getBrokerId(), e);
1398                return null;
1399            }
1400        } else if (info.isNetworkConnection() && info.isDuplexConnection()) {
1401            // so this TransportConnection is the rear end of a network bridge
1402            // We have been requested to create a two way pipe ...
1403            try {
1404                NetworkBridgeConfiguration config = getNetworkConfiguration(info);
1405                config.setBrokerName(broker.getBrokerName());
1406
1407                if (config.isSyncDurableSubs() && protocolVersion.get() >= CommandTypes.PROTOCOL_VERSION_DURABLE_SYNC) {
1408                    LOG.debug("SyncDurableSubs is enabled, Sending BrokerSubscriptionInfo");
1409                    dispatchSync(NetworkBridgeUtils.getBrokerSubscriptionInfo(this.broker.getBrokerService(), config));
1410                }
1411
1412                // check for existing duplex connection hanging about
1413
1414                // We first look if existing network connection already exists for the same broker Id and network connector name
1415                // It's possible in case of brief network fault to have this transport connector side of the connection always active
1416                // and the duplex network connector side wanting to open a new one
1417                // In this case, the old connection must be broken
1418                String duplexNetworkConnectorId = config.getName() + "@" + info.getBrokerId();
1419                CopyOnWriteArrayList<TransportConnection> connections = this.connector.getConnections();
1420                synchronized (connections) {
1421                    for (Iterator<TransportConnection> iter = connections.iterator(); iter.hasNext(); ) {
1422                        TransportConnection c = iter.next();
1423                        if ((c != this) && (duplexNetworkConnectorId.equals(c.getDuplexNetworkConnectorId()))) {
1424                            LOG.warn("Stopping an existing active duplex connection [{}] for network connector ({}).", c, duplexNetworkConnectorId);
1425                            c.stopAsync();
1426                            // better to wait for a bit rather than get connection id already in use and failure to start new bridge
1427                            c.getStopped().await(1, TimeUnit.SECONDS);
1428                        }
1429                    }
1430                    setDuplexNetworkConnectorId(duplexNetworkConnectorId);
1431                }
1432                Transport localTransport = NetworkBridgeFactory.createLocalTransport(config, broker.getVmConnectorURI());
1433                Transport remoteBridgeTransport = transport;
1434                if (! (remoteBridgeTransport instanceof ResponseCorrelator)) {
1435                    // the vm transport case is already wrapped
1436                    remoteBridgeTransport = new ResponseCorrelator(remoteBridgeTransport);
1437                }
1438                String duplexName = localTransport.toString();
1439                if (duplexName.contains("#")) {
1440                    duplexName = duplexName.substring(duplexName.lastIndexOf("#"));
1441                }
1442                MBeanNetworkListener listener = new MBeanNetworkListener(brokerService, config, brokerService.createDuplexNetworkConnectorObjectName(duplexName));
1443                listener.setCreatedByDuplex(true);
1444                duplexBridge = config.getBridgeFactory().createNetworkBridge(config, localTransport, remoteBridgeTransport, listener);
1445                duplexBridge.setBrokerService(brokerService);
1446                //Need to set durableDestinations to properly restart subs when dynamicOnly=false
1447                duplexBridge.setDurableDestinations(NetworkConnector.getDurableTopicDestinations(
1448                        broker.getDurableDestinations()));
1449
1450                // now turn duplex off this side
1451                info.setDuplexConnection(false);
1452                duplexBridge.setCreatedByDuplex(true);
1453                duplexBridge.duplexStart(this, brokerInfo, info);
1454                LOG.info("Started responder end of duplex bridge {}", duplexNetworkConnectorId);
1455                return null;
1456            } catch (TransportDisposedIOException e) {
1457                LOG.warn("Duplex bridge {} was stopped before it was correctly started.", duplexNetworkConnectorId);
1458                return null;
1459            } catch (Exception e) {
1460                LOG.error("Failed to create responder end of duplex network bridge {}", duplexNetworkConnectorId, e);
1461                return null;
1462            }
1463        }
1464        // We only expect to get one broker info command per connection
1465        if (this.brokerInfo != null) {
1466            LOG.warn("Unexpected extra broker info command received: {}", info);
1467        }
1468        this.brokerInfo = info;
1469        networkConnection = true;
1470        List<TransportConnectionState> connectionStates = listConnectionStates();
1471        for (TransportConnectionState cs : connectionStates) {
1472            cs.getContext().setNetworkConnection(true);
1473        }
1474        return null;
1475    }
1476
1477    @SuppressWarnings({"unchecked", "rawtypes"})
1478    private HashMap<String, String> createMap(Properties properties) {
1479        return new HashMap(properties);
1480    }
1481
1482    protected void dispatch(Command command) throws IOException {
1483        try {
1484            setMarkedCandidate(true);
1485            transport.oneway(command);
1486        } finally {
1487            setMarkedCandidate(false);
1488        }
1489    }
1490
1491    @Override
1492    public String getRemoteAddress() {
1493        return transport.getRemoteAddress();
1494    }
1495
1496    public Transport getTransport() {
1497        return transport;
1498    }
1499
1500    @Override
1501    public String getConnectionId() {
1502        List<TransportConnectionState> connectionStates = listConnectionStates();
1503        for (TransportConnectionState cs : connectionStates) {
1504            if (cs.getInfo().getClientId() != null) {
1505                return cs.getInfo().getClientId();
1506            }
1507            return cs.getInfo().getConnectionId().toString();
1508        }
1509        return null;
1510    }
1511
1512    @Override
1513    public void updateClient(ConnectionControl control) {
1514        if (isActive() && isBlocked() == false && isFaultTolerantConnection() && this.wireFormatInfo != null
1515                && this.wireFormatInfo.getVersion() >= 6) {
1516            dispatchAsync(control);
1517        }
1518    }
1519
1520    public ProducerBrokerExchange getProducerBrokerExchangeIfExists(ProducerInfo producerInfo){
1521        ProducerBrokerExchange result = null;
1522        if (producerInfo != null && producerInfo.getProducerId() != null){
1523            synchronized (producerExchanges){
1524                result = producerExchanges.get(producerInfo.getProducerId());
1525            }
1526        }
1527        return result;
1528    }
1529
1530    private ProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException {
1531        ProducerBrokerExchange result = producerExchanges.get(id);
1532        if (result == null) {
1533            synchronized (producerExchanges) {
1534                result = new ProducerBrokerExchange();
1535                TransportConnectionState state = lookupConnectionState(id);
1536                context = state.getContext();
1537                result.setConnectionContext(context);
1538                if (context.isReconnect() || (context.isNetworkConnection() && connector.isAuditNetworkProducers())) {
1539                    result.setLastStoredSequenceId(brokerService.getPersistenceAdapter().getLastProducerSequenceId(id));
1540                }
1541                SessionState ss = state.getSessionState(id.getParentId());
1542                if (ss != null) {
1543                    result.setProducerState(ss.getProducerState(id));
1544                    ProducerState producerState = ss.getProducerState(id);
1545                    if (producerState != null && producerState.getInfo() != null) {
1546                        ProducerInfo info = producerState.getInfo();
1547                        result.setMutable(info.getDestination() == null || info.getDestination().isComposite());
1548                    }
1549                }
1550                producerExchanges.put(id, result);
1551            }
1552        } else {
1553            context = result.getConnectionContext();
1554        }
1555        return result;
1556    }
1557
1558    private void removeProducerBrokerExchange(ProducerId id) {
1559        synchronized (producerExchanges) {
1560            producerExchanges.remove(id);
1561        }
1562    }
1563
1564    private ConsumerBrokerExchange getConsumerBrokerExchange(ConsumerId id) {
1565        ConsumerBrokerExchange result = consumerExchanges.get(id);
1566        return result;
1567    }
1568
1569    private ConsumerBrokerExchange addConsumerBrokerExchange(TransportConnectionState connectionState, ConsumerId id) {
1570        ConsumerBrokerExchange result = consumerExchanges.get(id);
1571        if (result == null) {
1572            synchronized (consumerExchanges) {
1573                result = new ConsumerBrokerExchange();
1574                context = connectionState.getContext();
1575                result.setConnectionContext(context);
1576                SessionState ss = connectionState.getSessionState(id.getParentId());
1577                if (ss != null) {
1578                    ConsumerState cs = ss.getConsumerState(id);
1579                    if (cs != null) {
1580                        ConsumerInfo info = cs.getInfo();
1581                        if (info != null) {
1582                            if (info.getDestination() != null && info.getDestination().isPattern()) {
1583                                result.setWildcard(true);
1584                            }
1585                        }
1586                    }
1587                }
1588                consumerExchanges.put(id, result);
1589            }
1590        }
1591        return result;
1592    }
1593
1594    private void removeConsumerBrokerExchange(ConsumerId id) {
1595        synchronized (consumerExchanges) {
1596            consumerExchanges.remove(id);
1597        }
1598    }
1599
1600    public int getProtocolVersion() {
1601        return protocolVersion.get();
1602    }
1603
1604    @Override
1605    public Response processControlCommand(ControlCommand command) throws Exception {
1606        return null;
1607    }
1608
1609    @Override
1610    public Response processMessageDispatch(MessageDispatch dispatch) throws Exception {
1611        return null;
1612    }
1613
1614    @Override
1615    public Response processConnectionControl(ConnectionControl control) throws Exception {
1616        if (control != null) {
1617            faultTolerantConnection = control.isFaultTolerant();
1618        }
1619        return null;
1620    }
1621
1622    @Override
1623    public Response processConnectionError(ConnectionError error) throws Exception {
1624        return null;
1625    }
1626
1627    @Override
1628    public Response processConsumerControl(ConsumerControl control) throws Exception {
1629        ConsumerBrokerExchange consumerExchange = getConsumerBrokerExchange(control.getConsumerId());
1630        broker.processConsumerControl(consumerExchange, control);
1631        return null;
1632    }
1633
1634    protected synchronized TransportConnectionState registerConnectionState(ConnectionId connectionId,
1635                                                                            TransportConnectionState state) {
1636        TransportConnectionState cs = null;
1637        if (!connectionStateRegister.isEmpty() && !connectionStateRegister.doesHandleMultipleConnectionStates()) {
1638            // swap implementations
1639            TransportConnectionStateRegister newRegister = new MapTransportConnectionStateRegister();
1640            newRegister.intialize(connectionStateRegister);
1641            connectionStateRegister = newRegister;
1642        }
1643        cs = connectionStateRegister.registerConnectionState(connectionId, state);
1644        return cs;
1645    }
1646
1647    protected synchronized TransportConnectionState unregisterConnectionState(ConnectionId connectionId) {
1648        return connectionStateRegister.unregisterConnectionState(connectionId);
1649    }
1650
1651    protected synchronized List<TransportConnectionState> listConnectionStates() {
1652        return connectionStateRegister.listConnectionStates();
1653    }
1654
1655    protected synchronized TransportConnectionState lookupConnectionState(String connectionId) {
1656        return connectionStateRegister.lookupConnectionState(connectionId);
1657    }
1658
1659    protected synchronized TransportConnectionState lookupConnectionState(ConsumerId id) {
1660        return connectionStateRegister.lookupConnectionState(id);
1661    }
1662
1663    protected synchronized TransportConnectionState lookupConnectionState(ProducerId id) {
1664        return connectionStateRegister.lookupConnectionState(id);
1665    }
1666
1667    protected synchronized TransportConnectionState lookupConnectionState(SessionId id) {
1668        return connectionStateRegister.lookupConnectionState(id);
1669    }
1670
1671    // public only for testing
1672    public synchronized TransportConnectionState lookupConnectionState(ConnectionId connectionId) {
1673        return connectionStateRegister.lookupConnectionState(connectionId);
1674    }
1675
1676    protected synchronized void setDuplexNetworkConnectorId(String duplexNetworkConnectorId) {
1677        this.duplexNetworkConnectorId = duplexNetworkConnectorId;
1678    }
1679
1680    protected synchronized String getDuplexNetworkConnectorId() {
1681        return this.duplexNetworkConnectorId;
1682    }
1683
1684    public boolean isStopping() {
1685        return stopping.get();
1686    }
1687
1688    protected CountDownLatch getStopped() {
1689        return stopped;
1690    }
1691
1692    private int getProducerCount(ConnectionId connectionId) {
1693        int result = 0;
1694        TransportConnectionState cs = lookupConnectionState(connectionId);
1695        if (cs != null) {
1696            for (SessionId sessionId : cs.getSessionIds()) {
1697                SessionState sessionState = cs.getSessionState(sessionId);
1698                if (sessionState != null) {
1699                    result += sessionState.getProducerIds().size();
1700                }
1701            }
1702        }
1703        return result;
1704    }
1705
1706    private int getConsumerCount(ConnectionId connectionId) {
1707        int result = 0;
1708        TransportConnectionState cs = lookupConnectionState(connectionId);
1709        if (cs != null) {
1710            for (SessionId sessionId : cs.getSessionIds()) {
1711                SessionState sessionState = cs.getSessionState(sessionId);
1712                if (sessionState != null) {
1713                    result += sessionState.getConsumerIds().size();
1714                }
1715            }
1716        }
1717        return result;
1718    }
1719
1720    public WireFormatInfo getRemoteWireFormatInfo() {
1721        return wireFormatInfo;
1722    }
1723
1724    /* (non-Javadoc)
1725     * @see org.apache.activemq.state.CommandVisitor#processBrokerSubscriptionInfo(org.apache.activemq.command.BrokerSubscriptionInfo)
1726     */
1727    @Override
1728    public Response processBrokerSubscriptionInfo(BrokerSubscriptionInfo info) throws Exception {
1729        return null;
1730    }
1731}