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.transport.failover;
018
019import java.io.BufferedReader;
020import java.io.FileReader;
021import java.io.IOException;
022import java.io.InputStreamReader;
023import java.io.InterruptedIOException;
024import java.net.InetAddress;
025import java.net.MalformedURLException;
026import java.net.URI;
027import java.net.URISyntaxException;
028import java.net.URL;
029import java.util.ArrayList;
030import java.util.Collections;
031import java.util.HashSet;
032import java.util.Iterator;
033import java.util.LinkedHashMap;
034import java.util.List;
035import java.util.Map;
036import java.util.StringTokenizer;
037import java.util.concurrent.CopyOnWriteArrayList;
038import java.util.concurrent.atomic.AtomicReference;
039
040import org.apache.activemq.broker.SslContext;
041import org.apache.activemq.command.Command;
042import org.apache.activemq.command.ConnectionControl;
043import org.apache.activemq.command.ConsumerControl;
044import org.apache.activemq.command.ConnectionId;
045import org.apache.activemq.command.MessageDispatch;
046import org.apache.activemq.command.MessagePull;
047import org.apache.activemq.command.RemoveInfo;
048import org.apache.activemq.command.Response;
049
050import org.apache.activemq.state.ConnectionStateTracker;
051import org.apache.activemq.state.Tracked;
052import org.apache.activemq.thread.Task;
053import org.apache.activemq.thread.TaskRunner;
054import org.apache.activemq.thread.TaskRunnerFactory;
055import org.apache.activemq.transport.CompositeTransport;
056import org.apache.activemq.transport.DefaultTransportListener;
057import org.apache.activemq.transport.FutureResponse;
058import org.apache.activemq.transport.ResponseCallback;
059import org.apache.activemq.transport.Transport;
060import org.apache.activemq.transport.TransportFactory;
061import org.apache.activemq.transport.TransportListener;
062import org.apache.activemq.util.IOExceptionSupport;
063import org.apache.activemq.util.ServiceSupport;
064import org.apache.activemq.util.URISupport;
065import org.slf4j.Logger;
066import org.slf4j.LoggerFactory;
067
068/**
069 * A Transport that is made reliable by being able to fail over to another
070 * transport when a transport failure is detected.
071 */
072public class FailoverTransport implements CompositeTransport {
073
074    private static final Logger LOG = LoggerFactory.getLogger(FailoverTransport.class);
075    private static final int DEFAULT_INITIAL_RECONNECT_DELAY = 10;
076    private static final int INFINITE = -1;
077    private TransportListener transportListener;
078    private boolean disposed;
079    private final CopyOnWriteArrayList<URI> uris = new CopyOnWriteArrayList<URI>();
080    private final CopyOnWriteArrayList<URI> updated = new CopyOnWriteArrayList<URI>();
081
082    private final Object reconnectMutex = new Object();
083    private final Object backupMutex = new Object();
084    private final Object sleepMutex = new Object();
085    private final Object listenerMutex = new Object();
086    private final ConnectionStateTracker stateTracker = new ConnectionStateTracker();
087    private final Map<Integer, Command> requestMap = new LinkedHashMap<Integer, Command>();
088
089    private URI connectedTransportURI;
090    private URI failedConnectTransportURI;
091    private final AtomicReference<Transport> connectedTransport = new AtomicReference<Transport>();
092    private final TaskRunnerFactory reconnectTaskFactory;
093    private final TaskRunner reconnectTask;
094    private boolean started;
095    private long initialReconnectDelay = DEFAULT_INITIAL_RECONNECT_DELAY;
096    private long maxReconnectDelay = 1000 * 30;
097    private double backOffMultiplier = 2d;
098    private long timeout = INFINITE;
099    private boolean useExponentialBackOff = true;
100    private boolean randomize = true;
101    private int maxReconnectAttempts = INFINITE;
102    private int startupMaxReconnectAttempts = INFINITE;
103    private int connectFailures;
104    private int warnAfterReconnectAttempts = 10;
105    private long reconnectDelay = DEFAULT_INITIAL_RECONNECT_DELAY;
106    private Exception connectionFailure;
107    private boolean firstConnection = true;
108    // optionally always have a backup created
109    private boolean backup = false;
110    private final List<BackupTransport> backups = new CopyOnWriteArrayList<BackupTransport>();
111    private int backupPoolSize = 1;
112    private boolean trackMessages = false;
113    private boolean trackTransactionProducers = true;
114    private int maxCacheSize = 128 * 1024;
115    private final TransportListener disposedListener = new DefaultTransportListener() {
116    };
117    private final TransportListener myTransportListener = createTransportListener();
118    private boolean updateURIsSupported = true;
119    private boolean reconnectSupported = true;
120    // remember for reconnect thread
121    private SslContext brokerSslContext;
122    private String updateURIsURL = null;
123    private boolean rebalanceUpdateURIs = true;
124    private boolean doRebalance = false;
125    private boolean connectedToPriority = false;
126
127    private boolean priorityBackup = false;
128    private final ArrayList<URI> priorityList = new ArrayList<URI>();
129    private boolean priorityBackupAvailable = false;
130    private String nestedExtraQueryOptions;
131    private boolean shuttingDown = false;
132
133    public FailoverTransport() throws InterruptedIOException {
134        brokerSslContext = SslContext.getCurrentSslContext();
135        stateTracker.setTrackTransactions(true);
136        // Setup a task that is used to reconnect the a connection async.
137        reconnectTaskFactory = new TaskRunnerFactory();
138        reconnectTaskFactory.init();
139        reconnectTask = reconnectTaskFactory.createTaskRunner(new Task() {
140            @Override
141            public boolean iterate() {
142                boolean result = false;
143                if (!started) {
144                    return result;
145                }
146                boolean buildBackup = true;
147                synchronized (backupMutex) {
148                    if ((connectedTransport.get() == null || doRebalance || priorityBackupAvailable) && !disposed) {
149                        result = doReconnect();
150                        buildBackup = false;
151                    }
152                }
153                if (buildBackup) {
154                    buildBackups();
155                    if (priorityBackup && !connectedToPriority) {
156                        try {
157                            doDelay();
158                            if (reconnectTask == null) {
159                                return true;
160                            }
161                            reconnectTask.wakeup();
162                        } catch (InterruptedException e) {
163                            LOG.debug("Reconnect task has been interrupted.", e);
164                        }
165                    }
166                } else {
167                    // build backups on the next iteration
168                    buildBackup = true;
169                    try {
170                        if (reconnectTask == null) {
171                            return true;
172                        }
173                        reconnectTask.wakeup();
174                    } catch (InterruptedException e) {
175                        LOG.debug("Reconnect task has been interrupted.", e);
176                    }
177                }
178                return result;
179            }
180
181        }, "ActiveMQ Failover Worker: " + System.identityHashCode(this));
182    }
183
184    TransportListener createTransportListener() {
185        return new TransportListener() {
186            @Override
187            public void onCommand(Object o) {
188                Command command = (Command) o;
189                if (command == null) {
190                    return;
191                }
192                if (command.isResponse()) {
193                    Object object = null;
194                    synchronized (requestMap) {
195                        object = requestMap.remove(Integer.valueOf(((Response) command).getCorrelationId()));
196                    }
197                    if (object != null && object.getClass() == Tracked.class) {
198                        ((Tracked) object).onResponses(command);
199                    }
200                }
201
202                if (command.isConnectionControl()) {
203                    handleConnectionControl((ConnectionControl) command);
204                }
205                else if (command.isConsumerControl()) {
206                    ConsumerControl consumerControl = (ConsumerControl)command;
207                    if (consumerControl.isClose()) {
208                        stateTracker.processRemoveConsumer(consumerControl.getConsumerId(), RemoveInfo.LAST_DELIVERED_UNKNOWN);
209                    }
210
211                }
212                if (transportListener != null) {
213                    transportListener.onCommand(command);
214                }
215            }
216
217            @Override
218            public void onException(IOException error) {
219                try {
220                    handleTransportFailure(error);
221                } catch (InterruptedException e) {
222                    Thread.currentThread().interrupt();
223                    transportListener.onException(new InterruptedIOException());
224                }
225            }
226
227            @Override
228            public void transportInterupted() {
229                if (transportListener != null) {
230                    transportListener.transportInterupted();
231                }
232            }
233
234            @Override
235            public void transportResumed() {
236                if (transportListener != null) {
237                    transportListener.transportResumed();
238                }
239            }
240        };
241    }
242
243    public final void disposeTransport(Transport transport) {
244        transport.setTransportListener(disposedListener);
245        ServiceSupport.dispose(transport);
246    }
247
248    public final void handleTransportFailure(IOException e) throws InterruptedException {
249        if (shuttingDown) {
250            // shutdown info sent and remote socket closed and we see that before a local close
251            // let the close do the work
252            return;
253        }
254
255        if (LOG.isTraceEnabled()) {
256            LOG.trace(this + " handleTransportFailure: " + e, e);
257        }
258
259        // could be blocked in write with the reconnectMutex held, but still needs to be whacked
260        Transport transport = connectedTransport.getAndSet(null);
261        if (transport != null) {
262            disposeTransport(transport);
263        }
264
265        synchronized (reconnectMutex) {
266            if (transport != null && connectedTransport.get() == null) {
267
268                boolean reconnectOk = false;
269
270                if (canReconnect()) {
271                    reconnectOk = true;
272                }
273                 LOG.warn("Transport (" + connectedTransportURI + ") failed"
274                        + (reconnectOk ? "," : ", not") + " attempting to automatically reconnect", e);
275
276                failedConnectTransportURI = connectedTransportURI;
277                connectedTransportURI = null;
278                connectedToPriority = false;
279
280                if (reconnectOk) {
281                    // notify before any reconnect attempt so ack state can be whacked
282                    if (transportListener != null) {
283                        transportListener.transportInterupted();
284                    }
285
286                    updated.remove(failedConnectTransportURI);
287                    reconnectTask.wakeup();
288                } else if (!isDisposed()) {
289                    propagateFailureToExceptionListener(e);
290                }
291            }
292        }
293    }
294
295    private boolean canReconnect() {
296        return started && 0 != calculateReconnectAttemptLimit();
297    }
298
299    public final void handleConnectionControl(ConnectionControl control) {
300        String reconnectStr = control.getReconnectTo();
301        if (LOG.isTraceEnabled()) {
302            LOG.trace("Received ConnectionControl: {}", control);
303        }
304
305        if (reconnectStr != null) {
306            reconnectStr = reconnectStr.trim();
307            if (reconnectStr.length() > 0) {
308                try {
309                    URI uri = new URI(reconnectStr);
310                    if (isReconnectSupported()) {
311                        reconnect(uri);
312                        LOG.info("Reconnected to: " + uri);
313                    }
314                } catch (Exception e) {
315                    LOG.error("Failed to handle ConnectionControl reconnect to " + reconnectStr, e);
316                }
317            }
318        }
319        processNewTransports(control.isRebalanceConnection(), control.getConnectedBrokers());
320    }
321
322    private final void processNewTransports(boolean rebalance, String newTransports) {
323        if (newTransports != null) {
324            newTransports = newTransports.trim();
325            if (newTransports.length() > 0 && isUpdateURIsSupported()) {
326                List<URI> list = new ArrayList<URI>();
327                StringTokenizer tokenizer = new StringTokenizer(newTransports, ",");
328                while (tokenizer.hasMoreTokens()) {
329                    String str = tokenizer.nextToken();
330                    try {
331                        URI uri = new URI(str);
332                        list.add(uri);
333                    } catch (Exception e) {
334                        LOG.error("Failed to parse broker address: " + str, e);
335                    }
336                }
337                if (list.isEmpty() == false) {
338                    try {
339                        updateURIs(rebalance, list.toArray(new URI[list.size()]));
340                    } catch (IOException e) {
341                        LOG.error("Failed to update transport URI's from: " + newTransports, e);
342                    }
343                }
344            }
345        }
346    }
347
348    @Override
349    public void start() throws Exception {
350        synchronized (reconnectMutex) {
351            if (LOG.isDebugEnabled()) {
352                LOG.debug("Started " + this);
353            }
354            if (started) {
355                return;
356            }
357            started = true;
358            stateTracker.setMaxCacheSize(getMaxCacheSize());
359            stateTracker.setTrackMessages(isTrackMessages());
360            stateTracker.setTrackTransactionProducers(isTrackTransactionProducers());
361            if (connectedTransport.get() != null) {
362                stateTracker.restore(connectedTransport.get());
363            } else {
364                reconnect(false);
365            }
366        }
367    }
368
369    @Override
370    public void stop() throws Exception {
371        Transport transportToStop = null;
372        List<Transport> backupsToStop = new ArrayList<Transport>(backups.size());
373
374        try {
375            synchronized (reconnectMutex) {
376                if (LOG.isDebugEnabled()) {
377                    LOG.debug("Stopped " + this);
378                }
379                if (!started) {
380                    return;
381                }
382                started = false;
383                disposed = true;
384
385                if (connectedTransport.get() != null) {
386                    transportToStop = connectedTransport.getAndSet(null);
387                }
388                reconnectMutex.notifyAll();
389            }
390            synchronized (sleepMutex) {
391                sleepMutex.notifyAll();
392            }
393        } finally {
394            reconnectTask.shutdown();
395            reconnectTaskFactory.shutdownNow();
396        }
397
398        synchronized(backupMutex) {
399            for (BackupTransport backup : backups) {
400                backup.setDisposed(true);
401                Transport transport = backup.getTransport();
402                if (transport != null) {
403                    transport.setTransportListener(disposedListener);
404                    backupsToStop.add(transport);
405                }
406            }
407            backups.clear();
408        }
409        for (Transport transport : backupsToStop) {
410            try {
411                if (LOG.isTraceEnabled()) {
412                    LOG.trace("Stopped backup: " + transport);
413                }
414                disposeTransport(transport);
415            } catch (Exception e) {
416            }
417        }
418        if (transportToStop != null) {
419            transportToStop.stop();
420        }
421    }
422
423    public long getInitialReconnectDelay() {
424        return initialReconnectDelay;
425    }
426
427    public void setInitialReconnectDelay(long initialReconnectDelay) {
428        this.initialReconnectDelay = initialReconnectDelay;
429    }
430
431    public long getMaxReconnectDelay() {
432        return maxReconnectDelay;
433    }
434
435    public void setMaxReconnectDelay(long maxReconnectDelay) {
436        this.maxReconnectDelay = maxReconnectDelay;
437    }
438
439    public long getReconnectDelay() {
440        return reconnectDelay;
441    }
442
443    public void setReconnectDelay(long reconnectDelay) {
444        this.reconnectDelay = reconnectDelay;
445    }
446
447    public double getReconnectDelayExponent() {
448        return backOffMultiplier;
449    }
450
451    public void setReconnectDelayExponent(double reconnectDelayExponent) {
452        this.backOffMultiplier = reconnectDelayExponent;
453    }
454
455    public Transport getConnectedTransport() {
456        return connectedTransport.get();
457    }
458
459    public URI getConnectedTransportURI() {
460        return connectedTransportURI;
461    }
462
463    public int getMaxReconnectAttempts() {
464        return maxReconnectAttempts;
465    }
466
467    public void setMaxReconnectAttempts(int maxReconnectAttempts) {
468        this.maxReconnectAttempts = maxReconnectAttempts;
469    }
470
471    public int getStartupMaxReconnectAttempts() {
472        return this.startupMaxReconnectAttempts;
473    }
474
475    public void setStartupMaxReconnectAttempts(int startupMaxReconnectAttempts) {
476        this.startupMaxReconnectAttempts = startupMaxReconnectAttempts;
477    }
478
479    public long getTimeout() {
480        return timeout;
481    }
482
483    public void setTimeout(long timeout) {
484        this.timeout = timeout;
485    }
486
487    /**
488     * @return Returns the randomize.
489     */
490    public boolean isRandomize() {
491        return randomize;
492    }
493
494    /**
495     * @param randomize The randomize to set.
496     */
497    public void setRandomize(boolean randomize) {
498        this.randomize = randomize;
499    }
500
501    public boolean isBackup() {
502        return backup;
503    }
504
505    public void setBackup(boolean backup) {
506        this.backup = backup;
507    }
508
509    public int getBackupPoolSize() {
510        return backupPoolSize;
511    }
512
513    public void setBackupPoolSize(int backupPoolSize) {
514        this.backupPoolSize = backupPoolSize;
515    }
516
517    public int getCurrentBackups() {
518        return this.backups.size();
519    }
520
521    public boolean isTrackMessages() {
522        return trackMessages;
523    }
524
525    public void setTrackMessages(boolean trackMessages) {
526        this.trackMessages = trackMessages;
527    }
528
529    public boolean isTrackTransactionProducers() {
530        return this.trackTransactionProducers;
531    }
532
533    public void setTrackTransactionProducers(boolean trackTransactionProducers) {
534        this.trackTransactionProducers = trackTransactionProducers;
535    }
536
537    public int getMaxCacheSize() {
538        return maxCacheSize;
539    }
540
541    public void setMaxCacheSize(int maxCacheSize) {
542        this.maxCacheSize = maxCacheSize;
543    }
544
545    public boolean isPriorityBackup() {
546        return priorityBackup;
547    }
548
549    public void setPriorityBackup(boolean priorityBackup) {
550        this.priorityBackup = priorityBackup;
551    }
552
553    public void setPriorityURIs(String priorityURIs) {
554        StringTokenizer tokenizer = new StringTokenizer(priorityURIs, ",");
555        while (tokenizer.hasMoreTokens()) {
556            String str = tokenizer.nextToken();
557            try {
558                URI uri = new URI(str);
559                priorityList.add(uri);
560            } catch (Exception e) {
561                LOG.error("Failed to parse broker address: " + str, e);
562            }
563        }
564    }
565
566    @Override
567    public void oneway(Object o) throws IOException {
568
569        Command command = (Command) o;
570        Exception error = null;
571        try {
572
573            synchronized (reconnectMutex) {
574
575                if (command != null && connectedTransport.get() == null) {
576                    if (command.isShutdownInfo()) {
577                        // Skipping send of ShutdownInfo command when not connected.
578                        return;
579                    } else if (command instanceof RemoveInfo || command.isMessageAck()) {
580                        // Simulate response to RemoveInfo command or MessageAck (as it will be stale)
581                        stateTracker.track(command);
582                        if (command.isResponseRequired()) {
583                            Response response = new Response();
584                            response.setCorrelationId(command.getCommandId());
585                            myTransportListener.onCommand(response);
586                        }
587                        return;
588                    } else if (command instanceof MessagePull) {
589                        // Simulate response to MessagePull if timed as we can't honor that now.
590                        MessagePull pullRequest = (MessagePull) command;
591                        if (pullRequest.getTimeout() != 0) {
592                            MessageDispatch dispatch = new MessageDispatch();
593                            dispatch.setConsumerId(pullRequest.getConsumerId());
594                            dispatch.setDestination(pullRequest.getDestination());
595                            myTransportListener.onCommand(dispatch);
596                        }
597                        return;
598                    }
599                }
600
601                // Keep trying until the message is sent.
602                for (int i = 0; !disposed; i++) {
603                    try {
604
605                        // Wait for transport to be connected.
606                        Transport transport = connectedTransport.get();
607                        long start = System.currentTimeMillis();
608                        boolean timedout = false;
609                        while (transport == null && !disposed && connectionFailure == null
610                                && !Thread.currentThread().isInterrupted()) {
611                            if (LOG.isTraceEnabled()) {
612                                LOG.trace("Waiting for transport to reconnect..: " + command);
613                            }
614                            long end = System.currentTimeMillis();
615                            if (command.isMessage() && timeout > 0 && (end - start > timeout)) {
616                                timedout = true;
617                                if (LOG.isInfoEnabled()) {
618                                    LOG.info("Failover timed out after " + (end - start) + "ms");
619                                }
620                                break;
621                            }
622                            try {
623                                reconnectMutex.wait(100);
624                            } catch (InterruptedException e) {
625                                Thread.currentThread().interrupt();
626                                if (LOG.isDebugEnabled()) {
627                                    LOG.debug("Interupted: " + e, e);
628                                }
629                            }
630                            transport = connectedTransport.get();
631                        }
632
633                        if (transport == null) {
634                            // Previous loop may have exited due to use being
635                            // disposed.
636                            if (disposed) {
637                                error = new IOException("Transport disposed.");
638                            } else if (connectionFailure != null) {
639                                error = connectionFailure;
640                            } else if (timedout == true) {
641                                error = new IOException("Failover timeout of " + timeout + " ms reached.");
642                            } else {
643                                error = new IOException("Unexpected failure.");
644                            }
645                            break;
646                        }
647
648                        Tracked tracked = null;
649                        try {
650                            tracked = stateTracker.track(command);
651                        } catch (IOException ioe) {
652                            LOG.debug("Cannot track the command " + command, ioe);
653                        }
654                        // If it was a request and it was not being tracked by
655                        // the state tracker,
656                        // then hold it in the requestMap so that we can replay
657                        // it later.
658                        synchronized (requestMap) {
659                            if (tracked != null && tracked.isWaitingForResponse()) {
660                                requestMap.put(Integer.valueOf(command.getCommandId()), tracked);
661                            } else if (tracked == null && command.isResponseRequired()) {
662                                requestMap.put(Integer.valueOf(command.getCommandId()), command);
663                            }
664                        }
665
666                        // Send the message.
667                        try {
668                            transport.oneway(command);
669                            stateTracker.trackBack(command);
670                            if (command.isShutdownInfo()) {
671                                shuttingDown = true;
672                            }
673                        } catch (IOException e) {
674
675                            // If the command was not tracked.. we will retry in
676                            // this method
677                            if (tracked == null && canReconnect()) {
678
679                                // since we will retry in this method.. take it
680                                // out of the request
681                                // map so that it is not sent 2 times on
682                                // recovery
683                                if (command.isResponseRequired()) {
684                                    requestMap.remove(Integer.valueOf(command.getCommandId()));
685                                }
686
687                                // Rethrow the exception so it will handled by
688                                // the outer catch
689                                throw e;
690                            } else {
691                                // Handle the error but allow the method to return since the
692                                // tracked commands are replayed on reconnect.
693                                if (LOG.isDebugEnabled()) {
694                                    LOG.debug("Send oneway attempt: " + i + " failed for command:" + command);
695                                }
696                                handleTransportFailure(e);
697                            }
698                        }
699
700                        return;
701
702                    } catch (IOException e) {
703                        if (LOG.isDebugEnabled()) {
704                            LOG.debug("Send oneway attempt: " + i + " failed for command:" + command);
705                        }
706                        handleTransportFailure(e);
707                    }
708                }
709            }
710        } catch (InterruptedException e) {
711            // Some one may be trying to stop our thread.
712            Thread.currentThread().interrupt();
713            throw new InterruptedIOException();
714        }
715
716        if (!disposed) {
717            if (error != null) {
718                if (error instanceof IOException) {
719                    throw (IOException) error;
720                }
721                throw IOExceptionSupport.create(error);
722            }
723        }
724    }
725
726    @Override
727    public FutureResponse asyncRequest(Object command, ResponseCallback responseCallback) throws IOException {
728        throw new AssertionError("Unsupported Method");
729    }
730
731    @Override
732    public Object request(Object command) throws IOException {
733        throw new AssertionError("Unsupported Method");
734    }
735
736    @Override
737    public Object request(Object command, int timeout) throws IOException {
738        throw new AssertionError("Unsupported Method");
739    }
740
741    @Override
742    public void add(boolean rebalance, URI u[]) {
743        boolean newURI = false;
744        for (URI uri : u) {
745            if (!contains(uri)) {
746                uris.add(uri);
747                newURI = true;
748            }
749        }
750        if (newURI) {
751            reconnect(rebalance);
752        }
753    }
754
755    @Override
756    public void remove(boolean rebalance, URI u[]) {
757        for (URI uri : u) {
758            uris.remove(uri);
759        }
760        // rebalance is automatic if any connected to removed/stopped broker
761    }
762
763    public void add(boolean rebalance, String u) {
764        try {
765            URI newURI = new URI(u);
766            if (contains(newURI) == false) {
767                uris.add(newURI);
768                reconnect(rebalance);
769            }
770
771        } catch (Exception e) {
772            LOG.error("Failed to parse URI: " + u);
773        }
774    }
775
776    public void reconnect(boolean rebalance) {
777        synchronized (reconnectMutex) {
778            if (started) {
779                if (rebalance) {
780                    doRebalance = true;
781                }
782                LOG.debug("Waking up reconnect task");
783                try {
784                    reconnectTask.wakeup();
785                } catch (InterruptedException e) {
786                    Thread.currentThread().interrupt();
787                }
788            } else {
789                LOG.debug("Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.");
790            }
791        }
792    }
793
794    private List<URI> getConnectList() {
795        if (!updated.isEmpty()) {
796            return updated;
797        }
798        ArrayList<URI> l = new ArrayList<URI>(uris);
799        boolean removed = false;
800        if (failedConnectTransportURI != null) {
801            removed = l.remove(failedConnectTransportURI);
802        }
803        if (randomize) {
804            // Randomly, reorder the list by random swapping
805            for (int i = 0; i < l.size(); i++) {
806                // meed parenthesis due other JDKs (see AMQ-4826)
807                int p = ((int) (Math.random() * 100)) % l.size();
808                URI t = l.get(p);
809                l.set(p, l.get(i));
810                l.set(i, t);
811            }
812        }
813        if (removed) {
814            l.add(failedConnectTransportURI);
815        }
816        if (LOG.isDebugEnabled()) {
817            LOG.debug("urlList connectionList:" + l + ", from: " + uris);
818        }
819        return l;
820    }
821
822    @Override
823    public TransportListener getTransportListener() {
824        return transportListener;
825    }
826
827    @Override
828    public void setTransportListener(TransportListener commandListener) {
829        synchronized (listenerMutex) {
830            this.transportListener = commandListener;
831            listenerMutex.notifyAll();
832        }
833    }
834
835    @Override
836    public <T> T narrow(Class<T> target) {
837
838        if (target.isAssignableFrom(getClass())) {
839            return target.cast(this);
840        }
841        Transport transport = connectedTransport.get();
842        if (transport != null) {
843            return transport.narrow(target);
844        }
845        return null;
846
847    }
848
849    protected void restoreTransport(Transport t) throws Exception, IOException {
850        t.start();
851        // send information to the broker - informing it we are an ft client
852        ConnectionControl cc = new ConnectionControl();
853        cc.setFaultTolerant(true);
854        t.oneway(cc);
855        stateTracker.restore(t);
856        Map<Integer, Command> tmpMap = null;
857        synchronized (requestMap) {
858            tmpMap = new LinkedHashMap<Integer, Command>(requestMap);
859        }
860        for (Command command : tmpMap.values()) {
861            if (LOG.isTraceEnabled()) {
862                LOG.trace("restore requestMap, replay: " + command);
863            }
864            t.oneway(command);
865        }
866    }
867
868    public boolean isUseExponentialBackOff() {
869        return useExponentialBackOff;
870    }
871
872    public void setUseExponentialBackOff(boolean useExponentialBackOff) {
873        this.useExponentialBackOff = useExponentialBackOff;
874    }
875
876    @Override
877    public String toString() {
878        return connectedTransportURI == null ? "unconnected" : connectedTransportURI.toString();
879    }
880
881    @Override
882    public String getRemoteAddress() {
883        Transport transport = connectedTransport.get();
884        if (transport != null) {
885            return transport.getRemoteAddress();
886        }
887        return null;
888    }
889
890    @Override
891    public boolean isFaultTolerant() {
892        return true;
893    }
894
895    private void doUpdateURIsFromDisk() {
896        // If updateURIsURL is specified, read the file and add any new
897        // transport URI's to this FailOverTransport.
898        // Note: Could track file timestamp to avoid unnecessary reading.
899        String fileURL = getUpdateURIsURL();
900        if (fileURL != null) {
901            BufferedReader in = null;
902            String newUris = null;
903            StringBuffer buffer = new StringBuffer();
904
905            try {
906                in = new BufferedReader(getURLStream(fileURL));
907                while (true) {
908                    String line = in.readLine();
909                    if (line == null) {
910                        break;
911                    }
912                    buffer.append(line);
913                }
914                newUris = buffer.toString();
915            } catch (IOException ioe) {
916                LOG.error("Failed to read updateURIsURL: " + fileURL, ioe);
917            } finally {
918                if (in != null) {
919                    try {
920                        in.close();
921                    } catch (IOException ioe) {
922                        // ignore
923                    }
924                }
925            }
926
927            processNewTransports(isRebalanceUpdateURIs(), newUris);
928        }
929    }
930
931    final boolean doReconnect() {
932        Exception failure = null;
933        synchronized (reconnectMutex) {
934
935            // First ensure we are up to date.
936            doUpdateURIsFromDisk();
937
938            if (disposed || connectionFailure != null) {
939                reconnectMutex.notifyAll();
940            }
941            if ((connectedTransport.get() != null && !doRebalance && !priorityBackupAvailable) || disposed || connectionFailure != null) {
942                return false;
943            } else {
944                List<URI> connectList = getConnectList();
945                if (connectList.isEmpty()) {
946                    failure = new IOException("No uris available to connect to.");
947                } else {
948                    if (doRebalance) {
949                        if (connectedToPriority || compareURIs(connectList.get(0), connectedTransportURI)) {
950                            // already connected to first in the list, no need to rebalance
951                            doRebalance = false;
952                            return false;
953                        } else {
954                            if (LOG.isDebugEnabled()) {
955                                LOG.debug("Doing rebalance from: " + connectedTransportURI + " to " + connectList);
956                            }
957
958                            try {
959                                Transport transport = this.connectedTransport.getAndSet(null);
960                                if (transport != null) {
961                                    disposeTransport(transport);
962                                }
963                            } catch (Exception e) {
964                                if (LOG.isDebugEnabled()) {
965                                    LOG.debug("Caught an exception stopping existing transport for rebalance", e);
966                                }
967                            }
968                        }
969                        doRebalance = false;
970                    }
971
972                    resetReconnectDelay();
973
974                    Transport transport = null;
975                    URI uri = null;
976
977                    // If we have a backup already waiting lets try it.
978                    synchronized (backupMutex) {
979                        if ((priorityBackup || backup) && !backups.isEmpty()) {
980                            ArrayList<BackupTransport> l = new ArrayList<BackupTransport>(backups);
981                            if (randomize) {
982                                Collections.shuffle(l);
983                            }
984                            BackupTransport bt = l.remove(0);
985                            backups.remove(bt);
986                            transport = bt.getTransport();
987                            uri = bt.getUri();
988                            if (priorityBackup && priorityBackupAvailable) {
989                                Transport old = this.connectedTransport.getAndSet(null);
990                                if (old != null) {
991                                    disposeTransport(old);
992                                }
993                                priorityBackupAvailable = false;
994                            }
995                        }
996                    }
997
998                    // Sleep for the reconnectDelay if there's no backup and we aren't trying
999                    // for the first time, or we were disposed for some reason.
1000                    if (transport == null && !firstConnection && (reconnectDelay > 0) && !disposed) {
1001                        synchronized (sleepMutex) {
1002                            if (LOG.isDebugEnabled()) {
1003                                LOG.debug("Waiting " + reconnectDelay + " ms before attempting connection. ");
1004                            }
1005                            try {
1006                                sleepMutex.wait(reconnectDelay);
1007                            } catch (InterruptedException e) {
1008                                Thread.currentThread().interrupt();
1009                            }
1010                        }
1011                    }
1012
1013                    Iterator<URI> iter = connectList.iterator();
1014                    while ((transport != null || iter.hasNext()) && (connectedTransport.get() == null && !disposed)) {
1015
1016                        try {
1017                            SslContext.setCurrentSslContext(brokerSslContext);
1018
1019                            // We could be starting with a backup and if so we wait to grab a
1020                            // URI from the pool until next time around.
1021                            if (transport == null) {
1022                                uri = addExtraQueryOptions(iter.next());
1023                                transport = TransportFactory.compositeConnect(uri);
1024                            }
1025
1026                            if (LOG.isDebugEnabled()) {
1027                                LOG.debug("Attempting  " + connectFailures + "th  connect to: " + uri);
1028                            }
1029                            transport.setTransportListener(myTransportListener);
1030                            transport.start();
1031
1032                            if (started &&  !firstConnection) {
1033                                restoreTransport(transport);
1034                            }
1035
1036                            if (LOG.isDebugEnabled()) {
1037                                LOG.debug("Connection established");
1038                            }
1039                            reconnectDelay = initialReconnectDelay;
1040                            connectedTransportURI = uri;
1041                            connectedTransport.set(transport);
1042                            connectedToPriority = isPriority(connectedTransportURI);
1043                            reconnectMutex.notifyAll();
1044                            connectFailures = 0;
1045
1046                            // Make sure on initial startup, that the transportListener
1047                            // has been initialized for this instance.
1048                            synchronized (listenerMutex) {
1049                                if (transportListener == null) {
1050                                    try {
1051                                        // if it isn't set after 2secs - it probably never will be
1052                                        listenerMutex.wait(2000);
1053                                    } catch (InterruptedException ex) {
1054                                    }
1055                                }
1056                            }
1057
1058                            if (transportListener != null) {
1059                                transportListener.transportResumed();
1060                            } else {
1061                                if (LOG.isDebugEnabled()) {
1062                                    LOG.debug("transport resumed by transport listener not set");
1063                                }
1064                            }
1065
1066                            if (firstConnection) {
1067                                firstConnection = false;
1068                                LOG.info("Successfully connected to " + uri);
1069                            } else {
1070                                LOG.info("Successfully reconnected to " + uri);
1071                            }
1072
1073                            return false;
1074                        } catch (Exception e) {
1075                            failure = e;
1076                            if (LOG.isDebugEnabled()) {
1077                                LOG.debug("Connect fail to: " + uri + ", reason: " + e);
1078                            }
1079                            if (transport != null) {
1080                                try {
1081                                    transport.stop();
1082                                    transport = null;
1083                                } catch (Exception ee) {
1084                                    if (LOG.isDebugEnabled()) {
1085                                        LOG.debug("Stop of failed transport: " + transport +
1086                                                  " failed with reason: " + ee);
1087                                    }
1088                                }
1089                            }
1090                        } finally {
1091                            SslContext.setCurrentSslContext(null);
1092                        }
1093                    }
1094                }
1095            }
1096
1097            int reconnectLimit = calculateReconnectAttemptLimit();
1098
1099            connectFailures++;
1100            if (reconnectLimit != INFINITE && connectFailures >= reconnectLimit) {
1101                LOG.error("Failed to connect to " + uris + " after: " + connectFailures + " attempt(s)");
1102                connectionFailure = failure;
1103
1104                // Make sure on initial startup, that the transportListener has been
1105                // initialized for this instance.
1106                synchronized (listenerMutex) {
1107                    if (transportListener == null) {
1108                        try {
1109                            listenerMutex.wait(2000);
1110                        } catch (InterruptedException ex) {
1111                        }
1112                    }
1113                }
1114
1115                propagateFailureToExceptionListener(connectionFailure);
1116                return false;
1117            }
1118
1119            int warnInterval = getWarnAfterReconnectAttempts();
1120            if (warnInterval > 0 && (connectFailures % warnInterval) == 0) {
1121                LOG.warn("Failed to connect to {} after: {} attempt(s) continuing to retry.",
1122                         uris, connectFailures);
1123            }
1124        }
1125
1126        if (!disposed) {
1127            doDelay();
1128        }
1129
1130        return !disposed;
1131    }
1132
1133    private void doDelay() {
1134        if (reconnectDelay > 0) {
1135            synchronized (sleepMutex) {
1136                if (LOG.isDebugEnabled()) {
1137                    LOG.debug("Waiting " + reconnectDelay + " ms before attempting connection");
1138                }
1139                try {
1140                    sleepMutex.wait(reconnectDelay);
1141                } catch (InterruptedException e) {
1142                    Thread.currentThread().interrupt();
1143                }
1144            }
1145        }
1146
1147        if (useExponentialBackOff) {
1148            // Exponential increment of reconnect delay.
1149            reconnectDelay *= backOffMultiplier;
1150            if (reconnectDelay > maxReconnectDelay) {
1151                reconnectDelay = maxReconnectDelay;
1152            }
1153        }
1154    }
1155
1156    private void resetReconnectDelay() {
1157        if (!useExponentialBackOff || reconnectDelay == DEFAULT_INITIAL_RECONNECT_DELAY) {
1158            reconnectDelay = initialReconnectDelay;
1159        }
1160    }
1161
1162    /*
1163      * called with reconnectMutex held
1164     */
1165    private void propagateFailureToExceptionListener(Exception exception) {
1166        if (transportListener != null) {
1167            if (exception instanceof IOException) {
1168                transportListener.onException((IOException)exception);
1169            } else {
1170                transportListener.onException(IOExceptionSupport.create(exception));
1171            }
1172        }
1173        reconnectMutex.notifyAll();
1174    }
1175
1176    private int calculateReconnectAttemptLimit() {
1177        int maxReconnectValue = this.maxReconnectAttempts;
1178        if (firstConnection && this.startupMaxReconnectAttempts != INFINITE) {
1179            maxReconnectValue = this.startupMaxReconnectAttempts;
1180        }
1181        return maxReconnectValue;
1182    }
1183
1184    private boolean shouldBuildBackups() {
1185       return (backup && backups.size() < backupPoolSize) || (priorityBackup && !(priorityBackupAvailable || connectedToPriority));
1186    }
1187
1188    final boolean buildBackups() {
1189        synchronized (backupMutex) {
1190            if (!disposed && shouldBuildBackups()) {
1191                ArrayList<URI> backupList = new ArrayList<URI>(priorityList);
1192                List<URI> connectList = getConnectList();
1193                for (URI uri: connectList) {
1194                    if (!backupList.contains(uri)) {
1195                        backupList.add(uri);
1196                    }
1197                }
1198                // removed disposed backups
1199                List<BackupTransport> disposedList = new ArrayList<BackupTransport>();
1200                for (BackupTransport bt : backups) {
1201                    if (bt.isDisposed()) {
1202                        disposedList.add(bt);
1203                    }
1204                }
1205                backups.removeAll(disposedList);
1206                disposedList.clear();
1207                for (Iterator<URI> iter = backupList.iterator(); !disposed && iter.hasNext() && shouldBuildBackups(); ) {
1208                    URI uri = addExtraQueryOptions(iter.next());
1209                    if (connectedTransportURI != null && !connectedTransportURI.equals(uri)) {
1210                        try {
1211                            SslContext.setCurrentSslContext(brokerSslContext);
1212                            BackupTransport bt = new BackupTransport(this);
1213                            bt.setUri(uri);
1214                            if (!backups.contains(bt)) {
1215                                Transport t = TransportFactory.compositeConnect(uri);
1216                                t.setTransportListener(bt);
1217                                t.start();
1218                                bt.setTransport(t);
1219                                if (priorityBackup && isPriority(uri)) {
1220                                   priorityBackupAvailable = true;
1221                                   backups.add(0, bt);
1222                                   // if this priority backup overflows the pool
1223                                   // remove the backup with the lowest priority
1224                                   if (backups.size() > backupPoolSize) {
1225                                       BackupTransport disposeTransport = backups.remove(backups.size() - 1);
1226                                       disposeTransport.setDisposed(true);
1227                                       Transport transport = disposeTransport.getTransport();
1228                                       if (transport != null) {
1229                                           transport.setTransportListener(disposedListener);
1230                                           disposeTransport(transport);
1231                                       }
1232                                   }
1233                                } else {
1234                                    backups.add(bt);
1235                                }
1236                            }
1237                        } catch (Exception e) {
1238                            LOG.debug("Failed to build backup ", e);
1239                        } finally {
1240                            SslContext.setCurrentSslContext(null);
1241                        }
1242                    }
1243                }
1244            }
1245        }
1246        return false;
1247    }
1248
1249    protected boolean isPriority(URI uri) {
1250        if (!priorityBackup) {
1251            return false;
1252        }
1253
1254        if (!priorityList.isEmpty()) {
1255            return priorityList.contains(uri);
1256        }
1257        return uris.indexOf(uri) == 0;
1258    }
1259
1260    @Override
1261    public boolean isDisposed() {
1262        return disposed;
1263    }
1264
1265    @Override
1266    public boolean isConnected() {
1267        return connectedTransport.get() != null;
1268    }
1269
1270    @Override
1271    public void reconnect(URI uri) throws IOException {
1272        add(true, new URI[]{uri});
1273    }
1274
1275    @Override
1276    public boolean isReconnectSupported() {
1277        return this.reconnectSupported;
1278    }
1279
1280    public void setReconnectSupported(boolean value) {
1281        this.reconnectSupported = value;
1282    }
1283
1284    @Override
1285    public boolean isUpdateURIsSupported() {
1286        return this.updateURIsSupported;
1287    }
1288
1289    public void setUpdateURIsSupported(boolean value) {
1290        this.updateURIsSupported = value;
1291    }
1292
1293    @Override
1294    public void updateURIs(boolean rebalance, URI[] updatedURIs) throws IOException {
1295        if (isUpdateURIsSupported()) {
1296            HashSet<URI> copy = new HashSet<URI>();
1297            synchronized (reconnectMutex) {
1298                copy.addAll(this.updated);
1299                updated.clear();
1300                if (updatedURIs != null && updatedURIs.length > 0) {
1301                    for (URI uri : updatedURIs) {
1302                        if (uri != null && !updated.contains(uri)) {
1303                            updated.add(uri);
1304                        }
1305                    }
1306                }
1307            }
1308            if (!(copy.isEmpty() && updated.isEmpty()) && !copy.equals(new HashSet<URI>(updated))) {
1309                buildBackups();
1310                reconnect(rebalance);
1311            }
1312        }
1313    }
1314
1315    /**
1316     * @return the updateURIsURL
1317     */
1318    public String getUpdateURIsURL() {
1319        return this.updateURIsURL;
1320    }
1321
1322    /**
1323     * @param updateURIsURL the updateURIsURL to set
1324     */
1325    public void setUpdateURIsURL(String updateURIsURL) {
1326        this.updateURIsURL = updateURIsURL;
1327    }
1328
1329    /**
1330     * @return the rebalanceUpdateURIs
1331     */
1332    public boolean isRebalanceUpdateURIs() {
1333        return this.rebalanceUpdateURIs;
1334    }
1335
1336    /**
1337     * @param rebalanceUpdateURIs the rebalanceUpdateURIs to set
1338     */
1339    public void setRebalanceUpdateURIs(boolean rebalanceUpdateURIs) {
1340        this.rebalanceUpdateURIs = rebalanceUpdateURIs;
1341    }
1342
1343    @Override
1344    public int getReceiveCounter() {
1345        Transport transport = connectedTransport.get();
1346        if (transport == null) {
1347            return 0;
1348        }
1349        return transport.getReceiveCounter();
1350    }
1351
1352    public int getConnectFailures() {
1353        return connectFailures;
1354    }
1355
1356    public void connectionInterruptProcessingComplete(ConnectionId connectionId) {
1357        synchronized (reconnectMutex) {
1358            stateTracker.connectionInterruptProcessingComplete(this, connectionId);
1359        }
1360    }
1361
1362    public ConnectionStateTracker getStateTracker() {
1363        return stateTracker;
1364    }
1365
1366    private boolean contains(URI newURI) {
1367        boolean result = false;
1368        for (URI uri : uris) {
1369            if (compareURIs(newURI, uri)) {
1370                result = true;
1371                break;
1372            }
1373        }
1374
1375        return result;
1376    }
1377
1378    private boolean compareURIs(final URI first, final URI second) {
1379
1380        boolean result = false;
1381        if (first == null || second == null) {
1382            return result;
1383        }
1384
1385        if (first.getPort() == second.getPort()) {
1386            InetAddress firstAddr = null;
1387            InetAddress secondAddr = null;
1388            try {
1389                firstAddr = InetAddress.getByName(first.getHost());
1390                secondAddr = InetAddress.getByName(second.getHost());
1391
1392                if (firstAddr.equals(secondAddr)) {
1393                    result = true;
1394                }
1395
1396            } catch(IOException e) {
1397
1398                if (firstAddr == null) {
1399                    LOG.error("Failed to Lookup INetAddress for URI[ " + first + " ] : " + e);
1400                } else {
1401                    LOG.error("Failed to Lookup INetAddress for URI[ " + second + " ] : " + e);
1402                }
1403
1404                if (first.getHost().equalsIgnoreCase(second.getHost())) {
1405                    result = true;
1406                }
1407            }
1408        }
1409
1410        return result;
1411    }
1412
1413    private InputStreamReader getURLStream(String path) throws IOException {
1414        InputStreamReader result = null;
1415        URL url = null;
1416        try {
1417            url = new URL(path);
1418            result = new InputStreamReader(url.openStream());
1419        } catch (MalformedURLException e) {
1420            // ignore - it could be a path to a a local file
1421        }
1422        if (result == null) {
1423            result = new FileReader(path);
1424        }
1425        return result;
1426    }
1427
1428    private URI addExtraQueryOptions(URI uri) {
1429        try {
1430            if( nestedExtraQueryOptions!=null && !nestedExtraQueryOptions.isEmpty() ) {
1431                if( uri.getQuery() == null ) {
1432                    uri = URISupport.createURIWithQuery(uri, nestedExtraQueryOptions);
1433                } else {
1434                    uri = URISupport.createURIWithQuery(uri, uri.getQuery()+"&"+nestedExtraQueryOptions);
1435                }
1436            }
1437        } catch (URISyntaxException e) {
1438            throw new RuntimeException(e);
1439        }
1440        return uri;
1441    }
1442
1443    public void setNestedExtraQueryOptions(String nestedExtraQueryOptions) {
1444        this.nestedExtraQueryOptions = nestedExtraQueryOptions;
1445    }
1446
1447    public int getWarnAfterReconnectAttempts() {
1448        return warnAfterReconnectAttempts;
1449    }
1450
1451    /**
1452     * Sets the number of Connect / Reconnect attempts that must occur before a warn message
1453     * is logged indicating that the transport is not connected.  This can be useful when the
1454     * client is running inside some container or service as it give an indication of some
1455     * problem with the client connection that might not otherwise be visible.  To disable the
1456     * log messages this value should be set to a value @{code attempts <= 0}
1457     *
1458     * @param warnAfterReconnectAttempts
1459     *      The number of failed connection attempts that must happen before a warning is logged.
1460     */
1461    public void setWarnAfterReconnectAttempts(int warnAfterReconnectAttempts) {
1462        this.warnAfterReconnectAttempts = warnAfterReconnectAttempts;
1463    }
1464
1465}