Called when the client has failed to connect to the broker.

        See the documentation of
        `twisted.internet.protocol.ReconnectingClientFactory` for details.
173579
def clientConnectionFailed(self, connector, reason):
        
        _legacy_twisted_log.msg(
            "Connection to the AMQP broker failed ({reason})",
            reason=reason.value,
            logLevel=logging.WARNING,
        )
        protocol.ReconnectingClientFactory.clientConnectionFailed(
            self, connector, reason
        )
1219340
def _get_brokerclient(self, node_id):
        
        if self._closing:
            raise ClientError("Cannot get broker client for node_id={}: {} has been closed".format(node_id, self))
        if node_id not in self.clients:
            broker_metadata = self._brokers[node_id]
            log.debug("%r: creating client for %s", self, broker_metadata)
            self.clients[node_id] = _KafkaBrokerClient(
                self.reactor, self._endpoint_factory,
                broker_metadata, self.clientId, self._retry_policy,
            )
        return self.clients[node_id]
1275819
public void clientFailedToLogon (Client client, Exception cause)
    {
        if (cause instanceof ConnectException) {
            // we'll reconnect at most one minute later in refreshPeers()
            log.info("Peer not online " + _record + ": " + cause.getMessage());
        } else {
            log.warning("Peer logon attempt failed " + _record + ": " + cause);
        }
    }
440436
public void reconnect() throws IOException, SlackApiException, URISyntaxException, DeploymentException {
        // Call rtm.connect again to refresh wss URL
        RTMConnectResponse response = slack.methods().rtmConnect(RTMConnectRequest.builder().token(botApiToken).build());
        if (response.isOk()) {
            this.wssUri = new URI(response.getUrl());
            this.connectedBotUser = response.getSelf();
        } else {
            throw new IllegalStateException("Failed to the RTM endpoint URL (error: " + response.getError() + ")");
        }
        // start a WebSocket session
        connect();
    }
904299
def _reconnect_cb(self):
        """"""
        @asyncio.coroutine
        def try_reconnect():
            """Actual coroutine ro try to reconnect or reschedule."""
            try:
                yield from self._do_connect()
            except IOError:
                self._loop.call_later(SERVER_RECONNECT_DELAY,
                                      self._reconnect_cb)
        asyncio.ensure_future(try_reconnect())
839523
protected void recoverFromException(final String curQueue, final Exception ex) {
        final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue);
        switch (recoveryStrategy) {
        case RECONNECT:
            LOG.info("Reconnecting to Redis in response to exception", ex);
            final int reconAttempts = getReconnectAttempts();
            if (!JedisUtils.reconnect(this.jedis, reconAttempts, RECONNECT_SLEEP_TIME)) {
                LOG.warn("Terminating in response to exception after " + reconAttempts + " to reconnect", ex);
                end(false);
            } else {
                authenticateAndSelectDB();
                LOG.info("Reconnected to Redis");
                try {
                    loadRedisScripts();
                } catch (IOException e) {
                    LOG.error("Failed to reload Lua scripts after reconnect", e);
                }
            }
            break;
        case TERMINATE:
            LOG.warn("Terminating in response to exception", ex);
            end(false);
            break;
        case PROCEED:
            this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex);
            break;
        default:
            LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy
                    + " while attempting to recover from the following exception; worker proceeding...", ex);
            break;
        }
    }
907689
def stopFactory(self):
        
        if self.client:
            yield self.client.stopProducing()
        protocol.ReconnectingClientFactory.stopFactory(self)
1257954
async def _reconnect(self, last_error):
        
        self._log.debug('Closing current connection...')
        await self._connection.disconnect()

        await helpers._cancel(
            self._log,
            send_loop_handle=self._send_loop_handle,
            recv_loop_handle=self._recv_loop_handle
        )

        # TODO See comment in `_start_reconnect`
        # Perhaps this should be the last thing to do?
        # But _connect() creates tasks which may run and,
        # if they see that reconnecting is True, they will end.
        # Perhaps that task creation should not belong in connect?
        self._reconnecting = False

        # Start with a clean state (and thus session ID) to avoid old msgs
        self._state.reset()

        retries = self._retries if self._auto_reconnect else 0
        for attempt in retry_range(retries):
            try:
                await self._connect()
            except (IOError, asyncio.TimeoutError) as e:
                last_error = e
                self._log.info('Failed reconnection attempt %d with %s',
                               attempt, e.__class__.__name__)

                await asyncio.sleep(self._delay)
            except Exception as e:
                last_error = e
                self._log.exception('Unexpected exception reconnecting on '
                                    'attempt %d', attempt)

                await asyncio.sleep(self._delay)
            else:
                self._send_queue.extend(self._pending_state.values())
                self._pending_state.clear()

                if self._auto_reconnect_callback:
                    self._loop.create_task(self._auto_reconnect_callback())

                break
        else:
            self._log.error('Automatic reconnection failed {} time(s)'
                            .format(attempt))
            await self._disconnect(error=last_error.with_traceback(None))
1332560
public void reconnect(boolean callFromQueue) throws InterruptedException
    {
        Set<MDC.MDCCloseable> contextEntries = null;
        Map<String, String> previousContext = null;
        {
            ConcurrentMap<String, String> contextMap = api.getContextMap();
            if (callFromQueue && contextMap != null)
            {
                previousContext = MDC.getCopyOfContextMap();
                contextEntries = contextMap.entrySet().stream()
                          .map((entry) -> MDC.putCloseable(entry.getKey(), entry.getValue()))
                          .collect(Collectors.toSet());
            }
        }
        if (shutdown)
        {
            api.setStatus(JDA.Status.SHUTDOWN);
            api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
            return;
        }
        String message = "";
        if (callFromQueue)
            message = String.format("Queue is attempting to reconnect a shard...%s ", shardInfo != null ? " Shard: " + shardInfo.getShardString() : "");
        LOG.debug("{}Attempting to reconnect in {}s", message, reconnectTimeoutS);
        while (shouldReconnect)
        {
            api.setStatus(JDA.Status.WAITING_TO_RECONNECT);
            int delay = reconnectTimeoutS;
            Thread.sleep(delay * 1000);
            handleIdentifyRateLimit = false;
            api.setStatus(JDA.Status.ATTEMPTING_TO_RECONNECT);
            LOG.debug("Attempting to reconnect!");
            try
            {
                connect();
                break;
            }
            catch (RejectedExecutionException ex)
            {
                // JDA has already been shutdown so we can stop here
                api.setStatus(JDA.Status.SHUTDOWN);
                api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
                return;
            }
            catch (RuntimeException ex)
            {
                reconnectTimeoutS = Math.min(reconnectTimeoutS << 1, api.getMaxReconnectDelay());
                LOG.warn("Reconnect failed! Next attempt in {}s", reconnectTimeoutS);
            }
        }
        if (contextEntries != null)
            contextEntries.forEach(MDC.MDCCloseable::close);
        if (previousContext != null)
            previousContext.forEach(MDC::put);
    }
293154
private void scheduleFailedHostRetry(final HttpServerExchange exchange) {
        final int retry = connectionPoolManager.getProblemServerRetry();
        // only schedule a retry task if the node is not available
        if (retry > 0 && !connectionPoolManager.isAvailable()) {
            WorkerUtils.executeAfter(exchange.getIoThread(), new Runnable() {
                @Override
                public void run() {
                    if (closed) {
                        return;
                    }

                    UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Attempting to reconnect to failed host %s", getUri());
                    client.connect(new ClientCallback<ClientConnection>() {
                        @Override
                        public void completed(ClientConnection result) {
                            UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Connected to previously failed host %s, returning to service", getUri());
                            if (connectionPoolManager.clearError()) {
                                // In case the node is available now, return the connection
                                final ConnectionHolder connectionHolder = new ConnectionHolder(result);
                                final HostThreadData data = getData();
                                result.getCloseSetter().set(new ChannelListener<ClientConnection>() {
                                    @Override
                                    public void handleEvent(ClientConnection channel) {
                                        handleClosedConnection(data, connectionHolder);
                                    }
                                });
                                data.connections++;
                                returnConnection(connectionHolder);
                            } else {
                                // Otherwise reschedule the retry task
                                scheduleFailedHostRetry(exchange);
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            UndertowLogger.PROXY_REQUEST_LOGGER.debugf("Failed to reconnect to failed host %s", getUri());
                            connectionPoolManager.handleError();
                            scheduleFailedHostRetry(exchange);
                        }
                    }, bindAddress, getUri(), exchange.getIoThread(), ssl, exchange.getConnection().getByteBufferPool(), options);
                }
            }, retry, TimeUnit.SECONDS);
        }
    }
1006100
@Override
	public synchronized boolean reconnect() {
		logger.debug("reconnect() called");
		try {
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_INIT);
			websocketEndpoint.close();

			permissions = BitfinexApiKeyPermissions.NO_PERMISSIONS;
			authenticated = false;
			sequenceNumberAuditor.reset();
			connectionFeatureManager.setActiveConnectionFeatures(0);

			// Invalidate old data
			quoteManager.invalidateTickerHeartbeat();
			orderManager.clear();
			positionManager.clear();

			final CountDownLatch connectionReadyLatch = new CountDownLatch(4);

			final Closeable authSuccessEventCallback = callbackRegistry.onAuthenticationSuccessEvent(c -> {
				permissions = c.getPermissions();
				authenticated = true;
				connectionReadyLatch.countDown();
			});
			final Closeable authFailedCallback = callbackRegistry.onAuthenticationFailedEvent(c -> {
				permissions = c.getPermissions();
				authenticated = false;
				while (connectionReadyLatch.getCount() != 0) {
					connectionReadyLatch.countDown();
				}
			});
			
			final Closeable positionInitCallback = callbackRegistry.onMyPositionEvent((a, p) -> connectionReadyLatch.countDown());
			final Closeable walletsInitCallback = callbackRegistry.onMyWalletEvent((a, w) -> connectionReadyLatch.countDown());
			final Closeable orderInitCallback = callbackRegistry.onMySubmittedOrderEvent((a, o) -> connectionReadyLatch.countDown());

			// Reset account info handler
			setupDefaultAccountInfoHandler();

			websocketEndpoint.connect();

			connectionFeatureManager.applyConnectionFeatures();
			if( configuration.isAuthenticationEnabled()) {
				authenticateAndWait(connectionReadyLatch);
			}
			authSuccessEventCallback.close();
			authFailedCallback.close();
			positionInitCallback.close();
			walletsInitCallback.close();
			orderInitCallback.close();

			resubscribeChannels();

			updateConnectionHeartbeat();
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_SUCCESS);
			return true;
		} catch (final Exception e) {
			logger.error("Got exception while reconnect", e);
			websocketEndpoint.close();
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_FAILED);
			return false;
		}
	}
523619
function _connectionFailureHandler(self) {
      return function() {
        if (this._connectionFailHandled) return;
        this._connectionFailHandled = true;
        // Destroy the connection
        this.destroy();
        // Count down the number of reconnects
        self.retriesLeft = self.retriesLeft - 1;
        // How many retries are left
        if (self.retriesLeft <= 0) {
          // Destroy the instance
          self.destroy();
          // Emit close event
          self.emit(
            'reconnectFailed',
            new MongoNetworkError(
              f(
                'failed to reconnect after %s attempts with interval %s ms',
                self.options.reconnectTries,
                self.options.reconnectInterval
              )
            )
          );
        } else {
          self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval);
        }
      };
    }
1005202
protected void nowReconnectedAsync() {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Reconnected async for " + this);
        }
        // reset the data buffers first
        if (!resetWriteBuffers()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Resetting buffers (async) failed");
            }
            // otherwise pass the error along to the channel above us, or close
            // the connection if nobody is above
            IOException ioe = new IOException("Failed reconnect");
            if (null != getAppWriteCallback()) {
                getAppWriteCallback().error(getVC(), ioe);
            } else {
                // nobody above us, just close the connection
                getLink().getDeviceLink().close(getVC(), ioe);
            }
            return;
        }

        // now that we've reconnected, we should reset the "broken" flag. First
        // we set it to the default and then recheck the request msg
        setPersistent(true);
        updatePersistence(getRequestImpl());

        // in case we previously read any partial data, clean out the response
        resetRead();

        // attempt to write the data
        VirtualConnection rc = getTSC().getWriteInterface().write(TCPWriteRequestContext.WRITE_ALL_DATA, HttpOSCWriteCallback.getRef(), isForceAsync(), getWriteTimeout());
        if (null != rc) {
            // if we've finished writing part of a request, let the channel
            // above know that it can write more, otherwise start the read
            // for the response
            if (!isMessageSent()) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Calling callback.complete of app channel.");
                }
                getAppWriteCallback().complete(getLink().getVirtualConnection());
            } else {
                if (isReadAheadEnabled()) {
                    // after a reconnect, there is no more read-ahead active
                    this.bReadAheadEnabled = false;
                }
                // force an async read for the response now. Avoid trying to
                // re-use any existing read buffer to skip complexity with
                // adjusting for partial reads before the reconnect.
                setupJITRead(getHttpConfig().getIncomingHdrBufferSize());
                getTSC().getReadInterface().read(1, HttpOSCReadCallback.getRef(), true, getReadTimeout());
            }
        }
    }
1345322
public void reconnect (int timeout) throws IOException {
		if (connectHost == null) throw new IllegalStateException("This client has never been connected.");
		connect(timeout, connectHost, connectTcpPort, connectUdpPort);
	}
749726
async def connect(self, req: 'ClientRequest',
                      traces: List['Trace'],
                      timeout: 'ClientTimeout') -> Connection:
        """"""
        key = req.connection_key
        available = self._available_connections(key)

        # Wait if there are no available connections.
        if available <= 0:
            fut = self._loop.create_future()

            # This connection will now count towards the limit.
            waiters = self._waiters[key]
            waiters.append(fut)

            if traces:
                for trace in traces:
                    await trace.send_connection_queued_start()

            try:
                await fut
            except BaseException as e:
                # remove a waiter even if it was cancelled, normally it's
                #  removed when it's notified
                try:
                    waiters.remove(fut)
                except ValueError:  # fut may no longer be in list
                    pass

                raise e
            finally:
                if not waiters:
                    try:
                        del self._waiters[key]
                    except KeyError:
                        # the key was evicted before.
                        pass

            if traces:
                for trace in traces:
                    await trace.send_connection_queued_end()

        proto = self._get(key)
        if proto is None:
            placeholder = cast(ResponseHandler, _TransportPlaceholder())
            self._acquired.add(placeholder)
            self._acquired_per_host[key].add(placeholder)

            if traces:
                for trace in traces:
                    await trace.send_connection_create_start()

            try:
                proto = await self._create_connection(req, traces, timeout)
                if self._closed:
                    proto.close()
                    raise ClientConnectionError("Connector is closed.")
            except BaseException:
                if not self._closed:
                    self._acquired.remove(placeholder)
                    self._drop_acquired_per_host(key, placeholder)
                    self._release_waiter()
                raise
            else:
                if not self._closed:
                    self._acquired.remove(placeholder)
                    self._drop_acquired_per_host(key, placeholder)

            if traces:
                for trace in traces:
                    await trace.send_connection_create_end()
        else:
            if traces:
                for trace in traces:
                    await trace.send_connection_reuseconn()

        self._acquired.add(proto)
        self._acquired_per_host[key].add(proto)
        return Connection(self, key, proto, self._loop)
314584
function tryReconnect() {
    self.retry.retries++;
    if (self.retry.retries >= self.retry.max) {
      return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));
    }

    doReconnect();
  }
193794
def clientConnectionFailed(self, connector, reason):
        
        print('. Reason:', reason)        
        ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)