24
25
import sqlalchemy.exc
27
from ceilometer.openstack.common.db.sqlalchemy import utils
26
28
from ceilometer.openstack.common.gettextutils import _
27
from ceilometer.openstack.common import log as logging
28
29
from ceilometer.openstack.common.py3kcompat import urlutils
29
30
from ceilometer.openstack.common import test
31
32
LOG = logging.getLogger(__name__)
34
def _get_connect_string(backend, user, passwd, database):
35
"""Get database connection
37
Try to get a connection with a very specific set of values, if we get
38
these then we'll run the tests, otherwise they are skipped
40
if backend == "postgres":
41
backend = "postgresql+psycopg2"
42
elif backend == "mysql":
43
backend = "mysql+mysqldb"
45
raise Exception("Unrecognized backend: '%s'" % backend)
47
return ("%(backend)s://%(user)s:%(passwd)s@localhost/%(database)s"
48
% {'backend': backend, 'user': user, 'passwd': passwd,
49
'database': database})
52
def _is_backend_avail(backend, user, passwd, database):
54
connect_uri = _get_connect_string(backend, user, passwd, database)
55
engine = sqlalchemy.create_engine(connect_uri)
56
connection = engine.connect()
58
# intentionally catch all to handle exceptions even if we don't
59
# have any backend code loaded.
67
35
def _have_mysql(user, passwd, database):
68
36
present = os.environ.get('TEST_MYSQL_PRESENT')
69
37
if present is None:
70
return _is_backend_avail('mysql', user, passwd, database)
38
return utils.is_backend_avail(backend='mysql',
71
42
return present.lower() in ('', 'true')
74
45
def _have_postgresql(user, passwd, database):
75
46
present = os.environ.get('TEST_POSTGRESQL_PRESENT')
76
47
if present is None:
77
return _is_backend_avail('postgres', user, passwd, database)
48
return utils.is_backend_avail(backend='postgres',
78
52
return present.lower() in ('', 'true')
81
def get_db_connection_info(conn_pieces):
82
database = conn_pieces.path.strip('/')
83
loc_pieces = conn_pieces.netloc.split('@')
86
auth_pieces = loc_pieces[0].split(':')
89
if len(auth_pieces) > 1:
90
password = auth_pieces[1].strip()
92
return (user, password, database, host)
95
55
def _set_db_lock(lock_path=None, lock_prefix=None):
97
57
@functools.wraps(f)
166
126
"Failed to run: %s\n%s" % (cmd, output))
168
128
def _reset_pg(self, conn_pieces):
169
(user, password, database, host) = get_db_connection_info(conn_pieces)
132
host) = utils.get_db_connection_info(conn_pieces)
170
133
os.environ['PGPASSWORD'] = password
171
134
os.environ['PGUSER'] = user
172
135
# note(boris-42): We must create and drop database, we can't
205
168
# the MYSQL database, which is easier and less error-prone
206
169
# than using SQLAlchemy to do this via MetaData...trust me.
207
170
(user, password, database, host) = \
208
get_db_connection_info(conn_pieces)
171
utils.get_db_connection_info(conn_pieces)
209
172
sql = ("drop database if exists %(db)s; "
210
173
"create database %(db)s;") % {'db': database}
211
174
cmd = ("mysql -u \"%(user)s\" -p\"%(password)s\" -h %(host)s "