Check communication, repeatedly if necessary

 === Parameters
 attempt(Integer):: Number of attempts thus far
 must_try(Boolean):: Try communicating regardless of whether required based on time limit

 === Return
 true:: Always return true
169543
def check_communication(attempt, must_try = false)
      attempt += 1
      begin
        if !must_try && (time = time_since_last_communication) < @options[:time_limit]
          @retry_timer.cancel if @retry_timer
          elapsed = elapsed(time)
          info("Passed communication check with activity as recently as #{elapsed} ago", to_console = !@options[:daemon])
          terminate unless @options[:daemon]
        elsif attempt <= @options[:max_attempts]
          debug("Trying communication" + (attempt > 1 ? ", attempt #{attempt}" : ""))
          try_communicating(attempt)
          @retry_timer = EM::Timer.new(@options[:retry_interval]) do
            error("Communication attempt #{attempt} timed out after #{elapsed(@options[:retry_interval])}")
            @agent = AgentConfig.agent_options('instance') # Reload in case not using right cookie
            check_communication(attempt)
          end
        else
          reenroll!
        end
      rescue SystemExit => e
        raise e
      rescue Exception => e
        abort = !@options[:daemon] && (attempt > @options[:max_attempts])
        error("Failed communication check", e, abort)
        check_communication(attempt)
      end
      true
    end
1267052
def is_rate_limited(response):
        
        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and
                int(response.headers['Retry-After']) >= 0):
            return True

        return False
509675
def _check_fulfilled(self):
        
        is_fulfilled = False
        result = None
        start_time = time.time()

        # Check whether the promise has been fulfilled until we run out of time or attempts
        while self._has_time_left(start_time) and self._has_more_tries():

            # Keep track of how many attempts we've made so far
            self._num_tries += 1

            is_fulfilled, result = self._check_func()

            # If the promise is satisfied, then continue execution
            if is_fulfilled:
                break

            # Delay between checks
            time.sleep(self._try_interval)

        return is_fulfilled, result
402247
def _reconnect_delay(self):
        
        if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED:
            if self._reconnect_attempts >= len(self.RECONNECT_DELAYS):
                return self.RECONNECT_DELAYS[-1]
            else:
                return self.RECONNECT_DELAYS[self._reconnect_attempts]
        else:
            return 0
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();
  }
1232570
def get_last_failed_access_attempt(cls, **kwargs):
        
        try:
            lockout = cls.objects.get(
                **kwargs
            )
        except cls.DoesNotExist:
            lockout = None

        if lockout:
            time_remaining = lockout.expiration_time
            if time_remaining and time_remaining <= 0:
                lockout.is_expired = True
                lockout.save()
                return None

        return lockout
281941
def wait_for_at_least_one_message(self, channel):
        

        unpacker = msgpack.Unpacker(encoding='utf-8')

        while True:
            try:
                start = time.time()
                chunk = self.ssh_channel[channel].recv(1024)
                end = time.time()
                self.read_speeds.append( len(chunk) / (end-start) )
                if len(self.read_speeds) > 20:
                    self.read_speeds = self.read_speeds[10:]

                if chunk == b'':
                    # happens only when connection broke. If nothing is to be received, it hangs instead.
                    self.connection_error(channel, 'Connection broken w')
                    return False
            except Exception as error:
                self.connection_error(channel, error)
                raise

            unpacker.feed(chunk)

            messages = [m for m in unpacker]
            if messages:
                return messages
809709
def trylock(self):
        ""
        if self.locked:
            return True
        if self.lockroutine:
            return False
        waiter = self.scheduler.send(LockEvent(self.context, self.key, self))
        if waiter:
            return False
        else:
            self.locked = True
            return True
194674
def rate_limit(self):
        
        rate_limited_msg = False

        while True:
            is_rate_limited = self.limit.is_rate_limited(uuid)
            if is_rate_limited:
                time.sleep(0.3)  # save hammering redis
                if not rate_limited_msg:
                    self.logger.info('Rate limit active..please wait...')
                    rate_limited_msg = True

            if not is_rate_limited:
                self.logger.info('Rate limit clear.')
                self.limit.attempt(uuid)
                return True
897429
def _is_connreset(self, exc: BaseException) -> bool:
        
        return (
            isinstance(exc, (socket.error, IOError))
            and errno_from_exception(exc) in _ERRNO_CONNRESET
        )
1267579
def after_start_check(self):
        
        try:
            if self.url.scheme == 'http':
                conn = HTTPConnection(self.host, self.port)
            elif self.url.scheme == 'https':
                ssl_context = None
                if not self.verify_tls:
                    ssl_context = ssl._create_unverified_context()
                conn = HTTPSConnection(
                    self.host,
                    self.port,
                    context=ssl_context,
                )
            else:
                raise ValueError(f'Unsupported URL scheme: "{self.url.scheme}"')

            self._send_request(conn)
            response = conn.getresponse()
            status = str(response.status)

            if not self._validate_response(response):
                return False

            if status == self.status or self.status_re.match(status):
                conn.close()
                return True

        except (HTTPException, socket.timeout, socket.error) as ex:
            log.debug('Executor process not healthy yet', command=self.command, error=ex)
            time.sleep(.05)
            return False

        return False
84715
def keep_trying(timeout=10, tries=0)
      puts "Try: #{tries}" if @announce_env
      yield
    rescue RSpec::Expectations::ExpectationNotMetError
      if tries < timeout
        sleep 1
        tries += 1
        retry
      else
        raise
      end
    end
937463
function() {
        var i = 0;
        while (i < this.requireFail.length) {
            if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
                return false;
            }
            i++;
        }
        return true;
    }
232375
final boolean trySetSignal() {
        int s = status;
        return s >= 0 && U.compareAndSwapInt(this, STATUS, s, s | SIGNAL);
    }
758374
def is_connected(self):
        
        if self._client is not None:
            try:
                self._client.server_info()
            except ConnectionFailure:
                return False
            return True
        else:
            return False
116417
function attempt() {
      connections[id].attempts++;
      if (connections[id].attempts > retry) {
        connections[id].attempts = 0;
        connections[id].deny++;
        self.log(chalk.yellow("Access denied: too many attempts."));
        callback("Access denied: too many attempts.", false);
        return;
      }
      if (connections[id].deny >= deny && unlockTime > 0) {
        setTimeout(function(){
          connections[id].deny = 0;
        }, unlockTime);
        connections[id].attempts = 0;
        self.log(chalk.yellow("Account locked out: too many login attempts."));
        callback("Account locked out: too many login attempts.", false);
        return;
      }
      gather(function(user, pass){
        user = search(user, pass, users);
        if (user) {
          connections[id].attempts = 0;
          connections[id].deny = 0;
          callback("Successfully Authenticated.", true);
        } else {
          state.pass = void 0;
          setTimeout(function(){
            if (connections[id].attempts <= retry) {
              self.log("Access denied.");
            }
            attempt();
          }, retryTime);
        }
      });
    }
203386
private synchronized boolean tryServerLock() throws IOException {
        if (!lockFile.exists() || lockFileChannel == null)
            return false;

        boolean lockObtained = true;

        try {
            serverLock = lockFileChannel.tryLock();

            // if server lock is not valid, it could not be obtained
            if (serverLock == null || !serverLock.isValid())
                lockObtained = false;
        } catch (OverlappingFileLockException e) {
            lockObtained = false;
        } catch (IOException e) {
            lockObtained = false;
        } finally {
            // make sure we release so the other process can obtain the lock file
            if (serverLock != null)
                serverLock.release();
        }

        return lockObtained;
    }