Skip to content

Commit bbbf692

Browse files
committed
Address Toshio's commments.
1 parent 1cb5c99 commit bbbf692

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

convert2rhel/applock.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ class ApplicationLock:
5959
def __init__(self, name):
6060
# Our application name
6161
self._name = name
62-
# Our process ID
62+
# Our process ID. We save this when the lock is created so it will be
63+
# consistent even if we check from inside a fork.
6364
self._pid = os.getpid()
6465
# Path to the file that contains the process id
6566
self._pidfile = os.path.join(_DEFAULT_LOCK_DIR, self._name + ".pid")
@@ -95,7 +96,7 @@ def _try_create(self):
9596
except OSError as exc:
9697
if exc.errno == errno.EEXIST:
9798
return False
98-
raise exc
99+
raise
99100
loggerinst.debug("%s." % self)
100101
return True
101102

@@ -114,23 +115,19 @@ def _read_pidfile(self):
114115
:returns: the file contents as an integer, or None if it doesn't exist
115116
:raises: ApplicationLockedError if the contents are corrupt
116117
"""
117-
if os.path.exists(self._pidfile):
118-
try:
119-
with open(self._pidfile, "r") as f:
120-
file_contents = f.read()
121-
pid = int(file_contents.rstrip())
122-
except OSError as exc:
123-
# This addresses a race condition in which another process
124-
# deletes the lock file between our check that it exists
125-
# and our attempt to read the contents.
126-
# In Python 3 this could be changed to FileNotFoundError.
127-
if exc.errno == errno.ENOENT:
128-
return None
129-
raise exc
130-
except ValueError:
131-
raise ApplicationLockedError("Lock file %s is corrupt" % self._pidfile)
118+
try:
119+
with open(self._pidfile, "r") as f:
120+
file_contents = f.read()
121+
pid = int(file_contents.rstrip())
132122
return pid
133-
return None
123+
except IOError as exc:
124+
# The open() failed because the file exists.
125+
# In Python 3 this could be changed to FileNotFoundError.
126+
if exc.errno == errno.ENOENT:
127+
return None
128+
raise
129+
except ValueError:
130+
raise ApplicationLockedError("Lock file %s is corrupt" % self._pidfile)
134131

135132
@staticmethod
136133
def _pid_exists(pid):
@@ -157,7 +154,7 @@ def _safe_unlink(self):
157154
# In Python 3 this could be changed to FileNotFoundError.
158155
if exc.errno == errno.ENOENT:
159156
return
160-
raise exc
157+
raise
161158

162159
def try_to_lock(self):
163160
"""Try to get a lock on this application. If this method does

0 commit comments

Comments
 (0)