// waitForChange waits for the transport to send a peer connection status
// change notification, but exits early if the transport releases the peer or
// stops.  waitForChange returns whether it is resuming due to a connection
// status change event.
354493
func (p *httpPeer) waitForChange() (changed bool) {
	// Wait for a connection status change
	select {
	case <-p.changed:
		return true
	case <-p.released:
		return false
	}
}
1175172
func (r *controller) Wait(pctx context.Context) error {
	if err := r.checkClosed(); err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(pctx)
	defer cancel()

	healthErr := make(chan error, 1)
	go func() {
		ectx, cancel := context.WithCancel(ctx) // cancel event context on first event
		defer cancel()
		if err := r.checkHealth(ectx); err == ErrContainerUnhealthy {
			healthErr <- ErrContainerUnhealthy
			if err := r.Shutdown(ectx); err != nil {
				log.G(ectx).WithError(err).Debug("shutdown failed on unhealthy")
			}
		}
	}()

	waitC, err := r.adapter.wait(ctx)
	if err != nil {
		return err
	}

	if status := <-waitC; status.ExitCode() != 0 {
		exitErr := &exitError{
			code: status.ExitCode(),
		}

		// Set the cause if it is knowable.
		select {
		case e := <-healthErr:
			exitErr.cause = e
		default:
			if status.Err() != nil {
				exitErr.cause = status.Err()
			}
		}

		return exitErr
	}

	return nil
}
1024932
func waitForProcess(ctx context.Context, process *process, p *os.Process, s *service) {
	pid := uint32(p.Pid)

	// Store the default non-exited value for calls to stat
	process.exit.Store(&processExit{
		pid:        pid,
		exitStatus: 255,
		exitedAt:   time.Time{},
		exitErr:    nil,
	})

	var status int
	processState, eerr := p.Wait()
	if eerr != nil {
		status = 255
		p.Kill()
	} else {
		status = processState.Sys().(syscall.WaitStatus).ExitStatus()
	}

	now := time.Now()
	process.exit.Store(&processExit{
		pid:        pid,
		exitStatus: uint32(status),
		exitedAt:   now,
		exitErr:    eerr,
	})

	// Wait for the relay
	process.relay.wait()

	// Wait for the started event to fire if it hasn't already
	process.startedWg.Wait()

	// We publish the exit before freeing upstream so that the exit event always
	// happens before any delete event.
	s.publisher.Publish(
		ctx,
		runtime.TaskExitEventTopic,
		&eventstypes.TaskExit{
			ContainerID: process.cid,
			ID:          process.id,
			Pid:         pid,
			ExitStatus:  uint32(status),
			ExitedAt:    now,
		})

	// close the client io, and free upstream waiters
	process.close()
}
1079365
func (s *ChangesService) SubmitChange(changeID string, input *SubmitInput) (*ChangeInfo, *Response, error) {
	return s.change("submit", changeID, input)
}
120786
func (c *Client) GetChange(statusID string) (*GetChangeResponse, error) {
	requestURL := fmt.Sprintf("%s/%s/change/%s", c.BaseURL, apiVersion, statusID)

	req, err := http.NewRequest(http.MethodGet, requestURL, nil)
	if err != nil {
		return nil, err
	}

	err = c.sign(req)
	if err != nil {
		return nil, fmt.Errorf("an error occurred during the creation of the signature: %v", err)
	}

	res, err := c.HTTPClient.Do(req)
	if err != nil {
		return nil, err
	}
	if res.Body == nil {
		return nil, errors.New("the response body is nil")
	}

	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		errResp := &ErrorResponse{}
		err = xml.NewDecoder(res.Body).Decode(errResp)
		if err != nil {
			return nil, fmt.Errorf("an error occurred while unmarshaling the error body to XML: %v", err)
		}

		return nil, fmt.Errorf("an error occurred: %s", errResp.Error.Message)
	}

	output := &GetChangeResponse{}
	err = xml.NewDecoder(res.Body).Decode(output)
	if err != nil {
		return nil, fmt.Errorf("an error occurred while unmarshaling the response body to XML: %v", err)
	}

	return output, nil
}
856905
func (client *Client) WaitForInstance(instanceId string, status InstanceStatus, timeout int) error {
	if timeout <= 0 {
		timeout = InstanceDefaultTimeout
	}
	for {
		instance, err := client.DescribeInstanceAttribute(instanceId)
		if err != nil {
			return err
		}
		if instance.Status == status {
			//TODO
			//Sleep one more time for timing issues
			time.Sleep(DefaultWaitForInterval * time.Second)
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)

	}
	return nil
}
1200237
func (fbo *folderBranchOps) PushConnectionStatusChange(service string, newStatus error) {
	switch service {
	case KeybaseServiceName, GregorServiceName:
	default:
		return
	}

	if newStatus != nil {
		return
	}

	monitoringCh := fbo.getEditMonitoringChannel()
	if monitoringCh == nil {
		return
	}

	fbo.vlog.CLogf(
		nil, libkb.VLog1, "Asking for an edit re-init after reconnection")
	fbo.editActivity.Add(1)
	select {
	case fbo.editChannels <- editChannelActivity{nil, "", ""}:
	case <-monitoringCh:
		fbo.editActivity.Done()
		fbo.log.CDebugf(nil, "Edit monitoring stopped while trying to "+
			"ask for a re-init")
	}
}
555138
func (pf *PortForwarder) waitForConnection(listener net.Listener, port ForwardedPort) {
	for {
		conn, err := listener.Accept()
		if err != nil {
			// TODO consider using something like https://github.com/hydrogen18/stoppableListener?
			if !strings.Contains(strings.ToLower(err.Error()), "use of closed network connection") {
				runtime.HandleError(fmt.Errorf("Error accepting connection on port %d: %v", port.Local, err))
			}
			return
		}
		go pf.handleConnection(conn, port)
	}
}
1209402
func (d *ResourceData) HasChange(key string) bool {
	o, n := d.GetChange(key)

	// If the type implements the Equal interface, then call that
	// instead of just doing a reflect.DeepEqual. An example where this is
	// needed is *Set
	if eq, ok := o.(Equal); ok {
		return !eq.Equal(n)
	}

	return !reflect.DeepEqual(o, n)
}
1110541
func NewChangeWatchResp(ctx context.Context, message *DataChangeRequest, callback func(error)) *ChangeEvent {
	return &ChangeEvent{
		ctx:     ctx,
		changes: []datasync.ProtoWatchResp{
			&ChangeWatchResp{message: message},
		},
		callback: callback,
	}
}
897462
func (client *Client) WaitForVSwitchAvailable(vpcId string, vswitchId string, timeout int) error {
	if timeout <= 0 {
		timeout = DefaultTimeout
	}
	args := DescribeVSwitchesArgs{
		VpcId:     vpcId,
		VSwitchId: vswitchId,
	}
	for {
		vswitches, _, err := client.DescribeVSwitches(&args)
		if err != nil {
			return err
		}
		if len(vswitches) == 0 {
			return common.GetClientErrorFromString("Not found")
		}
		if vswitches[0].Status == VSwitchStatusAvailable {
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)
	}
	return nil
}
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
}
781281
func (wg *WaitGroup) WaitFor(timeout time.Duration) bool {
	if timeout == time.Duration(0) {
		wg.Wait()
		return true // ### return, always true ###
	}

	start := time.Now()
	spin := NewSpinner(SpinPriorityHigh)
	for wg.Active() {
		if time.Since(start) > timeout {
			return false // ### return, timed out ###
		}
		spin.Yield()
	}
	return true
}
619116
func (s *ReindexService) WaitForCompletion(waitForCompletion bool) *ReindexService {
	s.waitForCompletion = &waitForCompletion
	return s
}
33756
func (c *ConnectionManager) WaitForClientType(clientType keybase1.ClientType, timeout time.Duration) bool {
	if c.hasClientType(clientType) {
		return true
	}
	ticker := time.NewTicker(time.Second)
	deadline := time.After(timeout)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			if c.hasClientType(clientType) {
				return true
			}
		case <-deadline:
			return false
		}
	}
}
396979
func (s *Store) WaitForLeader(timeout time.Duration) (string, error) {
	tck := time.NewTicker(leaderWaitDelay)
	defer tck.Stop()
	tmr := time.NewTimer(timeout)
	defer tmr.Stop()

	for {
		select {
		case <-tck.C:
			l := s.LeaderAddr()
			if l != "" {
				return l, nil
			}
		case <-tmr.C:
			return "", fmt.Errorf("timeout expired")
		}
	}
}
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
}