Escalate Read lock to exclusive level

@param  Zend_Search_Lucene_Storage_Directory $lockDirectory
@return boolean
336234
public static function escalateReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
    {
        self::_startReadLockProcessing($lockDirectory);

        $lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE);

        // First, release the shared lock for the benefit of GFS since
        // it will fail the conditional request to promote the lock to
        // "exclusive" while the shared lock is held (even when we are
        // the only holder).
        $lock->unlock();

        // GFS is really poor.  While the above "unlock" returns, GFS
        // doesn't clean up it's tables right away (which will potentially
        // cause the conditional locking for the "exclusive" lock to fail.
        // We will retry the conditional lock request several times on a
        // failure to get past this.  The performance hit is negligible
        // in the grand scheme of things and only will occur with GFS
        // filesystems or if another local process has the shared lock
        // on local filesystems.
        for ($retries = 0; $retries < 10; $retries++) {
            if ($lock->lock(LOCK_EX, true)) {
                // Exclusive lock is obtained!
                self::_stopReadLockProcessing($lockDirectory);
                return true;
            }

            // wait 1 microsecond
            usleep(1);
        }

        // Restore lock state
        $lock->lock(LOCK_SH);

        self::_stopReadLockProcessing($lockDirectory);
        return false;
    }
914196
public function lock()
    {
        if (!$this->isLocked()) {
            $file = fopen($this->getFilePath(), 'w');
            if ($file) {
                fwrite($file, getmypid());
                fclose($file);
                return true;
            }
        }
        return false;
    }
282830
public static function loadLockPackages(array $lockData)
    {
        $loader = new ArrayLoader();
        $lockData = static::loadLockPackage($loader, $lockData);
        $lockData = static::loadLockPackage($loader, $lockData, true);
        $lockData = static::convertLockAlias($lockData);

        return $lockData;
    }
884985
public function unlockNode($uri, LockInfo $lockInfo)
    {
        if (!$this->server->emit('beforeUnlock', [$uri, $lockInfo])) {
            return;
        }

        return $this->locksBackend->unlock($uri, $lockInfo);
    }
1131265
public boolean lock(boolean shared, boolean block)
  {
    if (shared && !_canRead) {
      // Invalid request for a shared "read" lock on a write only stream.

      return false;
    }

    if (!shared && !_canWrite) {
      // Invalid request for an exclusive "write" lock on a read only stream.

      return false;
    }

    return true;
  }
1329330
public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
    {
        if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
            clearstatcache(true, $cached->lock_id);
        } else {
            clearstatcache();
        }
        if (is_file($cached->lock_id)) {
            $t = @filemtime($cached->lock_id);
            return $t && (time() - $t < $smarty->locking_timeout);
        } else {
            return false;
        }
    }
597220
public function sharedLock()
    {
        // Pack query then move it to write DB from read DB for transaction
        $sql = $this->_dbr->get_compiled_select();
        $this->_dbr->reset_query();

        return $this->_db->query("{$sql} LOCK IN SHARE MODE");
    }
801452
public function _singleUpdateLock($lockFile)
    {
        $lockData = [
            'pid' => getmypid(),
            'expires_at' => time() + $this->singleSleep + $this->singleLockTimeout,
        ];

        return file_put_contents($lockFile, json_encode($lockData));
    }
1143265
public function find($id, $lockMode = null, $lockVersion = null)
    {
        $qb = $this->createQueryBuilder('n');

        if (preg_match('/^\d+$/', $id)) {
            $qb->where('n.id = :id');
        } else {
            $qb->where('n.uuid = :id');
        }

        return $qb
            ->getQuery()
            ->setParameter('id', $id)
            ->getOneOrNullResult();
    }
1201530
private void ensureIndexIsUnlocked(String dataDir) {

        Collection<File> lockFiles = new ArrayList<File>(2);
        lockFiles.add(
            new File(
                CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + "index") + "write.lock"));
        lockFiles.add(
            new File(
                CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + "spellcheck")
                    + "write.lock"));
        for (File lockFile : lockFiles) {
            if (lockFile.exists()) {
                lockFile.delete();
                LOG.warn(
                    "Forcely unlocking index with data dir \""
                        + dataDir
                        + "\" by removing file \""
                        + lockFile.getAbsolutePath()
                        + "\".");
            }
        }
    }
374864
public function acquireLock($entityId, $lockType, $expirationSeconds = null, $retryTimeoutSeconds = null)
        {
            /* Sanitize */
            
            if (is_null($expirationSeconds)) {
                $expirationSeconds = (int)config('locking.expiration_seconds', 30);
            }
            
            if (is_null($retryTimeoutSeconds)) {
                $retryTimeoutSeconds = (int)config('locking.retry_timeout_seconds', 10);
            }
            
            /* Initialize */

            $lock = null;

            if (is_null(Auth::user())) {
                throw new LockTimeoutException();
            }
            $userId = Auth::user()->id;

            /* Attempt to acquire the desired lock */

            $timestampEnd = time() + $retryTimeoutSeconds;
            while (is_null($lock) && time() <= $timestampEnd) {
                /* Determine whether a more important lock is set on the requested entity */

                $needToSleep = false;

                switch ($lockType) {
                    case $this::READ_LOCK:
                        if ($this->isWriteLocked($entityId)) {
                            $needToSleep = true;
                        }

                        break;

                    case $this::WRITE_LOCK:
                        /* We need to check all active locks for this entity */

                        $locks = $this->getLocks($entityId);
                        $activeLockCount = $this->getLocks($entityId)->filter(function ($lock, $key) use ($userId) {
                            // (new Dumper())->dump($lock);
                            return Locking::WRITE_LOCK == $lock->lock_type || $lock->user_id != $userId;
                        })->count();

                        $needToSleep = (0 != $activeLockCount);

                        break;
                }

                if ($needToSleep) {
                    usleep(500000);
                    continue;
                }

                $lock = Lock::create([
                    'user_id'    => Auth::user()->id,
                    'entity_id'  => $entityId,
                    'lock_type'  => $lockType,
                    'expires_at' => Carbon::now()->addSeconds($expirationSeconds),
                ]);
            }

            if (is_null($lock)) {
                throw new LockTimeoutException();
            }

            /* Return lock */

            return $lock->id;
        }
1244008
protected function setLockDirectory($lockDirectory)
    {
        if (! is_dir($lockDirectory)) {
            throw new InvalidArgumentException(sprintf('"%s" is not a valid directory', $lockDirectory));
        }

        if (! is_writable($lockDirectory)) {
            throw new InvalidArgumentException(sprintf('"%s" is not a writable directory', $lockDirectory));
        }

        $this->lockDirectory = $lockDirectory;
    }
926899
public function isDirectory()
    {
        clearstatcache();
        $fs = FileSystem::getFileSystem();
        if ($fs->checkAccess($this) !== true) {
            throw new IOException("No read access to " . $this->path);
        }

        return @is_dir($this->path) && !@is_link($this->path);
    }
1223237
public static function isLockPrivilegeGranted()
    {
        if (is_null(self::$lockPrivilegeGranted)) {
            try {
                Db::lockTables(Common::prefixTable('log_visit'));
                Db::unlockAllTables();

                self::$lockPrivilegeGranted = true;
            } catch (Exception $ex) {
                self::$lockPrivilegeGranted = false;
            }
        }

        return self::$lockPrivilegeGranted;
    }
246260
protected function lock(string $key, Closure $callback, int $lockType = LOCK_EX) {
		$filename = $this->generateFilename($key);
		$type     = is_file($filename) ? 'rb+' : 'wb+';
		if ($handle = fopen($filename, $type)) {
			if (flock($handle, $lockType)) {
				$callback($handle);
				flock($handle, LOCK_UN);
				fclose($handle);
				return true;
			}
		}
		return false;
	}
1339401
public function lock($uri, LockInfo $lockInfo)
    {
        // We're making the lock timeout 30 minutes
        $lockInfo->timeout = 1800;
        $lockInfo->created = time();
        $lockInfo->uri = $uri;

        $locks = $this->getData();

        foreach ($locks as $k => $lock) {
            if (
                ($lock->token == $lockInfo->token) ||
                (time() > $lock->timeout + $lock->created)
            ) {
                unset($locks[$k]);
            }
        }
        $locks[] = $lockInfo;
        $this->putData($locks);

        return true;
    }
1287824
DirectoryEntry lookUpWithLock(JimfsPath path, Set<? super LinkOption> options)
      throws IOException {
    store.readLock().lock();
    try {
      return lookUp(path, options);
    } finally {
      store.readLock().unlock();
    }
  }