Decorate the handle method with a file lock to ensure there is only ever
    one process running at any one time.
559939
def handle_lock(handle):
    
    
    def wrapper(self, *args, **options):
        def on_interrupt(signum, frame):
            # It's necessary to release lockfile
            sys.exit()
        signal.signal(signal.SIGTERM, on_interrupt)

        start_time = time.time()
        try:
            verbosity = int(options.get('verbosity', 0))
        except ValueError:
            verbosity = 0
        logger = logging.getLogger(self.__module__)
        if verbosity == 0:
            logger.level = logging.WARNING
        elif verbosity == 1:
            logger.level = logging.INFO
        else:
            logger.level = logging.DEBUG
       
        logger.debug("-" * 72)
        
        lock_name = self.__module__.split('.').pop()
        lock = FileLock(os.path.join(LOCK_ROOT, lock_name))
        
        logger.debug("%s - acquiring lock..." % lock_name)
        try:
            lock.acquire(LOCK_WAIT_TIMEOUT)
        except AlreadyLocked:
            logger.debug("lock already in place. quitting.")
            return
        except LockTimeout:
            logger.debug("waiting for the lock timed out. quitting.")
            return
        logger.debug("acquired.")
        
        try:
            handle(self, logger, *args, **options)
        except (KeyboardInterrupt, SystemExit):
            pass
        except:
            import traceback
            logging.warn("Command Failed")
            logging.warn('=' * 72)
            logging.warn(traceback.format_exc())
            logging.warn('=' * 72)
        
        logger.debug("releasing lock...")
        lock.release()
        logger.debug("released.")
        
        logger.info("done in %.2f seconds" % (time.time() - start_time))
        return
        
    return wrapper
693000
def _release_lock(self):
        """"""
        if not self._has_lock():
            return

        # if someone removed our file beforhand, lets just flag this issue
        # instead of failing, to make it more usable.
        lfp = self._lock_file_path()
        try:
            rmfile(lfp)
        except OSError:
            pass
        self._owns_lock = False
831450
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0):
    
    lock = lock_cls(path)
    max_t = time.time() + timeout
    while True:
        if time.time() >= max_t:
            raise LockTimeout("Timeout waiting to acquire lock for %s" % (path,))  # same exception messages as in lockfile
        try:
            lock.acquire(timeout=0)
        except AlreadyLocked:
            sleep(maxdelay)
        else:
            try:
                yield lock
                break
            finally:
                lock.release()
245010
public synchronized boolean lock() throws KeeperException, InterruptedException {
        if (isClosed()) {
            return false;
        }
        ensurePathExists(dir);

        return (Boolean) retryOperation(zop);
    }
793184
def lock(self):
        '''
        
        '''

        # Open file
        self.__fd = open(self.__lockfile, "w")

        # Get it locked
        if self.__locktype == "wait":
            # Try to get it locked until ready
            fcntl.flock(self.__fd.fileno(), fcntl.LOCK_EX)
        elif self.__locktype == "lock":
            # Try to get the locker if can not raise an exception
            try:
                fcntl.flock(self.__fd.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
            except IOError:
                raise AlreadyLocked("File is already locked")
1076288
def async_run(self, keyword, *args, **kwargs):
        '''  '''
        handle = self._last_thread_handle
        thread = self._threaded(keyword, *args, **kwargs)
        thread.start()
        self._thread_pool[handle] = thread
        self._last_thread_handle += 1
        return handle
1171450
def _HandleFlowProcessingRequestLoop(self, handler):
    """"""
    while not self.flow_handler_stop:
      with self.lock:
        todo = self._GetFlowRequestsReadyForProcessing()
        for request in todo:
          self.flow_handler_num_being_processed += 1
          del self.flow_processing_requests[(request.client_id,
                                             request.flow_id)]

      for request in todo:
        handler(request)
        with self.lock:
          self.flow_handler_num_being_processed -= 1

      time.sleep(0.2)
1156633
@Override
	public final void lock(int handle) throws DataStoreException 
    {
        if (SAFE_MODE) checkHandle(handle);
        if (!locks.flip(handle))
        {
            locks.flip(handle); // Restore state
            throw new DataStoreException("Handle already locked : "+handle);
        }
    }
46932
def one_instance(function=None, key='', timeout=DEFAULT_ONE_INSTANCE_TIMEOUT):
    
    def _dec(run_func):
        def _caller(*args, **kwargs):
            ret_value = None
            have_lock = False
            # Use Redis AOF for persistent lock.
            if REDIS_CLIENT.config_get('appendonly').values()[0] == 'no':
                REDIS_CLIENT.config_set('appendonly', 'yes')
            lock = REDIS_CLIENT.lock(key, timeout=timeout)
            try:
                logger.debug(
                    '%s: trying to acquire lock (PID %d).'
                    % (key, os.getpid()))
                have_lock = lock.acquire(blocking=False)
                if have_lock:
                    logger.debug(
                        '%s: acquired lock (PID %d).' % (key, os.getpid()))
                    ret_value = run_func(*args, **kwargs)
                else:
                    logger.error(
                        '%s: did not acquire lock (PID %d).'
                        % (key, os.getpid()))
            finally:
                if have_lock:
                    lock.release()
                    logger.debug(
                        '%s: released lock (PID %d).' % (key, os.getpid()))
            return ret_value
        return _caller
    return _dec(function) if function is not None else _dec
1272383
async def ensure_process(self):
        
        # We don't want multiple requests trying to start the process at the same time
        # FIXME: Make sure this times out properly?
        # Invariant here should be: when lock isn't being held, either 'proc' is in state &
        # running, or not.
        with (await self.state['proc_lock']):
            if 'proc' not in self.state:
                # FIXME: Prevent races here
                # FIXME: Handle graceful exits of spawned processes here
                cmd = self.get_cmd()
                server_env = os.environ.copy()

                # Set up extra environment variables for process
                server_env.update(self.get_env())

                timeout = self.get_timeout()

                proc = SupervisedProcess(self.name, *cmd, env=server_env, ready_func=self._http_ready_func, ready_timeout=timeout, log=self.log)
                self.state['proc'] = proc

                try:
                    await proc.start()

                    is_ready = await proc.ready()

                    if not is_ready:
                        await proc.kill()
                        raise web.HTTPError(500, 'could not start {} in time'.format(self.name))
                except:
                    # Make sure we remove proc from state in any error condition
                    del self.state['proc']
                    raise
748212
def lock_pid(self):
        
        
        if os.path.exists(self.lock_filename):
            return int(open(self.lock_filename).read())
        else:
            return None
435680
def assert_lock(fname):
    

    if not set_lock(fname):
        logger.error('File {} is already locked. Terminating.'.format(fname))
        sys.exit()
406365
def do_global_lock(self, args):
        ''''''
        if args.purge:
            self.task_master.registry.force_clear_lock()
        else:
            owner = self.task_master.registry.read_lock()
            if owner:
                heartbeat = self.task_master.get_heartbeat(owner)
                if 'hostname' in heartbeat:
                    self.stdout.write('{0} ({1})\n'.format(owner,
                                                         heartbeat['hostname']))
                else:
                    self.stdout.write('{0}\n'.format(owner))
            else:
                self.stdout.write('(unlocked)\n')
1218581
def synchronized(wrapped):
    

    @functools.wraps(wrapped)
    def wrapper(*args, **kwargs):
        self = args[0]
        with self._lock:
            return wrapped(*args, **kwargs)

    return wrapper
876485
def flush_one(self, process_name, ignore_priority=False):
        
        q = self.reprocess_uows[process_name]
        self._flush_queue(q, ignore_priority)
462738
def _postprocess(self, filehandle, metadata):
        ""
        for process in self._postprocessors:
            filehandle = process(filehandle, metadata)
        return filehandle
5876
def lifecycle_lock(self):
    """"""
    safe_mkdir(self._metadata_base_dir)
    return OwnerPrintingInterProcessFileLock(
      # N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock`
      # via `ProcessMetadataManager._get_metadata_dir_by_name()`) because of a need to purge
      # the named metadata dir on startup to avoid stale metadata reads.
      os.path.join(self._metadata_base_dir, '.lock.{}'.format(self._name))
    )