{my,pg}sql: close connections when out of retry

The connection is supposedly closed when blocking is False and the lock is not
acquired. Or when an exception happens in the locking code.

But if blocking is e.g. 5 seconds, then RetryError is raised but without
closing any connection at the end. This fixes that.

Change-Id: I7b40e466fe5fc01ee3f8c012f765aafca9ce716a
This commit is contained in:
Julien Danjou 2017-06-09 09:53:08 +02:00
parent 5625106703
commit ee66b6e4e4
2 changed files with 28 additions and 24 deletions

View File

@ -68,7 +68,6 @@ class MySQLLock(locking.Lock):
self.acquired = True
return True
except pymysql.MySQLError as e:
self._conn.close()
utils.raise_with_cause(
tooz.ToozError,
encodeutils.exception_to_unicode(e),
@ -79,7 +78,13 @@ class MySQLLock(locking.Lock):
self._conn.close()
return False
return _lock()
try:
return _lock()
except Exception:
# Close the connection if we tried too much and finally failed, or
# anything else bad happened.
self._conn.close()
raise
def release(self):
if not self.acquired:

View File

@ -123,32 +123,31 @@ class PostgresLock(locking.Lock):
if not self._conn or self._conn.closed:
self._conn = PostgresDriver.get_connection(self._parsed_url,
self._options)
try:
with _translating_cursor(self._conn) as cur:
if blocking is True:
cur.execute("SELECT pg_advisory_lock(%s, %s);",
self.key)
cur.fetchone()
with _translating_cursor(self._conn) as cur:
if blocking is True:
cur.execute("SELECT pg_advisory_lock(%s, %s);",
self.key)
cur.fetchone()
self.acquired = True
return True
else:
cur.execute("SELECT pg_try_advisory_lock(%s, %s);",
self.key)
if cur.fetchone()[0] is True:
self.acquired = True
return True
elif blocking is False:
self._conn.close()
return False
else:
cur.execute("SELECT pg_try_advisory_lock(%s, %s);",
self.key)
if cur.fetchone()[0] is True:
self.acquired = True
return True
elif blocking is False:
self._conn.close()
return False
else:
raise _retry.TryAgain
except _retry.TryAgain:
pass # contine to retrieve lock on same conn
except Exception:
self._conn.close()
raise
raise _retry.TryAgain
return _lock()
try:
return _lock()
except Exception:
self._conn.close()
raise
def release(self):
if not self.acquired: