Avoid multi-threading problem with sql backend

Now zaqar's sql backend always use only one connection
to db. It will lead an multi-thread problem:
pymysql.err.InternalError) Packet sequence number wrong

So we should use session in sqlalchemy to avoid this happen.

Change-Id: I84e2f9899e141aed151f7c06fc4b1f603481886e
Closes-bug: #1588117
This commit is contained in:
wangxiyuan 2016-06-02 09:23:00 +08:00
parent 454d4acf01
commit 8e5be21524

View File

@ -14,6 +14,8 @@
# the License. # the License.
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from zaqar.common import decorators from zaqar.common import decorators
from zaqar import storage from zaqar import storage
@ -63,9 +65,13 @@ class ControlDriver(storage.ControlDriverBase):
# TODO(cpp-cabrera): expose connect/close as a context manager # TODO(cpp-cabrera): expose connect/close as a context manager
# that acquires the connection to the DB for the desired scope and # that acquires the connection to the DB for the desired scope and
# closes it once the operations are completed # closes it once the operations are completed
# TODO(wangxiyuan): we should migrate to oslo.db asap.
@decorators.lazy_property(write=False) @decorators.lazy_property(write=False)
def connection(self): def connection(self):
return self.engine.connect() # use scoped_session to avoid multi-threading problem.
session = scoped_session(sessionmaker(bind=self.engine,
autocommit=True))
return session()
def run(self, *args, **kwargs): def run(self, *args, **kwargs):
return self.connection.execute(*args, **kwargs) return self.connection.execute(*args, **kwargs)