// tried in succession and the first to succeed is returned. If none succeed,
// a random high port is returned.
2396
func getFreePort(host string, ports ...int) (int, error) {
	for _, port := range ports {
		c, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
		if err == nil {
			c.Close()
			return port, nil
		}
	}

	c, err := net.Listen("tcp", host+":0")
	if err != nil {
		return 0, err
	}
	addr := c.Addr().(*net.TCPAddr)
	c.Close()
	return addr.Port, nil
}
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)
	}
}
926819
func (f *FileLock) TryRLock() error {
	return f.performLock(syscall.LOCK_SH | syscall.LOCK_NB)
}
636703
func (q *LinkedBlockingDeque) PutFirst(ctx context.Context, e interface{}) {
	if e == nil {
		return
	}
	q.lock.Lock()
	defer q.lock.Unlock()
	for !q.linkFirst(e) {
		q.notFull.Wait(ctx)
	}
}
1018860
func (iter *iterator) Next() bool {
	if iter.first {
		iter.first = false
		return iter.n != nil
	}

	if iter.n == nil {
		return false
	}

	iter.n = iter.n.forward[0]
	return iter.n != nil
}
548957
func (b *ExponentialBackoff) Next(retry int) (time.Duration, bool) {
	r := 1.0 + rand.Float64() // random number in [1..2]
	m := math.Min(r*b.t*math.Pow(b.f, float64(retry)), b.m)
	if m >= b.m {
		return 0, false
	}
	d := time.Duration(int64(m)) * time.Millisecond
	return d, true
}
30107
func TryListen(network, hostPort string) (bool, error) {
	l, err := net.Listen(network, hostPort)
	if err != nil {
		klog.V(5).Infof("Failure while checking listen on %s: %v", hostPort, err)
		return false, err
	}
	defer l.Close()
	return true, nil
}
232165
func (r *retrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
	// Fail hard on a specific error
	if err == syscall.ECONNREFUSED {
		err = errors.New("Elasticsearch or network down")
		r.logger.Error(err)
		return 0, false, err
	}

	// Stop after n retries
	if retry >= r.retry {
		r.logger.Debugf("Stop retrying after '%d' retries", retry)
		return 0, false, nil
	}

	// Let the backoff strategy decide how long to wait and whether to stop
	r.logger.Debugln("Retry to connect to Elasticsearch")
	wait, stop := r.backoff.Next(retry)
	return wait, stop, nil
}
1250874
func CompareFailed(message string, args ...interface{}) error {
	return WrapWithMessage(&CompareFailedError{Message: fmt.Sprintf(message, args...)}, message, args...)
}
170497
func (a *EventCorrelator) AttemptsForActivity(info *ActivityInfo) int {
	a.checkInit()
	if info == nil || info.ActivityId == "" {
		return 0
	}
	return a.ActivityAttempts[info.ActivityId]
}
174547
func (d *IGD) checkForward(port uint16, proto string) (bool, error) {
	time.Sleep(time.Millisecond)
	_, _, enabled, _, _, err := d.client.GetSpecificPortMappingEntry("", port, proto)

	if err != nil {
		// 714 "NoSuchEntryInArray" means that there is no such forwarding
		if strings.Contains(err.Error(), "<errorCode>714</errorCode>") {
			return false, nil
		}
		return false, err
	}

	return enabled, nil
}
15023
func Retry(action Action, strategies ...strategy.Strategy) error {
	var err error

	for attempt := uint(0); (0 == attempt || nil != err) && shouldAttempt(attempt, strategies...); attempt++ {
		err = action(attempt)
	}

	return err
}
298048
func (s *sender) trySend() {
	for s.pLink.Credit() > 0 && len(s.sending) > 0 {
		sm := s.sending[0]
		s.sending = s.sending[1:]
		s.send(sm)
	}
}
975157
func AttemptFromID(aid *dm.Attempt_ID) *Attempt {
	ret := &Attempt{}
	ret.ID = *aid
	return ret
}
121926
func AttemptRangeQuery(quest string, low, high uint32) *GraphQuery {
	return &GraphQuery{
		AttemptRange: []*GraphQuery_AttemptRange{{Quest: quest, Low: low, High: high}}}
}
1232525
func (f *FetchRetrier) Failure(ctx context.Context, uid gregor1.UID, desc types.RetryDescription) (err error) {
	f.Lock()
	defer f.Unlock()
	defer f.Trace(ctx, func() error { return err }, fmt.Sprintf("Failure(%s)", desc))()
	if !f.running {
		f.Debug(ctx, "Failure: not starting new retrier, not running")
		return nil
	}
	key := f.key(uid, desc)
	if _, ok := f.retriers[key]; !ok {
		f.Debug(ctx, "Failure: spawning new retrier: desc: %s", desc)
		control := newRetrierControl(desc)
		f.retriers[key] = control
		f.spawnRetrier(ctx, uid, desc, control)
	}

	return nil
}
1060635
func EnsureFirstHostPort(first HostPort, hps []HostPort) []HostPort {
	var result []HostPort
	found := false
	for _, hp := range hps {
		if hp.NetAddr() == first.NetAddr() && !found {
			// Found, so skip it.
			found = true
			continue
		}
		result = append(result, hp)
	}
	// Insert it at the top.
	result = append([]HostPort{first}, result...)
	return result
}