// WaitForObservedDeployment polls for deployment to be updated so that deployment.Status.ObservedGeneration >= desiredGeneration.
// Returns error if polling timesout.
432873
func WaitForObservedDeployment(getDeploymentFunc func() (*apps.Deployment, error), desiredGeneration int64, interval, timeout time.Duration) error {
	// TODO: This should take clientset.Interface when all code is updated to use clientset. Keeping it this way allows the function to be used by callers who have client.Interface.
	return wait.PollImmediate(interval, timeout, func() (bool, error) {
		deployment, err := getDeploymentFunc()
		if err != nil {
			return false, err
		}
		return deployment.Status.ObservedGeneration >= desiredGeneration, nil
	})
}
265684
func (w *deploymentWatcher) getDeploymentStatusUpdate(status, desc string) *structs.DeploymentStatusUpdate {
	return &structs.DeploymentStatusUpdate{
		DeploymentID:      w.deploymentID,
		Status:            status,
		StatusDescription: desc,
	}
}
224829
func (s *DeploymentConfigStatusViewer) Status(obj runtime.Unstructured, desiredRevision int64) (string, bool, error) {
	config := &appsv1.DeploymentConfig{}
	err := scheme.Scheme.Convert(obj, config, nil)
	if err != nil {
		return "", false, fmt.Errorf("failed to convert %T to %T: %v", obj, config, err)
	}
	latestRevision := config.Status.LatestVersion

	if latestRevision == 0 {
		switch {
		case appsutil.HasImageChangeTrigger(config):
			return fmt.Sprintf("Deployment config %q waiting on image update\n", config.Name), false, nil

		case len(config.Spec.Triggers) == 0:
			return "", true, fmt.Errorf("Deployment config %q waiting on manual update (use 'oc rollout latest %s')", config.Name, config.Name)
		}
	}

	if desiredRevision > 0 && latestRevision != desiredRevision {
		return "", false, fmt.Errorf("desired revision (%d) is different from the running revision (%d)", desiredRevision, latestRevision)
	}

	cond := appsutil.GetDeploymentCondition(config.Status, appsv1.DeploymentProgressing)

	if config.Generation <= config.Status.ObservedGeneration {
		switch {
		case cond != nil && cond.Reason == appsutil.NewRcAvailableReason:
			return fmt.Sprintf("%s\n", cond.Message), true, nil

		case cond != nil && cond.Reason == appsutil.TimedOutReason:
			return "", true, errors.New(cond.Message)

		case cond != nil && cond.Reason == appsutil.CancelledRolloutReason:
			return "", true, errors.New(cond.Message)

		case cond != nil && cond.Reason == appsutil.PausedConfigReason:
			return "", true, fmt.Errorf("Deployment config %q is paused. Resume to continue watching the status of the rollout.\n", config.Name)

		case config.Status.UpdatedReplicas < config.Spec.Replicas:
			return fmt.Sprintf("Waiting for rollout to finish: %d out of %d new replicas have been updated...\n", config.Status.UpdatedReplicas, config.Spec.Replicas), false, nil

		case config.Status.Replicas > config.Status.UpdatedReplicas:
			return fmt.Sprintf("Waiting for rollout to finish: %d old replicas are pending termination...\n", config.Status.Replicas-config.Status.UpdatedReplicas), false, nil

		case config.Status.AvailableReplicas < config.Status.UpdatedReplicas:
			return fmt.Sprintf("Waiting for rollout to finish: %d of %d updated replicas are available...\n", config.Status.AvailableReplicas, config.Status.UpdatedReplicas), false, nil
		}
	}
	return fmt.Sprintf("Waiting for latest deployment config spec to be observed by the controller loop...\n"), false, nil
}
341158
func (d *Deployment) Wait(id string, timeout time.Duration, log log15.Logger) error {
	timeoutCh := time.After(timeout)
	for {
		actual := 0
		select {
		case event, ok := <-d.events:
			if !ok {
				return fmt.Errorf("service stream closed unexpectedly: %s", d.stream.Err())
			}
			if event.Kind == discoverd.EventKindServiceMeta {
				deploymentMeta, err := d.decode(event.ServiceMeta)
				if err != nil {
					return err
				}
				log.Info("got service meta event", "state", deploymentMeta)
				if deploymentMeta.ID == id {
					actual = 0
					for _, state := range deploymentMeta.States {
						if state == DeploymentStateDone {
							actual++
						}
					}
					if actual == d.jobCount {
						return nil
					}
				} else {
					log.Warn("ignoring service meta even with wrong ID", "expected", id, "got", deploymentMeta.ID)
				}

			}
		case <-timeoutCh:
			return fmt.Errorf("timed out waiting for discoverd deployment (expected=%d actual=%d)", d.jobCount, actual)
		}
	}
}
318775
func (client *Client) WaitForImageReady(regionId common.Region, imageId string, timeout int) error {
	if timeout <= 0 {
		timeout = ImageDefaultTimeout
	}
	for {
		args := DescribeImagesArgs{
			RegionId: regionId,
			ImageId:  imageId,
			Status:   ImageStatusCreating,
		}

		images, _, err := client.DescribeImages(&args)
		if err != nil {
			return err
		}
		if images == nil || len(images) == 0 {
			args.Status = ImageStatusAvailable
			images, _, er := client.DescribeImages(&args)
			if er == nil && len(images) == 1 {
				break
			} else {
				return common.GetClientErrorFromString("Not found")
			}
		}
		if images[0].Progress == "100%" {
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)
	}
	return nil
}
29625
func (wi *Instance) WaitForCommand(wrk Worker, done chan struct{}) error {
	// display the status every second
	timer := time.NewTicker(wi.commandDisplayInterval)
	defer timer.Stop()
	for {
		select {
		case <-done:
			log.Info(wrk.StatusAsText())
			wi.currentWorkerMutex.Lock()
			err := wi.lastRunError
			wi.currentWorkerMutex.Unlock()
			if err != nil {
				return err
			}
			return nil
		case <-timer.C:
			log.Info(wrk.StatusAsText())
		}
	}
}
1137215
func Wait(ctx context.Context, c *Collector, obj types.ManagedObjectReference, ps []string, f func([]types.PropertyChange) bool) error {
	filter := new(WaitFilter).Add(obj, obj.Type, ps)

	return WaitForUpdates(ctx, c, filter, func(updates []types.ObjectUpdate) bool {
		for _, update := range updates {
			if f(update.ChangeSet) {
				return true
			}
		}

		return false
	})
}
539447
func (pc *ProtoClient) waitForData() {
	for {
		select {
		case response := <-pc.Client.IncomingMsgChan:

			inputMsg := dynamic.NewMessage(pc.expectedInputDescriptor)

			msg, ok := pc.info.Commands[response.Route]
			if ok {
				inputMsg = dynamic.NewMessage(msg.outputMsgDescriptor)
			} else {
				pc.expectedInputDescriptor = nil
			}

			if response.Err {
				errMsg := &protos.Error{}
				err := proto.Unmarshal(response.Data, errMsg)
				if err != nil {
					logger.Log.Errorf("Erro decode error data: %s", string(response.Data))
					continue
				}
				response.Data, err = json.Marshal(errMsg)
				if err != nil {
					logger.Log.Errorf("Erro encode error to json: %s", string(response.Data))
					continue
				}
				pc.IncomingMsgChan <- response
				continue
			}

			if inputMsg == nil {
				logger.Log.Errorf("Not expected data: %s", string(response.Data))
				continue
			}

			err := inputMsg.Unmarshal(response.Data)
			if err != nil {
				logger.Log.Errorf("Erro decode data: %s", string(response.Data))
				continue
			}

			data, err2 := inputMsg.MarshalJSON()
			if err2 != nil {
				logger.Log.Errorf("Erro encode data to json: %s", string(response.Data))
				continue
			}

			response.Data = data
			pc.IncomingMsgChan <- response
		case <-pc.closeChan:
			return
		}
	}
}
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
}
212139
func (c *Glacier) WaitUntilVaultNotExists(input *DescribeVaultInput) error {
	return c.WaitUntilVaultNotExistsWithContext(aws.BackgroundContext(), input)
}
363942
func (client *Client) WaitForListener(loadBalancerId string, port int, listenerType ListenerType) (status ListenerStatus, err error) {
	timeout := DefaultTimeout

	args := &CommonLoadBalancerListenerArgs{
		LoadBalancerId: loadBalancerId,
		ListenerPort:   port,
	}

	method := fmt.Sprintf("DescribeLoadBalancer%sListenerAttribute", listenerType)
	response := &DescribeLoadBalancerListenerAttributeResponse{}

	for {
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return response.Status, common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)
		//Sleep first to ensure the previous request is sent
		err = client.Invoke(method, args, response)
		if err != nil {
			return "", err
		}
		if response.Status == Running || response.Status == Stopped {
			break
		}
	}
	return response.Status, nil
}
654248
func (client *Client) WaitForNetworkInterface(regionId common.Region, eniID string, status string, timeout int) error {
	if timeout <= 0 {
		timeout = NetworkInterfacesDefaultTimeout
	}
	for {

		eniIds := []string{eniID}

		describeNetworkInterfacesArgs := DescribeNetworkInterfacesArgs{
			RegionId:           regionId,
			NetworkInterfaceId: eniIds,
		}

		nisResponse, err := client.DescribeNetworkInterfaces(&describeNetworkInterfacesArgs)
		if err != nil {
			return fmt.Errorf("Failed to describe network interface %v: %v", eniID, err)
		}

		if len(nisResponse.NetworkInterfaceSets.NetworkInterfaceSet) > 0 && nisResponse.NetworkInterfaceSets.NetworkInterfaceSet[0].Status == status {
			break
		}

		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return fmt.Errorf("Timeout for waiting available status for network interfaces")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)

	}
	return nil
}
273483
func WaitForState(conf *StateChangeConf) (i interface{}, err error) {
	log.Printf("Waiting for state to become: %s", conf.Target)

	for {
		var currentProgress int
		var currentState string
		i, currentState, currentProgress, err = conf.Refresh()
		if err != nil {
			return
		}

		for _, t := range conf.Target {
			if currentState == t {
				return
			}
		}

		if conf.StepState != nil {
			if _, ok := conf.StepState.GetOk(multistep.StateCancelled); ok {
				return nil, errors.New("interrupted")
			}
		}

		found := false
		for _, allowed := range conf.Pending {
			if currentState == allowed {
				found = true
				break
			}
		}

		if !found {
			return nil, fmt.Errorf("unexpected state '%s', wanted target '%s'", currentState, conf.Target)
		}

		log.Printf("Waiting for state to become: %s currently %s (%d%%)", conf.Target, currentState, currentProgress)
		time.Sleep(2 * time.Second)
	}
}
1113210
func (rc *rawConn) waitOperation(projectID string, op *compute.Operation, attempts utils.AttemptStrategy) error {
	// TODO(perrito666) 2016-05-02 lp:1558657
	started := time.Now()
	logger.Infof("GCE operation %q, waiting...", op.Name)
	for a := attempts.Start(); a.Next(); {
		if op.Status == StatusDone {
			break
		}

		var err error
		op, err = rc.checkOperation(projectID, op)
		if err != nil {
			return errors.Trace(err)
		}
	}
	if op.Status != StatusDone {
		// lp:1558657
		err := errors.Errorf("timed out after %d seconds", time.Now().Sub(started)/time.Second)
		return waitError{op, err}
	}
	if op.Error != nil {
		for _, err := range op.Error.Errors {
			logger.Errorf("GCE operation error: (%s) %s", err.Code, err.Message)
		}
		return waitError{op, nil}
	}

	logger.Infof("GCE operation %q finished", op.Name)
	return nil
}
496455
func (w *deploymentWatcher) getDeployment() *structs.Deployment {
	w.l.RLock()
	defer w.l.RUnlock()
	return w.d
}
899247
func (vm *VM) WaitVMCreation(timeoutSeconds int, pollIntervalSeconds int) error {

	if vm.JobID == "" {
		return fmt.Errorf("No JobID informed. Cannot poll machine creation state")
	}

	jobCh := make(chan *egoscale.QueryAsyncJobResultResponse, 1)
	errCh := make(chan error, 1)

	go func() {
		params := url.Values{}
		params.Set("jobid", vm.JobID)

		for {
			client := vm.getExoClient()
			resp, err := client.Request("queryAsyncJobResult", params)
			if err != nil {
				errCh <- err
			}

			jobResult := &egoscale.QueryAsyncJobResultResponse{}
			err = json.Unmarshal(resp, jobResult)
			if err != nil {
				errCh <- err
			}

			if jobResult.Jobstatus == 1 {
				jobCh <- jobResult
				break
			}
			time.Sleep(time.Duration(pollIntervalSeconds) * time.Second)
		}
	}()

	select {
	case jobResult := <-jobCh:
		var vmWrap egoscale.DeployVirtualMachineWrappedResponse
		if err := json.Unmarshal(jobResult.Jobresult, &vmWrap); err != nil {
			return err
		}
		vm.ID = vmWrap.Wrapped.Id
	case err := <-errCh:
		return err
	case <-time.After(time.Duration(timeoutSeconds) * time.Second):
		return fmt.Errorf("Create VM Job has not completed after %d seconds", timeoutSeconds)
	}

	return nil
}
190526
func (client *Client) WaitForScalingGroup(regionId common.Region, groupId string, status LifecycleState, timeout int) error {
	if timeout <= 0 {
		timeout = DefaultWaitTimeout
	}
	for {
		sgs, _, err := client.DescribeScalingGroups(&DescribeScalingGroupsArgs{
			RegionId:       regionId,
			ScalingGroupId: []string{groupId},
		})
		if err != nil {
			return err
		}

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

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

		if len(sgs) < 1 {
			return common.GetClientErrorFromString("Not found")
		}
		if sgs[0].LifecycleState == status {
			break
		}

	}
	return nil
}