// acquireChan wraps a signal chan with a func that can be used with rateLimit.
// should only be called by rate limiting funcs (that implement deadlock avoidance).
300
func acquireChan(tokenCh <-chan struct{}) func(context.Context, bool) bool {
	if tokenCh == nil {
		// always false: acquire never succeeds; panic if told to block (to avoid deadlock)
		return func(ctx context.Context, block bool) bool {
			if block {
				select {
				case <-ctx.Done():
				default:
					panic("deadlock detected: block should never be true when the token chan is nil")
				}
			}
			return false
		}
	}
	return func(ctx context.Context, block bool) bool {
		if block {
			select {
			case <-tokenCh:
				// tie breaker prefers Done
				select {
				case <-ctx.Done():
				default:
					return true
				}
			case <-ctx.Done():
			}
			return false
		}
		select {
		case <-tokenCh:
			return true
		default:
			return false
		}
	}
}
335870
func (bk *Backend) AcquireLock(token string, ttl time.Duration) (err error) {
	bk.log.Debugf("AcquireLock(%s)", token)

	if err = legacy.ValidateLockTTL(ttl); err != nil {
		return trace.Wrap(err)
	}

	bucket := []string{locksBucket}
	for {
		// GetVal will clear TTL on a lock
		bk.GetVal(bucket, token)

		// CreateVal is atomic:
		err = bk.CreateVal(bucket, token, []byte{1}, ttl)
		if err == nil {
			break // success
		}
		if trace.IsAlreadyExists(err) { // locked? wait and repeat:
			bk.Clock().Sleep(250 * time.Millisecond)
			continue
		}
		return trace.ConvertSystemError(err)
	}

	return nil
}
1147212
func (m *MockLock) Acquire(arg0 machinelock.Spec) (func(), error) {
	ret := m.ctrl.Call(m, "Acquire", arg0)
	ret0, _ := ret[0].(func())
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1012355
func NewChan(chanSize int) *Chan {
	return &Chan{
		MsgChan:   make(chan []byte, chanSize),
		ErrChan:   make(chan error, 1),
		CloseChan: make(chan bool, 2),
	}
}
1030746
func grabToken(src oauth2.TokenSource) (*oauth2.Token, error) {
	switch tok, err := src.Token(); {
	case isBadTokenError(err):
		return nil, err
	case isBadKeyError(err):
		return nil, err
	case err != nil:
		// More often than not errors here are transient (network connectivity
		// errors, HTTP 500 responses, etc). Retrying a fatal error a bunch of times
		// is not very bad, so pick safer approach and assume any error is
		// transient. Revoked refresh token or bad credentials (most common source
		// of fatal errors) is already handled above.
		return nil, transient.Tag.Apply(err)
	default:
		return tok, nil
	}
}
1132112
func (s *Semaphore) Acquire() error {
	select {
	case s.sem <- struct{}{}:
		return nil
	case <-time.After(s.timeout):
		return ErrNoTickets
	}
}
850076
func (w *hookRunner) acquireExecutionLock(action string, interrupt <-chan struct{}) (func(), error) {
	spec := machinelock.Spec{
		Cancel:  interrupt,
		Worker:  "meterstatus",
		Comment: action,
	}
	releaser, err := w.machineLock.Acquire(spec)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return releaser, nil
}
106229
func acquireGlobalID(l3n4Addr loadbalancer.L3n4Addr, baseID uint32) (*loadbalancer.L3n4AddrID, error) {
	// Retrieve unique SHA256Sum for service
	sha256Sum := l3n4Addr.SHA256Sum()
	svcPath := path.Join(common.ServicesKeyPath, sha256Sum)

	// Lock that sha256Sum
	lockKey, err := kvstore.LockPath(context.Background(), svcPath)
	if err != nil {
		return nil, err
	}
	defer lockKey.Unlock()

	// After lock complete, get svc's path
	rmsg, err := kvstore.Client().Get(svcPath)
	if err != nil {
		return nil, err
	}

	sl4KV := loadbalancer.L3n4AddrID{}
	if rmsg != nil {
		if err := json.Unmarshal(rmsg, &sl4KV); err != nil {
			return nil, err
		}
	}
	if sl4KV.ID == 0 {
		sl4KV.L3n4Addr = l3n4Addr
		if err := gasNewL3n4AddrID(&sl4KV, baseID); err != nil {
			return nil, err
		}
		marshaledSl4Kv, err := json.Marshal(sl4KV)
		if err != nil {
			return nil, err
		}
		err = kvstore.Client().Set(svcPath, marshaledSl4Kv)
		if err != nil {
			return nil, err
		}
	}

	return &sl4KV, err
}
572450
func (e SensuEvent) AcquireSensuEvent() *SensuEvent {
	results, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(results, &e)
	if err != nil {
		panic(err)
	}
	return &e
}
1116371
func AcquireBytes(size int) []byte {
	if size < 1 {
		return nil
	}
	capacity := pow2roundup(int64(size))
	if capacity > maxSize {
		return make([]byte, size, capacity)
	}
	if capacity < 512 {
		capacity = 512
	}
	return bytePool[log2(capacity)-9].Get().([]byte)[:size]
}
575300
func (c *Chan) SendChan() chan<- interface{} {

	c.mutx.Lock()
	defer c.mutx.Unlock()

	if c.sendch == nil {
		c.sendch = make(chan interface{})
		go c.sendLoop()
	}
	return c.sendch
}
937800
func signalTrap(sig ...os.Signal) <-chan bool {
	// channel to notify the caller.
	trapCh := make(chan bool, 1)

	go func(chan<- bool) {
		// channel to receive signals.
		sigCh := make(chan os.Signal, 1)
		defer close(sigCh)

		// `signal.Notify` registers the given channel to
		// receive notifications of the specified signals.
		signal.Notify(sigCh, sig...)

		// Wait for the signal.
		<-sigCh

		// Once signal has been received stop signal Notify handler.
		signal.Stop(sigCh)

		// Notify the caller.
		trapCh <- true
	}(trapCh)

	return trapCh
}
102063
func (e SensuEvent) AcquireThreshold() string {
	var w, c string

	if e.Check.Thresholds.Warning != -1 {
		w = strconv.Itoa(e.Check.Thresholds.Warning)
	}
	if e.Check.Thresholds.Critical != -1 {
		c = strconv.Itoa(e.Check.Thresholds.Critical)
	}

	switch e.Check.Status {
	case 0:
		if w != "" { // this is stupid and ugly, fix it
			if c != "" {
				return "Warning Threshold: " + w + " Critical Threshold: " + c
			}
		}
		return "No thresholds set"
	case 1:
		if w != "" {
			return "Warning Threshold: " + w
		}
		return "No " + strings.ToLower(DefineStatus(1)) + " threshold set"
	case 2:
		if c != "" {
			return "Critical Threshold: " + c
		}
		return "No " + strings.ToLower(DefineStatus(2)) + " threshold set"
	case 3:
		return "No " + strings.ToLower(DefineStatus(3)) + " threshold set"
	default:
		return "No threshold information"
	}
}
137569
func (i *info) AvailabilityChan() <-chan struct{} {
	i.m.RLock()
	ch := i.available
	i.m.RUnlock()
	return ch
}
1186832
func (r *rpcServer) GetChanInfo(ctx context.Context,
	in *lnrpc.ChanInfoRequest) (*lnrpc.ChannelEdge, error) {

	graph := r.server.chanDB.ChannelGraph()

	edgeInfo, edge1, edge2, err := graph.FetchChannelEdgesByID(in.ChanId)
	if err != nil {
		return nil, err
	}

	// Convert the database's edge format into the network/RPC edge format
	// which couples the edge itself along with the directional node
	// routing policies of each node involved within the channel.
	channelEdge := marshalDbEdge(edgeInfo, edge1, edge2)

	return channelEdge, nil
}
573559
func AcquireLock(ctx context.Context, backend Backend, lockName string, ttl time.Duration) (err error) {
	if lockName == "" {
		return trace.BadParameter("missing parameter lock name")
	}
	key := []byte(filepath.Join(locksPrefix, lockName))
	for {
		// Get will clear TTL on a lock
		backend.Get(ctx, key)

		// CreateVal is atomic:
		_, err = backend.Create(ctx, Item{Key: key, Value: []byte{1}, Expires: backend.Clock().Now().UTC().Add(ttl)})
		if err == nil {
			break // success
		}
		if trace.IsAlreadyExists(err) { // locked? wait and repeat:
			backend.Clock().Sleep(250 * time.Millisecond)
			continue
		}
		return trace.ConvertSystemError(err)
	}
	return nil
}
1035448
func (p *pool) Acquire(sn SubnetSelector, i IPSelector, logger lager.Logger) (network *linux_backend.Network, err error) {
	p.mu.Lock()
	defer p.mu.Unlock()

	logger = logger.Session("acquire")

	network = &linux_backend.Network{}

	allocatedSubnets := subnets(p.allocated)
	logger.Info("subnet-selecting", lager.Data{"allocated-subnets": subnetsStr(allocatedSubnets)})
	if network.Subnet, err = sn.SelectSubnet(p.dynamicRange, allocatedSubnets); err != nil {
		logger.Error("subnet-selecting-failed", err)
		return nil, err
	}
	logger.Info("subnet-selected", lager.Data{"subnet": network.Subnet.String(), "allocated-subnets": subnetsStr(allocatedSubnets)})

	ips := p.allocated[network.Subnet.String()]
	logger.Info("ip-selecting", lager.Data{"allocated-ips": ipsStr(ips)})
	allocatedIPs := append(ips, NetworkIP(network.Subnet), GatewayIP(network.Subnet), BroadcastIP(network.Subnet))
	if network.IP, err = i.SelectIP(network.Subnet, allocatedIPs); err != nil {
		logger.Error("ip-selecting-failed", err)
		return nil, err
	}
	logger.Info("ip-selected", lager.Data{"ip": network.IP.String()})

	p.allocated[network.Subnet.String()] = append(ips, network.IP)
	logger.Info("new-allocated", lager.Data{"allocated-ips": ipsStr(p.allocated[network.Subnet.String()])})

	return network, nil
}