// WaitUntilInstanceProfileExists uses the IAM API operation
// GetInstanceProfile to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
185613
func (c *IAM) WaitUntilInstanceProfileExists(input *GetInstanceProfileInput) error {
	return c.WaitUntilInstanceProfileExistsWithContext(aws.BackgroundContext(), input)
}
35677
func (e Endpoints) GetProfile(ctx context.Context, id string) (Profile, error) {
	request := getProfileRequest{ID: id}
	response, err := e.GetProfileEndpoint(ctx, request)
	if err != nil {
		return Profile{}, err
	}
	resp := response.(getProfileResponse)
	return resp.Profile, resp.Err
}
679557
func waitAnyInstanceAddresses(
	env Environ,
	ctx context.ProviderCallContext,
	instanceIds []instance.Id,
) ([]network.Address, error) {
	var addrs []network.Address
	for a := AddressesRefreshAttempt.Start(); len(addrs) == 0 && a.Next(); {
		instances, err := env.Instances(ctx, instanceIds)
		if err != nil && err != ErrPartialInstances {
			logger.Debugf("error getting state instances: %v", err)
			return nil, err
		}
		addrs = getAddresses(ctx, instances)
	}
	if len(addrs) == 0 {
		return nil, errors.NotFoundf("addresses for %v", instanceIds)
	}
	return addrs, nil
}
323646
func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) (
	idx int,
	instance *instancePool,
	isDown bool,
	err error) {

	pool.lock.RLock()
	defer pool.lock.RUnlock()
	if len(pool.instanceList) == 0 {
		return 0, nil, false, errors.Newf("no available instances")
	}
	now := time.Now().Unix()
	numInstancesToTry := uint64(len(pool.instanceList))

	start := 0
	// map used to implement soft swapping to avoid picking the same instance multiple times
	// when we randomly pick instances for consistent-hashing. We could have used this actually
	// for the other strategies.
	// TODO(bashar): get rid of the random shuffle for the other strategies
	var idxMap map[int]int

	if pool.strategy == LBRoundRobin &&
		pool.activeSetSize < numInstancesToTry {
		numInstancesToTry = pool.activeSetSize
	} else if pool.strategy == LBConsistentHashing {

		// we must have a key
		if len(key) == 0 {
			return 0, nil, false, errors.Newf("key was not specified for consistent-hashing")
		} else if maxInstances <= 0 {
			return 0, nil, false, errors.Newf(
				"invalid maxInstances for consistent-hashing: %v", maxInstances)
		}

		// in case we're asked to try more than the number of servers we have
		if maxInstances > int(numInstancesToTry) {
			maxInstances = int(numInstancesToTry)
		}

		// let's find the closest server to start. We don't start from 0 in that case
		hash := pool.hashFunction(key, pool.hashSeed)
		// we need to find the closest server that hashes to >= hash.
		start = sort.Search(len(pool.instanceList), func(i int) bool {
			return pool.instanceHashes[i] >= hash
		})

		// In the case where hash > all elements, sort.Search returns len(pool.instanceList).
		// Hence, we mod the result
		start = start % len(pool.instanceHashes)

		idxMap = make(map[int]int)
	}

	for i := 0; uint64(i) < numInstancesToTry; i++ {
		switch pool.strategy {
		case LBRoundRobin:
			// In RoundRobin strategy instanceIdx keeps changing, to
			// achieve round robin load balancing.
			instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1)
			idx = int(instanceIdx % numInstancesToTry)
		case LBSortedFixed:
			// In SortedFixed strategy instances are always traversed in same
			// exact order.
			idx = i
		case LBShuffledFixed:
			// In ShuffledFixed strategy instances are also always traversed in
			// same exact order.
			idx = i
		case LBConsistentHashing:
			// In ConsistentHashing strategy instances are picked up randomly between
			// start and start + numInstancesToTry. This is to load balance between
			// the alive servers that are closest to the key in the hash space

			// consistent-hashing will prefer availability over consistency. In the case some
			// server is down, we will try new servers in the hash-ring. The way we do this is by
			// picking random instances next (excluding already picked instances). That's why we
			// do a 'soft-swap' between already picked instance and move the start offset by 1
			// every time. We don't touch the pool.instanceList to make sure we don't
			// screw up any order. The swap below guarantees that start always has an idx that
			// has never been tried before.
			newStart := i + start
			idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList)
			// we need to swap idxMap[newStart] with idxMap[idx] (or fill them).
			var ok bool
			if idxMap[idx], ok = idxMap[idx]; ok {
				idxMap[newStart] = idxMap[idx]
			} else {
				idxMap[newStart] = idx
			}
			idxMap[idx] = newStart

			// we need to pick the correct idx after the swap
			idx = idxMap[newStart]
		}

		if pool.markDownUntil[idx] < now {
			break
		}
	}
	return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil
}
731314
func (client *Client) WaitForInstance(instanceId string, status InstanceStatus, timeout int) error {
	if timeout <= 0 {
		timeout = InstanceDefaultTimeout
	}
	for {
		args := DescribeDBInstanceAttributeArgs{
			DBInstanceId: instanceId,
		}

		resp, err := client.DescribeDBInstanceAttribute(&args)
		if err != nil {
			return err
		}

		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}

		timeout = timeout - DefaultWaitForInterval
		time.Sleep(DefaultWaitForInterval * time.Second)

		if len(resp.Items.DBInstanceAttribute) < 1 {
			continue
		}
		instance := resp.Items.DBInstanceAttribute[0]
		if instance.DBInstanceStatus == status {
			break
		}

	}
	return nil
}
812543
func (c *MachineLearning) WaitUntilDataSourceAvailable(input *DescribeDataSourcesInput) error {
	return c.WaitUntilDataSourceAvailableWithContext(aws.BackgroundContext(), input)
}
941908
func callGetProfileService(email string) (rest.ResponseDTOWithProfile, apihelper.ApiErrors, int) {

	// call api
	req, err := http.NewRequest("GET", profileBaseUrl+"/"+email, nil)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// read response
	body, _ := ioutil.ReadAll(resp.Body)

	userWithProfile := rest.ResponseDTOWithProfile{}
	apiErrors := apihelper.ApiErrors{}
	json.Unmarshal(body, &userWithProfile)
	json.Unmarshal(body, &apiErrors)

	return userWithProfile, apiErrors, resp.StatusCode
}
880050
func checkPropsExist(loginDoc map[string]interface{}) error {
	// Make sure the user provides a username
	id, ok := loginDoc["username"].(string)
	if ok != true {
		return errors.New("Need username to login")
	} else if len(id) < variables.ShortestUsername {
		// FIXME: Make concatination constant
		return errors.New("Username must be at least " + strconv.Itoa(variables.ShortestUsername))
	}
	// Make sure the user provides a password
	password, ok := loginDoc["password"].(string)
	if ok != true {
		return errors.New("Need password to login")
	} else if len(password) < variables.ShortestPassword {
		// FIXME: Make concatination constant
		return errors.New("Password must be at least " + strconv.Itoa(variables.ShortestPassword))
	}
	return nil
}
635537
func (c *SageMaker) WaitUntilEndpointInService(input *DescribeEndpointInput) error {
	return c.WaitUntilEndpointInServiceWithContext(aws.BackgroundContext(), input)
}
83119
func (o *Once) WaitUntilRunning(ctx context.Context) error {
	state := State(o.state.Load())
	if state == Running {
		return nil
	}
	if state > Running {
		return yarpcerrors.FailedPreconditionErrorf("could not wait for instance to start running: current state is %q", getStateName(state))
	}

	if _, ok := ctx.Deadline(); !ok {
		return yarpcerrors.InvalidArgumentErrorf("could not wait for instance to start running: deadline required on request context")
	}

	select {
	case <-o.startCh:
		state := State(o.state.Load())
		if state == Running {
			return nil
		}
		return yarpcerrors.FailedPreconditionErrorf("instance did not enter running state, current state is %q", getStateName(state))
	case <-ctx.Done():
		return yarpcerrors.FailedPreconditionErrorf("context finished while waiting for instance to start: %s", ctx.Err().Error())
	}
}
457630
func (zk *zkf) WaitInstance(ctx datastore.Context, svc *service.Service, instanceID int, checkInstance func(*zks.State, bool) bool, cancel <-chan struct{}) error {
	logger := plog.WithFields(log.Fields{
		"serviceid":   svc.ID,
		"servicename": svc.Name,
		"poolid":      svc.PoolID,
	})

	// get the root-based connection
	rootconn, err := getLocalConnection(ctx, "/")
	if err != nil {
		logger.WithError(err).Debug("Could not acquire root-based connection")
		return err
	}

	// do wait
	errC := make(chan error)
	stop := make(chan struct{})
	go func() {
		errC <- zks.WaitInstance(stop, rootconn, svc.PoolID, svc.ID, instanceID, checkInstance)
	}()

	select {
	case err := <-errC:
		if err != nil {
			logger.WithError(err).Debug("Could not monitor the instance in zookeeper")
			return err
		}
		return err
	case <-cancel:
		close(stop)
		return <-errC
	}
}
1198455
func (d *driverOCI) WaitForInstanceState(ctx context.Context, id string, waitStates []string, terminalState string) error {
	return waitForResourceToReachState(
		func(string) (string, error) {
			instance, err := d.computeClient.GetInstance(ctx, core.GetInstanceRequest{InstanceId: &id})
			if err != nil {
				return "", err
			}
			return string(instance.LifecycleState), nil
		},
		id,
		waitStates,
		terminalState,
		0,             //Unlimited Retries
		5*time.Second, //5 second wait between retries
	)
}
407643
func (c *DynamoDB) WaitUntilTableExists(input *DescribeTableInput) error {
	return c.WaitUntilTableExistsWithContext(aws.BackgroundContext(), input)
}
737177
func (api *Client) GetUserProfile(userID string, includeLabels bool) (*UserProfile, error) {
	return api.GetUserProfileContext(context.Background(), userID, includeLabels)
}
776830
func (n *NetworkServerAPI) GetRoutingProfile(ctx context.Context, req *ns.GetRoutingProfileRequest) (*ns.GetRoutingProfileResponse, error) {
	var rpID uuid.UUID
	copy(rpID[:], req.Id)

	rp, err := storage.GetRoutingProfile(storage.DB(), rpID)
	if err != nil {
		return nil, errToRPCError(err)
	}

	resp := ns.GetRoutingProfileResponse{
		RoutingProfile: &ns.RoutingProfile{
			Id:      rp.ID.Bytes(),
			AsId:    rp.ASID,
			CaCert:  rp.CACert,
			TlsCert: rp.TLSCert,
		},
	}

	resp.CreatedAt, err = ptypes.TimestampProto(rp.CreatedAt)
	if err != nil {
		return nil, errToRPCError(err)
	}

	resp.UpdatedAt, err = ptypes.TimestampProto(rp.UpdatedAt)
	if err != nil {
		return nil, errToRPCError(err)
	}

	return &resp, nil
}
741396
func (s *Signer) getMatchingProfile(profile string) (*config.SigningProfile, error) {
	if profile == "" {
		return s.policy.Default, nil
	}

	for p, signingProfile := range s.policy.Profiles {
		if p == profile {
			return signingProfile, nil
		}
	}

	return nil, cferr.New(cferr.PolicyError, cferr.UnknownProfile)
}
918803
func (c *OpsWorks) WaitUntilInstanceTerminated(input *DescribeInstancesInput) error {
	return c.WaitUntilInstanceTerminatedWithContext(aws.BackgroundContext(), input)
}