Acquires the lock on the status/lock file.

 Returns true on success or if this instance already holds the lock.
 Returns false if another process holds the lock.
422123
def acquire_lock
      return true if @handle
      begin
        @handle = File.open(status_file_path, File::RDWR | File::CREAT)
        raise StandardError.new('Already locked') unless @handle.flock(File::LOCK_EX | File::LOCK_NB)
        @handle.rewind
        @handle.truncate 0
      rescue
        if @handle
          @handle.flock(File::LOCK_UN)
          @handle.close
        end
        @handle = nil
      end
      !!@handle
    end
235789
def confirm_lock(lockfile):
    
    pidfile = open(lockfile, "r")
    pidfile_pid = pidfile.readline().strip()
    pidfile.close()
    if int(pidfile_pid) != os.getpid():
        raise RuntimeError, ("pidfile %s contains pid %s; expected pid %s!" %
                             (lockfile, os.getpid(), pidfile_pid))
    return True
625085
def is_lock(lock):
    
    if lock is None:
        # Don't do useless tests
        return False

    for attr in "acquire", "release", "__enter__", "__exit__":
        if not hasattr(lock, attr):
            # Missing something
            return False

    # Same API as a lock
    return True
227236
def lock(self, timeout=10):
        
        logger.debug("Locking %s", self.lock_file)
        if not os.path.exists(self.lock_file):
            self.ensure_path(self.lock_file)
            with open(self.lock_file, "w"):
                os.utime(self.lock_file)
        self._lock.acquire(timeout=timeout)
155565
def _lock(self, lock_type='update', failhard=False):
        '''
        
        '''
        try:
            fh_ = os.open(self._get_lock_file(lock_type),
                          os.O_CREAT | os.O_EXCL | os.O_WRONLY)
            with os.fdopen(fh_, 'wb'):
                # Write the lock file and close the filehandle
                os.write(fh_, salt.utils.stringutils.to_bytes(six.text_type(os.getpid())))
        except (OSError, IOError) as exc:
            if exc.errno == errno.EEXIST:
                with salt.utils.files.fopen(self._get_lock_file(lock_type), 'r') as fd_:
                    try:
                        pid = int(salt.utils.stringutils.to_unicode(fd_.readline()).rstrip())
                    except ValueError:
                        # Lock file is empty, set pid to 0 so it evaluates as
                        # False.
                        pid = 0
                global_lock_key = self.role + '_global_lock'
                lock_file = self._get_lock_file(lock_type=lock_type)
                if self.opts[global_lock_key]:
                    msg = (
                        '{0} is enabled and {1} lockfile {2} is present for '
                        '{3} remote \'{4}\'.'.format(
                            global_lock_key,
                            lock_type,
                            lock_file,
                            self.role,
                            self.id,
                        )
                    )
                    if pid:
                        msg += ' Process {0} obtained the lock'.format(pid)
                        if not pid_exists(pid):
                            msg += (' but this process is not running. The '
                                    'update may have been interrupted. If '
                                    'using multi-master with shared gitfs '
                                    'cache, the lock may have been obtained '
                                    'by another master.')
                    log.warning(msg)
                    if failhard:
                        raise exc
                    return
                elif pid and pid_exists(pid):
                    log.warning('Process %d has a %s %s lock (%s)',
                                pid, self.role, lock_type, lock_file)
                    if failhard:
                        raise
                    return
                else:
                    if pid:
                        log.warning(
                            'Process %d has a %s %s lock (%s), but this '
                            'process is not running. Cleaning up lock file.',
                            pid, self.role, lock_type, lock_file
                        )
                    success, fail = self.clear_lock()
                    if success:
                        return self._lock(lock_type='update',
                                          failhard=failhard)
                    elif failhard:
                        raise
                    return
            else:
                msg = 'Unable to set {0} lock for {1} ({2}): {3} '.format(
                    lock_type,
                    self.id,
                    self._get_lock_file(lock_type),
                    exc
                )
                log.error(msg, exc_info=True)
                raise GitLockError(exc.errno, msg)
        msg = 'Set {0} lock for {1} remote \'{2}\''.format(
            lock_type,
            self.role,
            self.id
        )
        log.debug(msg)
        return msg
754007
def get_lock(self, path):
        
        if self.lockfile:
            return self.lockfile.LockFile(path)
        else:
            with self.job_locks_lock:
                if path not in self.job_locks:
                    lock = threading.Lock()
                    self.job_locks[path] = lock
                else:
                    lock = self.job_locks[path]
            return lock
1181767
async def is_locked(self, resource):
        

        successes = await asyncio.gather(*[
            i.is_locked(resource) for
            i in self.instances
        ], return_exceptions=True)
        successful_sets = sum(s is True for s in successes)

        locked = True if successful_sets >= int(len(self.instances) / 2) + 1 else False

        return locked
801827
private synchronized boolean getServerLock() {

        Boolean fileExists = Boolean.FALSE;
        final File sDir = lockFile;
        try {
            fileExists = AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<Boolean>() {
                @Override
                public Boolean run() throws Exception {
                    if (!sDir.exists()) {
                        return Boolean.FALSE;
                    }
                    return Boolean.TRUE;
                }
            });
        } catch (Exception ex) {
            // Oh well.
        }
        if (!(fileExists.booleanValue()))
            return false;

        // Change to the "locking" state
        FileOutputStream fos = null;
        FileChannel fc = null;
        try {
            fos = new FileOutputStream(lockFile);
            fc = fos.getChannel();
            lockFileChannel = fc;

            // Try for a short period of time to obtain the lock
            // (if status mechanisms temporarily grab the file, we want to wait
            // to try to grab it.. )
            for (int i = 0; i < BootstrapConstants.MAX_POLL_ATTEMPTS; i++) {
                serverLock = fc.tryLock();
                if (serverLock != null) {
                    break;
                } else {
                    try {
                        Thread.sleep(BootstrapConstants.POLL_INTERVAL_MS);
                    } catch (InterruptedException e) {
                    }
                }
            }
        } catch (OverlappingFileLockException e) {
            // If we encounter an exception obtaining the lock, we can try
            // try closing the the relevant streams (channel first)
            if (!Utils.tryToClose(fc))
                Utils.tryToClose(fos);
        } catch (IOException e) {
            // If we encounter an exception obtaining the lock, we can try
            // try closing the the relevant streams (channel first)
            if (!Utils.tryToClose(fc)) // try to close the wrapping-channel first.
                Utils.tryToClose(fos);
        }

        return serverLock != null && serverLock.isValid();
    }
167395
def with_lock
      @zk_lock ||= @zk.locker(current_lock_path)

      begin
        @zk_lock.lock!(true)
      rescue Exception
        # handle shutdown case
        running? ? raise : return
      end

      if running?
        @zk_lock.assert!
        yield
      end
    ensure
      if @zk_lock
        begin
          @zk_lock.unlock!
        rescue => ex
          logger.warn("Failed to release lock: #{ex.inspect}")
        end
      end
    end
86192
def _recoverfile_from_lockfile(self, lockfile):
        
        # Require that the lock file path be absolute, or at least relative
        # and starting with the pipeline output folder.
        if not (os.path.isabs(lockfile) or lockfile.startswith(self.outfolder)):
            lockfile = self._make_lock_path(lockfile)
        return lockfile.replace(LOCK_PREFIX, "recover." + LOCK_PREFIX)
722923
private function acquireLock()
    {
        $this->logger->info('Acquire lock file.');

        if (!$this->lock->lock()) {
            $locked = false;
            $retry  = 3;
            // Try up to 3 times to acquire with short delay in between.
            while ($retry > 0) {
                usleep(1000);
                if ($locked = $this->lock->lock()) {
                    break;
                }
                $retry--;
            }
            if (!$locked) {
                $this->logger->error('Could not acquire lock file.');
                throw new \RuntimeException(
                    'Another task appears to be running. If this is not the case, please remove the lock file.'
                );
            }
        }
    }
130105
@Override
    public synchronized Lock obtainReadLock() {
        File writeLock = getWriteLock();

        if (writeLock != null && writeLock.exists()) {
            return null;
        }

        return createLock(false);
    }
249812
def _obtain_lock_or_raise(self):
        """"""
        if self._has_lock():
            return
        lock_file = self._lock_file_path()
        if os.path.isfile(lock_file):
            raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file))

        try:
            fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0)
            os.close(fd)
        except OSError,e:
            raise IOError(str(e))

        self._owns_lock = True
1186834
def _is_locked(self):
        '''
        
        '''
        if os.path.isfile(self._lck):
            try:
                import psutil
            except ImportError:
                return True #Lock file exists and no psutil
            #If psutil is imported
            with open(self._lck) as f:
                pid = f.read()
            return True if psutil.pid_exists(int(pid)) else False
        else:
            return False
1145156
def valid_lock(self):
        

        lock_pid = self.get_lock_pid()

        # If we're unable to get lock_pid
        if lock_pid is None:
            return False

        # this is our process
        if self._pid == lock_pid:
            return True

        # it is/was another process
        # see if it is running
        try:
            os.kill(lock_pid, 0)
        except OSError:
            self.release()
            return False

        # it is running
        return True
371077
def __checkLock(self):
        
        if self._isLocked:
            if (time.time() - self._timer) > TIMEOUT_TIMES[self._operation]:
                self.__unLock()
                return False
            return True
        return False
954933
def acquire(self, timeout=None):
        

        timeout = timeout is not None and timeout or self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        while True:
            try:
                write_pid_to_pidfile(self.path)
            except OSError as exc:
                if exc.errno == errno.EEXIST:
                    # The lock creation failed.  Maybe sleep a bit.
                    if timeout is not None and time.time() > end_time:
                        if timeout > 0:
                            raise LockTimeout("Timeout waiting to acquire"
                                              " lock for %s" %
                                              self.path)
                        else:
                            raise AlreadyLocked("%s is already locked" %
                                                self.path)
                    time.sleep(timeout is not None and timeout/10 or 0.1)
                else:
                    raise LockFailed("failed to create %s" % self.path)
            else:
                return