invoked when peer fails to connect
190197
function onPeerFailed(peer)
    {
        scope._servConn.sendRTCState(false,peer.id);
        scope.dispatchEvent("peerFailed",peer.id);
    }
795324
def connect(self):
        ""
        log.info("connecting")

        # don't have the connection attempt reconnects, because when it goes
        # down we are going to cycle to the next potential peer from the Client
        self._peer = connection.Peer(
                None, self._dispatcher, self._addrs.popleft(),
                backend.Socket(), reconnect=False)
        self._peer.start()
1257022
void connectEnvelope(Envelope envelope) throws TransactionException {

        if (shutdown) {
            logger.warn(format("%s not connecting is shutdown.", toString()));
            return;
        }

        final AtomicBoolean retry = new AtomicBoolean(true); // make sure we only retry connection once for each connection attempt.

        ManagedChannel lmanagedChannel = managedChannel;

        if (lmanagedChannel == null || lmanagedChannel.isTerminated() || lmanagedChannel.isShutdown()) {

            lmanagedChannel = channelBuilder.build();
            managedChannel = lmanagedChannel;

        }

        try {

            DeliverGrpc.DeliverStub broadcast = DeliverGrpc.newStub(lmanagedChannel);

            // final DeliverResponse[] ret = new DeliverResponse[1];
            //   final List<DeliverResponse> retList = new ArrayList<>();
            final List<Throwable> throwableList = new ArrayList<>();
            final CountDownLatch finishLatch = new CountDownLatch(1);

            so = new StreamObserver<DeliverResponse>() {

                @Override
                public void onNext(DeliverResponse resp) {

                    // logger.info("Got Broadcast response: " + resp);
                    logger.trace(format("DeliverResponse %s resp status value:%d  status %s, typecase %s ",
                            PeerEventServiceClient.this.toString(), resp.getStatusValue(), resp.getStatus(), resp.getTypeCase()));

                    final DeliverResponse.TypeCase typeCase = resp.getTypeCase();

                    if (typeCase == STATUS) {

                        logger.debug(format("DeliverResponse  %s setting done.",
                                PeerEventServiceClient.this.toString()));

                        if (resp.getStatus() == Common.Status.SUCCESS) { // unlike you may think this only happens when all blocks are fetched.
                            peer.setLastConnectTime(System.currentTimeMillis());
                            peer.resetReconnectCount();
                        } else {

                            final long rec = peer.getReconnectCount();

                            PeerEventingServiceException peerEventingServiceException = new PeerEventingServiceException(format("%s attempts %s Status returned failure code %d (%s) during peer service event registration",
                                    PeerEventServiceClient.this.toString(), rec, resp.getStatusValue(), resp.getStatus().name()));
                            peerEventingServiceException.setResponse(resp);
                            if (rec % 10 == 0) {
                                logger.warn(PeerEventServiceClient.this.toString() + " " + peerEventingServiceException.getMessage());
                            }

                            throwableList.add(peerEventingServiceException);
                        }

                    } else if (typeCase == FILTERED_BLOCK || typeCase == BLOCK) {
                        if (typeCase == BLOCK) {
                            logger.trace(format("%s got event block hex hashcode: %016x, block number: %d",
                                    PeerEventServiceClient.this.toString(), resp.getBlock().hashCode(), resp.getBlock().getHeader().getNumber()));
                        } else {
                            logger.trace(format("%s got event block hex hashcode: %016x, block number: %d",
                                    PeerEventServiceClient.this.toString(), resp.getFilteredBlock().hashCode(), resp.getFilteredBlock().getNumber()));
                        }

                        peer.setLastConnectTime(System.currentTimeMillis());
                        long reconnectCount = peer.getReconnectCount();
                        if (reconnectCount > 1) {
                            logger.info(format("%s reconnected after %d attempts on channel %s, peer %s, url %s",
                                    PeerEventServiceClient.this.toString(), reconnectCount, channelName, name, url));
                        }
                        peer.resetReconnectCount();

                        BlockEvent blockEvent = new BlockEvent(peer, resp);
                        peer.setLastBlockSeen(blockEvent);

                        channelEventQue.addBEvent(blockEvent);
                    } else {
                        logger.error(format("%s got event block with unknown type: %s, %d",
                                PeerEventServiceClient.this.toString(), typeCase.name(), typeCase.getNumber()));

                        PeerEventingServiceException peerEventingServiceException = new PeerEventingServiceException(format("% got event block with unknown type: %s, %d",
                                PeerEventServiceClient.this.toString(), typeCase.name(), typeCase.getNumber()));
                        peerEventingServiceException.setResponse(resp);

                        throwableList.add(peerEventingServiceException);

                    }
                    finishLatch.countDown();

                }

                @Override
                public void onError(Throwable t) {
                    ManagedChannel llmanagedChannel = managedChannel;
                    if (llmanagedChannel != null) {
                        try {
                            llmanagedChannel.shutdownNow();
                        } catch (Exception e) {
                            logger.warn(format("Received error on %s, attempts %d. %s shut down of grpc channel.",
                                    PeerEventServiceClient.this.toString(), peer == null ? -1 : peer.getReconnectCount(), e.getMessage()), e);
                        }
                        managedChannel = null;
                    }
                    if (!shutdown) {
                        final long reconnectCount = peer.getReconnectCount();
                        if (PEER_EVENT_RECONNECTION_WARNING_RATE > 1 && reconnectCount % PEER_EVENT_RECONNECTION_WARNING_RATE == 1) {
                            logger.warn(format("Received error on  %s, attempts %d. %s",
                                    PeerEventServiceClient.this.toString(), reconnectCount, t.getMessage()));

                        } else {
                            logger.trace(format("Received error on %s, attempts %d. %s",
                                    PeerEventServiceClient.this.toString(), reconnectCount, t.getMessage()));

                        }

                        if (retry.getAndSet(false)) {
                            peer.reconnectPeerEventServiceClient(PeerEventServiceClient.this, t);
                        }

                    }
                    finishLatch.countDown();
                }

                @Override
                public void onCompleted() {
                    logger.debug(format("DeliverResponse onCompleted %s setting done.",
                            PeerEventServiceClient.this.toString()));
                    //            done = true;
                    //There should have been a done before this...
                    finishLatch.countDown();
                }
            };

            nso = filterBlock ? broadcast.deliverFiltered(so) : broadcast.deliver(so);

            nso.onNext(envelope);

            // try {
            if (!finishLatch.await(peerEventRegistrationWaitTimeMilliSecs, TimeUnit.MILLISECONDS)) {
                PeerEventingServiceException ex = new PeerEventingServiceException(format(
                        "Channel %s connect time exceeded for peer eventing service %s, timed out at %d ms.", channelName, name, peerEventRegistrationWaitTimeMilliSecs));
                ex.setTimedOut(peerEventRegistrationWaitTimeMilliSecs);
                logger.warn(toString() + " " + ex.getMessage());
                throwableList.add(0, ex);

            }
            logger.trace(toString() + " done waiting for reply!");

            if (!throwableList.isEmpty()) {
                ManagedChannel llmanagedChannel = managedChannel;
                if (llmanagedChannel != null) {
                    llmanagedChannel.shutdownNow();
                    managedChannel = null;
                }
                Throwable throwable = throwableList.get(0);
                if (retry.getAndSet(false)) {
                    peer.reconnectPeerEventServiceClient(this, throwable);
                }

            }

        } catch (InterruptedException e) {
            ManagedChannel llmanagedChannel = managedChannel;
            if (llmanagedChannel != null) {
                llmanagedChannel.shutdownNow();
                managedChannel = null;
            }
            logger.error(toString() + " error message: " + e.getMessage(), e); // not likely

            if (retry.getAndSet(false)) {
                peer.reconnectPeerEventServiceClient(this, e);
            }

        } finally {
            if (null != nso) {

                try {
                    nso.onCompleted();
                } catch (Exception e) {  //Best effort only report on debug
                    logger.debug(format("Exception completing connect with %s %s",
                            toString(), e.getMessage()), e);
                }

            }
        }
    }
626113
def Disconnect(self, reason=None, isDead=True):
        """"""
        self.disconnecting = True
        self.expect_verack_next = False
        if reason:
            logger.debug(f"Disconnecting with reason: {reason}")
        self.stop_block_loop()
        self.stop_header_loop()
        self.stop_peerinfo_loop()
        if isDead:
            self.leader.AddDeadAddress(self.address, reason=f"{self.prefix} Forced disconnect by us")

        self.leader.forced_disconnect_by_us += 1

        self.disconnect_deferred = defer.Deferred()
        self.disconnect_deferred.debug = True
        # force disconnection without waiting on the other side
        # calling later to give func caller time to add callbacks to the deferred
        reactor.callLater(1, self.transport.abortConnection)
        return self.disconnect_deferred
847488
def _run(self, peer):
        
        # We know the peer we are connected to, we send open message.
        self._peer = peer
        self.connection_made()

        # We wait for peer to send messages.
        self._recv_loop()
208782
private void error(ErrorReason error)
    {
        if (options.rawSocket) {
            //  For raw sockets, send a final 0-length message to the application
            //  so that it knows the peer has been disconnected.
            Msg terminator = new Msg();
            processMsg.apply(terminator);
        }
        assert (session != null);
        socket.eventDisconnected(endpoint, fd);
        session.flush();
        session.engineError(error);
        unplug();
        destroy();
    }
36222
function onRTCFallback(from,data,isArray)
    {
        var peer = getPeerByRTCId(from);
        
        if(peer)
        {
            if(isArray == true)
            {
                data = sliceArray(data,0,data.length-2);// data.slice(0,data.length-2);
            }
            scope.dispatchEvent("peerMessage",{message:data,id:peer.id,rtc:peer.rtcId,array:isArray,fallback:true});
        }
    }
1033716
function onPeerMessage(peer,msg)
    {
        scope.dispatchEvent("peerMessage",{message:msg,id:peer.id,rtc:peer.rtcId,array:false,fallback:false});
    }
139088
public void connect(
		final String endpoint,
		final Callback<? super HttpSocket> onConnect,
		final Callback<? super Exception> onError
	) {
		executors.getUnbounded().submit(
			new Runnable() {
				@Override
				public void run() {
					try {
						// Build request bytes
						AoByteArrayOutputStream bout = new AoByteArrayOutputStream();
						try {
							try (DataOutputStream out = new DataOutputStream(bout)) {
								out.writeBytes("action=connect");
							}
						} finally {
							bout.close();
						}
						long connectTime = System.currentTimeMillis();
						URL endpointURL = new URL(endpoint);
						HttpURLConnection conn = (HttpURLConnection)endpointURL.openConnection();
						conn.setAllowUserInteraction(false);
						conn.setConnectTimeout(CONNECT_TIMEOUT);
						conn.setDoOutput(true);
						conn.setFixedLengthStreamingMode(bout.size());
						conn.setInstanceFollowRedirects(false);
						conn.setReadTimeout(CONNECT_TIMEOUT);
						conn.setRequestMethod("POST");
						conn.setUseCaches(false);
						// Write request
						OutputStream out = conn.getOutputStream();
						try {
							out.write(bout.getInternalByteArray(), 0, bout.size());
							out.flush();
						} finally {
							out.close();
						}
						// Get response
						int responseCode = conn.getResponseCode();
						if(responseCode != 200) throw new IOException("Unexpect response code: " + responseCode);
						if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got connection");
						DocumentBuilder builder = builderFactory.newDocumentBuilder();
						Element document = builder.parse(conn.getInputStream()).getDocumentElement();
						if(!"connection".equals(document.getNodeName())) throw new IOException("Unexpected root node name: " + document.getNodeName());
						Identifier id = Identifier.valueOf(document.getAttribute("id"));
						if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got id=" + id);
						HttpSocket httpSocket = new HttpSocket(
							HttpSocketClient.this,
							id,
							connectTime,
							endpointURL
						);
						if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: adding socket");
						addSocket(httpSocket);
						if(onConnect!=null) {
							if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onConnect");
							onConnect.call(httpSocket);
						}
					} catch(Exception exc) {
						if(onError!=null) {
							if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onError");
							onError.call(exc);
						}
					}
				}
			}
		);
	}
841018
@ObjectiveCName("onProfileClosedWithUid:")
    public void onProfileClosed(int uid) {
        modules.getEvents().post(new PeerInfoClosed(Peer.user(uid)));
    }
810665
public void eventHubConnect(String peerUrl, String pem) {
        this.eventHub.setPeerAddr(peerUrl, pem);
        this.eventHub.connect();
    }
639534
void deliverError(final OtpCookedConnection conn, final Exception e) {
        removeConnection(conn);
        remoteStatus(conn.name, false, e);
    }
1334066
function (dataChannel, info, err) {
        console.error(dataChannel.peerName + ": dataChannel(" +
                      dataChannel.dataChannel.label + "): error: ", err);
      }
464171
public void onFailedUpgrade() {
        assert (this.state == ConnectionState.CONNECTING);
        ConnectionState event = null;
        synchronized (this) {
            this.state = ConnectionState.CLOSED;
            cleanClose = false;
            inputAvailable = false;
            outputAvailable = false;
            event = this.state;
        }
        notifyStateListeners(event);
    }
217211
private void notifyConnected(Peer peer) {
		for(Listener listener : new HashSet<>(listeners)) {
			listener.onConnected(peer);
		}
	}
654424
@Override
  public void join(String peer) throws Exception {
    LOG.debug("Follower joins in.");
    try {
      LOG.debug("Query leader from {}", peer);
      Message query = MessageBuilder.buildQueryLeader();
      MessageTuple tuple = null;
      while (true) {
        // The joiner might gets started before the cluster gets started.
        // Instead of reporting failure immediately, the follower will retry
        // joining the cluster until joining the cluster successfully.
        try {
          sendMessage(peer, query);
          tuple = filter.getExpectedMessage(MessageType.QUERY_LEADER_REPLY,
                                            peer, config.getTimeoutMs());
          break;
        } catch (TimeoutException ex) {
          long retryInterval = 1;
          LOG.warn("Timeout while contacting leader, going to retry after {} "
              + "second.", retryInterval);
          // Waits for 1 second.
          Thread.sleep(retryInterval * 1000);
        }
      }
      this.electedLeader = tuple.getMessage().getReply().getLeader();
      LOG.debug("Got current leader {}", this.electedLeader);

      /* -- Synchronizing phase -- */
      while (true) {
        try {
          joinSynchronization();
          break;
        } catch (TimeoutException | BackToElectionException ex) {
          LOG.debug("Timeout({} ms) in synchronizing, retrying. Last zxid : {}",
                    getSyncTimeoutMs(),
                    persistence.getLatestZxid());
          transport.clear(electedLeader);
          clearMessageQueue();
        }
      }
      // See if it can be restored from the snapshot file.
      restoreFromSnapshot();
      // Delivers all transactions in log before entering broadcasting phase.
      deliverUndeliveredTxns();

      /* -- Broadcasting phase -- */
      // Initialize the vote for leader election.
      this.election.specifyLeader(this.electedLeader);
      changePhase(Phase.BROADCASTING);
      accepting();
    } catch (InterruptedException e) {
      LOG.debug("Participant is canceled by user.");
      throw e;
    } catch (TimeoutException e) {
      LOG.debug("Didn't hear message from {} for {} milliseconds. Going"
                + " back to leader election.",
                this.electedLeader,
                this.config.getTimeoutMs());
      if (persistence.getLastSeenConfig() == null) {
        throw new JoinFailure("Fails to join cluster.");
      }
    } catch (BackToElectionException e) {
      LOG.debug("Got GO_BACK message from queue, going back to electing.");
      if (persistence.getLastSeenConfig() == null) {
        throw new JoinFailure("Fails to join cluster.");
      }
    } catch (LeftCluster e) {
      LOG.debug("Exit running : {}", e.getMessage());
      throw e;
    } catch (Exception e) {
      LOG.error("Caught exception", e);
      throw e;
    } finally {
      changePhase(Phase.FINALIZING);
    }
  }
1186698
def on_update_enabled(self, conf_evt):
        
        enabled = conf_evt.value
        # If we do not have any protocol bound and configuration asks us to
        # enable this peer, we try to establish connection again.
        if enabled:
            LOG.info('%s enabled', self)
            if self._protocol and self._protocol.started:
                LOG.error('Tried to enable neighbor that is already enabled')
            else:
                self.state.bgp_state = const.BGP_FSM_CONNECT
                # Restart connect loop if not already running.
                if not self._connect_retry_event.is_set():
                    self._connect_retry_event.set()
                    LOG.debug('Starting connect loop as neighbor is enabled.')
        else:
            LOG.info('%s disabled', self)
            if self._protocol:
                # Stopping protocol will eventually trigger connection_lost
                # handler which will do some clean-up.
                # But the greenlet that is in charge of the socket may be kill
                # when we stop the protocol, hence we call connection_lost
                # here as we triggered socket to close.
                self._protocol.send_notification(
                    BGP_ERROR_CEASE,
                    BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN
                )
                self._protocol.stop()
                self._protocol = None
                self.state.bgp_state = const.BGP_FSM_IDLE
            # If this peer is not enabled any-more we stop trying to make any
            # connection.
            LOG.debug('Disabling connect-retry as neighbor was disabled')
            self._connect_retry_event.clear()