// WaitForService waits until the service appears (exist == true), or disappears (exist == false)
493666
func WaitForService(c kubernetes.Interface, namespace, name string, exist bool, interval, timeout time.Duration) error {
	err := wait.PollImmediate(interval, timeout, func() (bool, error) {
		_, err := c.Core().Services(namespace).Get(name, metav1.GetOptions{})
		switch {
		case err == nil:
			glog.Infof("Service %s in namespace %s found.", name, namespace)
			return exist, nil
		case apierrs.IsNotFound(err):
			glog.Infof("Service %s in namespace %s disappeared.", name, namespace)
			return !exist, nil
		case !IsRetryableAPIError(err):
			glog.Info("Non-retryable failure while getting service.")
			return false, err
		default:
			glog.Infof("Get service %s in namespace %s failed: %v", name, namespace, err)
			return false, nil
		}
	})
	if err != nil {
		stateMsg := map[bool]string{true: "to appear", false: "to disappear"}
		return fmt.Errorf("error waiting for service %s/%s %s: %v", namespace, name, stateMsg[exist], err)
	}
	return nil
}
1024000
func WaitForEvent(c kubernetes.Interface, ns string, reason string) error {
	return wait.PollImmediate(constants.APICallRetryInterval, ReasonableMutateTime, func() (bool, error) {
		events, err := c.Events().Events("default").List(metav1.ListOptions{})
		if err != nil {
			glog.Infof("error getting events: %v", err)
			return false, nil
		}
		for _, e := range events.Items {
			if e.Reason == reason {
				return true, nil
			}
		}
		return false, nil
	})
}
911031
func (s *Server) WaitService(request *WaitServiceRequest, throwaway *string) error {
	err := s.f.WaitService(s.context(), request.State, request.Timeout, request.Recursive, request.ServiceIDs...)
	return err
}
940993
func (s *BatchServiceStateManager) Wait(tenantID string) {
	s.lock.RLock()
	var wg sync.WaitGroup
	for _, queue := range s.TenantQueues[tenantID] {
		wg.Add(1)
		go func(q *ServiceStateQueue) {
			s.drainQueue(q)
			wg.Done()
		}(queue)
	}
	s.lock.RUnlock()
	wg.Wait()
}
1224325
func (s Service) WaitForStatus(wait time.Duration, delay time.Duration) (*ServiceStatus, error) {
	s.log.Info("Waiting for %s to be loaded...", s.label)
	return waitForStatus(wait, delay, s.LoadStatus)
}
105593
func (client *Client) WaitForAssembly(ctx context.Context, assembly *AssemblyInfo) (*AssemblyInfo, error) {
	for {
		res, err := client.GetAssembly(ctx, assembly.AssemblySSLURL)
		if err != nil {
			return nil, err
		}

		// Abort polling if the assembly has entered an error state
		if res.Error != "" {
			return res, nil
		}

		// The polling is done if the assembly is not uploading or executing anymore.
		if res.Ok != "ASSEMBLY_UPLOADING" && res.Ok != "ASSEMBLY_EXECUTING" {
			return res, nil
		}

		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-time.After(time.Second):
			continue
		}
	}
}
122286
func (c *Conn) WaitForNotification(ctx context.Context) (notification *Notification, err error) {
	// Return already received notification immediately
	if len(c.notifications) > 0 {
		notification := c.notifications[0]
		c.notifications = c.notifications[1:]
		return notification, nil
	}

	err = c.waitForPreviousCancelQuery(ctx)
	if err != nil {
		return nil, err
	}

	err = c.initContext(ctx)
	if err != nil {
		return nil, err
	}
	defer func() {
		err = c.termContext(err)
	}()

	if err = c.lock(); err != nil {
		return nil, err
	}
	defer func() {
		if unlockErr := c.unlock(); unlockErr != nil && err == nil {
			err = unlockErr
		}
	}()

	if err := c.ensureConnectionReadyForQuery(); err != nil {
		return nil, err
	}

	for {
		msg, err := c.rxMsg()
		if err != nil {
			return nil, err
		}

		err = c.processContextFreeMsg(msg)
		if err != nil {
			return nil, err
		}

		if len(c.notifications) > 0 {
			notification := c.notifications[0]
			c.notifications = c.notifications[1:]
			return notification, nil
		}
	}
}
691983
func (svc *googleService) waitForOperationReady(operation string) error {
	return waitForOperation(OperationTimeout, func() (*googlecloud.Operation, error) {
		return svc.service.ZoneOperations.Get(svc.vm.Project, svc.vm.Zone, operation).Do()
	})
}
269899
func (e *Endpoint) WaitForProxyCompletions(proxyWaitGroup *completion.WaitGroup) error {
	if proxyWaitGroup == nil {
		return nil
	}

	err := proxyWaitGroup.Context().Err()
	if err != nil {
		return fmt.Errorf("context cancelled before waiting for proxy updates: %s", err)
	}

	start := time.Now()

	e.getLogger().Debug("Waiting for proxy updates to complete...")
	err = proxyWaitGroup.Wait()
	if err != nil {
		return fmt.Errorf("proxy state changes failed: %s", err)
	}
	e.getLogger().Debug("Wait time for proxy updates: ", time.Since(start))

	return nil
}
408153
func (f *Facade) WaitService(ctx datastore.Context, dstate service.DesiredState, timeout time.Duration, recursive bool, serviceIDs ...string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.WaitService"))
	glog.V(4).Infof("Facade.WaitService (%s)", dstate)

	// error out if the desired state is invalid
	if dstate.String() == "unknown" {
		return fmt.Errorf("desired state unknown")
	}

	// waitstatus is the return result for the awaiting service
	type waitstatus struct {
		ServiceID string
		Err       error
	}

	cancel := make(chan interface{})
	processing := make(map[string]struct{})
	done := make(chan waitstatus)
	defer close(cancel)

	waitSvcIds := make([]string, len(serviceIDs))
	copy(waitSvcIds, serviceIDs)
	if recursive {
		// Get all child services
		for _, svcID := range serviceIDs {
			childSvcs, err := f.GetServiceList(ctx, svcID)
			if err != nil {
				return err
			}
			for _, childSvc := range childSvcs {
				waitSvcIds = append(waitSvcIds, childSvc.ID)
			}
		}
	}
	for _, serviceID := range waitSvcIds {
		// spawn a goroutine to wait for each particular service
		svc, err := f.GetService(ctx, serviceID)
		if err != nil {
			glog.Errorf("Error while getting service %s: %s", serviceID, err)
			return err
		}
		processing[svc.ID] = struct{}{}
		go func(s *service.Service) {
			err := f.zzk.WaitService(s, dstate, cancel)
			// this blocks until we pass a waitstatus object into the channel or we get a signal to cancel
			select {
			case done <- waitstatus{s.ID, err}:
			case <-cancel:
			}
			glog.V(1).Infof("Finished waiting for %s (%s) to %s: %s", s.Name, s.ID, dstate, err)
		}(svc)
	}

	timeoutC := time.After(timeout)
	for len(processing) > 0 {
		// wait for all the services to return within the desired timeout
		select {
		case result := <-done:
			delete(processing, result.ServiceID)
			if result.Err != nil {
				glog.Errorf("Error while waiting for service %s to %s: %s", result.ServiceID, dstate, result.Err)
				return result.Err
			}
		case <-timeoutC:
				errMessage := "Timeout waiting for services"
				for svcID := range processing {
					s, err := f.GetService(ctx, svcID)
					errMessage += fmt.Sprintf("\n%v id:%v", s.Name, svcID)
					if err != nil {
						glog.Errorf(errMessage + "\nError while getting service %s: %s", svcID, err)
						return err
					}
				}
				return fmt.Errorf(errMessage)
		}
	}

	return nil
}
873008
func waitForFile(p string, to time.Duration) []error {
	done := time.After(to)
	for {
		select {
		case <-done:
			return []error{
				fmt.Errorf("timed out waiting for %s", p),
			}
		case <-time.After(1):
			if ok, _ := fileExists(p); ok {
				return nil
			}
		}
	}
}
260885
func waitForOperation(timeout int, funcOperation func() (*googlecloud.Operation, error)) error {
	var op *googlecloud.Operation
	var err error

	for i := 0; i < timeout; i++ {
		op, err = funcOperation()
		if err != nil {
			return err
		}

		if op.Status == "DONE" {
			if op.Error != nil {
				return fmt.Errorf("operation error: %v", *op.Error.Errors[0])
			}
			return nil
		}
		time.Sleep(1 * time.Second)
	}

	return fmt.Errorf("operation timeout, operations status: %v", op.Status)
}
99029
func WaitForResume() chan struct{} {
	ch := make(chan struct{})
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		ticker := time.NewTicker(10 * time.Millisecond)
		t := time.Now()
		wg.Done()
		for {
			now := <-ticker.C
			if now.Sub(t) > 100*time.Millisecond {
				break
			}
			t = now
		}
		ticker.Stop()
		ch <- struct{}{}
	}()
	wg.Wait()
	return ch
}
427685
func waitForClusterOp(client automationservicepb.AutomationClient, id string) (*automationpb.GetClusterOperationDetailsResponse, error) {
	for {
		req := &automationpb.GetClusterOperationDetailsRequest{
			Id: id,
		}

		resp, err := client.GetClusterOperationDetails(context.Background(), req, grpc.FailFast(false))
		if err != nil {
			return nil, fmt.Errorf("failed to get ClusterOperation Details. Request: %v Error: %v", req, err)
		}

		switch resp.ClusterOp.State {
		case automationpb.ClusterOperationState_UNKNOWN_CLUSTER_OPERATION_STATE:
			return resp, fmt.Errorf("ClusterOperation is in an unknown state. Details: %v", resp)
		case automationpb.ClusterOperationState_CLUSTER_OPERATION_DONE:
			if resp.ClusterOp.Error != "" {
				return resp, fmt.Errorf("ClusterOperation failed. Details:\n%v", proto.MarshalTextString(resp))
			}
			return resp, nil
		}

		time.Sleep(50 * time.Millisecond)
	}
}
721496
func (p *tchannelPeer) waitForChange() (changed bool) {
	select {
	case <-p.changed:
		return true
	case <-p.released:
		return false
	case <-p.transport.once.Stopping():
		return false
	}
}
418948
func waitOnService(ctx context.Context, dockerCli command.Cli, serviceID string, quiet bool) error {
	errChan := make(chan error, 1)
	pipeReader, pipeWriter := io.Pipe()

	go func() {
		errChan <- progress.ServiceProgress(ctx, dockerCli.Client(), serviceID, pipeWriter)
	}()

	if quiet {
		go io.Copy(ioutil.Discard, pipeReader)
		return <-errChan
	}

	err := jsonmessage.DisplayJSONMessagesToStream(pipeReader, dockerCli.Out(), nil)
	if err == nil {
		err = <-errChan
	}
	return err
}
1210675
func (self *Commands) WaitFor(event string, args *WaitForArgs) error {
	if args == nil {
		args = &WaitForArgs{}
	}

	defaults.SetDefaults(args)
	args.Timeout = utils.FudgeDuration(args.Timeout)

	if waiter, err := self.browser.Tab().CreateEventWaiter(event); err == nil {
		defer waiter.Remove()

		// wait for the first event matching the given pattern
		_, err := waiter.Wait(args.Timeout)
		return err
	} else {
		return err
	}
}