Lock process

Lock the process so that multiple instances can't run simultaneously.
Override if applicable, but the duration should be greater than that
defined in the time_exceeded() method.
507460
protected function lock_process() {
		Logger::info( "Locking process {$this->identifier}");
		$this->start_time = time(); // Set start time of current process.

		$lock_duration = ( property_exists( $this, 'queue_lock_time' ) ) ? $this->queue_lock_time : 60; // 1 minute
		$lock_duration = apply_filters( $this->identifier . '_queue_lock_time', $lock_duration );

		update_option($this->identifier . '_process_lock', ['time' => microtime(), 'expires' => time() + $lock_duration]);
	}
260468
def lock(self):
        
        if isinstance(self._session, manager.Manager):
            self._session.lock()
442363
public void setLockDuration(Duration lockDuration)
    {
        this.lockDuration = lockDuration;
        if (this.lockDuration.compareTo(ManagementClientConstants.MAX_DURATION) > 0) {
            this.lockDuration = ManagementClientConstants.MAX_DURATION;
        }
    }
372515
def raise_or_lock(self, key, timeout):
        
        lock_path = self._get_lock_path(key)
        try:
            # Create lock file, raise exception if it exists
            fd = os.open(lock_path, os.O_CREAT | os.O_EXCL)
        except OSError as error:
            if error.errno == errno.EEXIST:
                # File already exists, check its modification time
                mtime = os.path.getmtime(lock_path)
                ttl = mtime + timeout - time.time()
                if ttl > 0:
                    raise AlreadyQueued(ttl)
                else:
                    # Update modification time if timeout happens
                    os.utime(lock_path, None)
                    return
            else:
                # Re-raise unexpected OSError
                raise
        else:
            os.close(fd)
742931
def simple_locking(lock_id, expiration=None):
    
    def inner_decorator(function):
        def wrapper(*args, **kwargs):
            try:
                # Trying to acquire lock
                lock = Lock.acquire_lock(lock_id, expiration)
            except LockError:
                # Unable to acquire lock - non fatal
                pass
            else:
                # Lock acquired, proceed normally, release lock afterwards
                logger.debug('acquired lock: %s' % lock_id)
                try:
                    return function(*args, **kwargs)
                except:
                    # Re raise any exception that occured when calling wrapped
                    # function
                    raise
                finally:
                    lock.release()
        return wraps(function)(wrapper)
    return inner_decorator
575080
def lock_file(f, block=False):
    
    try:
        flags = fcntl.LOCK_EX
        if not block:
            flags |= fcntl.LOCK_NB
        fcntl.flock(f.fileno(), flags)
    except IOError as e:
        if e.errno in (errno.EACCES, errno.EAGAIN):
            raise SystemExit("ERROR: %s is locked by another process." %
                             f.name)
        raise
834244
def _enable_lock(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if self.is_concurrent:
            only_read = kwargs.get('only_read')
            if only_read is None or only_read:
                with self._rwlock:
                    return func(*args, **kwargs)
            else:
                self._rwlock.acquire_writer()
                try:
                    return func(*args, **kwargs)
                finally:
                    self._rwlock.release()
        else:
            return func(*args, **kwargs)

    return wrapper
1020623
void lock(String serverId) {
        Assert.notNull(serverId);
        if (this.locked) {
            throw new IllegalStateException("Cannot lock already locked mutex: " + this);
        }
        this.locked = true;
        this.lockStart = new Date();
        this.lastUpdate = this.lockStart;
        this.serverId = serverId;
    }
198009
def _stop_cpulimit(self):
        

        if self._cpulimit_process and self._cpulimit_process.returncode is None:
            self._cpulimit_process.kill()
            try:
                self._process.wait(3)
            except subprocess.TimeoutExpired:
                log.error("Could not kill cpulimit process {}".format(self._cpulimit_process.pid))
1129793
public synchronized void lock()
  {
    if (tc.isEntryEnabled())
      SibTr.entry(tc, "lock", this);

    boolean interrupted = false;

    // Attempt to get a lock on the mutex.
    // if we fail, then that is because the lock
    // must be held exclusively.
    while (!tryLock())
      try
      {
        // Wait for 1 second then try again.
        if (tc.isDebugEnabled())
          SibTr.debug(tc, "Waiting for lock");
        wait(1000);
      }
      catch (InterruptedException e)
      {
        // No FFDC code needed
        interrupted = true;
      }

    if (interrupted)
      Thread.currentThread().interrupt();

    if (tc.isEntryEnabled())
      SibTr.exit(tc, "lock");

  }
1125105
def lock(self):
        
        clean = True
        while True:
            try:
                symlink(str(os.getpid()), self.name)
            except OSError as e:
                if _windows and e.errno in (errno.EACCES, errno.EIO):
                    # The lock is in the middle of being deleted because we're
                    # on Windows where lock removal isn't atomic.  Give up, we
                    # don't know how long this is going to take.
                    return False
                if e.errno == errno.EEXIST:
                    try:
                        pid = readlink(self.name)
                    except OSError as e:
                        if e.errno == errno.ENOENT:
                            # The lock has vanished, try to claim it in the
                            # next iteration through the loop.
                            continue
                        raise
                    except IOError as e:
                        if _windows and e.errno == errno.EACCES:
                            # The lock is in the middle of being
                            # deleted because we're on Windows where
                            # lock removal isn't atomic.  Give up, we
                            # don't know how long this is going to
                            # take.
                            return False
                        raise
                    try:
                        if kill is not None:
                            kill(int(pid), 0)
                        # Verify that the running process corresponds to
                        # a Spyder one
                        p = psutil.Process(int(pid))

                        # Valid names for main script
                        names = set(['spyder', 'spyder3', 'spyder.exe',
                                     'spyder3.exe', 'bootstrap.py',
                                     'spyder-script.py'])
                        if running_under_pytest():
                            names.add('runtests.py')

                        # Check the first three command line arguments
                        arguments = set(os.path.basename(arg)
                                        for arg in p.cmdline()[:3])
                        conditions = [names & arguments]
                        if not any(conditions):
                            raise(OSError(errno.ESRCH, 'No such process'))
                    except OSError as e:
                        if e.errno == errno.ESRCH:
                            # The owner has vanished, try to claim it in the
                            # next iteration through the loop.
                            try:
                                rmlink(self.name)
                            except OSError as e:
                                if e.errno == errno.ENOENT:
                                    # Another process cleaned up the lock.
                                    # Race them to acquire it in the next
                                    # iteration through the loop.
                                    continue
                                raise
                            clean = False
                            continue
                        raise
                    return False
                raise
            self.locked = True
            self.clean = clean
            return True
1090210
def acquire(self, blocking=True, timeout=None):
        
        logger.debug("Getting %r ...", self._name)

        if self._held:
            raise AlreadyAcquired("Already acquired from this Lock instance.")

        if not blocking and timeout is not None:
            raise TimeoutNotUsable("Timeout cannot be used if blocking=False")

        timeout = timeout if timeout is None else int(timeout)
        if timeout is not None and timeout <= 0:
            raise InvalidTimeout("Timeout (%d) cannot be less than or equal to 0" % timeout)

        if timeout and self._expire and timeout > self._expire:
            raise TimeoutTooLarge("Timeout (%d) cannot be greater than expire (%d)" % (timeout, self._expire))

        busy = True
        blpop_timeout = timeout or self._expire or 0
        timed_out = False
        while busy:
            busy = not self._client.set(self._name, self._id, nx=True, ex=self._expire)
            if busy:
                if timed_out:
                    return False
                elif blocking:
                    timed_out = not self._client.blpop(self._signal, blpop_timeout) and timeout
                else:
                    logger.debug("Failed to get %r.", self._name)
                    return False

        logger.debug("Got lock for %r.", self._name)
        if self._lock_renewal_interval is not None:
            self._start_lock_renewer()
        return True
1086084
public synchronized boolean lock(ActivityLog log, long maxWait, TimeUnit unit) throws Exception
    {
        if ( ownsTheLock )
        {
            throw new IllegalStateException("Already locked");
        }

        lockStartMs = System.currentTimeMillis();

        key = lockPrefix + lockKeySeparator + newRandomSequence();

        long        startMs = System.currentTimeMillis();
        boolean     hasMaxWait = (unit != null);
        long        maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE;
        Preconditions.checkState(maxWaitMs >= settlingMs, String.format("The maxWait ms (%d) is less than the settling ms (%d)", maxWaitMs, settlingMs));

        createFile(key, content.getBytes());

        for(;;)
        {
            checkUpdate();
            if ( ownsTheLock )
            {
                break;
            }
            long        thisWaitMs;
            if ( hasMaxWait )
            {
                long        elapsedMs = System.currentTimeMillis() - startMs;
                thisWaitMs = maxWaitMs - elapsedMs;
                if ( thisWaitMs <= 0 )
                {
                    log.add(ActivityLog.Type.ERROR, String.format("Could not acquire lock within %d ms, polling: %d ms, key: %s", maxWaitMs, pollingMs, key));
                    break;
                }
            }
            else
            {
                thisWaitMs = pollingMs;
            }
            wait(Math.min(pollingMs, thisWaitMs));
        }
        return ownsTheLock;
    }
251132
def lock_account(self, identifier):
        
        locked_time = int(time.time() * 1000)  # milliseconds
        self.account_store.lock_account(identifier, locked_time)
382749
def acquire_lock(self):
        
        key = '%s_lock' % self.scheduler_key
        now = time.time()
        expires = int(self._interval) + 10
        self._lock_acquired = self.connection.set(
                key, now, ex=expires, nx=True)
        return self._lock_acquired
87761
public void lock() {
		if (cancel != null)
			return;
		if (error != null)
			return;
		Thread t;
		BlockedThreadHandler blockedHandler;
		do {
			synchronized (this) {
				if (!locked) {
					locked = true;
					return;
				}
				t = Thread.currentThread();
				blockedHandler = Threading.getBlockedThreadHandler(t);
				if (blockedHandler != null) break;
				try { this.wait(0); }
				catch (InterruptedException e) { continue; }
			}
		} while (true);
		blockedHandler.blocked(this, 0);
	}
884643
private <T> Optional<T> tryWithLock(long timeout, TimeUnit unit, Supplier<T> task)
    {
        checkLockNotHeld("Lock can not be reacquired");

        boolean acquired = false;
        try {
            acquired = exclusiveLock.tryLock(timeout, unit);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        if (!acquired) {
            return Optional.empty();
        }

        Optional<T> result;
        try {
            result = Optional.of(task.get());
        }
        finally {
            try {
                try {
                    processNewSources();
                }
                finally {
                    destroyIfNecessary();
                }
            }
            finally {
                exclusiveLock.unlock();
            }
        }

        // If there are more source updates available, attempt to reacquire the lock and process them.
        // This can happen if new sources are added while we're holding the lock here doing work.
        // NOTE: this is separate duplicate code to make debugging lock reacquisition easier
        // The first condition is for processing the pending updates if this driver is still ALIVE
        // The second condition is to destroy the driver if the state is NEED_DESTRUCTION
        while (((pendingTaskSourceUpdates.get() != null && state.get() == State.ALIVE) || state.get() == State.NEED_DESTRUCTION)
                && exclusiveLock.tryLock()) {
            try {
                try {
                    processNewSources();
                }
                finally {
                    destroyIfNecessary();
                }
            }
            finally {
                exclusiveLock.unlock();
            }
        }

        return result;
    }