// databaseUserV1StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch db user.
558962
func databaseUserV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string, userName string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		pages, err := users.List(client, instanceID).AllPages()
		if err != nil {
			return nil, "", fmt.Errorf("Unable to retrieve OpenStack database users: %s", err)
		}

		allUsers, err := users.ExtractUsers(pages)
		if err != nil {
			return nil, "", fmt.Errorf("Unable to extract OpenStack database users: %s", err)
		}

		for _, v := range allUsers {
			if v.Name == userName {
				return v, "ACTIVE", nil
			}
		}

		return nil, "BUILD", nil
	}
}
1049118
func NGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		opts := &ec2.DescribeNatGatewaysInput{
			NatGatewayIds: []*string{aws.String(id)},
		}
		resp, err := conn.DescribeNatGateways(opts)
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "NatGatewayNotFound" {
				resp = nil
			} else {
				log.Printf("Error on NGStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		ng := resp.NatGateways[0]
		return ng, *ng.State, nil
	}
}
471752
func (rcvr *Receiver) FetchInitialState(stateUrl string) error {
	rcvr.StateLock.Lock()
	defer rcvr.StateLock.Unlock()

	log.Info("Fetching initial state on startup...")
	state, err := FetchState(stateUrl)
	if err != nil {
		return err
	} else {
		log.Info("Successfully retrieved state")
		rcvr.CurrentState = state
		if rcvr.OnUpdate == nil {
			log.Error("OnUpdate() callback not defined!")
		} else {
			rcvr.OnUpdate(state)
		}
	}

	return nil
}
287489
func (c *Cassandra) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error {
	// NOOP
	return nil
}
157341
func (t *TokenRefresher) RefreshAuthToken() (string, error) {
	tokens, err := t.uaaClient.RefreshAccessToken(t.cache.RefreshToken())
	if err != nil {
		return "", err
	}

	t.cache.SetAccessToken(tokens.AuthorizationToken())
	t.cache.SetRefreshToken(tokens.RefreshToken)
	return tokens.AuthorizationToken(), nil
}
828089
func (s *Storage) LoadRefresh(code string) (*osin.AccessData, error) {
	row := s.db.QueryRow("SELECT access FROM refresh WHERE token=$1 LIMIT 1", code)
	var access string
	if err := row.Scan(&access); err == sql.ErrNoRows {
		return nil, pkg.ErrNotFound
	} else if err != nil {
		return nil, errors.New(err)
	}
	return s.LoadAccess(access)
}
20548
func LoadState(db dbm.DB, version int64) (*State, error) {
	s := NewState(db)
	err := s.writeState.forest.Load(version)
	if err != nil {
		return nil, fmt.Errorf("could not load MutableForest at version %d: %v", version, err)
	}
	// Populate stats. If this starts taking too long, store the value rather than the full scan at startup
	err = s.IterateAccounts(func(acc *acm.Account) error {
		if len(acc.Code) > 0 {
			s.writeState.accountStats.AccountsWithCode++
		} else {
			s.writeState.accountStats.AccountsWithoutCode++
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	// load the validator ring
	ring, err := LoadValidatorRing(version, DefaultValidatorsWindowSize, s.writeState.forest.GetImmutable)
	if err != nil {
		return nil, err
	}
	s.writeState.ring = ring
	s.ReadState.History = ring

	return s, nil
}
1326978
func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string, failStates []string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		resp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{
			InstanceIds: []*string{aws.String(instanceID)},
		})
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" {
				// Set this to nil as if we didn't find anything.
				resp = nil
			} else {
				log.Printf("Error on InstanceStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		i := resp.Reservations[0].Instances[0]
		state := *i.State.Name

		for _, failState := range failStates {
			if state == failState {
				return i, state, fmt.Errorf("Failed to reach target state. Reason: %s",
					stringifyStateReason(i.StateReason))
			}
		}

		return i, state, nil
	}
}
379799
func (h *HANA) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error {
	statements = dbutil.StatementCompatibilityHelper(statements)

	// Get connection
	db, err := h.getConnection(ctx)
	if err != nil {
		return err
	}

	// Start a transaction
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// If expiration is in the role SQL, HANA will deactivate the user when time is up,
	// regardless of whether vault is alive to revoke lease
	expirationStr, err := h.GenerateExpiration(expiration)
	if err != nil {
		return err
	}

	// Renew user's valid until property field
	stmt, err := tx.PrepareContext(ctx, "ALTER USER "+username+" VALID UNTIL "+"'"+expirationStr+"'")
	if err != nil {
		return err
	}
	defer stmt.Close()
	if _, err := stmt.ExecContext(ctx); err != nil {
		return err
	}

	// Commit the transaction
	if err := tx.Commit(); err != nil {
		return err
	}

	return nil
}
1242977
func (w *WalletState) backgroundRefresh() {
	w.backgroundDone = make(chan struct{})
	for accountID := range w.refreshReqs {
		a, ok := w.accountState(accountID)
		if !ok {
			continue
		}
		a.RLock()
		rt := a.rtime
		a.RUnlock()

		mctx := libkb.NewMetaContextBackground(w.G()).WithLogTag("WABR")
		if time.Since(rt) < 120*time.Second {
			mctx.Debug("WalletState.backgroundRefresh skipping for %s due to recent refresh", accountID)
			continue
		}

		if err := a.Refresh(mctx, w.G().NotifyRouter, "background"); err != nil {
			mctx.Debug("WalletState.backgroundRefresh error for %s: %s", accountID, err)
		}
	}
	close(w.backgroundDone)
}
879291
func IGAttachStateRefreshFunc(conn *ec2.EC2, id string, expected string) resource.StateRefreshFunc {
	var start time.Time
	return func() (interface{}, string, error) {
		if start.IsZero() {
			start = time.Now()
		}

		resp, err := conn.DescribeInternetGateways(&ec2.DescribeInternetGatewaysInput{
			InternetGatewayIds: []*string{aws.String(id)},
		})
		if err != nil {
			ec2err, ok := err.(awserr.Error)
			if ok && ec2err.Code() == "InvalidInternetGatewayID.NotFound" {
				resp = nil
			} else {
				log.Printf("[ERROR] Error on IGStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		ig := resp.InternetGateways[0]

		if time.Since(start) > 10*time.Second {
			return ig, expected, nil
		}

		if len(ig.Attachments) == 0 {
			// No attachments, we're detached
			return ig, "detached", nil
		}

		return ig, *ig.Attachments[0].State, nil
	}
}
1280281
func (st *State) ModelBasicInfoForUser(user names.UserTag) ([]ModelAccessInfo, error) {
	isSuperuser, err := st.isUserSuperuser(user)
	if err != nil {
		return nil, errors.Trace(err)
	}
	modelQuery, closer1, err := st.modelQueryForUser(user, isSuperuser)
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer closer1()
	modelQuery.Select(bson.M{"_id": 1, "name": 1, "owner": 1, "type": 1})
	var accessInfo []ModelAccessInfo
	if err := modelQuery.All(&accessInfo); err != nil {
		return nil, errors.Trace(err)
	}
	// Now we need to find the last-connection time for each model for this user
	username := user.Id()
	connDocIds := make([]string, len(accessInfo))
	for i, acc := range accessInfo {
		connDocIds[i] = acc.UUID + ":" + username
	}
	lastConnections, closer2 := st.db().GetRawCollection(modelUserLastConnectionC)
	defer closer2()
	query := lastConnections.Find(bson.M{"_id": bson.M{"$in": connDocIds}})
	query.Select(bson.M{"last-connection": 1, "_id": 0, "model-uuid": 1})
	query.Batch(100)
	iter := query.Iter()
	lastConns := make(map[string]time.Time, len(connDocIds))
	var connInfo modelUserLastConnectionDoc
	for iter.Next(&connInfo) {
		lastConns[connInfo.ModelUUID] = connInfo.LastConnection
	}
	if err := iter.Close(); err != nil {
		return nil, errors.Trace(err)
	}
	for i := range accessInfo {
		uuid := accessInfo[i].UUID
		accessInfo[i].LastConnection = lastConns[uuid]
	}
	return accessInfo, nil
}
992959
func checkAndInitDBPriv(ctx sessionctx.Context, dbName string, is infoschema.InfoSchema, user string, host string) error {
	ok, err := dbUserExists(ctx, user, host, dbName)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}
	// Entry does not exist for user-host-db. Insert a new entry.
	return initDBPrivEntry(ctx, user, host, dbName)
}
1272999
func (p *Pool) refreshRefreshables(ctx context.Context) {
	for _, r := range p.refreshables {
		r.Refresh(ctx)
	}
}
544645
func RefreshUser(host, token string) (*map[string]interface{}, error) {
	path := variables.APIPathRefreshUser
	return GenericRequest(host, path, token, nil)
}
499145
func (s *AccessTokenSession) TokenFunc(retried bool) (string, error) {
	if !s.token.IsValid() || retried {
		refreshToken, refreshable := s.token.(RefreshableAccessToken)
		if !refreshable {
			return "", errors.New("not a refresh token")
		}

		tokenResp, err := s.uaa.RefreshTokenGrant(refreshToken.RefreshValue())
		if err != nil {
			return "", bosherr.WrapError(err, "refreshing token")
		}

		s.token = tokenResp
		if err = s.saveTokenCreds(); err != nil {
			return "", err
		}
	}

	return s.token.Type() + " " + s.token.Value(), nil
}
144861
func (u *modelUserEntity) Refresh() error {
	if u.user == nil {
		return nil
	}
	return u.user.Refresh()
}