usr/bin/lockfile000075500000046560147207335000007657 0ustar00ELF>@0F@8 @@@@88899 h<h< h<  << < TTTDDPtd424242\\QtdRtdh<h< h< /lib64/ld-linux-x86-64.so.2GNU GNUg.cID.ҽl@Vo,@ ,.BE|qX  u|Ko8@|' g)!2uF6 J nRX"@ x@ @ libm.so.6_ITM_deregisterTMCloneTable__gmon_start___Jv_RegisterClasses_ITM_registerTMCloneTablelibc.so.6setuidstrcpygetpwuidsignaltime__stack_chk_fail__lxstatunlinkstrpbrkgetpidendpwentstrtolgetpwnamstrlenmemset__errno_locationmemcpymallocgetgidgetenvnicegetuidgetegid__fxstatchowngeteuidcloseopenstrchrsleep__cxa_finalize__xstatunamesetgid__libc_start_mainwritefree_edata__bss_start_endGLIBC_2.14GLIBC_2.4GLIBC_2.2.5dii ui h< p< P< < ? ? ? &? (? +> > > > > > >  >  >  >  >  > ? ? ? ?  ? (? 0? 8? @? H? P? X? `? h? p? x? ? ?  ? !? "? #? $? %? '? )? *? +HH1 HtcH5Z0 %\0 @%Z0 h%R0 h%J0 h%B0 h%:0 h%20 h%*0 h%"0 hp%0 h`%0 h P% 0 h @%0 h 0%/ h %/ h %/ h%/ h%/ h%/ h%/ h%/ h%/ h%/ h%/ h%/ hp%/ h`%/ hP%/ h@%/ h0%z/ h %r/ h%j/ h%b/ h%Z/ h %R/ h!%J/ h"%B/ h#%:/ h$%2/ h%%*/ h&AWAVAUATUSHdH%(H$1Ht$H/ ſ XqAtdH= 1AG H=1 H$dH3 %(D&H[]A\A]A^A_H=U 1A@h 9D$b|$=D$8OBH=E1CH=%15D$IHHT$X1HHHуyHcH=Kt*H\H= H=1H|$X1H=1HD$X(HH|$XHl$XHEHD$XEHDL$LHT$@Ht$8DT$0#DT$0C RHcH|-HHHh DL$LHDT$0Ht$8HT$@u>fEu%HEtnDA/HFt$vA:tA\tDHHf.AA\AAAH0A0@wAq0DG@wHHT$8HL$0HL$0HT$8HGL|$@\$LH$4HD$PH9$!HD$XH9$D$l9$D$p9$|$ Ht LL$ Hh 05L$ QH H HfAWAVAUATIUHSHH8dH%(H$(1u*H$(dH3 %(H8[]A\A]A^A_ÐHH޿ID0ItE7@H$HuH$H9 $t ME7t^LLH_H$H9L$uы$9L$uċ$9L$ uT$ f.SHHHdH%(H$1~,H|$wF8uDAE@HHPuFDHE1HIDHAIHHuD9~bD)HD9DHA H9uMcIIAL@HHIHH Copyright (c) 1997-2001, Philip A. Guenther Submit questions/answers to the procmail-related mailinglist by sending to: And of course, subscription and information requests for this list to: Your system mailbox's lockfile: -v display the version number and exit -nnn wait nnn seconds between locking attempts -r nnn make at most nnn retries before giving up on a lock -l nnn set locktimeout to nnn seconds -s nnn suspend nnn seconds after a locktimeout occurred -! invert the exitcode of lockfile -ml lock your system mail-spool file -mu unlock your system mail-spool file Can't determine your mailbox, who are you? again, already dropped my privilegesUsage: lockfile -v | -nnn | -r nnn | -l nnn | -s nnn | -! | -ml | -mu | file ... LOGNAMElockfile: .lock/0.,+%;X*|$}tt,<\l| $< <,Dd<4t< <4LLl \$ lzRx *zRx $PFJ w?;*3$"D \AT|AWLP BBB B(A0A8I 8A0A(B BBBA p'DN F N $x<pDLTxlph`LXgBBB B(D0D8J 8A0A(B BBBH Lx%BBB B(D0D8Jz 8A0A(B BBBB $TXAJe AG <|]BBA A(G0u (A ABBH AC D PVAO A $AGy AF $[<PT <ljAKF m AAG D DAG DHA<JBGA  ABH M ABH ,ACG ~ AAE LA@ G <$D_,TBDD i ABJ $^AGG EDA qAM B `XPH,@D8\0>Du$tX6AAG gDADpeBEE E(H0H8M@l8A0A(B BBBP< d  D-h< p< o0  > `   oo` oo o< FVfv&6FVfv&6FVfvlockfile.debug̬7zXZִF!t/]?Eh=ڊ2N/> (CL#xczH ^:=M&`\< //q߫Q*whm>iA(KGë(xJAw=e- > [+n=CWA6ụG`BFSj9Q"<κUzc}cэ< D~&ޥd00ufLnۭXnM =B[/wUiX@Գ Q9Z{VXxk(9m H%?D3MP̰M5@GG6u-k$ %V ЮP 8 :q$iC6 ]<$XX^ T}.6 SP M-vs:zm-7" ޶B|OǾ*H%-~cM#=2i8R.{;7emf}*sPR% 6>w0걷=h踹J^-~r'FbޢB ́&vE|eb j]<ӄs?C,2N;E[*HH{TTׄaʻaNyO7Gm~=UgQ/Dl !G͞QCOH>/OMg021_%svF͇{Ɔ2,ǚOY`@.?:cMivR ~wcL7VXTId3e;J\TCdnhr)C[dNR1E&$@ x JS]bb"l w ؤ@5l`~}R~6)-t` {8k~,1w cak^]K2-1jGVVNk]~gƸ,oAM>] T#Bh㙓Oǵ"I7 j\.+CDf2]*ûyI ȋyڀ9kX_1j+9l;jyL! o"1ꍅac&0&/T缭#Δc '(gYZ.shstrtab.interp.note.ABI-tag.note.gnu.build-id.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.text.fini.rodata.eh_frame_hdr.eh_frame.init_array.fini_array.jcr.data.rel.ro.dynamic.got.data.bss.gnu_debuglink.gnu_debugdata 88TT !tt$4o0> hF00No  ^[o` ` @j tB` `  ~y00D-D- `-`- 4242\33,h< h<p< p<x< x<< << <> >x@ @@ @h@@E__init__.py000064400000022233147230510270006660 0ustar00# -*- coding: utf-8 -*- """ lockfile.py - Platform-independent advisory file locks. Requires Python 2.5 unless you apply 2.4.diff Locking is done on a per-thread basis instead of a per-process basis. Usage: >>> lock = LockFile('somefile') >>> try: ... lock.acquire() ... except AlreadyLocked: ... print 'somefile', 'is locked already.' ... except LockFailed: ... print 'somefile', 'can\\'t be locked.' ... else: ... print 'got lock' got lock >>> print lock.is_locked() True >>> lock.release() >>> lock = LockFile('somefile') >>> print lock.is_locked() False >>> with lock: ... print lock.is_locked() True >>> print lock.is_locked() False >>> lock = LockFile('somefile') >>> # It is okay to lock twice from the same thread... >>> with lock: ... lock.acquire() ... >>> # Though no counter is kept, so you can't unlock multiple times... >>> print lock.is_locked() False Exceptions: Error - base class for other exceptions LockError - base class for all locking exceptions AlreadyLocked - Another thread or process already holds the lock LockFailed - Lock failed for some other reason UnlockError - base class for all unlocking exceptions AlreadyUnlocked - File was not locked. NotMyLock - File was locked but not by the current thread/process """ from __future__ import absolute_import import functools import os import socket import threading import warnings # Work with PEP8 and non-PEP8 versions of threading module. if not hasattr(threading, "current_thread"): threading.current_thread = threading.currentThread if not hasattr(threading.Thread, "get_name"): threading.Thread.get_name = threading.Thread.getName __all__ = ['Error', 'LockError', 'LockTimeout', 'AlreadyLocked', 'LockFailed', 'UnlockError', 'NotLocked', 'NotMyLock', 'LinkFileLock', 'MkdirFileLock', 'SQLiteFileLock', 'LockBase', 'locked'] class Error(Exception): """ Base class for other exceptions. >>> try: ... raise Error ... except Exception: ... pass """ pass class LockError(Error): """ Base class for error arising from attempts to acquire the lock. >>> try: ... raise LockError ... except Error: ... pass """ pass class LockTimeout(LockError): """Raised when lock creation fails within a user-defined period of time. >>> try: ... raise LockTimeout ... except LockError: ... pass """ pass class AlreadyLocked(LockError): """Some other thread/process is locking the file. >>> try: ... raise AlreadyLocked ... except LockError: ... pass """ pass class LockFailed(LockError): """Lock file creation failed for some other reason. >>> try: ... raise LockFailed ... except LockError: ... pass """ pass class UnlockError(Error): """ Base class for errors arising from attempts to release the lock. >>> try: ... raise UnlockError ... except Error: ... pass """ pass class NotLocked(UnlockError): """Raised when an attempt is made to unlock an unlocked file. >>> try: ... raise NotLocked ... except UnlockError: ... pass """ pass class NotMyLock(UnlockError): """Raised when an attempt is made to unlock a file someone else locked. >>> try: ... raise NotMyLock ... except UnlockError: ... pass """ pass class _SharedBase(object): def __init__(self, path): self.path = path def acquire(self, timeout=None): """ Acquire the lock. * If timeout is omitted (or None), wait forever trying to lock the file. * If timeout > 0, try to acquire the lock for that many seconds. If the lock period expires and the file is still locked, raise LockTimeout. * If timeout <= 0, raise AlreadyLocked immediately if the file is already locked. """ raise NotImplemented("implement in subclass") def release(self): """ Release the lock. If the file is not locked, raise NotLocked. """ raise NotImplemented("implement in subclass") def __enter__(self): """ Context manager support. """ self.acquire() return self def __exit__(self, *_exc): """ Context manager support. """ self.release() def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.path) class LockBase(_SharedBase): """Base class for platform-specific lock classes.""" def __init__(self, path, threaded=True, timeout=None): """ >>> lock = LockBase('somefile') >>> lock = LockBase('somefile', threaded=False) """ super(LockBase, self).__init__(path) self.lock_file = os.path.abspath(path) + ".lock" self.hostname = socket.gethostname() self.pid = os.getpid() if threaded: t = threading.current_thread() # Thread objects in Python 2.4 and earlier do not have ident # attrs. Worm around that. ident = getattr(t, "ident", hash(t)) self.tname = "-%x" % (ident & 0xffffffff) else: self.tname = "" dirname = os.path.dirname(self.lock_file) # unique name is mostly about the current process, but must # also contain the path -- otherwise, two adjacent locked # files conflict (one file gets locked, creating lock-file and # unique file, the other one gets locked, creating lock-file # and overwriting the already existing lock-file, then one # gets unlocked, deleting both lock-file and unique file, # finally the last lock errors out upon releasing. self.unique_name = os.path.join(dirname, "%s%s.%s%s" % (self.hostname, self.tname, self.pid, hash(self.path))) self.timeout = timeout def is_locked(self): """ Tell whether or not the file is locked. """ raise NotImplemented("implement in subclass") def i_am_locking(self): """ Return True if this object is locking the file. """ raise NotImplemented("implement in subclass") def break_lock(self): """ Remove a lock. Useful if a locking thread failed to unlock. """ raise NotImplemented("implement in subclass") def __repr__(self): return "<%s: %r -- %r>" % (self.__class__.__name__, self.unique_name, self.path) def _fl_helper(cls, mod, *args, **kwds): warnings.warn("Import from %s module instead of lockfile package" % mod, DeprecationWarning, stacklevel=2) # This is a bit funky, but it's only for awhile. The way the unit tests # are constructed this function winds up as an unbound method, so it # actually takes three args, not two. We want to toss out self. if not isinstance(args[0], str): # We are testing, avoid the first arg args = args[1:] if len(args) == 1 and not kwds: kwds["threaded"] = True return cls(*args, **kwds) def LinkFileLock(*args, **kwds): """Factory function provided for backwards compatibility. Do not use in new code. Instead, import LinkLockFile from the lockfile.linklockfile module. """ from . import linklockfile return _fl_helper(linklockfile.LinkLockFile, "lockfile.linklockfile", *args, **kwds) def MkdirFileLock(*args, **kwds): """Factory function provided for backwards compatibility. Do not use in new code. Instead, import MkdirLockFile from the lockfile.mkdirlockfile module. """ from . import mkdirlockfile return _fl_helper(mkdirlockfile.MkdirLockFile, "lockfile.mkdirlockfile", *args, **kwds) def SQLiteFileLock(*args, **kwds): """Factory function provided for backwards compatibility. Do not use in new code. Instead, import SQLiteLockFile from the lockfile.mkdirlockfile module. """ from . import sqlitelockfile return _fl_helper(sqlitelockfile.SQLiteLockFile, "lockfile.sqlitelockfile", *args, **kwds) def locked(path, timeout=None): """Decorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... """ def decor(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock = FileLock(path, timeout=timeout) lock.acquire() try: return func(*args, **kwargs) finally: lock.release() return wrapper return decor if hasattr(os, "link"): from . import linklockfile as _llf LockFile = _llf.LinkLockFile else: from . import mkdirlockfile as _mlf LockFile = _mlf.MkdirLockFile FileLock = LockFile mkdirlockfile.py000064400000006030147230510270007735 0ustar00from __future__ import absolute_import, division import time import os import sys import errno from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout, AlreadyLocked) class MkdirLockFile(LockBase): """Lock file by creating a directory.""" def __init__(self, path, threaded=True, timeout=None): """ >>> lock = MkdirLockFile('somefile') >>> lock = MkdirLockFile('somefile', threaded=False) """ LockBase.__init__(self, path, threaded, timeout) # Lock file itself is a directory. Place the unique file name into # it. self.unique_name = os.path.join(self.lock_file, "%s.%s%s" % (self.hostname, self.tname, self.pid)) def acquire(self, timeout=None): timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout if timeout is None: wait = 0.1 else: wait = max(0, timeout / 10) while True: try: os.mkdir(self.lock_file) except OSError: err = sys.exc_info()[1] if err.errno == errno.EEXIST: # Already locked. if os.path.exists(self.unique_name): # Already locked by me. return 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: # Someone else has the lock. raise AlreadyLocked("%s is already locked" % self.path) time.sleep(wait) else: # Couldn't create the lock for some other reason raise LockFailed("failed to create %s" % self.lock_file) else: open(self.unique_name, "wb").close() return def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) elif not os.path.exists(self.unique_name): raise NotMyLock("%s is locked, but not by me" % self.path) os.unlink(self.unique_name) os.rmdir(self.lock_file) def is_locked(self): return os.path.exists(self.lock_file) def i_am_locking(self): return (self.is_locked() and os.path.exists(self.unique_name)) def break_lock(self): if os.path.exists(self.lock_file): for name in os.listdir(self.lock_file): os.unlink(os.path.join(self.lock_file, name)) os.rmdir(self.lock_file) __pycache__/sqlitelockfile.cpython-36.pyc000064400000007126147230510270014423 0ustar003 . g @srddlmZmZddlZddlZyeWnek r@eZYnXddlm Z m Z m Z m Z m Z Gddde ZdS))absolute_importdivisionN)LockBase NotLocked NotMyLock LockTimeout AlreadyLockedc@sPeZdZdZdZdddZdddZdd Zd d Zd d Z ddZ ddZ dS)SQLiteLockFilezDemonstrate SQL-based locking.NTc Cstj||||t|j|_t|j|_tjdkrdddl}|j\}}t j |t j |~~|t_ddl }|j tj|_|jj}y|jdWn|jk rYn$X|jjddl} | jt j tjdS)zu >>> lock = SQLiteLockFile('somefile') >>> lock = SQLiteLockFile('somefile', threaded=False) NrzGcreate table locks( lock_file varchar(32), unique_name varchar(32)))r__init__unicode lock_file unique_namer testdbtempfileZmkstemposcloseunlinksqlite3Zconnect connectioncursorexecuteZOperationalErrorcommitatexitregister) selfpathZthreadedtimeoutrZ_fdrrcrr$/usr/lib/python3.6/sqlitelockfile.pyr s(        zSQLiteLockFile.__init__cCsH|dk r |n|j}tj}|dk r2|dkr2||7}|dkr@d}n|dkrNd}n|d}|jj}x|js|jd|j|jf|jj|jd|jf|j }t |dkr|jd|jf|jjqdSn(|jd|jf|j }t |dkrdS|dk r6tj|kr6|dkr(t d|j nt d |j tj|qbWdS) Nrg? z;insert into locks (lock_file, unique_name) values (?, ?)z*select * from locks where unique_name = ?rz(delete from locks where unique_name = ?z&Timeout waiting to acquire lock for %sz%s is already locked)rtimerr is_lockedrr rrfetchalllenrrr Zsleep)rrZend_timewaitrrowsrrr acquire5sD          zSQLiteLockFile.acquirecCs\|jstd|j|js4td|j|jf|jj}|j d|jf|jj dS)Nz%s is not lockedz#%s is locked, but not by me (by %s)z(delete from locks where unique_name = ?) r#rr i_am_lockingrr_who_is_lockingrrrr)rrrrr releasets  zSQLiteLockFile.releasecCs&|jj}|jd|jf|jdS)Nz2select unique_name from locks where lock_file = ?r)rrrr Zfetchone)rrrrr r*s  zSQLiteLockFile._who_is_lockingcCs*|jj}|jd|jf|j}| S)Nz(select * from locks where lock_file = ?)rrrr r$)rrr'rrr r#s   zSQLiteLockFile.is_lockedcCs*|jj}|jd|j|jf|j S)Nz?select * from locks where lock_file = ? and unique_name = ?)rrrr rr$)rrrrr r)s zSQLiteLockFile.i_am_lockingcCs(|jj}|jd|jf|jjdS)Nz&delete from locks where lock_file = ?)rrrr r)rrrrr break_locks  zSQLiteLockFile.break_lock)TN)N) __name__ __module__ __qualname____doc__rr r(r+r*r#r)r,rrrr r s " ? r )Z __future__rrr"rr NameErrorstrrrrrr r rrrr s __pycache__/pidlockfile.cpython-36.pyc000064400000011243147230510270013671 0ustar003 . g@stdZddlmZddlZddlZddlZddlmZmZm Z m Z m Z m Z GdddeZ dd Zd d Zd d ZdS)z8 Lockfile behaviour implemented via Unix PID files. )absolute_importN)LockBase AlreadyLocked LockFailed NotLocked NotMyLock LockTimeoutc@sLeZdZdZdddZddZdd Zd d Zdd d ZddZ ddZ dS) PIDLockFileaA Lockfile implemented as a Unix PID file. The lock file is a normal file named by the attribute `path`. A lock's PID file contains a single line of text, containing the process ID (PID) of the process that acquired the lock. >>> lock = PIDLockFile('somefile') >>> lock = PIDLockFile('somefile') FNcCstj||d||j|_dS)NF)r__init__pathZ unique_name)selfr Zthreadedtimeoutr!/usr/lib/python3.6/pidlockfile.pyr $szPIDLockFile.__init__cCs t|jS)z- Get the PID from the lock file. )read_pid_from_pidfiler )r rrrread_pid*szPIDLockFile.read_pidcCstjj|jS)zv Test if the lock is currently held. The lock is held if the PID file for this lock exists. )osr exists)r rrr is_locked/szPIDLockFile.is_lockedcCs|jotj|jkS)z Test if the lock is held by the current process. Returns ``True`` if the current process ID matches the number stored in the PID file. )rrgetpidr)r rrr i_am_locking7szPIDLockFile.i_am_lockingcCs|dk r |n|j}tj}|dk r2|dkr2||7}xyt|jWntk r}zv|jtjkrtj|kr|dk r|dkrtd|jntd|jtj |dk r|dpdnt d|jWYdd}~Xq4XdSq4WdS)z Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. Nrz&Timeout waiting to acquire lock for %sz%s is already locked g?zfailed to create %s) rtimewrite_pid_to_pidfiler OSErrorerrnoZEEXISTr rZsleepr)r rZend_timeexcrrracquire?s$     zPIDLockFile.acquirecCs:|jstd|j|js,td|jt|jdS)z Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. z%s is not lockedz%s is locked, but not by meN)rrr rrremove_existing_pidfile)r rrrrelease_s zPIDLockFile.releasecCst|jdS)z Break an existing lock. Removes the PID file if it already exists, otherwise does nothing. N)rr )r rrr break_locklszPIDLockFile.break_lock)FN)N) __name__ __module__ __qualname____doc__r rrrrr r!rrrrr s    r cCsbd}yt|d}Wntk r&Yn8X|jj}y t|}Wntk rTYnX|j|S)z Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``. Nr)openIOErrorreadlinestripint ValueErrorclose) pidfile_pathpidpidfilelinerrrrvs  rcCsRtjtjBtjB}d}tj|||}tj|d}tj}|jd||jdS)u Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. iwz%s N) rO_CREATO_EXCLO_WRONLYr'fdopenrwriter-)r.Z open_flagsZ open_modeZ pidfile_fdr0r/rrrrs rcCsFytj|Wn2tk r@}z|jtjkr.nWYdd}~XnXdS)z Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. N)rremoverrENOENT)r.rrrrrs  r)r%Z __future__rrrrrrrrrr r rrrrrrr s  ]"__pycache__/symlinklockfile.cpython-36.opt-1.pyc000064400000004056147230510270015546 0ustar003 . g8 @sLddlmZddlZddlZddlmZmZmZmZm Z GdddeZ dS))absolute_importN)LockBase NotLocked NotMyLock LockTimeout AlreadyLockedc@sDeZdZdZdddZdddZdd Zd d Zd d ZddZ dS)SymlinkLockFilez'Lock access to a file using symlink(2).TNcCs(tj||||tjj|jd|_dS)Nr)r__init__ospathsplit unique_name)selfr Zthreadedtimeoutr%/usr/lib/python3.6/symlinklockfile.pyr szSymlinkLockFile.__init__c Cs|dk r |n|j}tj}|dk r2|dkr2||7}xytj|j|jWnttk r|jrddS|dk rtj|kr|dkrtd|j nt d|j tj |dk r|dndYq4XdSq4WdS)Nrz&Timeout waiting to acquire lock for %sz%s is already locked g?) rtimer symlinkr lock_fileOSError i_am_lockingrr rZsleep)rrZend_timerrracquires$   zSymlinkLockFile.acquirecCs>|jstd|jn|js.td|jtj|jdS)Nz%s is not lockedz%s is locked, but not by me) is_lockedrr rrr unlinkr)rrrrrelease6s zSymlinkLockFile.releasecCstjj|jS)N)r r islinkr)rrrrr=szSymlinkLockFile.is_lockedcCs tjj|jotj|j|jkS)N)r r rrreadlinkr)rrrrr@szSymlinkLockFile.i_am_lockingcCstjj|jrtj|jdS)N)r r rrr)rrrr break_lockDszSymlinkLockFile.break_lock)TN)N) __name__ __module__ __qualname____doc__r rrrrrrrrrr s  #r ) Z __future__rr rrrrrrr rrrrs __pycache__/linklockfile.cpython-36.opt-1.pyc000064400000004241147230510270015011 0ustar003 . g\ @sPddlmZddlZddlZddlmZmZmZmZm Z m Z GdddeZ dS))absolute_importN)LockBase LockFailed NotLocked NotMyLock LockTimeout AlreadyLockedc@s:eZdZdZd ddZddZddZd d Zd d ZdS) LinkLockFilezLock access to a file using atomic property of link(2). >>> lock = LinkLockFile('somefile') >>> lock = LinkLockFile('somefile', threaded=False) NcCs"yt|jdjWn"tk r6td|jYnX|dk rD|n|j}tj}|dk rj|dkrj||7}xytj|j|j Wnt k rtj |jj }|dkrdS|dk rtj|krtj |j|dkrtd|jntd|jtj|dk r |dp dYqlXdSqlWdS) Nwbzfailed to create %srz&Timeout waiting to acquire lock for %sz%s is already locked g?)open unique_namecloseIOErrorrtimeouttimeoslink lock_fileOSErrorstatst_nlinkunlinkrpathr Zsleep)selfrZend_timeZnlinksr"/usr/lib/python3.6/linklockfile.pyacquires0   $zLinkLockFile.acquirecCsP|jstd|jntjj|js4td|jtj|jtj|jdS)Nz%s is not lockedz%s is locked, but not by me) is_lockedrrrexistsrrrr)rrrrrelease7s  zLinkLockFile.releasecCstjj|jS)N)rrr!r)rrrrr ?szLinkLockFile.is_lockedcCs(|jo&tjj|jo&tj|jjdkS)Nr )r rrr!rrr)rrrr i_am_lockingBszLinkLockFile.i_am_lockingcCstjj|jrtj|jdS)N)rrr!rr)rrrr break_lockGszLinkLockFile.break_lock)N) __name__ __module__ __qualname____doc__rr"r r#r$rrrrr s  &r ) Z __future__rrrrrrrrr r rrrrs  __pycache__/sqlitelockfile.cpython-36.opt-1.pyc000064400000007126147230510270015362 0ustar003 . g @srddlmZmZddlZddlZyeWnek r@eZYnXddlm Z m Z m Z m Z m Z Gddde ZdS))absolute_importdivisionN)LockBase NotLocked NotMyLock LockTimeout AlreadyLockedc@sPeZdZdZdZdddZdddZdd Zd d Zd d Z ddZ ddZ dS)SQLiteLockFilezDemonstrate SQL-based locking.NTc Cstj||||t|j|_t|j|_tjdkrdddl}|j\}}t j |t j |~~|t_ddl }|j tj|_|jj}y|jdWn|jk rYn$X|jjddl} | jt j tjdS)zu >>> lock = SQLiteLockFile('somefile') >>> lock = SQLiteLockFile('somefile', threaded=False) NrzGcreate table locks( lock_file varchar(32), unique_name varchar(32)))r__init__unicode lock_file unique_namer testdbtempfileZmkstemposcloseunlinksqlite3Zconnect connectioncursorexecuteZOperationalErrorcommitatexitregister) selfpathZthreadedtimeoutrZ_fdrrcrr$/usr/lib/python3.6/sqlitelockfile.pyr s(        zSQLiteLockFile.__init__cCsH|dk r |n|j}tj}|dk r2|dkr2||7}|dkr@d}n|dkrNd}n|d}|jj}x|js|jd|j|jf|jj|jd|jf|j }t |dkr|jd|jf|jjqdSn(|jd|jf|j }t |dkrdS|dk r6tj|kr6|dkr(t d|j nt d |j tj|qbWdS) Nrg? z;insert into locks (lock_file, unique_name) values (?, ?)z*select * from locks where unique_name = ?rz(delete from locks where unique_name = ?z&Timeout waiting to acquire lock for %sz%s is already locked)rtimerr is_lockedrr rrfetchalllenrrr Zsleep)rrZend_timewaitrrowsrrr acquire5sD          zSQLiteLockFile.acquirecCs\|jstd|j|js4td|j|jf|jj}|j d|jf|jj dS)Nz%s is not lockedz#%s is locked, but not by me (by %s)z(delete from locks where unique_name = ?) r#rr i_am_lockingrr_who_is_lockingrrrr)rrrrr releasets  zSQLiteLockFile.releasecCs&|jj}|jd|jf|jdS)Nz2select unique_name from locks where lock_file = ?r)rrrr Zfetchone)rrrrr r*s  zSQLiteLockFile._who_is_lockingcCs*|jj}|jd|jf|j}| S)Nz(select * from locks where lock_file = ?)rrrr r$)rrr'rrr r#s   zSQLiteLockFile.is_lockedcCs*|jj}|jd|j|jf|j S)Nz?select * from locks where lock_file = ? and unique_name = ?)rrrr rr$)rrrrr r)s zSQLiteLockFile.i_am_lockingcCs(|jj}|jd|jf|jjdS)Nz&delete from locks where lock_file = ?)rrrr r)rrrrr break_locks  zSQLiteLockFile.break_lock)TN)N) __name__ __module__ __qualname____doc__rr r(r+r*r#r)r,rrrr r s " ? r )Z __future__rrr"rr NameErrorstrrrrrr r rrrr s __pycache__/mkdirlockfile.cpython-36.pyc000064400000005013147230510270014221 0ustar003 . g @sdddlmZmZddlZddlZddlZddlZddlmZm Z m Z m Z m Z m Z GdddeZdS))absolute_importdivisionN)LockBase LockFailed NotLocked NotMyLock LockTimeout AlreadyLockedc@sDeZdZdZdddZdddZdd Zd d Zd d ZddZ dS) MkdirLockFilez"Lock file by creating a directory.TNcCs6tj||||tjj|jd|j|j|jf|_ dS)zs >>> lock = MkdirLockFile('somefile') >>> lock = MkdirLockFile('somefile', threaded=False) z%s.%s%sN) r__init__ospathjoin lock_fileZhostnameZtnamepid unique_name)selfrZthreadedtimeoutr#/usr/lib/python3.6/mkdirlockfile.pyr s  zMkdirLockFile.__init__c Cs|dk r |n|j}tj}|dk r2|dkr2||7}|dkr@d}ntd|d}xytj|jWntk rtjd}|j t j krtj j |j rdS|dk rtj|kr|dkrtd|j ntd|j tj|ntd|jYqPXt|j djdSqPWdS) Nrg? rz&Timeout waiting to acquire lock for %sz%s is already lockedzfailed to create %swb)rtimemaxr mkdirrOSErrorsysexc_infoerrnoZEEXISTrexistsrr r Zsleepropenclose)rrZend_timewaiterrrrracquires2     zMkdirLockFile.acquirecCsP|jstd|jntjj|js4td|jtj|jtj|j dS)Nz%s is not lockedz%s is locked, but not by me) is_lockedrrr r rrunlinkrmdirr)rrrrreleaseAs  zMkdirLockFile.releasecCstjj|jS)N)r rr r)rrrrr&IszMkdirLockFile.is_lockedcCs|jotjj|jS)N)r&r rr r)rrrr i_am_lockingLszMkdirLockFile.i_am_lockingcCsJtjj|jrFx*tj|jD]}tjtjj|j|qWtj|jdS)N)r rr rlistdirr'rr()rnamerrr break_lockPszMkdirLockFile.break_lock)TN)N) __name__ __module__ __qualname____doc__r r%r)r&r*r-rrrrr s &r )Z __future__rrrr rrrrrrr r r rrrrs  __pycache__/pidlockfile.cpython-36.opt-1.pyc000064400000011243147230510270014630 0ustar003 . g@stdZddlmZddlZddlZddlZddlmZmZm Z m Z m Z m Z GdddeZ dd Zd d Zd d ZdS)z8 Lockfile behaviour implemented via Unix PID files. )absolute_importN)LockBase AlreadyLocked LockFailed NotLocked NotMyLock LockTimeoutc@sLeZdZdZdddZddZdd Zd d Zdd d ZddZ ddZ dS) PIDLockFileaA Lockfile implemented as a Unix PID file. The lock file is a normal file named by the attribute `path`. A lock's PID file contains a single line of text, containing the process ID (PID) of the process that acquired the lock. >>> lock = PIDLockFile('somefile') >>> lock = PIDLockFile('somefile') FNcCstj||d||j|_dS)NF)r__init__pathZ unique_name)selfr Zthreadedtimeoutr!/usr/lib/python3.6/pidlockfile.pyr $szPIDLockFile.__init__cCs t|jS)z- Get the PID from the lock file. )read_pid_from_pidfiler )r rrrread_pid*szPIDLockFile.read_pidcCstjj|jS)zv Test if the lock is currently held. The lock is held if the PID file for this lock exists. )osr exists)r rrr is_locked/szPIDLockFile.is_lockedcCs|jotj|jkS)z Test if the lock is held by the current process. Returns ``True`` if the current process ID matches the number stored in the PID file. )rrgetpidr)r rrr i_am_locking7szPIDLockFile.i_am_lockingcCs|dk r |n|j}tj}|dk r2|dkr2||7}xyt|jWntk r}zv|jtjkrtj|kr|dk r|dkrtd|jntd|jtj |dk r|dpdnt d|jWYdd}~Xq4XdSq4WdS)z Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. Nrz&Timeout waiting to acquire lock for %sz%s is already locked g?zfailed to create %s) rtimewrite_pid_to_pidfiler OSErrorerrnoZEEXISTr rZsleepr)r rZend_timeexcrrracquire?s$     zPIDLockFile.acquirecCs:|jstd|j|js,td|jt|jdS)z Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. z%s is not lockedz%s is locked, but not by meN)rrr rrremove_existing_pidfile)r rrrrelease_s zPIDLockFile.releasecCst|jdS)z Break an existing lock. Removes the PID file if it already exists, otherwise does nothing. N)rr )r rrr break_locklszPIDLockFile.break_lock)FN)N) __name__ __module__ __qualname____doc__r rrrrr r!rrrrr s    r cCsbd}yt|d}Wntk r&Yn8X|jj}y t|}Wntk rTYnX|j|S)z Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``. Nr)openIOErrorreadlinestripint ValueErrorclose) pidfile_pathpidpidfilelinerrrrvs  rcCsRtjtjBtjB}d}tj|||}tj|d}tj}|jd||jdS)u Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. iwz%s N) rO_CREATO_EXCLO_WRONLYr'fdopenrwriter-)r.Z open_flagsZ open_modeZ pidfile_fdr0r/rrrrs rcCsFytj|Wn2tk r@}z|jtjkr.nWYdd}~XnXdS)z Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. N)rremoverrENOENT)r.rrrrrs  r)r%Z __future__rrrrrrrrrr r rrrrrrr s  ]"__pycache__/__init__.cpython-36.opt-1.pyc000064400000023146147230510270014107 0ustar003 . g$ @sdZddlmZddlZddlZddlZddlZddlZeedsJej e_ eej dsbej j ej _ dddd d d d d dddddg ZGdddeZGdddeZGdddeZGdd d eZGdd d eZGdd d eZGdd d eZGdd d eZGdddeZGdddeZddZd dZd!dZd"dZd(d#dZeed$rjd%d&l m!Z"e"j#Z$nd%d'l m%Z&e&j'Z$e$Z(dS))a lockfile.py - Platform-independent advisory file locks. Requires Python 2.5 unless you apply 2.4.diff Locking is done on a per-thread basis instead of a per-process basis. Usage: >>> lock = LockFile('somefile') >>> try: ... lock.acquire() ... except AlreadyLocked: ... print 'somefile', 'is locked already.' ... except LockFailed: ... print 'somefile', 'can\'t be locked.' ... else: ... print 'got lock' got lock >>> print lock.is_locked() True >>> lock.release() >>> lock = LockFile('somefile') >>> print lock.is_locked() False >>> with lock: ... print lock.is_locked() True >>> print lock.is_locked() False >>> lock = LockFile('somefile') >>> # It is okay to lock twice from the same thread... >>> with lock: ... lock.acquire() ... >>> # Though no counter is kept, so you can't unlock multiple times... >>> print lock.is_locked() False Exceptions: Error - base class for other exceptions LockError - base class for all locking exceptions AlreadyLocked - Another thread or process already holds the lock LockFailed - Lock failed for some other reason UnlockError - base class for all unlocking exceptions AlreadyUnlocked - File was not locked. NotMyLock - File was locked but not by the current thread/process )absolute_importNcurrent_threadget_nameError LockError LockTimeout AlreadyLocked LockFailed UnlockError NotLocked NotMyLock LinkFileLock MkdirFileLockSQLiteFileLockLockBaselockedc@seZdZdZdS)rzw Base class for other exceptions. >>> try: ... raise Error ... except Exception: ... pass N)__name__ __module__ __qualname____doc__rr/usr/lib/python3.6/__init__.pyrJsc@seZdZdZdS)rz Base class for error arising from attempts to acquire the lock. >>> try: ... raise LockError ... except Error: ... pass N)rrrrrrrrrVsc@seZdZdZdS)rzRaised when lock creation fails within a user-defined period of time. >>> try: ... raise LockTimeout ... except LockError: ... pass N)rrrrrrrrrbsc@seZdZdZdS)rzSome other thread/process is locking the file. >>> try: ... raise AlreadyLocked ... except LockError: ... pass N)rrrrrrrrrmsc@seZdZdZdS)r zLock file creation failed for some other reason. >>> try: ... raise LockFailed ... except LockError: ... pass N)rrrrrrrrr xsc@seZdZdZdS)r z Base class for errors arising from attempts to release the lock. >>> try: ... raise UnlockError ... except Error: ... pass N)rrrrrrrrr sc@seZdZdZdS)r zRaised when an attempt is made to unlock an unlocked file. >>> try: ... raise NotLocked ... except UnlockError: ... pass N)rrrrrrrrr sc@seZdZdZdS)r zRaised when an attempt is made to unlock a file someone else locked. >>> try: ... raise NotMyLock ... except UnlockError: ... pass N)rrrrrrrrr sc@s>eZdZddZdddZddZdd Zd d Zd d ZdS) _SharedBasecCs ||_dS)N)path)selfrrrr__init__sz_SharedBase.__init__NcCs tddS)a Acquire the lock. * If timeout is omitted (or None), wait forever trying to lock the file. * If timeout > 0, try to acquire the lock for that many seconds. If the lock period expires and the file is still locked, raise LockTimeout. * If timeout <= 0, raise AlreadyLocked immediately if the file is already locked. zimplement in subclassN)NotImplemented)rtimeoutrrracquiresz_SharedBase.acquirecCs tddS)zX Release the lock. If the file is not locked, raise NotLocked. zimplement in subclassN)r)rrrrreleasesz_SharedBase.releasecCs |j|S)z* Context manager support. )r)rrrr __enter__sz_SharedBase.__enter__cGs |jdS)z* Context manager support. N)r)rZ_excrrr__exit__sz_SharedBase.__exit__cCsd|jj|jfS)Nz<%s: %r>) __class__rr)rrrr__repr__sz_SharedBase.__repr__)N) rrrrrrr r!r#rrrrrs  rcsBeZdZdZdfdd ZddZdd Zd d Zd d ZZ S)rz.Base class for platform-specific lock classes.TNcstt|j|tjj|d|_tj|_ tj |_ |rbt j }t|dt|}d|d@|_nd|_tjj|j}tjj|d|j |j|j t|jf|_||_dS)zi >>> lock = LockBase('somefile') >>> lock = LockBase('somefile', threaded=False) z.lockidentz-%xlz %s%s.%s%sN)superrrosrabspathZ lock_filesocketZ gethostnameZhostnamegetpidpid threadingrgetattrhashZtnamedirnamejoin unique_namer)rrthreadedrtr$r/)r"rrrs    zLockBase.__init__cCs tddS)z9 Tell whether or not the file is locked. zimplement in subclassN)r)rrrr is_lockedszLockBase.is_lockedcCs tddS)zA Return True if this object is locking the file. zimplement in subclassN)r)rrrr i_am_lockingszLockBase.i_am_lockingcCs tddS)zN Remove a lock. Useful if a locking thread failed to unlock. zimplement in subclassN)r)rrrr break_lockszLockBase.break_lockcCsd|jj|j|jfS)Nz<%s: %r -- %r>)r"rr1r)rrrrr#s zLockBase.__repr__)TN) rrrrrr4r5r6r# __classcell__rr)r"rrs !cOsRtjd|tddt|dts.|dd}t|dkrH| rHd|d<|||S)Nz1Import from %s module instead of lockfile package) stacklevelrTr2)warningswarnDeprecationWarning isinstancestrlen)clsmodargskwdsrrr _fl_helper s   rEcOs ddlm}t|jdf||S)zFactory function provided for backwards compatibility. Do not use in new code. Instead, import LinkLockFile from the lockfile.linklockfile module. r:) linklockfilezlockfile.linklockfile)r%rFrE LinkLockFile)rCrDrFrrrr s  cOs ddlm}t|jdf||S)zFactory function provided for backwards compatibility. Do not use in new code. Instead, import MkdirLockFile from the lockfile.mkdirlockfile module. r:) mkdirlockfilezlockfile.mkdirlockfile)r%rHrE MkdirLockFile)rCrDrHrrrr%s  cOs ddlm}t|jdf||S)zFactory function provided for backwards compatibility. Do not use in new code. Instead, import SQLiteLockFile from the lockfile.mkdirlockfile module. r:)sqlitelockfilezlockfile.sqlitelockfile)r%rJrEZSQLiteLockFile)rCrDrJrrrr0s  csfdd}|S)aDecorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... cstjfdd}|S)Nc s.td}|jz ||S|jXdS)N)r)FileLockrr)rCkwargslock)funcrrrrwrapperHs   z&locked..decor..wrapper) functoolswraps)rNrO)rr)rNrdecorGszlocked..decorr)rrrRr)rrrr;s  linkr:)rF)rH)N))rZ __future__rrPr'r)r,r;hasattrZ currentThreadrZThreadZgetNamer__all__ Exceptionrrrrr r r r objectrrrEr rrrr%rFZ_llfrGZLockFilerHZ_mlfrIrKrrrr4sF            -:      __pycache__/symlinklockfile.cpython-36.pyc000064400000004056147230510270014607 0ustar003 . g8 @sLddlmZddlZddlZddlmZmZmZmZm Z GdddeZ dS))absolute_importN)LockBase NotLocked NotMyLock LockTimeout AlreadyLockedc@sDeZdZdZdddZdddZdd Zd d Zd d ZddZ dS)SymlinkLockFilez'Lock access to a file using symlink(2).TNcCs(tj||||tjj|jd|_dS)Nr)r__init__ospathsplit unique_name)selfr Zthreadedtimeoutr%/usr/lib/python3.6/symlinklockfile.pyr szSymlinkLockFile.__init__c Cs|dk r |n|j}tj}|dk r2|dkr2||7}xytj|j|jWnttk r|jrddS|dk rtj|kr|dkrtd|j nt d|j tj |dk r|dndYq4XdSq4WdS)Nrz&Timeout waiting to acquire lock for %sz%s is already locked g?) rtimer symlinkr lock_fileOSError i_am_lockingrr rZsleep)rrZend_timerrracquires$   zSymlinkLockFile.acquirecCs>|jstd|jn|js.td|jtj|jdS)Nz%s is not lockedz%s is locked, but not by me) is_lockedrr rrr unlinkr)rrrrrelease6s zSymlinkLockFile.releasecCstjj|jS)N)r r islinkr)rrrrr=szSymlinkLockFile.is_lockedcCs tjj|jotj|j|jkS)N)r r rrreadlinkr)rrrrr@szSymlinkLockFile.i_am_lockingcCstjj|jrtj|jdS)N)r r rrr)rrrr break_lockDszSymlinkLockFile.break_lock)TN)N) __name__ __module__ __qualname____doc__r rrrrrrrrrr s  #r ) Z __future__rr rrrrrrr rrrrs __pycache__/__init__.cpython-36.pyc000064400000023146147230510270013150 0ustar003 . g$ @sdZddlmZddlZddlZddlZddlZddlZeedsJej e_ eej dsbej j ej _ dddd d d d d dddddg ZGdddeZGdddeZGdddeZGdd d eZGdd d eZGdd d eZGdd d eZGdd d eZGdddeZGdddeZddZd dZd!dZd"dZd(d#dZeed$rjd%d&l m!Z"e"j#Z$nd%d'l m%Z&e&j'Z$e$Z(dS))a lockfile.py - Platform-independent advisory file locks. Requires Python 2.5 unless you apply 2.4.diff Locking is done on a per-thread basis instead of a per-process basis. Usage: >>> lock = LockFile('somefile') >>> try: ... lock.acquire() ... except AlreadyLocked: ... print 'somefile', 'is locked already.' ... except LockFailed: ... print 'somefile', 'can\'t be locked.' ... else: ... print 'got lock' got lock >>> print lock.is_locked() True >>> lock.release() >>> lock = LockFile('somefile') >>> print lock.is_locked() False >>> with lock: ... print lock.is_locked() True >>> print lock.is_locked() False >>> lock = LockFile('somefile') >>> # It is okay to lock twice from the same thread... >>> with lock: ... lock.acquire() ... >>> # Though no counter is kept, so you can't unlock multiple times... >>> print lock.is_locked() False Exceptions: Error - base class for other exceptions LockError - base class for all locking exceptions AlreadyLocked - Another thread or process already holds the lock LockFailed - Lock failed for some other reason UnlockError - base class for all unlocking exceptions AlreadyUnlocked - File was not locked. NotMyLock - File was locked but not by the current thread/process )absolute_importNcurrent_threadget_nameError LockError LockTimeout AlreadyLocked LockFailed UnlockError NotLocked NotMyLock LinkFileLock MkdirFileLockSQLiteFileLockLockBaselockedc@seZdZdZdS)rzw Base class for other exceptions. >>> try: ... raise Error ... except Exception: ... pass N)__name__ __module__ __qualname____doc__rr/usr/lib/python3.6/__init__.pyrJsc@seZdZdZdS)rz Base class for error arising from attempts to acquire the lock. >>> try: ... raise LockError ... except Error: ... pass N)rrrrrrrrrVsc@seZdZdZdS)rzRaised when lock creation fails within a user-defined period of time. >>> try: ... raise LockTimeout ... except LockError: ... pass N)rrrrrrrrrbsc@seZdZdZdS)rzSome other thread/process is locking the file. >>> try: ... raise AlreadyLocked ... except LockError: ... pass N)rrrrrrrrrmsc@seZdZdZdS)r zLock file creation failed for some other reason. >>> try: ... raise LockFailed ... except LockError: ... pass N)rrrrrrrrr xsc@seZdZdZdS)r z Base class for errors arising from attempts to release the lock. >>> try: ... raise UnlockError ... except Error: ... pass N)rrrrrrrrr sc@seZdZdZdS)r zRaised when an attempt is made to unlock an unlocked file. >>> try: ... raise NotLocked ... except UnlockError: ... pass N)rrrrrrrrr sc@seZdZdZdS)r zRaised when an attempt is made to unlock a file someone else locked. >>> try: ... raise NotMyLock ... except UnlockError: ... pass N)rrrrrrrrr sc@s>eZdZddZdddZddZdd Zd d Zd d ZdS) _SharedBasecCs ||_dS)N)path)selfrrrr__init__sz_SharedBase.__init__NcCs tddS)a Acquire the lock. * If timeout is omitted (or None), wait forever trying to lock the file. * If timeout > 0, try to acquire the lock for that many seconds. If the lock period expires and the file is still locked, raise LockTimeout. * If timeout <= 0, raise AlreadyLocked immediately if the file is already locked. zimplement in subclassN)NotImplemented)rtimeoutrrracquiresz_SharedBase.acquirecCs tddS)zX Release the lock. If the file is not locked, raise NotLocked. zimplement in subclassN)r)rrrrreleasesz_SharedBase.releasecCs |j|S)z* Context manager support. )r)rrrr __enter__sz_SharedBase.__enter__cGs |jdS)z* Context manager support. N)r)rZ_excrrr__exit__sz_SharedBase.__exit__cCsd|jj|jfS)Nz<%s: %r>) __class__rr)rrrr__repr__sz_SharedBase.__repr__)N) rrrrrrr r!r#rrrrrs  rcsBeZdZdZdfdd ZddZdd Zd d Zd d ZZ S)rz.Base class for platform-specific lock classes.TNcstt|j|tjj|d|_tj|_ tj |_ |rbt j }t|dt|}d|d@|_nd|_tjj|j}tjj|d|j |j|j t|jf|_||_dS)zi >>> lock = LockBase('somefile') >>> lock = LockBase('somefile', threaded=False) z.lockidentz-%xlz %s%s.%s%sN)superrrosrabspathZ lock_filesocketZ gethostnameZhostnamegetpidpid threadingrgetattrhashZtnamedirnamejoin unique_namer)rrthreadedrtr$r/)r"rrrs    zLockBase.__init__cCs tddS)z9 Tell whether or not the file is locked. zimplement in subclassN)r)rrrr is_lockedszLockBase.is_lockedcCs tddS)zA Return True if this object is locking the file. zimplement in subclassN)r)rrrr i_am_lockingszLockBase.i_am_lockingcCs tddS)zN Remove a lock. Useful if a locking thread failed to unlock. zimplement in subclassN)r)rrrr break_lockszLockBase.break_lockcCsd|jj|j|jfS)Nz<%s: %r -- %r>)r"rr1r)rrrrr#s zLockBase.__repr__)TN) rrrrrr4r5r6r# __classcell__rr)r"rrs !cOsRtjd|tddt|dts.|dd}t|dkrH| rHd|d<|||S)Nz1Import from %s module instead of lockfile package) stacklevelrTr2)warningswarnDeprecationWarning isinstancestrlen)clsmodargskwdsrrr _fl_helper s   rEcOs ddlm}t|jdf||S)zFactory function provided for backwards compatibility. Do not use in new code. Instead, import LinkLockFile from the lockfile.linklockfile module. r:) linklockfilezlockfile.linklockfile)r%rFrE LinkLockFile)rCrDrFrrrr s  cOs ddlm}t|jdf||S)zFactory function provided for backwards compatibility. Do not use in new code. Instead, import MkdirLockFile from the lockfile.mkdirlockfile module. r:) mkdirlockfilezlockfile.mkdirlockfile)r%rHrE MkdirLockFile)rCrDrHrrrr%s  cOs ddlm}t|jdf||S)zFactory function provided for backwards compatibility. Do not use in new code. Instead, import SQLiteLockFile from the lockfile.mkdirlockfile module. r:)sqlitelockfilezlockfile.sqlitelockfile)r%rJrEZSQLiteLockFile)rCrDrJrrrr0s  csfdd}|S)aDecorator which enables locks for decorated function. Arguments: - path: path for lockfile. - timeout (optional): Timeout for acquiring lock. Usage: @locked('/var/run/myname', timeout=0) def myname(...): ... cstjfdd}|S)Nc s.td}|jz ||S|jXdS)N)r)FileLockrr)rCkwargslock)funcrrrrwrapperHs   z&locked..decor..wrapper) functoolswraps)rNrO)rr)rNrdecorGszlocked..decorr)rrrRr)rrrr;s  linkr:)rF)rH)N))rZ __future__rrPr'r)r,r;hasattrZ currentThreadrZThreadZgetNamer__all__ Exceptionrrrrr r r r objectrrrEr rrrr%rFZ_llfrGZLockFilerHZ_mlfrIrKrrrr4sF            -:      __pycache__/mkdirlockfile.cpython-36.opt-1.pyc000064400000005013147230510270015160 0ustar003 . g @sdddlmZmZddlZddlZddlZddlZddlmZm Z m Z m Z m Z m Z GdddeZdS))absolute_importdivisionN)LockBase LockFailed NotLocked NotMyLock LockTimeout AlreadyLockedc@sDeZdZdZdddZdddZdd Zd d Zd d ZddZ dS) MkdirLockFilez"Lock file by creating a directory.TNcCs6tj||||tjj|jd|j|j|jf|_ dS)zs >>> lock = MkdirLockFile('somefile') >>> lock = MkdirLockFile('somefile', threaded=False) z%s.%s%sN) r__init__ospathjoin lock_fileZhostnameZtnamepid unique_name)selfrZthreadedtimeoutr#/usr/lib/python3.6/mkdirlockfile.pyr s  zMkdirLockFile.__init__c Cs|dk r |n|j}tj}|dk r2|dkr2||7}|dkr@d}ntd|d}xytj|jWntk rtjd}|j t j krtj j |j rdS|dk rtj|kr|dkrtd|j ntd|j tj|ntd|jYqPXt|j djdSqPWdS) Nrg? rz&Timeout waiting to acquire lock for %sz%s is already lockedzfailed to create %swb)rtimemaxr mkdirrOSErrorsysexc_infoerrnoZEEXISTrexistsrr r Zsleepropenclose)rrZend_timewaiterrrrracquires2     zMkdirLockFile.acquirecCsP|jstd|jntjj|js4td|jtj|jtj|j dS)Nz%s is not lockedz%s is locked, but not by me) is_lockedrrr r rrunlinkrmdirr)rrrrreleaseAs  zMkdirLockFile.releasecCstjj|jS)N)r rr r)rrrrr&IszMkdirLockFile.is_lockedcCs|jotjj|jS)N)r&r rr r)rrrr i_am_lockingLszMkdirLockFile.i_am_lockingcCsJtjj|jrFx*tj|jD]}tjtjj|j|qWtj|jdS)N)r rr rlistdirr'rr()rnamerrr break_lockPszMkdirLockFile.break_lock)TN)N) __name__ __module__ __qualname____doc__r r%r)r&r*r-rrrrr s &r )Z __future__rrrr rrrrrrr r r rrrrs  __pycache__/linklockfile.cpython-36.pyc000064400000004241147230510270014052 0ustar003 . g\ @sPddlmZddlZddlZddlmZmZmZmZm Z m Z GdddeZ dS))absolute_importN)LockBase LockFailed NotLocked NotMyLock LockTimeout AlreadyLockedc@s:eZdZdZd ddZddZddZd d Zd d ZdS) LinkLockFilezLock access to a file using atomic property of link(2). >>> lock = LinkLockFile('somefile') >>> lock = LinkLockFile('somefile', threaded=False) NcCs"yt|jdjWn"tk r6td|jYnX|dk rD|n|j}tj}|dk rj|dkrj||7}xytj|j|j Wnt k rtj |jj }|dkrdS|dk rtj|krtj |j|dkrtd|jntd|jtj|dk r |dp dYqlXdSqlWdS) Nwbzfailed to create %srz&Timeout waiting to acquire lock for %sz%s is already locked g?)open unique_namecloseIOErrorrtimeouttimeoslink lock_fileOSErrorstatst_nlinkunlinkrpathr Zsleep)selfrZend_timeZnlinksr"/usr/lib/python3.6/linklockfile.pyacquires0   $zLinkLockFile.acquirecCsP|jstd|jntjj|js4td|jtj|jtj|jdS)Nz%s is not lockedz%s is locked, but not by me) is_lockedrrrexistsrrrr)rrrrrelease7s  zLinkLockFile.releasecCstjj|jS)N)rrr!r)rrrrr ?szLinkLockFile.is_lockedcCs(|jo&tjj|jo&tj|jjdkS)Nr )r rrr!rrr)rrrr i_am_lockingBszLinkLockFile.i_am_lockingcCstjj|jrtj|jdS)N)rrr!rr)rrrr break_lockGszLinkLockFile.break_lock)N) __name__ __module__ __qualname____doc__rr"r r#r$rrrrr s  &r ) Z __future__rrrrrrrrr r rrrrs  linklockfile.py000064400000005134147230510270007570 0ustar00from __future__ import absolute_import import time import os from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout, AlreadyLocked) class LinkLockFile(LockBase): """Lock access to a file using atomic property of link(2). >>> lock = LinkLockFile('somefile') >>> lock = LinkLockFile('somefile', threaded=False) """ def acquire(self, timeout=None): try: open(self.unique_name, "wb").close() except IOError: raise LockFailed("failed to create %s" % self.unique_name) timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout while True: # Try and create a hard link to it. try: os.link(self.unique_name, self.lock_file) except OSError: # Link creation failed. Maybe we've double-locked? nlinks = os.stat(self.unique_name).st_nlink if nlinks == 2: # The original link plus the one I created == 2. We're # good to go. return else: # Otherwise the lock creation failed. if timeout is not None and time.time() > end_time: os.unlink(self.unique_name) 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: # Link creation succeeded. We're good to go. return def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) elif not os.path.exists(self.unique_name): raise NotMyLock("%s is locked, but not by me" % self.path) os.unlink(self.unique_name) os.unlink(self.lock_file) def is_locked(self): return os.path.exists(self.lock_file) def i_am_locking(self): return (self.is_locked() and os.path.exists(self.unique_name) and os.stat(self.unique_name).st_nlink == 2) def break_lock(self): if os.path.exists(self.lock_file): os.unlink(self.lock_file) symlinklockfile.py000064400000005070147230510270010320 0ustar00from __future__ import absolute_import import os import time from . import (LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked) class SymlinkLockFile(LockBase): """Lock access to a file using symlink(2).""" def __init__(self, path, threaded=True, timeout=None): # super(SymlinkLockFile).__init(...) LockBase.__init__(self, path, threaded, timeout) # split it back! self.unique_name = os.path.split(self.unique_name)[1] def acquire(self, timeout=None): # Hopefully unnecessary for symlink. # try: # open(self.unique_name, "wb").close() # except IOError: # raise LockFailed("failed to create %s" % self.unique_name) timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout while True: # Try and create a symbolic link to it. try: os.symlink(self.unique_name, self.lock_file) except OSError: # Link creation failed. Maybe we've double-locked? if self.i_am_locking(): # Linked to out unique name. Proceed. return else: # Otherwise the lock creation failed. 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 / 10 if timeout is not None else 0.1) else: # Link creation succeeded. We're good to go. return def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) elif not self.i_am_locking(): raise NotMyLock("%s is locked, but not by me" % self.path) os.unlink(self.lock_file) def is_locked(self): return os.path.islink(self.lock_file) def i_am_locking(self): return (os.path.islink(self.lock_file) and os.readlink(self.lock_file) == self.unique_name) def break_lock(self): if os.path.islink(self.lock_file): # exists && link os.unlink(self.lock_file) pidlockfile.py000064400000013712147230510270007410 0ustar00# -*- coding: utf-8 -*- # pidlockfile.py # # Copyright © 2008–2009 Ben Finney # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Lockfile behaviour implemented via Unix PID files. """ from __future__ import absolute_import import errno import os import time from . import (LockBase, AlreadyLocked, LockFailed, NotLocked, NotMyLock, LockTimeout) class PIDLockFile(LockBase): """ Lockfile implemented as a Unix PID file. The lock file is a normal file named by the attribute `path`. A lock's PID file contains a single line of text, containing the process ID (PID) of the process that acquired the lock. >>> lock = PIDLockFile('somefile') >>> lock = PIDLockFile('somefile') """ def __init__(self, path, threaded=False, timeout=None): # pid lockfiles don't support threaded operation, so always force # False as the threaded arg. LockBase.__init__(self, path, False, timeout) self.unique_name = self.path def read_pid(self): """ Get the PID from the lock file. """ return read_pid_from_pidfile(self.path) def is_locked(self): """ Test if the lock is currently held. The lock is held if the PID file for this lock exists. """ return os.path.exists(self.path) def i_am_locking(self): """ Test if the lock is held by the current process. Returns ``True`` if the current process ID matches the number stored in the PID file. """ return self.is_locked() and os.getpid() == self.read_pid() def acquire(self, timeout=None): """ Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. """ timeout = timeout if timeout is not None else 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 time.time() > end_time: if timeout is not None and 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 def release(self): """ Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. """ if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) if not self.i_am_locking(): raise NotMyLock("%s is locked, but not by me" % self.path) remove_existing_pidfile(self.path) def break_lock(self): """ Break an existing lock. Removes the PID file if it already exists, otherwise does nothing. """ remove_existing_pidfile(self.path) def read_pid_from_pidfile(pidfile_path): """ Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``. """ pid = None try: pidfile = open(pidfile_path, 'r') except IOError: pass else: # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid def write_pid_to_pidfile(pidfile_path): """ Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. """ open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY) open_mode = 0o644 pidfile_fd = os.open(pidfile_path, open_flags, open_mode) pidfile = os.fdopen(pidfile_fd, 'w') # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. For # example, if crond was process number 25, /var/run/crond.pid # would contain three characters: two, five, and newline. pid = os.getpid() pidfile.write("%s\n" % pid) pidfile.close() def remove_existing_pidfile(pidfile_path): """ Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. """ try: os.remove(pidfile_path) except OSError as exc: if exc.errno == errno.ENOENT: pass else: raise sqlitelockfile.py000064400000012602147230510270010132 0ustar00from __future__ import absolute_import, division import time import os try: unicode except NameError: unicode = str from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked class SQLiteLockFile(LockBase): "Demonstrate SQL-based locking." testdb = None def __init__(self, path, threaded=True, timeout=None): """ >>> lock = SQLiteLockFile('somefile') >>> lock = SQLiteLockFile('somefile', threaded=False) """ LockBase.__init__(self, path, threaded, timeout) self.lock_file = unicode(self.lock_file) self.unique_name = unicode(self.unique_name) if SQLiteLockFile.testdb is None: import tempfile _fd, testdb = tempfile.mkstemp() os.close(_fd) os.unlink(testdb) del _fd, tempfile SQLiteLockFile.testdb = testdb import sqlite3 self.connection = sqlite3.connect(SQLiteLockFile.testdb) c = self.connection.cursor() try: c.execute("create table locks" "(" " lock_file varchar(32)," " unique_name varchar(32)" ")") except sqlite3.OperationalError: pass else: self.connection.commit() import atexit atexit.register(os.unlink, SQLiteLockFile.testdb) def acquire(self, timeout=None): timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout if timeout is None: wait = 0.1 elif timeout <= 0: wait = 0 else: wait = timeout / 10 cursor = self.connection.cursor() while True: if not self.is_locked(): # Not locked. Try to lock it. cursor.execute("insert into locks" " (lock_file, unique_name)" " values" " (?, ?)", (self.lock_file, self.unique_name)) self.connection.commit() # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows = cursor.fetchall() if len(rows) > 1: # Nope. Someone else got there. Remove our lock. cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() else: # Yup. We're done, so go home. return else: # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows = cursor.fetchall() if len(rows) == 1: # We're the locker, so go home. return # Maybe we should wait a bit longer. if timeout is not None and time.time() > end_time: if timeout > 0: # No more waiting. raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) else: # Someone else has the lock and we are impatient.. raise AlreadyLocked("%s is already locked" % self.path) # Well, okay. We'll give it a bit longer. time.sleep(wait) def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) if not self.i_am_locking(): raise NotMyLock("%s is locked, but not by me (by %s)" % (self.unique_name, self._who_is_locking())) cursor = self.connection.cursor() cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() def _who_is_locking(self): cursor = self.connection.cursor() cursor.execute("select unique_name from locks" " where lock_file = ?", (self.lock_file,)) return cursor.fetchone()[0] def is_locked(self): cursor = self.connection.cursor() cursor.execute("select * from locks" " where lock_file = ?", (self.lock_file,)) rows = cursor.fetchall() return not not rows def i_am_locking(self): cursor = self.connection.cursor() cursor.execute("select * from locks" " where lock_file = ?" " and unique_name = ?", (self.lock_file, self.unique_name)) return not not cursor.fetchall() def break_lock(self): cursor = self.connection.cursor() cursor.execute("delete from locks" " where lock_file = ?", (self.lock_file,)) self.connection.commit()