// Must be called when endpoint is still locked.
770325
func (e *Endpoint) createEpInfoCache(epdir string) *epInfoCache {
	cidr6, cidr4 := e.GetCIDRPrefixLengths()

	ep := &epInfoCache{
		revision: e.nextPolicyRevision,
		keys:     e.GetBPFKeys(),

		epdir:  epdir,
		id:     e.GetID(),
		ifName: e.IfName,
		ipvlan: e.HasIpvlanDataPath(),

		identity:           e.GetIdentity(),
		mac:                e.GetNodeMAC(),
		ipv4:               e.IPv4Address(),
		ipv6:               e.IPv6Address(),
		conntrackLocal:     e.ConntrackLocalLocked(),
		cidr4PrefixLengths: cidr4,
		cidr6PrefixLengths: cidr6,
		options:            e.Options.DeepCopy(),

		endpoint: e,
	}

	var err error
	ep.value, err = e.GetBPFValue()
	if err != nil {
		log.WithField(logfields.EndpointID, e.ID).WithError(err).Error("getBPFValue failed")
		return nil
	}
	return ep
}
959900
func (proxier *Proxier) appendServiceCommentLocked(args []string, svcName string) {
	// Not printing these comments, can reduce size of iptables (in case of large
	// number of endpoints) even by 40%+. So if total number of endpoint chains
	// is large enough, we simply drop those comments.
	if proxier.endpointChainsNumber > endpointChainsNumberThreshold {
		return
	}
	args = append(args, "-m", "comment", "--comment", svcName)
}
936939
func waitForDropletUnlocked(
	client *godo.Client, dropletId int, timeout time.Duration) error {
	done := make(chan struct{})
	defer close(done)

	result := make(chan error, 1)
	go func() {
		attempts := 0
		for {
			attempts += 1

			log.Printf("[DEBUG] Checking droplet lock state... (attempt: %d)", attempts)
			droplet, _, err := client.Droplets.Get(context.TODO(), dropletId)
			if err != nil {
				result <- err
				return
			}

			if !droplet.Locked {
				result <- nil
				return
			}

			// Wait 3 seconds in between
			time.Sleep(3 * time.Second)

			// Verify we shouldn't exit
			select {
			case <-done:
				// We finished, so just exit the goroutine
				return
			default:
				// Keep going
			}
		}
	}()

	log.Printf("[DEBUG] Waiting for up to %d seconds for droplet to unlock", timeout/time.Second)
	select {
	case err := <-result:
		return err
	case <-time.After(timeout):
		return fmt.Errorf(
			"Timeout while waiting to for droplet to unlock")
	}
}
636730
func (s *scene) WaitFlagLimitedAndFetch(topic string, timeout time.Duration) (interface{}, error) {
	err := s.WaitFlagLimited(topic, timeout)
	if err != nil {
		return nil, err
	}
	return s.Fetch(topic)
}
1246467
func (a *Application) EndpointBindings() (map[string]string, error) {
	// We don't need the TxnRevno below.
	bindings, _, err := readEndpointBindings(a.st, a.globalKey())
	if err != nil && !errors.IsNotFound(err) {
		return nil, errors.Trace(err)
	}
	if bindings == nil {
		bindings, err = a.defaultEndpointBindings()
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	return bindings, nil
}
1036660
func required(s *status.Status) (bool, string) {
	if s.Group == status.EndorserClientStatus && s.Code == status.ConnectionFailed.ToInt32() {
		return true, peerURLFromConnectionFailedStatus(s.Details)
	}
	return false, ""
}
140367
func (e *Endpoint) LogStatusOKLocked(typ StatusType, msg string) {
	e.logStatusLocked(typ, OK, msg)
}
887401
func (client *lockRESTClient) Expired(args dsync.LockArgs) (reply bool, err error) {
	return client.restCall(lockRESTMethodExpired, args)
}
279269
func (e *Endpoint) logStatusLocked(typ StatusType, code StatusCode, msg string) {
	e.Status.indexMU.Lock()
	defer e.Status.indexMU.Unlock()
	sts := &statusLogMsg{
		Status: Status{
			Code:  code,
			Msg:   msg,
			Type:  typ,
			State: e.state,
		},
		Timestamp: time.Now().UTC(),
	}
	e.Status.addStatusLog(sts)
	e.getLogger().WithFields(logrus.Fields{
		"code":                   sts.Status.Code,
		"type":                   sts.Status.Type,
		logfields.EndpointState:  sts.Status.State,
		logfields.PolicyRevision: e.policyRevision,
	}).Debug(msg)
}
486594
func (client *lockRESTClient) Lock(args dsync.LockArgs) (reply bool, err error) {
	return client.restCall(lockRESTMethodLock, args)
}
967021
func (c *Controller) updateParamsLocked(params ControllerParams) {
	c.params = params

	maxInterval := time.Duration(option.Config.MaxControllerInterval) * time.Second
	if maxInterval > 0 && params.RunInterval > maxInterval {
		c.getLogger().Infof("Limiting interval to %s", maxInterval)
		c.params.RunInterval = maxInterval
	}
}
1357155
func (e *Endpoint) PolicyMapPathLocked() string {
	return bpf.LocalMapPath(policymap.MapName, e.ID)
}
1210179
func (client *lockRESTClient) restCall(call string, args dsync.LockArgs) (reply bool, err error) {

	reader := bytes.NewBuffer(make([]byte, 0, 2048))
	err = gob.NewEncoder(reader).Encode(args)
	if err != nil {
		return false, err
	}
	respBody, err := client.call(call, nil, reader, -1)
	if err != nil {
		return false, err
	}

	var resp lockResponse
	defer http.DrainBody(respBody)
	err = gob.NewDecoder(respBody).Decode(&resp)

	if err != nil || !resp.Success {
		reqInfo := &logger.ReqInfo{}
		reqInfo.AppendTags("resource", args.Resource)
		reqInfo.AppendTags("serveraddress", args.ServerAddr)
		reqInfo.AppendTags("serviceendpoint", args.ServiceEndpoint)
		reqInfo.AppendTags("source", args.Source)
		reqInfo.AppendTags("uid", args.UID)
		ctx := logger.SetReqInfo(context.Background(), reqInfo)
		logger.LogIf(ctx, err)
	}
	return resp.Success, err
}
771530
func Endpoint(rawurl string) Opt {
	return func(c *Client) Opt {
		old := c.url
		c.url = rawurl
		return Endpoint(old)
	}
}
114483
func (dbp *Process) CheckAndClearManualStopRequest() bool {
	dbp.stopMu.Lock()
	defer dbp.stopMu.Unlock()

	msr := dbp.manualStopRequested
	dbp.manualStopRequested = false

	return msr
}
145430
func TryConnectEndpoints(service proxy.ServicePortName, srcAddr net.Addr, protocol string, loadBalancer LoadBalancer) (out net.Conn, err error) {
	sessionAffinityReset := false
	for _, dialTimeout := range EndpointDialTimeouts {
		endpoint, err := loadBalancer.NextEndpoint(service, srcAddr, sessionAffinityReset)
		if err != nil {
			klog.Errorf("Couldn't find an endpoint for %s: %v", service, err)
			return nil, err
		}
		klog.V(3).Infof("Mapped service %q to endpoint %s", service, endpoint)
		// TODO: This could spin up a new goroutine to make the outbound connection,
		// and keep accepting inbound traffic.
		outConn, err := net.DialTimeout(protocol, endpoint, dialTimeout)
		if err != nil {
			if isTooManyFDsError(err) {
				panic("Dial failed: " + err.Error())
			}
			klog.Errorf("Dial failed: %v", err)
			sessionAffinityReset = true
			continue
		}
		return outConn, nil
	}
	return nil, fmt.Errorf("failed to connect to an endpoint.")
}
666822
func (ep *endpoint) enableService() {
	ep.Lock()
	defer ep.Unlock()
	ep.serviceEnabled = true
}