wraps method with lock acquire/release cycle
     decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock
323406
def thread_safe(method):
    

    @functools.wraps(method)
    def _locker(self, *args, **kwargs):
        assert hasattr(self, 'lock'), \
            'thread_safe decorator applied to method {0}.{1}: missing required field {0}.lock'\
            .format(self.__class__.__name__, method.__name__)

        try:
            self.lock.acquire()
            return method(self, *args, **kwargs)
        finally:
            try:
                self.lock.release()
            except:
                sys.stderr.write('Exception on releasing lock at method {0}'.format(method.__name__))
                traceback.print_exc(file=sys.stderr)

    return _locker
1351141
def singleton(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if wrapper.__call_state__ == CALLED:
            return
        ret = func(*args, **kwargs)
        wrapper.__call_state__ = CALLED
        return ret

    def reset():
        wrapper.__call_state__ = NOT_CALLED

    wrapper.reset = reset
    reset()

    # save original func to be able to patch and restore multiple times from
    # unit tests
    wrapper.__original_func = func
    return wrapper
1307451
def return_self_updater(func):
    '''
    
    '''
    @functools.wraps(func)
    def decorator(k,v):
        func(k,v)
        return v
    return decorator
722213
def requires_lock(function):
    

    def new_lock_requiring_function(self, filename, *args, **kwargs):
        if self.owns_lock(filename):
            return function(self, filename, *args, **kwargs)
        else:
            raise RequiresLockException()

    return new_lock_requiring_function
1361054
def with_lock(lock):
  """"""
  def decorator(func):
    @functools.wraps(func)
    def _with_lock(*args, **kwargs):
      with lock:
        return func(*args, **kwargs)
    return _with_lock
  return decorator
719403
def wrapply(func, *args, **kwargs):
    ''
    val = args[0]
    if val is None:
        return TypedWrapper(func, None)
    elif isinstance(val, TypedExceptionWrapper):
        tew = copy(val)
        tew.forwarded = True
        return tew
    elif isinstance(val, TypedWrapper):
        return val
    elif isinstance(val, Exception):
        return TypedWrapper(func, *args)

    try:
        return func(*args, **kwargs)
    except Exception as e:
        e.stacktrace = stacktrace()
        return TypedExceptionWrapper(func, *args, exception=e)
152220
def require(self, lock, guard_func, *guard_args, **guard_kw):
        
        def decorator(f):
            @wraps(f)
            def wrapper(*args, **kw):
                if self.granted(lock):
                    self.msg('Granted {}'.format(lock))
                    return f(*args, **kw)
                if guard_func(*guard_args, **guard_kw) and self.acquire(lock):
                    return f(*args, **kw)
                return None
            return wrapper
        return decorator
449087
def decorate(decorator_cls, *args, **kwargs):
    """"""
    global _wrappers

    wrapper_cls = _wrappers.get(decorator_cls, None)
    if wrapper_cls is None:

        class PythonWrapper(decorator_cls):
            pass

        wrapper_cls = PythonWrapper
        wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
        _wrappers[decorator_cls] = wrapper_cls

    def decorator(fn):
        wrapped = wrapper_cls(fn, *args, **kwargs)
        _update_wrapper(wrapped, fn)
        return wrapped

    return decorator
187323
function maybeReleaseLock() {
    var lock = self.client.lock;

    function done(err) {
      log.debug({client: self.client}, 'Closed client sync handler');
      self.client.lock = null;
      self.client = null;
      callback(err);
    }

    // No lock
    if(!lock) {
      return done();
    }
    // Lock reference, but it's already unlocked
    if(lock.unlocked) {
      return done();
    }
    // Holding lock, release it
    lock.release(function(err) {
      if(err) {
        log.error({err: err, client: self.client}, 'Error releasing sync lock');
        return done(err);
      }
      done();
    });
  }
1106265
def synchronized(sync_lock):
    """"""

    def wrapper(f):
        """The decorator's core function.

        :param f:
        :return:
        """

        @functools.wraps(f)
        def inner_wrapper(*args, **kw):
            """

            :param args:
            :param kw:
            :return:
            """
            with sync_lock:
                return f(*args, **kw)

        return inner_wrapper

    return wrapper
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
109767
def synchronized(func):
    
    @wraps(func)
    def wrapped(self, *args, **kwargs):
        try:
            rlock = self._sync_lock
        except AttributeError:
            from multiprocessing import RLock
            rlock = self.__dict__.setdefault('_sync_lock', RLock())
        with rlock:
            return func(self, *args, **kwargs)
    return wrapped
315707
def _AcquireLock(self,
                   urn,
                   blocking=None,
                   blocking_lock_timeout=None,
                   lease_time=None,
                   blocking_sleep_interval=None):
    """"""
    if urn is None:
      raise ValueError("URN cannot be None")

    urn = rdfvalue.RDFURN(urn)

    try:
      return data_store.DB.LockRetryWrapper(
          urn,
          retrywrap_timeout=blocking_sleep_interval,
          retrywrap_max_timeout=blocking_lock_timeout,
          blocking=blocking,
          lease_time=lease_time)
    except data_store.DBSubjectLockError as e:
      raise LockError(e)
33852
def wrap(self, func, delay=0):
        '''
        
        '''
        def wrapped():
            self.start()
            if delay:
                self.sleep(delay)
            x = None
            try:
                x = func()
            except OSError as oserror:
                log.debug('OSError exception:%s', oserror)
                self.oserror = oserror
                raise EasyProcessError(self, 'wrap error!')
            finally:
                self.stop()
            return x
        return wrapped
285990
def decorate_method(wrapped):
    
    def wrapper(self):
        lines = Lines()
        if hasattr(self.model, wrapped.__name__):
            print('            . %s' % wrapped.__name__)
            lines.add(1, method_header(wrapped.__name__, nogil=True))
            for line in wrapped(self):
                lines.add(2, line)
        return lines
    functools.update_wrapper(wrapper, wrapped)
    wrapper.__doc__ = 'Lines of model method %s.' % wrapped.__name__
    return property(wrapper)
1356875
def threaded(system, func, *args, **kwargs):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            if system.raven_client:
                system.raven_client.captureException()
            logger.exception('Exception occurred in thread: %s', e)
            return False

    return lambda: wrapper(*args, **kwargs)
452025
def wrap_sync(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.Future()
        def green():
            try:
                fut.set_result(func(*args, **kwargs))
            except BaseException as e:
                fut.set_exception(e)
        greenlet.greenlet(green).switch()
        return fut
    return wrapped