lockedobjects_db: Move lock logic to a context-manager method

Partial-Bug: #1740667
Change-Id: I4b1fd42e05785dc7ec3b06ba69c3655f60d43a19
This commit is contained in:
Omer Anson 2018-04-11 13:07:36 +03:00
parent d083aa6211
commit dc8610a2bc
1 changed files with 22 additions and 24 deletions

View File

@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import contextlib
import inspect import inspect
import random import random
@ -21,7 +22,6 @@ from oslo_config import cfg
from oslo_db import api as oslo_db_api from oslo_db import api as oslo_db_api
from oslo_db import exception as db_exc from oslo_db import exception as db_exc
from oslo_log import log from oslo_log import log
from oslo_utils import excutils
from oslo_utils import timeutils from oslo_utils import timeutils
import six import six
from sqlalchemy.orm import exc as orm_exc from sqlalchemy.orm import exc as orm_exc
@ -70,25 +70,18 @@ class wrap_db_lock(object):
return True return True
return False return False
def __call__(self, f): @contextlib.contextmanager
@six.wraps(f) def lock(self, lock_id):
def wrap_db_lock(*args, **kwargs):
session_id = 0
result = None
lock_id = _get_lock_id_by_resource_type(self.type, *args, **kwargs)
within_wrapper = self.is_within_wrapper() within_wrapper = self.is_within_wrapper()
if not within_wrapper: if not within_wrapper:
# test and create the lock if necessary # test and create the lock if necessary
_test_and_create_object(lock_id) _test_and_create_object(lock_id)
session_id = _acquire_lock(lock_id) session_id = _acquire_lock(lock_id)
try: try:
result = f(*args, **kwargs) # Code in context may throw exception,
except Exception as e: # but we still need cleanup
with excutils.save_and_reraise_exception() as ctxt: yield
ctxt.reraise = True
finally: finally:
if not within_wrapper: if not within_wrapper:
try: try:
@ -96,7 +89,12 @@ class wrap_db_lock(object):
except Exception as e: except Exception as e:
LOG.exception(e) LOG.exception(e)
return result def __call__(self, f):
@six.wraps(f)
def wrap_db_lock(*args, **kwargs):
lock_id = _get_lock_id_by_resource_type(self.type, *args, **kwargs)
with self.lock(lock_id):
return f(*args, **kwargs)
return wrap_db_lock return wrap_db_lock