// parseWaitCmd makes sure that the parsed node's timeout and 'recursive'
// marker, if they exist, are valid
// SVC_WAIT <svcs>+ (started|stopped|paused) (<timeout>|recursive)? (recursive)?
779773
func parseWaitCmd(parser lineParser) lineParser {
	return func(ctx *parseContext, cmd string, args []string) (node, error) {
		n, err := parser(ctx, cmd, args)
		if err == nil {
			// At this point, we're guaranteed to have a valid set of args
			stateIdx := -1
			for i, arg := range args {
				if arg == "started" || arg == "stopped" || arg == "paused" {
					stateIdx = i
					break
				}
			}
			// Parse timeout/'recursive' value if exists
			if len(args) > stateIdx+1 && (strings.Trim(args[stateIdx+1], "1234567890") != "" && args[stateIdx+1] != "recursive") {
				return node{}, fmt.Errorf("line %d: expected integer timeout; got %s", ctx.lineNum, args[stateIdx+1])
			}
			// Parse 'recursive' arg
			if len(args) == stateIdx+3 && args[stateIdx+2] != "recursive" {
				return node{}, fmt.Errorf("line %d: invalid string for recursive identifier: %s", ctx.lineNum, args[stateIdx+2])
			}
		}
		return n, err
	}
}
753197
func (s *blockDiskStore) startOpOrWait(id kbfsblock.ID) (
	closeCh chan<- struct{}, waitCh <-chan struct{}) {
	s.lock.Lock()
	defer s.lock.Unlock()

	waitCh = s.puts[id]
	if waitCh == nil {
		// If this caller is getting exclusive access to this `id`,
		// make a channel, store it as receive-only in `puts`, and
		// return it as send-only to the caller, to ensure that only
		// this caller can finish the exclusive access.
		ch := make(chan struct{})
		s.puts[id] = ch
		closeCh = ch
	}

	return closeCh, waitCh
}
573695
func (s *TasksGetTaskService) WaitForCompletion(waitForCompletion bool) *TasksGetTaskService {
	s.waitForCompletion = &waitForCompletion
	return s
}
1115842
func getWaitTime(now time.Time, maxWait time.Duration) time.Duration {
	wait := nextProvision.Sub(now) // might be negative

	// When the system clock falls back an hour, the wait time might be an hour.
	// This sanity check prevents this error.
	if wait > maxWait {
		return maxWait
	}
	if wait < 0 {
		return 0
	}
	return wait
}
1163601
func (v *Future) GetWaitTimeout(t time.Duration) (bool, interface{}) {
	select {
	case <-v.signal:
		return true, v.result
	case <-time.After(t):
		return false, nil
	}
}
1232403
func startKubectlWaitCmd(resourceNamespace string, resourceName string) (*exec.Cmd, *bufio.Reader, error) {
	args := []string{"get", resourceName, "-w", "-o", "json"}
	if resourceNamespace != "" {
		args = append(args, "-n", resourceNamespace)
	}
	cmd := exec.Command("kubectl", args...)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, nil, errors.InternalWrapError(err)
	}
	reader := bufio.NewReader(stdout)
	log.Info(strings.Join(cmd.Args, " "))
	if err := cmd.Start(); err != nil {
		return nil, nil, errors.InternalWrapError(err)
	}

	return cmd, reader, nil
}
933698
func (p *Project) StopWithTimeout(c *check.C, containerID string, timeout int) {
	c.Assert(p.project.StopWithTimeout(containerID, timeout), check.IsNil,
		check.Commentf("error while stopping container %s with timeout %d", containerID, timeout))
}
1224498
func (sem *Sem) TryWait() error {
	ret := int(C.SDL_SemTryWait(sem.cptr()))
	if ret != 0 {
		return GetError()
	}
	return nil
}
916851
func (v *vcsCmd) tagSync(dir, tag string) error {
	if v.tagSyncCmd == "" {
		return nil
	}
	if tag != "" {
		for _, tc := range v.tagLookupCmd {
			out, err := v.runOutput(dir, tc.cmd, "tag", tag)
			if err != nil {
				return err
			}
			re := regexp.MustCompile(`(?m-s)` + tc.pattern)
			m := re.FindStringSubmatch(string(out))
			if len(m) > 1 {
				tag = m[1]
				break
			}
		}
	}
	if tag == "" && v.tagSyncDefault != "" {
		return v.run(dir, v.tagSyncDefault)
	}
	return v.run(dir, v.tagSyncCmd, "tag", tag)
}
744346
func (zm *zMutex) LockWithTimeout(wait time.Duration, desc string) (err error) {
	timer := time.NewTimer(wait)
	defer func() {
		if panicErr := recover(); panicErr != nil || err != nil {
			zm.deleteLock()
		}
	}()
	// Ensure the rendezvous node is here.
	// FIXME(msolo) Assuming locks are contended, it will be cheaper to assume this just
	// exists.
	_, err = zkhelper.CreateRecursive(zm.zconn, zm.path, "", 0, zk.WorldACL(zkhelper.PERM_DIRECTORY))
	if err != nil && !zkhelper.ZkErrorEqual(err, zk.ErrNodeExists) {
		return err
	}

	lockPrefix := path.Join(zm.path, "lock-")
	zflags := zk.FlagSequence
	if zm.ephemeral {
		zflags = zflags | zk.FlagEphemeral
	}

	// update node content
	var lockContent map[string]interface{}
	err = json.Unmarshal([]byte(zm.contents), &lockContent)
	if err != nil {
		return err
	}
	lockContent["desc"] = desc
	newContent, err := json.Marshal(lockContent)
	if err != nil {
		return err
	}

createlock:
	lockCreated, err := zm.zconn.Create(lockPrefix, newContent, int32(zflags), zk.WorldACL(zkhelper.PERM_FILE))
	if err != nil {
		return err
	}
	name := path.Base(lockCreated)
	zm.mu.Lock()
	zm.name = name
	zm.mu.Unlock()

trylock:
	children, _, err := zm.zconn.Children(zm.path)
	if err != nil {
		return fmt.Errorf("zkutil: trylock failed %v", err)
	}
	sort.Strings(children)
	if len(children) == 0 {
		return fmt.Errorf("zkutil: empty lock: %v", zm.path)
	}

	if children[0] == name {
		// We are the lock owner.
		return nil
	}

	if zm.onRetryLock != nil {
		zm.onRetryLock()
	}

	// This is the degenerate case of a nonblocking lock check. It's not optimal, but
	// also probably not worth optimizing.
	if wait == 0 {
		return zkhelper.ErrTimeout
	}
	prevLock := ""
	for i := 1; i < len(children); i++ {
		if children[i] == name {
			prevLock = children[i-1]
			break
		}
	}
	if prevLock == "" {
		// This is an interesting case. The node disappeared
		// underneath us, probably due to a session loss. We can
		// recreate the lock node (with a new sequence number) and
		// keep trying.
		log.Warnf("zkutil: no lock node found: %v/%v", zm.path, zm.name)
		goto createlock
	}

	zkPrevLock := path.Join(zm.path, prevLock)
	exist, stat, watch, err := zm.zconn.ExistsW(zkPrevLock)
	if err != nil {
		// FIXME(msolo) Should this be a retry?
		return fmt.Errorf("zkutil: unable to watch previous lock node %v %v", zkPrevLock, err)
	}
	if stat == nil || !exist {
		goto trylock
	}
	select {
	case <-timer.C:
		return zkhelper.ErrTimeout
	case <-zm.interrupted:
		return zkhelper.ErrInterrupted
	case event := <-watch:
		log.Infof("zkutil: lock event: %v", event)
		// The precise event doesn't matter - try to read again regardless.
		goto trylock
	}
	panic("unexpected")
}
1357490
func (db *DB) compTriggerWait(compC chan<- cCmd) (err error) {
	ch := make(chan error)
	defer close(ch)
	// Send cmd.
	select {
	case compC <- cAuto{ch}:
	case err = <-db.compErrC:
		return
	case <-db.closeC:
		return ErrClosed
	}
	// Wait cmd.
	select {
	case err = <-ch:
	case err = <-db.compErrC:
	case <-db.closeC:
		return ErrClosed
	}
	return err
}
326524
func ReadWait(readWait time.Duration) func(*WSClient) {
	return func(c *WSClient) {
		c.readWait = readWait
	}
}
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
}
1199081
func (e *Element) WaitForReady() error {
	e.lock.RLock()
	ready := e.ready
	e.lock.RUnlock()

	if ready {
		return nil
	}

	timeout := time.NewTimer(e.tab.elementTimeout)
	defer timeout.Stop()

	select {
	case <-e.readyGate:
		return nil
	case <-timeout.C:
		return &ElementNotReadyErr{}
	}
}
426774
func (pool *SimplePool) DoWithTimeout(req *http.Request,
	timeout time.Duration) (resp *http.Response, err error) {
	return pool.DoWithParams(req, DoParams{Timeout: timeout})
}
1046211
func WaitFunc(wait func(context.Context, *cdp.Frame, ...cdp.NodeID) ([]*cdp.Node, error)) QueryOption {
	return func(s *Selector) {
		s.wait = wait
	}
}
755119
func WaitForTermination(c KubernetesClientInterface, containerID string, timeout time.Duration) error {
	ticker := time.NewTicker(time.Second * 1)
	defer ticker.Stop()
	timer := time.NewTimer(timeout)
	if timeout == 0 {
		timer.Stop()
	} else {
		defer timer.Stop()
	}

	log.Infof("Starting to wait completion of containerID %s ...", containerID)
	for {
		select {
		case <-ticker.C:
			_, containerStatus, err := c.GetContainerStatus(containerID)
			if err != nil {
				return err
			}
			if containerStatus.State.Terminated == nil {
				continue
			}
			log.Infof("ContainerID %q is terminated: %v", containerID, containerStatus.String())
			return nil
		case <-timer.C:
			return fmt.Errorf("timeout after %s", timeout.String())
		}
	}
}