Check whether the credentials have expired.

    :param awsclient:
    :return: exit_code
335793
def are_credentials_still_valid(awsclient):
    
    client = awsclient.get_client('lambda')
    try:
        client.list_functions()
    except GracefulExit:
        raise
    except Exception as e:
        log.debug(e)
        log.error(e)
        return 1
    return 0
1153494
def expired?(request, method)
      if (expires_at = request.expires_at) && expires_at > 0 && (now = Time.now.to_i) >= expires_at
        @reject_stats.update("expired (#{method})")
        Log.info("REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago")
        # For agents that do not know about non-delivery, use error result
        if can_handle_non_delivery_result?(request.recv_version)
          OperationResult.non_delivery(OperationResult::TTL_EXPIRATION)
        else
          OperationResult.error("Could not deliver request (#{OperationResult::TTL_EXPIRATION})")
        end
      end
    end
394444
def endpoint_is_activated(endpoint_id, until, absolute_time):
    
    client = get_client()
    res = client.endpoint_get_activation_requirements(endpoint_id)

    def fail(deadline=None):
        exp_string = ""
        if deadline is not None:
            exp_string = " or will expire within {} seconds".format(deadline)

        message = "The endpoint is not activated{}.\n\n".format(
            exp_string
        ) + activation_requirements_help_text(res, endpoint_id)
        formatted_print(res, simple_text=message)
        click.get_current_context().exit(1)

    def success(msg, *format_params):
        formatted_print(res, simple_text=(msg.format(endpoint_id, *format_params)))
        click.get_current_context().exit(0)

    # eternally active endpoints have a special expires_in value
    if res["expires_in"] == -1:
        success("{} does not require activation")

    # autoactivation is not supported and --until was not passed
    if until is None:
        # and we are active right now (0s in the future)...
        if res.active_until(0):
            success("{} is activated")
        # or we are not active
        fail()

    # autoactivation is not supported and --until was passed
    if res.active_until(until, relative_time=not absolute_time):
        success("{} will be active for at least {} seconds", until)
    else:
        fail(deadline=until)
1178562
def is_authorization_expired(self):
        
        if not self.auth.token_expiration:
            return True
        return (datetime.datetime.utcnow() > self.auth.token_expiration)
930836
def auth_expired(self):
        
        if self._auth and self._expires:
            now_with_skew = time.time() + AUTH_TOKEN_CLOCK_SKEW_MAX
            return now_with_skew > self._expires
        return True
1012868
def validate_key(self, activation_key):
        
        try:
            username = signing.loads(
                activation_key,
                salt=self.key_salt,
                max_age=conf.get('ACCOUNT_ACTIVATION_DAYS') * 86400
            )
            return username
        # SignatureExpired is a subclass of BadSignature, so this will
        # catch either one.
        except signing.BadSignature:
            return None
188479
def validate(self, signature, timestamp, nonce):
        
        if not self.token:
            raise RuntimeError('WEIXIN_TOKEN is missing')

        if self.expires_in:
            try:
                timestamp = int(timestamp)
            except (ValueError, TypeError):
                # fake timestamp
                return False

            delta = time.time() - timestamp
            if delta < 0:
                # this is a fake timestamp
                return False

            if delta > self.expires_in:
                # expired timestamp
                return False

        values = [self.token, str(timestamp), str(nonce)]
        s = ''.join(sorted(values))
        hsh = hashlib.sha1(s.encode('utf-8')).hexdigest()
        return signature == hsh
436238
def require_valid(self):
        
        expired = self.get_expired()
        valid = self.exclude(pk__in=expired)
        valid_expired = expired.bulk_refresh()
        return valid_expired | valid
990682
def is_expired(self, max_idle_seconds):
        

        now = current_time()
        return (self.expiration_time is not None and self.expiration_time < now) or \
               (max_idle_seconds is not None and self.last_access_time + max_idle_seconds < now)
140044
def _stop_ec2_instances(awsclient, ec2_instances, wait=True):
    
    if len(ec2_instances) == 0:
        return
    client_ec2 = awsclient.get_client('ec2')

    # get running instances
    running_instances = all_pages(
        client_ec2.describe_instance_status,
        {
            'InstanceIds': ec2_instances,
            'Filters': [{
                'Name': 'instance-state-name',
                'Values': ['pending', 'running']
            }]
        },
        lambda r: [i['InstanceId'] for i in r.get('InstanceStatuses', [])],
    )

    if running_instances:
        log.info('Stopping EC2 instances: %s', running_instances)
        client_ec2.stop_instances(InstanceIds=running_instances)

        if wait:
            # wait for instances to stop
            waiter_inst_stopped = client_ec2.get_waiter('instance_stopped')
            waiter_inst_stopped.wait(InstanceIds=running_instances)
786680
def check_for_expire_acknowledge(self):
        
        if (self.acknowledgement and
                self.acknowledgement.end_time != 0 and
                self.acknowledgement.end_time < time.time()):
            self.unacknowledge_problem()
74913
private synchronized void fetchCredentials() {
        if (!needsToLoadCredentials()) return;

        JsonNode accessKey;
        JsonNode secretKey;
        JsonNode node;
        JsonNode token;
        try {
            lastInstanceProfileCheck = new Date();

            String credentialsResponse = EC2CredentialsUtils.getInstance().readResource(credentailsEndpointProvider.getCredentialsEndpoint(), credentailsEndpointProvider.getRetryPolicy());

            node = Jackson.jsonNodeOf(credentialsResponse);
            accessKey = node.get(ACCESS_KEY_ID);
            secretKey = node.get(SECRET_ACCESS_KEY);
            token = node.get(TOKEN);

            if (null == accessKey || null == secretKey) {
                throw new SdkClientException("Unable to load credentials.");
            }

            if (null != token) {
                credentials = new BasicSessionCredentials(accessKey.asText(),
                        secretKey.asText(), token.asText());
            } else {
                credentials = new BasicAWSCredentials(accessKey.asText(),
                        secretKey.asText());
            }

            JsonNode expirationJsonNode = node.get("Expiration");
            if (null != expirationJsonNode) {
                /*
                 * TODO: The expiration string comes in a different format
                 * than what we deal with in other parts of the SDK, so we
                 * have to convert it to the ISO8601 syntax we expect.
                 */
                String expiration = expirationJsonNode.asText();
                expiration = expiration.replaceAll("\\+0000$", "Z");

                try {
                    credentialsExpiration = DateUtils.parseISO8601Date(expiration);
                } catch(Exception ex) {
                    handleError("Unable to parse credentials expiration date from Amazon EC2 instance", ex);
                }
            }
        } catch (JsonMappingException e) {
            handleError("Unable to parse response returned from service endpoint", e);
        } catch (IOException e) {
            handleError("Unable to load credentials from service endpoint", e);
        } catch (URISyntaxException e) {
            handleError("Unable to load credentials from service endpoint", e);
        }
    }
683068
def wire_deprecated(awsclient, function_name, s3_event_sources=None,
                    time_event_sources=None,
                    alias_name=ALIAS_NAME):
    
    if not lambda_exists(awsclient, function_name):
        log.error(colored.red('The function you try to wire up doesn\'t ' +
                          'exist... Bailing out...'))
        return 1
    client_lambda = awsclient.get_client('lambda')
    lambda_function = client_lambda.get_function(FunctionName=function_name)
    lambda_arn = client_lambda.get_alias(FunctionName=function_name,
                                         Name=alias_name)['AliasArn']
    log.info('wiring lambda_arn %s ...' % lambda_arn)

    if lambda_function is not None:
        s3_events_ensure_exists, s3_events_ensure_absent = filter_events_ensure(
            s3_event_sources)
        cloudwatch_events_ensure_exists, cloudwatch_events_ensure_absent = \
            filter_events_ensure(time_event_sources)

        for s3_event_source in s3_events_ensure_absent:
            _ensure_s3_event(awsclient, s3_event_source, function_name,
                             alias_name, lambda_arn, s3_event_source['ensure'])
        for s3_event_source in s3_events_ensure_exists:
            _ensure_s3_event(awsclient, s3_event_source, function_name,
                             alias_name, lambda_arn, s3_event_source['ensure'])

        for time_event in cloudwatch_events_ensure_absent:
            _ensure_cloudwatch_event(awsclient, time_event, function_name,
                                     alias_name, lambda_arn,
                                     time_event['ensure'])
        for time_event in cloudwatch_events_ensure_exists:
            _ensure_cloudwatch_event(awsclient, time_event, function_name,
                                     alias_name, lambda_arn,
                                     time_event['ensure'])
    return 0
175048
def query_expired(cls, dt, bucket=None):
        """"""
        q = cls.query.filter(cls.created < dt).filter_by(completed=True)
        if bucket:
            q = q.filter(cls.bucket_id == as_bucket_id(bucket))
        return q
875336
def is_expired(self, token, when=0):
        
        verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg])
        _payload = verifier.unpack(token)
        return is_expired(_payload['exp'], when)
1358114
function verifyExpiration() {
    if(opt.removeExpired === false) return;
    let items = thorin.util.readDirectory(rootPath, {
      ext: '.sess'
    });
    let calls = [],
      removes = 0,
      now = Date.now();
    items.forEach((fpath) => {
      calls.push((done) => {
        fse.readJson(fpath, (e, json) => {
          if(e) {
            logger.warn('Failed to lookup session file [%s] for cleaning.', fpath, e);
            return done();
          }
          if(now < json.e) return done();
          // remove the file.
          fse.remove(fpath, (e) => {
            if(e && e.code !== 'ENOENT') {
              logger.warn(`Failed to remove expired session file ${fpath}.`, e);
            } else {
              removes++;
            }
            return done();
          });
        });
      });
    });
    async.series(calls, () => {
      if(removes > 0) {
        logger.trace(`Removed ${removes} expired sessions.`);
      }
      setTimeout(verifyExpiration, CLEANUP_TIMER);
    });
  }
1089678
protected boolean isExpired(OAuthProviderTokenImpl authToken) {
    if (authToken.isAccessToken()) {
      if ((authToken.getTimestamp() + (getAccessTokenValiditySeconds() * 1000L)) < System.currentTimeMillis()) {
        return true;
      }
    }
    else {
      if ((authToken.getTimestamp() + (getRequestTokenValiditySeconds() * 1000L)) < System.currentTimeMillis()) {
        return true;
      }
    }

    return false;
  }