// Acquire acquires a lock on a file for the duration of the process. This method
// is reentrant.
352170
func Acquire(path string) error {
	fd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR, 0600)
	if err != nil {
		return err
	}

	// We don't need to close the fd since we should hold
	// it until the process exits.

	return unix.Flock(fd, unix.LOCK_EX)
}
1132112
func (s *Semaphore) Acquire() error {
	select {
	case s.sem <- struct{}{}:
		return nil
	case <-time.After(s.timeout):
		return ErrNoTickets
	}
}
29401
func (f *LockPIDFile) Lock() (err error) {
	if isIOS {
		// on iOS, our share extension can have multiple copies running, and furthermore this lock
		// doesn't do anything there, so let's just do nothing.
		f.G().Log.Debug("Skipping PID file lock on iOS")
		return nil
	}

	if f.file, err = os.OpenFile(f.name, os.O_CREATE|os.O_RDWR, 0600); err != nil {
		return PIDFileLockError{f.name}
	}

	// LOCK_EX = exclusive
	// LOCK_NB = nonblocking
	if err = syscall.Flock(int(f.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
		f.file.Close()
		f.file = nil
		return PIDFileLockError{f.name}
	}

	pid := os.Getpid()
	fmt.Fprintf(f.file, "%d", pid)
	f.file.Sync()

	f.G().Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)

	return nil
}
1250729
func Capture(id string, params *stripe.PaymentIntentCaptureParams) (*stripe.PaymentIntent, error) {
	return getC().Capture(id, params)
}
817129
func (l *FileLock) Unlock() error {
	return syscall.Flock(l.fd, syscall.LOCK_UN)
}
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
}
554780
func (e *Engine) acquireConfig() (cfg types.Config, err error) {

	// First try read the config @ e.ConfigCache.
	b, err := ioutil.ReadFile(e.ConfigCache)
	if err == nil {
		if err = json.Unmarshal(b, &cfg); err != nil {
			e.Logger.Crit("failed to parse cached config: %v", err)
		}
		// Create an http client and fetcher with the timeouts from the cached
		// config
		err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfg.Ignition.Timeouts, cfg.Ignition.Security.TLS.CertificateAuthorities, cfg.Ignition.Proxy)
		if err != nil {
			e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err)
			return
		}
		return
	}

	// Create a new http client and fetcher with the timeouts set via the flags,
	// since we don't have a config with timeout values we can use
	timeout := int(e.FetchTimeout.Seconds())
	emptyProxy := types.Proxy{}
	err = e.Fetcher.UpdateHttpTimeoutsAndCAs(types.Timeouts{HTTPTotal: &timeout}, nil, emptyProxy)
	if err != nil {
		e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err)
		return
	}

	// (Re)Fetch the config if the cache is unreadable.
	cfg, err = e.fetchProviderConfig()
	if err != nil {
		e.Logger.Warning("failed to fetch config: %s", err)
		return
	}

	// Update the http client to use the timeouts and CAs from the newly fetched
	// config
	err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfg.Ignition.Timeouts, cfg.Ignition.Security.TLS.CertificateAuthorities, cfg.Ignition.Proxy)
	if err != nil {
		e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err)
		return
	}

	err = e.Fetcher.RewriteCAsWithDataUrls(cfg.Ignition.Security.TLS.CertificateAuthorities)
	if err != nil {
		e.Logger.Crit("error handling CAs: %v", err)
		return
	}

	rpt := validate.ValidateWithoutSource(reflect.ValueOf(cfg))
	e.logReport(rpt)
	if rpt.IsFatal() {
		err = errors.ErrInvalid
		e.Logger.Crit("merging configs resulted in an invalid config")
		return
	}

	// Populate the config cache.
	b, err = json.Marshal(cfg)
	if err != nil {
		e.Logger.Crit("failed to marshal cached config: %v", err)
		return
	}
	if err = ioutil.WriteFile(e.ConfigCache, b, 0640); err != nil {
		e.Logger.Crit("failed to write cached config: %v", err)
		return
	}

	return
}
157942
func (r *Reader) Release() {
	r.mu.Lock()
	defer r.mu.Unlock()

	if closer, ok := r.reader.(io.Closer); ok {
		closer.Close()
	}
	if r.indexBlock != nil {
		r.indexBlock.Release()
		r.indexBlock = nil
	}
	if r.filterBlock != nil {
		r.filterBlock.Release()
		r.filterBlock = nil
	}
	r.reader = nil
	r.cache = nil
	r.bpool = nil
	r.err = ErrReaderReleased
}
1321944
func (f *LockPIDFile) Lock() (err error) {
	pathp, err := syscall.UTF16PtrFromString(f.name)
	if err != nil {
		return PIDFileLockError{f.name}
	}
	access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE)
	createmode := uint32(syscall.OPEN_ALWAYS)
	sharemode := uint32(syscall.FILE_SHARE_READ) // os.Open always uses FILE_SHARE_READ | FILE_SHARE_WRITE
	var sa *syscall.SecurityAttributes
	r, err := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0)
	if err != nil {
		return PIDFileLockError{f.name}
	}
	// this is what os.openFile does
	f.file = os.NewFile(uintptr(r), f.name)

	pid := os.Getpid()
	fmt.Fprintf(f.file, "%d", pid)
	f.file.Sync()

	f.G().Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)

	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
}
918772
func (device *Device) Acquire() error {
	ret := Status(C.cairo_device_acquire(device.Ptr)).toError()
	if err := device.status(); err != nil {
		panic(err)
	}
	return ret
}
1009957
func (lk *consulLock) Acquire(timeout uint64) error {
	// Create consul session
	err := lk.createSession()
	if err != nil {
		log.Errorf("Error Creating session for lock %s. Err: %v", lk.keyName, err)
		return err
	}

	// Refresh the session in background
	go lk.renewSession()

	// Watch for changes on the lock
	go lk.acquireLock()

	// Wait till timeout and see if we were able to acquire the lock
	if timeout != 0 {
		go func() {
			time.Sleep(time.Duration(timeout) * time.Second)

			if !lk.IsAcquired() {
				lk.eventChan <- LockEvent{EventType: LockAcquireTimeout}

				// release the lock
				lk.Release()
			}
		}()
	}

	return nil
}
410938
func (s *SQLStore) acquireDBLock(steal bool) (bool, string, uint64, error) {
	s.dbLock.Lock()
	defer s.dbLock.Unlock()
	var (
		lockID  string
		tick    uint64
		hasLock bool
	)
	tx, err := s.dbLock.db.Begin()
	if err != nil {
		return false, "", 0, err
	}
	defer func() {
		if tx != nil {
			tx.Rollback()
		}
	}()
	r := tx.QueryRow(sqlStmts[sqlDBLockSelect])
	err = r.Scan(&lockID, &tick)
	if err != nil && err != sql.ErrNoRows {
		return false, "", 0, sqlStmtError(sqlDBLockSelect, err)
	}
	if err == sql.ErrNoRows || steal || lockID == "" || lockID == s.dbLock.id {
		// If we are stealing, reset tick to 0 (so it will become 1 in update statement)
		if steal {
			tick = 0
		}
		stmt := sqlStmts[sqlDBLockUpdate]
		if err == sql.ErrNoRows {
			stmt = sqlStmts[sqlDBLockInsert]
		}
		if _, err := tx.Exec(stmt, s.dbLock.id, tick+1); err != nil {
			return false, "", 0, sqlStmtError(sqlDBLockUpdate, err)
		}
		hasLock = true
	}
	if err := tx.Commit(); err != nil {
		return false, "", 0, err
	}
	tx = nil
	return hasLock, lockID, tick, nil
}
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
}
1039610
func acquireLock(config Config) func(string, <-chan struct{}) (func(), error) {
	return func(comment string, abort <-chan struct{}) (func(), error) {
		spec := machinelock.Spec{
			Cancel:  abort,
			Worker:  config.Name,
			Comment: comment,
		}
		return config.MachineLock.Acquire(spec)
	}
}
877451
func (c *lock) Acquire(spec Spec) (func(), error) {
	if err := spec.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	current := &info{
		worker:    spec.Worker,
		comment:   spec.Comment,
		stack:     string(debug.Stack()),
		requested: c.clock.Now(),
	}
	c.mu.Lock()

	id := c.next
	c.next++
	c.waiting[id] = current

	mSpec := c.spec
	mSpec.Cancel = spec.Cancel

	c.mu.Unlock()
	c.logger.Debugf("acquire machine lock for %s (%s)", spec.Worker, spec.Comment)
	releaser, err := c.acquire(mSpec)
	c.mu.Lock()
	defer c.mu.Unlock()
	// Remove from the waiting map.
	delete(c.waiting, id)

	if err != nil {
		return nil, errors.Trace(err)
	}
	c.logger.Debugf("machine lock acquired for %s (%s)", spec.Worker, spec.Comment)
	c.holder = current
	current.acquired = c.clock.Now()
	return func() {
		// We need to acquire the mutex before we call the releaser
		// to ensure that we move the current to the history before
		// another pending acquisition overwrites the current value.
		c.mu.Lock()
		defer c.mu.Unlock()
		// We write the log file entry before we release the execution
		// lock to ensure that no other agent is attempting to write to the
		// log file.
		current.released = c.clock.Now()
		c.writeLogEntry()
		c.logger.Debugf("machine lock released for %s (%s)", spec.Worker, spec.Comment)
		releaser.Release()
		c.history.PushFront(current)
		c.holder = nil
	}, nil
}