From 71829664b2ac4547c54940ad62bd8d0123f6e422 Mon Sep 17 00:00:00 2001 From: Dave McCowan Date: Sun, 22 Oct 2017 22:19:26 -0400 Subject: [PATCH] Fix Race Condition in get_or_create_project() get_or_create_project() first calls a get (query of the database). If that fails, then it calls create. The issues is when there are two threads and both fail the original get, then each will call create. One of those creates will fail, resulting in the traceback. One way to protect this critical region is to call create first, then if that fails, call get. In this case, get_or_create_project() is called for every Barbican API operation. The create action (which is slow), happens once per project for the life of the cloud. The get action happens every other time. For performance gains, I left call get first, since that call succeeds almost always. Change-Id: I2f13b495a6b45e226e0742291f76ee88dbcf52df Closes-bug: #1726203 --- barbican/common/resources.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/barbican/common/resources.py b/barbican/common/resources.py index 4f9067dd7..b0680a26e 100644 --- a/barbican/common/resources.py +++ b/barbican/common/resources.py @@ -16,6 +16,7 @@ """ Shared business logic. """ +from barbican.common import exception from barbican.common import utils from barbican.model import models from barbican.model import repositories @@ -46,5 +47,12 @@ def get_or_create_project(project_id): project = models.Project() project.external_id = project_id project.status = models.States.ACTIVE - project_repo.create_from(project) + try: + project_repo.create_from(project) + except exception.ConstraintCheck: + # catch race condition for when another thread just created one + project = project_repo.find_by_external_project_id( + project_id, + suppress_exception=False) + return project