Start healthcheck (status monitoring) for a peer

        It also whitelists the address to answer invites and listen for messages
781
def start_health_check(self, node_address):
        
        if self._stop_event.ready():
            return

        with self._health_lock:
            if self._address_mgr.is_address_known(node_address):
                return  # already healthchecked

            node_address_hex = to_normalized_address(node_address)
            self.log.debug('Healthcheck', peer_address=node_address_hex)

            candidates = [
                self._get_user(user)
                for user in self._client.search_user_directory(node_address_hex)
            ]
            user_ids = {
                user.user_id
                for user in candidates
                if validate_userid_signature(user) == node_address
            }
            self.whitelist(node_address)
            self._address_mgr.add_userids_for_address(node_address, user_ids)

            # Ensure network state is updated in case we already know about the user presences
            # representing the target node
            self._address_mgr.refresh_address_presence(node_address)
1356933
function notify () {
    const newId = options.peerId
    const peerIds = Object.keys(peerTable)
    // check for all the peers
    // if same id skip
    // if notify === false skip
    // check the first finger that matches the criteria for ideal or next to ideal
    peerIds.forEach((peerId) => {
      if (newId === peerId) {
        return // skip ourselves
      }
      if (!peerTable[peerId].notify) {
        return // skip if it doesn't want to be notified of available peers
      }

      // if it had none, notify to get a successor
      if (peerTable[peerId].fingers['0'].current === undefined) {
        peerTable[peerId].fingers['0'].current = newId
        peerTable[peerId].socket.emit('we-update-finger', {
          row: '0',
          id: newId
        })
        return
      }

      const rows = Object.keys(peerTable[peerId].fingers)
      // find the first row that could use this finger
      rows.some((row) => {
        const finger = peerTable[peerId].fingers[row]
        const bestCandidate = fingerBestFit(
            new Id(peerId),
            new Id(finger.ideal),
            new Id(finger.current),
            new Id(newId))
        if (bestCandidate) {
          peerTable[peerId].fingers[row].current = newId
          peerTable[peerId].socket.emit('we-update-finger', {
            row: row,
            id: newId
          })
          return true
        }
      })
    })
  }
894817
def healthcheck(
        transport: 'UDPTransport',
        recipient: Address,
        stop_event: Event,
        event_healthy: Event,
        event_unhealthy: Event,
        nat_keepalive_retries: int,
        nat_keepalive_timeout: int,
        nat_invitation_timeout: int,
        ping_nonce: Dict[str, Nonce],
):
    
    # pylint: disable=too-many-branches

    log.debug(
        'starting healthcheck for',
        node=pex(transport.address),
        to=pex(recipient),
    )

    # The state of the node is unknown, the events are set to allow the tasks
    # to do work.
    last_state = NODE_NETWORK_UNKNOWN
    transport.set_node_network_state(
        recipient,
        last_state,
    )

    # Always call `clear` before `set`, since only `set` does context-switches
    # it's easier to reason about tasks that are waiting on both events.

    # Wait for the end-point registration or for the node to quit
    try:
        transport.get_host_port(recipient)
    except UnknownAddress:
        log.debug(
            'waiting for endpoint registration',
            node=pex(transport.address),
            to=pex(recipient),
        )

        event_healthy.clear()
        event_unhealthy.set()

        backoff = udp_utils.timeout_exponential_backoff(
            nat_keepalive_retries,
            nat_keepalive_timeout,
            nat_invitation_timeout,
        )
        sleep = next(backoff)

        while not stop_event.wait(sleep):
            try:
                transport.get_host_port(recipient)
            except UnknownAddress:
                sleep = next(backoff)
            else:
                break

    # Don't wait to send the first Ping and to start sending messages if the
    # endpoint is known
    sleep = 0
    event_unhealthy.clear()
    event_healthy.set()

    while not stop_event.wait(sleep):
        sleep = nat_keepalive_timeout

        ping_nonce['nonce'] = Nonce(ping_nonce['nonce'] + 1)
        messagedata = transport.get_ping(ping_nonce['nonce'])
        message_id = ('ping', ping_nonce['nonce'], recipient)

        # Send Ping a few times before setting the node as unreachable
        acknowledged = udp_utils.retry(
            transport,
            messagedata,
            message_id,
            recipient,
            stop_event,
            [nat_keepalive_timeout] * nat_keepalive_retries,
        )

        if stop_event.is_set():
            return

        if not acknowledged:
            log.debug(
                'node is unresponsive',
                node=pex(transport.address),
                to=pex(recipient),
                current_state=last_state,
                new_state=NODE_NETWORK_UNREACHABLE,
                retries=nat_keepalive_retries,
                timeout=nat_keepalive_timeout,
            )

            # The node is not healthy, clear the event to stop all queue
            # tasks
            last_state = NODE_NETWORK_UNREACHABLE
            transport.set_node_network_state(
                recipient,
                last_state,
            )
            event_healthy.clear()
            event_unhealthy.set()

            # Retry until recovery, used for:
            # - Checking node status.
            # - Nat punching.
            acknowledged = udp_utils.retry(
                transport,
                messagedata,
                message_id,
                recipient,
                stop_event,
                repeat(nat_invitation_timeout),
            )

        if acknowledged:
            current_state = views.get_node_network_status(
                views.state_from_raiden(transport.raiden),
                recipient,
            )

            if last_state != NODE_NETWORK_REACHABLE:
                log.debug(
                    'node answered',
                    node=pex(transport.raiden.address),
                    to=pex(recipient),
                    current_state=current_state,
                    new_state=NODE_NETWORK_REACHABLE,
                )

                last_state = NODE_NETWORK_REACHABLE
                transport.set_node_network_state(
                    recipient,
                    last_state,
                )
                event_unhealthy.clear()
                event_healthy.set()
1235870
function Peer (options) {
  EventEmitter.call(this)
  bindFns(this)

  extend(this, options)
  var addr = this.address
  var hp = addr.split(':')
  this.host = hp[0]
  this.port = Number(hp[1])
  this._deliveryTrackers = []
  this.setMaxListeners(0)
  this._debug('new peer')
}
44786
def add_indicators(self, indicators=list(), private=False, tags=list()):
        """"""
        if len(indicators) == 0:
            raise Exception("No indicators were identified.")
        self.logger.debug("Checking {} indicators".format(len(indicators)))
        cleaned = clean_indicators(indicators)
        self.logger.debug("Cleaned {} indicators".format(len(cleaned)))
        whitelisted = check_whitelist(cleaned)
        self.logger.debug("Non-whitelisted {} indicators".format(len(whitelisted)))
        indicators = prune_cached(whitelisted)
        hashed = hash_values(indicators)
        self.logger.debug("Non-cached {} indicators".format(len(indicators)))
        self.logger.debug("Processing {} indicators".format(len(indicators)))
        request_count = int(math.ceil(len(indicators)/100.0))
        if request_count == 0:
            mesg = "[!] No indicators were left to process after "
            mesg += "cleaning, whitelisting and checking the cache."
            return {'message': mesg}
        stats = {'success': 0, 'failure': 0, 'requests': request_count,
                 'written': 0}
        mesg = "{} indicators found, making {} requests"
        self.logger.debug(mesg.format(len(indicators), request_count))

        if private:
            indicators = hashed

        if type(tags) == str:
            tags = [t.strip().lower() for t in tags.split(',')]

        start, end = (0, 100)
        for i, idx in enumerate(range(0, request_count)):
            if idx > 0:
                time.sleep(3)  # Ensure we never trip the limit
                self.logger.debug("Waiting 3 seconds before next request.")
            to_send = {'indicators': indicators[start:end], 'tags': tags}
            r = self._send_data('POST', 'admin', 'add-indicators', to_send)
            start, end = (end, end + 100)
            if not r['success']:
                stats['failure'] += 1
                continue
            stats['success'] += 1
            stats['written'] += r['writeCount']
            cache_items(to_send['indicators'])
        msg = ""
        msg += "{written} indicators written using {requests} requests: "
        msg += "{success} success, {failure} failure"
        stats['message'] = msg.format(**stats)
        return stats
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()
396221
def AddConnectedPeer(self, peer):
        
        # if present
        self.RemoveFromQueue(peer.address)
        self.AddKnownAddress(peer.address)

        if len(self.Peers) > settings.CONNECTED_PEER_MAX:
            peer.Disconnect("Max connected peers reached", isDead=False)

        if peer not in self.Peers:
            self.Peers.append(peer)
        else:
            # either peer is already in the list and it has reconnected before it timed out on our side
            # or it's trying to connect multiple times
            # or we hit the max connected peer count
            self.RemoveKnownAddress(peer.address)
            peer.Disconnect()
1209883
def do_health_checks(self, list_of_ips):
        
        # Calculate a decent overall timeout time for a ping attempt: 3/4th of
        # the monitoring interval. That way, we know we're done with this ping
        # attempt before the next monitoring attempt is started.
        ping_timeout = self.get_monitor_interval() * 0.75

        # Calculate a decent number of retries. For very short intervals we
        # shouldn't have any retries, for very long ones, we should have
        # several ones. Converting the timeout to an integer gives us what we
        # want: For timeouts less than 1 we have no retry at all.
        num_retries = int(ping_timeout)

        try:
            self.ping_count += len(list_of_ips)
            responses, no_responses = multiping.multi_ping(
                                        list_of_ips, ping_timeout, num_retries)
            self.update_stats(responses, no_responses)

        except Exception as e:
            logging.error("Exception while trying to monitor servers: %s" %
                          str(e))
            # Need to assume all IPs failed
            no_responses = list_of_ips

        return no_responses, []
1138032
def post(self, request, *args, **kwargs):
        
        status = 201
        accepted = {"accepted": True}
        send_invite_messages.apply_async()
        return Response(accepted, status=status)
212259
async def on_message(message):
    

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Commands section
        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]

            # Commands
            if command == 'gamedeals':
                await client.send_typing(channel)

                # Get posts from Reddit API
                posts = api_reddit.get_top10()

                if posts:
                    for post in posts:
                        # Create embed UI
                        embed = ui_embed.success(channel, post)
                        await embed.send()
                else:
                    embed = ui_embed.no_results(channel)
                    await embed.send()
1226406
public void start(final URI defaultTrackerURI, final AnnounceResponseListener listener, final Peer[] peers, final int announceInterval) {
    myAnnounceInterval = announceInterval;
    myPeers.addAll(Arrays.asList(peers));
    if (defaultTrackerURI != null) {
      try {
        myDefaultTracker = myTrackerClientFactory.createTrackerClient(myPeers, defaultTrackerURI);
        myDefaultTracker.register(listener);
        this.clients.put(defaultTrackerURI.toString(), myDefaultTracker);
      } catch (Exception e) {
      }
    } else {
      myDefaultTracker = null;
    }

    this.stop = false;
    this.forceStop = false;

    if (this.thread == null || !this.thread.isAlive()) {
      this.thread = new Thread(this);
      this.thread.setName("torrent tracker announce thread");
      this.thread.start();
    }
  }
331058
private void notifyInactive(Peer peer) {
		for(Listener listener : new HashSet<>(listeners)) {
			listener.onInactive(peer);
		}
	}
606432
def _send_container_healthcheck_sc(self, containers_by_id):
        """"""
        for container in containers_by_id.itervalues():
            healthcheck_tags = self._get_tags(container, HEALTHCHECK)
            match = False
            for tag in healthcheck_tags:
                for rule in self.whitelist_patterns:
                    if re.match(rule, tag):
                        match = True

                        self._submit_healthcheck_sc(container)
                        break

                if match:
                    break
889305
@Override
    protected void doHealthCheck(final Health.Builder builder) {
        val samlServices = servicesManager.findServiceBy(registeredService -> registeredService instanceof SamlRegisteredService);
        val availableResolvers = this.metadataResolutionPlan.getRegisteredMetadataResolvers();
        LOGGER.debug("There are [{}] metadata resolver(s) available in the chain", availableResolvers.size());

        builder.up();

        samlServices
            .stream()
            .map(SamlRegisteredService.class::cast)
            .forEach(service -> {
                val map = new LinkedHashMap<String, Object>();
                map.put("name", service.getName());
                map.put("id", service.getId());
                map.put("metadataLocation", service.getMetadataLocation());
                map.put("serviceId", service.getServiceId());
                val available = availableResolvers
                    .stream()
                    .filter(Objects::nonNull)
                    .peek(r -> LOGGER.debug("Checking if metadata resolver [{}] is available for service [{}]", r.getName(), service.getName()))
                    .anyMatch(r -> r.isAvailable(service));
                map.put("availability", BooleanUtils.toStringYesNo(available));
                builder.withDetail(service.getName(), map);
                if (!available) {
                    LOGGER.debug("No metadata resolver is available for service [{}]", service.getName());
                    builder.down();
                }
            });
    }
1099861
def start(self):
        
        if self._shutdown:
            raise ShutdownError()

        self.read_watcher.start()
        logger.info("server started listening on {}".format(self.address))
31691
function start() {
      // Listen to the port
      app.listen(hrsConfigs.port, function (err) {
        if (err) {
          info(err);
        }
        info('Running on http://%s:%s', hrsConfigs.address, hrsConfigs.port);
      });
    }
465674
public void addPeer(TrackedPeer peer) {
    this.peers.put(new PeerUID(peer.getAddress(), this.getHexInfoHash()), peer);
  }