// WaitForStart delays until Docker appears to be up and running.
//
// Params:
// 	- client (*docker.Client): Docker client.
// 	- timeout (time.Duration): Time after which to give up.
//
// Returns:
// 	- boolean true if the server is up.
774152
func WaitForStart(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	if ok, missing := p.RequiresValue("client"); !ok {
		return nil, &cookoo.FatalError{"Missing required fields: " + strings.Join(missing, ", ")}
	}
	cli := p.Get("client", nil).(*docli.Client)
	timeout := p.Get("timeout", 30*time.Second).(time.Duration)

	keepon := true
	timer := time.AfterFunc(timeout, func() {
		keepon = false
	})

	for keepon == true {
		if err := cli.Ping(); err == nil {
			timer.Stop()
			log.Infof(c, "Docker is running.")
			return true, nil
		}
		time.Sleep(time.Second)
	}
	return false, fmt.Errorf("Docker timed out after waiting %s for server.", timeout)
}
1301642
func wait(epfd, eventfd int, timeout time.Duration) (bool, error) {
	events := make([]unix.EpollEvent, numFdEvents+1)
	timeoutMS := int(timeout / time.Millisecond)
	n, err := unix.EpollWait(epfd, events, timeoutMS)
	if n == -1 {
		if err == unix.EINTR {
			// Interrupt, ignore the error
			return false, nil
		}
		return false, err
	}
	if n == 0 {
		// Timeout
		return false, nil
	}
	if n > numFdEvents {
		return false, fmt.Errorf("epoll_wait returned more events than we know what to do with")
	}
	for _, event := range events[:n] {
		if event.Fd == int32(eventfd) {
			if event.Events&unix.EPOLLHUP != 0 || event.Events&unix.EPOLLERR != 0 || event.Events&unix.EPOLLIN != 0 {
				// EPOLLHUP: should not happen, but if it does, treat it as a wakeup.

				// EPOLLERR: If an error is waiting on the file descriptor, we should pretend
				// something is ready to read, and let unix.Read pick up the error.

				// EPOLLIN: There is data to read.
				return true, nil
			}
		}
	}
	// An event occurred that we don't care about.
	return false, nil
}
1302220
func (tt *timeoutThread) waitForEntry(e *entry) bool {
	windowExceeded := time.NewTimer(time.Until(e.deadline))
	defer windowExceeded.Stop()

	select {
	// a) Always check these channels, regardless of the state.
	case <-tt.maxDuration.C:
		// Max duration is up. Stop buffering. Do not error out entries explicitly.
		tt.sb.stopBufferingDueToMaxDuration()
		return true
	case <-tt.stopChan:
		// Failover ended before timeout. Do nothing.
		return true
	// b) Entry-specific checks.
	case <-e.done:
		// Entry was drained or evicted. Get the next entry.
		return false
	// NOTE: We're not waiting for e.bufferCtx here (which triggers when the
	// request was externally aborted e.g. due to context canceled) because then
	// this thread would race with the request thread which runs
	// shardBuffer.remove(). Instead, remove() will notify us here eventually by
	// closing "e.done".
	case <-windowExceeded.C:
		// Entry expired. Evict it and then get the next entry.
		tt.sb.evictOldestEntry(e)
		return false
	}
}
541173
func (t *Tab) WaitFor(rate, timeout time.Duration, conditionFn ConditionalFunc) error {
	rateTicker := time.NewTicker(rate)
	timeoutTimer := time.NewTimer(timeout)

	defer func() {
		timeoutTimer.Stop()
		rateTicker.Stop()
	}()

	for {
		select {
		case <-timeoutTimer.C:
			return &TimeoutErr{Message: "waiting for conditional func to return true"}
		case <-rateTicker.C:
			ret := conditionFn(t)
			if ret == true {
				return nil
			}
		}
	}
}
1331803
func (self *Commands) WaitForLoad(args *WaitForArgs) error {
	return self.WaitFor(WaitForLoadEventName, args)
}
751680
func (s *TasksListService) WaitForCompletion(waitForCompletion bool) *TasksListService {
	s.waitForCompletion = &waitForCompletion
	return s
}
304595
func (client *Client) WaitForInstanceAsyn(instanceId string, status InstanceStatus, timeout int) error {
	if timeout <= 0 {
		timeout = InstanceDefaultTimeout
	}
	for {
		instance, err := client.DescribeInstanceAttribute(instanceId)
		if err != nil {
			e, _ := err.(*common.Error)
			if e.Code != "InvalidInstanceId.NotFound" && e.Code != "Forbidden.InstanceNotFound" {
				return err
			}
		} else if instance != nil && instance.Status == status {
			//TODO
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)

	}
	return nil
}
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
}
323186
func (client *SSHClient) WaitForSSH(maxWait time.Duration) error {
	start := time.Now()

	for {
		if err := client.Connect(); err == nil {
			defer client.Disconnect()
			return nil
		}

		timePassed := time.Since(start)
		if timePassed >= maxWait {
			break
		}

		time.Sleep(5 * time.Second)
	}

	return ErrTimeout
}
248402
func waitForPath(pool, image string, maxRetries int, useNbdDriver bool) (string, bool) {
	for i := 0; i < maxRetries; i++ {
		if i != 0 {
			time.Sleep(time.Second)
		}
		if useNbdDriver {
			if devicePath, found := getNbdDevFromImageAndPool(pool, image); found {
				return devicePath, true
			}
		} else {
			if devicePath, found := getRbdDevFromImageAndPool(pool, image); found {
				return devicePath, true
			}
		}
	}
	return "", false
}
593511
func WaitForVolume(blockStorageClient *gophercloud.ServiceClient, volumeID string) error {
	maxNumErrors := 10
	numErrors := 0

	for {
		status, err := GetVolumeStatus(blockStorageClient, volumeID)
		if err != nil {
			errCode, ok := err.(*gophercloud.ErrUnexpectedResponseCode)
			if ok && (errCode.Actual == 500 || errCode.Actual == 404) {
				numErrors++
				if numErrors >= maxNumErrors {
					log.Printf("[ERROR] Maximum number of errors (%d) reached; failing with: %s", numErrors, err)
					return err
				}
				log.Printf("[ERROR] %d error received, will ignore and retry: %s", errCode.Actual, err)
				time.Sleep(2 * time.Second)
				continue
			}

			return err
		}

		if status == "available" {
			return nil
		}

		log.Printf("Waiting for volume creation status: %s", status)
		time.Sleep(2 * time.Second)
	}
}
75670
func (api *API) WaitForState(in ApiInstance, state string, sec time.Duration, count int) error {
	if in != nil {
		for i := 0; i < count; i++ {
			s, err := in.GetState()
			if err != nil {
				return err
			}
			if s == state {
				return nil
			}
			time.Sleep(sec * time.Second)
		}
		return errors.New(reflect.ValueOf(in).Type().String() + " operation timeout.")
	}
	return nil
}
437717
func (c *ContainerServer) ContainerWait(container string) (int32, error) {
	ctr, err := c.LookupContainer(container)
	if err != nil {
		return 0, errors.Wrapf(err, "failed to find container %s", container)
	}

	err = wait.PollImmediateInfinite(1,
		func() (bool, error) {
			return isStopped(c, ctr), nil
		},
	)

	if err != nil {
		return 0, err
	}
	exitCode := ctr.State().ExitCode
	c.ContainerStateToDisk(ctr)
	return exitCode, nil
}
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
}
253635
func (c *Client) AsyncStart() error {
	if err := c.Listen(); err != nil {
		return err
	}
	var started sync.WaitGroup
	started.Add(1)
	go func() {
		started.Done()
		c.Serve()
	}()
	started.Wait()
	return nil
}
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
}
116544
func (_m *APIClient) ContainerWait(ctx context.Context, _a1 string, condition container.WaitCondition) (<-chan container.ContainerWaitOKBody, <-chan error) {
	ret := _m.Called(ctx, _a1, condition)

	var r0 <-chan container.ContainerWaitOKBody
	if rf, ok := ret.Get(0).(func(context.Context, string, container.WaitCondition) <-chan container.ContainerWaitOKBody); ok {
		r0 = rf(ctx, _a1, condition)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(<-chan container.ContainerWaitOKBody)
		}
	}

	var r1 <-chan error
	if rf, ok := ret.Get(1).(func(context.Context, string, container.WaitCondition) <-chan error); ok {
		r1 = rf(ctx, _a1, condition)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(<-chan error)
		}
	}

	return r0, r1
}