// AcquireLock grabs a lock that will be released automatically in TTL.
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
}
386488
func (r *GormWorkItemLinkRepository) acquireLock(spaceID uuid.UUID) error {
	// hash the UUID to get a 32 bit value from a 128 UUID that we can then use
	// with a PostgreSQL advisory lock.
	//
	// TODO(kwk): Reducing the 128 bit UUID to a 32 bit number potentially ends
	// up in longer wait times for locks because there exists a certain
	// potential to have hash collisions for two distinct UUIDs. But currently
	// Postgres only allows for 64 bit numbers without the high bit set. That
	// effectively limits us to just 32 bit hashes. Once we allow cross-space
	// linking we need to revisit the locking.
	h := fnv.New32()
	h.Write([]byte("links-" + spaceID.String()))
	key := h.Sum32()

	db := r.db.Exec("SELECT pg_advisory_xact_lock($1)", key)
	if db.Error != nil {
		return errs.Wrapf(db.Error, "failed to acquire pg_advisory_xact_lock(%d)\n", key)
	}
	return nil
}
437408
func (mutex *Mutex) Lock() error {
	ret := int(C.SDL_LockMutex(mutex.cptr()))
	if ret != 0 {
		return GetError()
	}
	return nil
}
970175
func AcquireWithContext(ctx context.Context, lock sync.Locker) (err error) {
	if err = ctx.Err(); err != nil {
		return err
	}
	acquiredCh := make(chan struct{})
	shouldReleaseCh := make(chan bool, 1)
	go func() {
		lock.Lock()
		close(acquiredCh)
		shouldRelease := <-shouldReleaseCh
		if shouldRelease {
			lock.Unlock()
		}
	}()
	select {
	case <-acquiredCh:
		err = nil
	case <-ctx.Done():
		err = ctx.Err()
	}
	shouldReleaseCh <- err != nil
	return err
}
885236
func NewLock(log Logger, api Agency, key []string, id string, ttl time.Duration) (Lock, error) {
	if ttl < minLockTTL {
		ttl = minLockTTL
	}
	if id == "" {
		randBytes := make([]byte, 16)
		rand.Read(randBytes)
		id = hex.EncodeToString(randBytes)
	}
	return &lock{
		log: log,
		api: api,
		key: key,
		id:  id,
		ttl: ttl,
	}, nil
}
1155987
func (r *reservationWithCtx) lock() {
	r.updateMtx.Lock()
	defer r.updateMtx.Unlock()

	r.lastUpdated = time.Time{}
}
657168
func (m *MockLocker) Acquire(arg0 string, arg1 int) (lock.Lock, error) {
	ret := m.ctrl.Call(m, "Acquire", arg0, arg1)
	ret0, _ := ret[0].(lock.Lock)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
59172
func lock() error {
	var err error
	var lock lockfile.Lockfile

	daemonMutex.Lock()
	lock, err = getLockfile()
	if err != nil {
		daemonMutex.Unlock()
		return fmt.Errorf("[lock] cannot init lockfile: %v", err)
	}

	// Try to acquire the lock and in case of a temporary error, sleep for
	// two seconds until the next retry (at most 10 times).  Return fatal
	// errors immediately, as we can't recover.
	for i := 0; i < 10; i++ {
		if err = lock.TryLock(); err != nil {
			switch err.(type) {
			case lockfile.TemporaryError:
				logrus.Debugf("[lock] busy: next retry in two seconds")
				time.Sleep(2 * time.Second)
			default:
				daemonMutex.Unlock()
				return fmt.Errorf("[lock] error acquiring lock: %s", err)
			}
		}
	}
	if err != nil {
		daemonMutex.Unlock()
		return fmt.Errorf("[lock] error acquiring lock: too many tries")
	}

	logrus.Debugf("[lock] lock acquired")
	return nil
}
629046
func (m *Mutex) Lock() error {
	value, err := m.genValueFunc()
	if err != nil {
		return err
	}

	for i := 0; i < m.tries; i++ {
		if i != 0 {
			time.Sleep(m.delayFunc(i))
		}

		start := time.Now()

		n := m.actOnPoolsAsync(func(pool Pool) bool {
			return m.acquire(pool, value)
		})

		until := time.Now().Add(m.expiry - time.Now().Sub(start) - time.Duration(int64(float64(m.expiry)*m.factor)) + 2*time.Millisecond)
		if n >= m.quorum && time.Now().Before(until) {
			m.value = value
			m.until = until
			return nil
		}
		m.actOnPoolsAsync(func(pool Pool) bool {
			return m.release(pool, value)
		})
	}

	return ErrFailed
}
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
}
1053571
func (l *Lock) get(ctx context.Context) (*LockRecord, error) {
	// Pooling
	l.backend.permitPool.Acquire()
	defer l.backend.permitPool.Release()

	// Read
	row, err := l.backend.client.Single().ReadRow(ctx, l.backend.haTable, spanner.Key{l.key}, []string{"Key", "Value", "Timestamp", "Identity"})
	if spanner.ErrCode(err) == codes.NotFound {
		return nil, nil
	}
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("failed to read value for %q: {{err}}", l.key), err)
	}

	var r LockRecord
	if err := row.ToStruct(&r); err != nil {
		return nil, errwrap.Wrapf("failed to decode lock: {{err}}", err)
	}
	return &r, nil
}
1213425
func (fp *Failpoint) Acquire() (interface{}, error) {
	fp.mu.RLock()
	if fp.t == nil {
		fp.mu.RUnlock()
		return nil, ErrDisabled
	}
	v, err := fp.t.eval()
	if v == nil {
		err = ErrDisabled
	}
	if err != nil {
		fp.mu.RUnlock()
	}
	return v, err
}
991067
func (latches *Latches) acquire(lock *Lock) acquireResult {
	if lock.IsStale() {
		return acquireStale
	}
	for lock.acquiredCount < len(lock.requiredSlots) {
		status := latches.acquireSlot(lock)
		if status != acquireSuccess {
			return status
		}
	}
	return acquireSuccess
}
698727
func NewLock(l *kvrpcpb.LockInfo) *Lock {
	ttl := l.GetLockTtl()
	if ttl == 0 {
		ttl = defaultLockTTL
	}
	return &Lock{
		Key:     l.GetKey(),
		Primary: l.GetPrimaryLock(),
		TxnID:   l.GetLockVersion(),
		TTL:     ttl,
	}
}
1357535
func (l *lock) Unlock(ctx context.Context) error {
	l.mutex.Lock()
	defer l.mutex.Unlock()

	if !l.locked {
		return driver.WithStack(NotLockedError)
	}

	// Release the lock
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	if err := l.api.RemoveKeyIfEqualTo(ctx, l.key, l.id); err != nil {
		return driver.WithStack(err)
	}

	// Cleanup
	l.locked = false
	if l.cancelRenewal != nil {
		l.cancelRenewal()
		l.cancelRenewal = nil
	}

	return nil
}
281530
func (db *Database) Acquire(sid string, expires time.Duration) (lifetime sessions.LifeTime) {
	bsid := []byte(sid)
	err := db.Service.Update(func(tx *bolt.Tx) (err error) {
		root := db.getBucket(tx)

		if expires > 0 { // should check or create the expiration bucket.
			name := getExpirationBucketName(bsid)
			b := root.Bucket(name)
			if b == nil {
				// not found, create a session bucket and an expiration bucket and save the given "expires" of time.Time,
				// don't return a lifetime, let it empty, session manager will do its job.
				b, err = root.CreateBucket(name)
				if err != nil {
					return err
				}

				expirationTime := time.Now().Add(expires)
				timeBytes, err := sessions.DefaultTranscoder.Marshal(expirationTime)
				if err != nil {
					return err
				}

				if err := b.Put(expirationKey, timeBytes); err == nil {
					// create the session bucket now, so the rest of the calls can be easly get the bucket without any further checks.
					_, err = root.CreateBucket(bsid)
				}

				return err
			}

			// found, get the associated expiration bucket, wrap its value and return.
			_, expValue := b.Cursor().First()
			if expValue == nil {
				return nil // does not expire.
			}

			var expirationTime time.Time
			if err = sessions.DefaultTranscoder.Unmarshal(expValue, &expirationTime); err != nil {
				return
			}

			lifetime = sessions.LifeTime{Time: expirationTime}
			return nil
		}

		// does not expire, just create the session bucket if not exists so we can be ready later on.
		_, err = root.CreateBucketIfNotExists(bsid)
		return
	})

	if err != nil {
		return sessions.LifeTime{Time: sessions.CookieExpireDelete}
	}

	return
}
980452
func (r *keyring) Lock(passphrase []byte) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.locked {
		return errLocked
	}

	r.locked = true
	r.passphrase = passphrase
	return nil
}