Skip to content

Commit

Permalink
Embed intent, pid and progress info in LockAcquire and LockTimeout ex…
Browse files Browse the repository at this point in the history
…ceptions

And add tests for these exceptions in the tests suite.
  • Loading branch information
cvaroqui committed Mar 9, 2018
1 parent 0ea71a6 commit d58bc34
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
27 changes: 19 additions & 8 deletions lib/lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@

from rcGlobalEnv import rcEnv

class LockTimeout(Exception):
""" acquire lock timed out
"""

class LockNoLockFile(Exception):
""" no lockfile specified
"""
Expand All @@ -27,6 +23,20 @@ class LockCreateError(Exception):
class LockAcquire(Exception):
""" could not acquire lock on lockfile
"""
def __init__(self, intent="", pid=0, progress=None):
Exception.__init__(self)
self.intent = intent
self.pid = pid
self.progress = progress
def __str__(self):
s = "holder pid %(pid)d, holder intent '%(intent)s'" % dict(pid=self.pid, intent=self.intent)
if self.progress:
s += ", progress '%s'" % str(self.progress)
return s

class LockTimeout(LockAcquire):
""" acquire lock timed out
"""

LOCK_EXCEPTIONS = (
LockTimeout,
Expand Down Expand Up @@ -84,17 +94,18 @@ def lock(timeout=30, delay=1, lockfile=None, intent=None):
ticks = range(int(float(timeout)/float(delay)))
if len(ticks) == 0:
ticks = [0]
err = ""
err = {}
for tick in ticks:
if tick > 0:
time.sleep(delay)
try:
return lock_nowait(lockfile, intent)
except LockAcquire as exc:
err = str(exc)
err["intent"] = exc.intent
err["pid"] = exc.pid
except Exception:
raise
raise LockTimeout(err)
raise LockTimeout(**err)

def lock_nowait(lockfile=None, intent=None):
"""
Expand Down Expand Up @@ -158,7 +169,7 @@ def lock_nowait(lockfile=None, intent=None):
return lockfd
except IOError:
os.close(lockfd)
raise LockAcquire("holder pid %(pid)d, holder intent '%(intent)s'" % prev_data)
raise LockAcquire(**prev_data)
except:
os.close(lockfd)
raise
Expand Down
21 changes: 21 additions & 0 deletions lib/tests/test_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,24 @@ def proc_lock():

# release
lock.unlock(lockfd)

def test_timeout_exc(self):
"""
LockTimeOut exception
"""
try:
raise lock.LockTimeout(intent="test", pid=20000)
except lock.LockTimeout as exc:
assert exc.intent == "test"
assert exc.pid == 20000

def test_acquire_exc(self):
"""
LockAcquire exception
"""
try:
raise lock.LockAcquire(intent="test", pid=20000)
except lock.LockAcquire as exc:
assert exc.intent == "test"
assert exc.pid == 20000

0 comments on commit d58bc34

Please sign in to comment.