Debian Codegraph @

oslo_db/sqlalchemy/provision.py

raw symbols SCIP
1 # Copyright 2014 Red Hat
2 # Copyright 2013 Mirantis.inc
3 # All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16
17 """Provision test environment for specific DB backends"""
18
19 import abc
20 import logging
21 import os
22 import random
23 import re
24 import string
25
26 import sqlalchemy
27 from sqlalchemy import schema
28 from sqlalchemy import sql
29 import testresources
30
31 from oslo_db import exception
32 from oslo_db.sqlalchemy import enginefacade
33 from oslo_db.sqlalchemy import utils
34
35 LOG = logging.getLogger(__name__)
36
37
38 class ProvisionedDatabase:
39 """Represents a database engine pointing to a DB ready to run tests.
40
41 backend: an instance of :class:`.Backend`
42
43 enginefacade: an instance of :class:`._TransactionFactory`
44
45 engine: a SQLAlchemy :class:`.Engine`
46
47 db_token: if provision_new_database were used, this is the randomly
48 generated name of the database. Note that with SQLite memory
49 connections, this token is ignored. For a database that
50 wasn't actually created, will be None.
51
52 """
53
54 __slots__ = 'backend', 'enginefacade', 'engine', 'db_token'
55
56 def __init__(self, backend, enginefacade, engine, db_token):
57 self.backend = backend
58 self.enginefacade = enginefacade
59 self.engine = engine
60 self.db_token = db_token
61
62
63 class Schema:
64 """"Represents a database schema that has or will be populated.
65
66 This is a marker object as required by testresources but otherwise
67 serves no purpose.
68
69 """
70 __slots__ = 'database',
71
72
73 class BackendResource(testresources.TestResourceManager):
74 def __init__(self, database_type, ad_hoc_url=None):
75 super().__init__()
76 self.database_type = database_type
77 self.backend = Backend.backend_for_database_type(self.database_type)
78 self.ad_hoc_url = ad_hoc_url
79 if ad_hoc_url is None:
80 self.backend = Backend.backend_for_database_type(
81 self.database_type)
82 else:
83 self.backend = Backend(self.database_type, ad_hoc_url)
84 self.backend._verify()
85
86 def make(self, dependency_resources):
87 return self.backend
88
89 def clean(self, resource):
90 self.backend._dispose()
91
92 def isDirty(self):
93 return False
94
95
96 class DatabaseResource(testresources.TestResourceManager):
97 """Database resource which connects and disconnects to a URL.
98
99 For SQLite, this means the database is created implicitly, as a result
100 of SQLite's usual behavior. If the database is a file-based URL,
101 it will remain after the resource has been torn down.
102
103 For all other kinds of databases, the resource indicates to connect
104 and disconnect from that database.
105
106 """
107
108 def __init__(self, database_type, _enginefacade=None,
109 provision_new_database=True, ad_hoc_url=None):
110 super().__init__()
111 self.database_type = database_type
112 self.provision_new_database = provision_new_database
113
114 # NOTE(zzzeek) the _enginefacade is an optional argument
115 # here in order to accomodate Neutron's current direct use
116 # of the DatabaseResource object. Within oslo_db's use,
117 # the "enginefacade" will always be passed in from the
118 # test and/or fixture.
119 if _enginefacade:
120 self._enginefacade = _enginefacade
121 else:
122 self._enginefacade = enginefacade._context_manager
123 self.resources = [
124 ('backend', BackendResource(database_type, ad_hoc_url))
125 ]
126
127 def make(self, dependency_resources):
128 backend = dependency_resources['backend']
129 _enginefacade = self._enginefacade.make_new_manager()
130
131 if self.provision_new_database:
132 db_token = _random_ident()
133 url = backend.provisioned_database_url(db_token)
134 LOG.info(
135 "CREATE BACKEND %s TOKEN %s", backend.engine.url, db_token)
136 backend.create_named_database(db_token, conditional=True)
137 else:
138 db_token = None
139 url = backend.url
140
141 _enginefacade.configure(
142 logging_name=f"{self.database_type}@{db_token}")
143
144 _enginefacade._factory._start(connection=url)
145 engine = _enginefacade._factory._writer_engine
146 return ProvisionedDatabase(backend, _enginefacade, engine, db_token)
147
148 def clean(self, resource):
149 if self.provision_new_database:
150 LOG.info(
151 "DROP BACKEND %s TOKEN %s",
152 resource.backend.engine, resource.db_token)
153 resource.backend.drop_named_database(resource.db_token)
154
155 def isDirty(self):
156 return False
157
158
159 class SchemaResource(testresources.TestResourceManager):
160
161 def __init__(self, database_resource, generate_schema, teardown=False):
162 super().__init__()
163 self.generate_schema = generate_schema
164 self.teardown = teardown
165 self.resources = [
166 ('database', database_resource)
167 ]
168
169 def clean(self, resource):
170 LOG.info(
171 "DROP ALL OBJECTS, BACKEND %s",
172 resource.database.engine.url)
173 resource.database.backend.drop_all_objects(
174 resource.database.engine)
175
176 def make(self, dependency_resources):
177 if self.generate_schema:
178 self.generate_schema(dependency_resources['database'].engine)
179 return Schema()
180
181 def isDirty(self):
182 if self.teardown:
183 return True
184 else:
185 return False
186
187
188 class Backend:
189 """Represent a particular database backend that may be provisionable.
190
191 The ``Backend`` object maintains a database type (e.g. database without
192 specific driver type, such as "sqlite", "postgresql", etc.),
193 a target URL, a base ``Engine`` for that URL object that can be used
194 to provision databases and a ``BackendImpl`` which knows how to perform
195 operations against this type of ``Engine``.
196
197 """
198
199 backends_by_database_type = {}
200
201 def __init__(self, database_type, url):
202 self.database_type = database_type
203 self.url = url
204 self.verified = False
205 self.engine = None
206 self.impl = BackendImpl.impl(database_type)
207 self.current_dbs = set()
208
209 @classmethod
210 def backend_for_database_type(cls, database_type):
211 """Return the ``Backend`` for the given database type.
212
213 """
214 try:
215 backend = cls.backends_by_database_type[database_type]
216 except KeyError:
217 raise exception.BackendNotAvailable(
218 "Backend '%s' is unavailable: No such backend" % database_type)
219 else:
220 return backend._verify()
221
222 @classmethod
223 def all_viable_backends(cls):
224 """Return an iterator of all ``Backend`` objects that are present
225
226 and provisionable.
227
228 """
229
230 for backend in cls.backends_by_database_type.values():
231 try:
232 yield backend._verify()
233 except exception.BackendNotAvailable:
234 pass
235
236 def _verify(self):
237 """Verify that this ``Backend`` is available and provisionable.
238
239 :return: this ``Backend``
240
241 :raises: ``BackendNotAvailable`` if the backend is not available.
242
243 """
244 if not self.verified:
245 try:
246 eng = self._ensure_backend_available(self.url)
247 except exception.BackendNotAvailable as bne:
248 self._no_engine_reason = str(bne)
249 raise
250 else:
251 self.engine = eng
252 finally:
253 self.verified = True
254 if self.engine is None:
255 raise exception.BackendNotAvailable(self._no_engine_reason)
256 return self
257
258 @classmethod
259 def _ensure_backend_available(cls, url):
260 url = utils.make_url(url)
261 try:
262 eng = sqlalchemy.create_engine(url)
263 except ImportError as i_e:
264 # SQLAlchemy performs an "import" of the DBAPI module
265 # within create_engine(). So if mysql etc.
266 # isn't installed, we get an ImportError here.
267 LOG.info(
268 "The %(dbapi)s backend is unavailable: %(err)s",
269 dict(dbapi=url.drivername, err=i_e))
270 raise exception.BackendNotAvailable(
271 "Backend '%s' is unavailable: No DBAPI installed" %
272 url.drivername)
273 else:
274 try:
275 conn = eng.connect()
276 except sqlalchemy.exc.DBAPIError as d_e:
277 # upon connect, SQLAlchemy calls dbapi.connect(). This
278 # usually raises OperationalError and should always at
279 # least raise a SQLAlchemy-wrapped DBAPI Error.
280 LOG.info(
281 "The %(dbapi)s backend is unavailable: %(err)s",
282 dict(dbapi=url.drivername, err=d_e)
283 )
284 raise exception.BackendNotAvailable(
285 "Backend '%s' is unavailable: Could not connect" %
286 url.drivername)
287 else:
288 conn.close()
289 return eng
290
291 def _dispose(self):
292 """Dispose main resources of this backend."""
293 self.impl.dispose(self.engine)
294
295 def create_named_database(self, ident, conditional=False):
296 """Create a database with the given name."""
297
298 if not conditional or ident not in self.current_dbs:
299 self.current_dbs.add(ident)
300 self.impl.create_named_database(
301 self.engine, ident, conditional=conditional)
302
303 def drop_named_database(self, ident, conditional=False):
304 """Drop a database with the given name."""
305
306 self.impl.drop_named_database(
307 self.engine, ident,
308 conditional=conditional)
309 self.current_dbs.discard(ident)
310
311 def drop_all_objects(self, engine):
312 """Drop all database objects.
313
314 Drops all database objects remaining on the default schema of the
315 given engine.
316
317 """
318 self.impl.drop_all_objects(engine)
319
320 def database_exists(self, ident):
321 """Return True if a database of the given name exists."""
322
323 return self.impl.database_exists(self.engine, ident)
324
325 def provisioned_database_url(self, ident):
326 """Given the identifier of an anoymous database, return a URL.
327
328 For hostname-based URLs, this typically involves switching just the
329 'database' portion of the URL with the given name and creating
330 a URL.
331
332 For SQLite URLs, the identifier may be used to create a filename
333 or may be ignored in the case of a memory database.
334
335 """
336 return self.impl.provisioned_database_url(self.url, ident)
337
338 @classmethod
339 def _setup(cls):
340 """Initial startup feature will scan the environment for configured
341
342 URLs and place them into the list of URLs we will use for provisioning.
343
344 This searches through OS_TEST_DBAPI_ADMIN_CONNECTION for URLs. If
345 not present, we set up URLs based on the "opportunstic" convention,
346 e.g. username+password = "openstack_citest".
347
348 The provisioning system will then use or discard these URLs as they
349 are requested, based on whether or not the target database is actually
350 found to be available.
351
352 """
353 configured_urls = os.getenv('OS_TEST_DBAPI_ADMIN_CONNECTION', None)
354 if configured_urls:
355 configured_urls = configured_urls.split(";")
356 else:
357 configured_urls = [
358 impl.create_opportunistic_driver_url()
359 for impl in BackendImpl.all_impls()
360 ]
361
362 for url_str in configured_urls:
363 url = utils.make_url(url_str)
364 m = re.match(r'([^+]+?)(?:\+(.+))?$', url.drivername)
365 database_type = m.group(1)
366 Backend.backends_by_database_type[database_type] = \
367 Backend(database_type, url)
368
369
370 class BackendImpl(metaclass=abc.ABCMeta):
371 """Provide database-specific implementations of key provisioning
372
373 functions.
374
375 ``BackendImpl`` is owned by a ``Backend`` instance which delegates
376 to it for all database-specific features.
377
378 """
379
380 default_engine_kwargs = {}
381
382 supports_drop_fk = True
383
384 def dispose(self, engine):
385 LOG.info("DISPOSE ENGINE %s", engine)
386 engine.dispose()
387
388 @classmethod
389 def all_impls(cls):
390 """Return an iterator of all possible BackendImpl objects.
391
392 These are BackendImpls that are implemented, but not
393 necessarily provisionable.
394
395 """
396 for database_type in cls.impl.reg:
397 if database_type == '*':
398 continue
399 yield BackendImpl.impl(database_type)
400
401 @utils.dispatch_for_dialect("*")
402 def impl(drivername):
403 """Return a ``BackendImpl`` instance corresponding to the
404
405 given driver name.
406
407 This is a dispatched method which will refer to the constructor
408 of implementing subclasses.
409
410 """
411 raise NotImplementedError(
412 "No provision impl available for driver: %s" % drivername)
413
414 def __init__(self, drivername):
415 self.drivername = drivername
416
417 @abc.abstractmethod
418 def create_opportunistic_driver_url(self):
419 """Produce a string url known as the 'opportunistic' URL.
420
421 This URL is one that corresponds to an established OpenStack
422 convention for a pre-established database login, which, when
423 detected as available in the local environment, is automatically
424 used as a test platform for a specific type of driver.
425
426 """
427
428 @abc.abstractmethod
429 def create_named_database(self, engine, ident, conditional=False):
430 """Create a database with the given name."""
431
432 @abc.abstractmethod
433 def drop_named_database(self, engine, ident, conditional=False):
434 """Drop a database with the given name."""
435
436 def drop_all_objects(self, engine):
437 """Drop all database objects.
438
439 Drops all database objects remaining on the default schema of the
440 given engine.
441
442 Per-db implementations will also need to drop items specific to those
443 systems, such as sequences, custom types (e.g. pg ENUM), etc.
444
445 """
446
447 with engine.begin() as conn:
448 inspector = sqlalchemy.inspect(engine)
449 metadata = schema.MetaData()
450 tbs = []
451 all_fks = []
452
453 for table_name in inspector.get_table_names():
454 fks = []
455 for fk in inspector.get_foreign_keys(table_name):
456 # note that SQLite reflection does not have names
457 # for foreign keys until SQLAlchemy 1.0
458 if not fk['name']:
459 continue
460 fks.append(
461 schema.ForeignKeyConstraint((), (), name=fk['name'])
462 )
463 table = schema.Table(table_name, metadata, *fks)
464 tbs.append(table)
465 all_fks.extend(fks)
466
467 if self.supports_drop_fk:
468 for fkc in all_fks:
469 conn.execute(schema.DropConstraint(fkc))
470
471 for table in tbs:
472 conn.execute(schema.DropTable(table))
473
474 self.drop_additional_objects(conn)
475
476 def drop_additional_objects(self, conn):
477 pass
478
479 def provisioned_database_url(self, base_url, ident):
480 """Return a provisioned database URL.
481
482 Given the URL of a particular database backend and the string
483 name of a particular 'database' within that backend, return
484 an URL which refers directly to the named database.
485
486 For hostname-based URLs, this typically involves switching just the
487 'database' portion of the URL with the given name and creating
488 an engine.
489
490 For URLs that instead deal with DSNs, the rules may be more custom;
491 for example, the engine may need to connect to the root URL and
492 then emit a command to switch to the named database.
493
494 """
495 url = utils.make_url(base_url)
496 url = url.set(database=ident)
497
498 return url
499
500
501 @BackendImpl.impl.dispatch_for("mysql")
502 class MySQLBackendImpl(BackendImpl):
503
504 def create_opportunistic_driver_url(self):
505 return "mysql+pymysql://openstack_citest:openstack_citest@localhost/"
506
507 def create_named_database(self, engine, ident, conditional=False):
508 with engine.begin() as conn:
509 if not conditional or not self.database_exists(conn, ident):
510 conn.exec_driver_sql("CREATE DATABASE %s" % ident)
511
512 def drop_named_database(self, engine, ident, conditional=False):
513 with engine.begin() as conn:
514 if not conditional or self.database_exists(conn, ident):
515 conn.exec_driver_sql("DROP DATABASE %s" % ident)
516
517 def database_exists(self, engine, ident):
518 s = sql.text("SHOW DATABASES LIKE :ident")
519 return bool(engine.scalar(s, {'ident': ident}))
520
521
522 @BackendImpl.impl.dispatch_for("sqlite")
523 class SQLiteBackendImpl(BackendImpl):
524
525 supports_drop_fk = False
526
527 def dispose(self, engine):
528 LOG.info("DISPOSE ENGINE %s", engine)
529 engine.dispose()
530 url = engine.url
531 self._drop_url_file(url, True)
532
533 def _drop_url_file(self, url, conditional):
534 filename = url.database
535 if filename and (not conditional or os.access(filename, os.F_OK)):
536 os.remove(filename)
537
538 def create_opportunistic_driver_url(self):
539 return "sqlite://"
540
541 def create_named_database(self, engine, ident, conditional=False):
542 url = self.provisioned_database_url(engine.url, ident)
543 filename = url.database
544 if filename and (not conditional or not os.access(filename, os.F_OK)):
545 eng = sqlalchemy.create_engine(url)
546 eng.connect().close()
547
548 def drop_named_database(self, engine, ident, conditional=False):
549 url = self.provisioned_database_url(engine.url, ident)
550 filename = url.database
551 if filename and (not conditional or os.access(filename, os.F_OK)):
552 os.remove(filename)
553
554 def database_exists(self, engine, ident):
555 url = self._provisioned_database_url(engine.url, ident)
556 filename = url.database
557 return not filename or os.access(filename, os.F_OK)
558
559 def provisioned_database_url(self, base_url, ident):
560 if base_url.database:
561 return utils.make_url("sqlite:////tmp/%s.db" % ident)
562 else:
563 return base_url
564
565
566 @BackendImpl.impl.dispatch_for("postgresql")
567 class PostgresqlBackendImpl(BackendImpl):
568 def create_opportunistic_driver_url(self):
569 return "postgresql+psycopg2://openstack_citest:openstack_citest@localhost/postgres" # noqa: E501
570
571 def create_named_database(self, engine, ident, conditional=False):
572 with engine.connect().execution_options(
573 isolation_level="AUTOCOMMIT",
574 ) as conn:
575 if not conditional or not self.database_exists(conn, ident):
576 conn.exec_driver_sql("CREATE DATABASE %s" % ident)
577
578 def drop_named_database(self, engine, ident, conditional=False):
579 with engine.connect().execution_options(
580 isolation_level="AUTOCOMMIT",
581 ) as conn:
582 self._close_out_database_users(conn, ident)
583 if conditional:
584 conn.exec_driver_sql("DROP DATABASE IF EXISTS %s" % ident)
585 else:
586 conn.exec_driver_sql("DROP DATABASE %s" % ident)
587
588 def drop_additional_objects(self, conn):
589 enums = [e['name'] for e in sqlalchemy.inspect(conn).get_enums()]
590
591 for e in enums:
592 conn.exec_driver_sql("DROP TYPE %s" % e)
593
594 def database_exists(self, engine, ident):
595 return bool(
596 engine.scalar(
597 sqlalchemy.text(
598 "SELECT datname FROM pg_database WHERE datname=:name"
599 ),
600 {'name': ident},
601 )
602 )
603
604 def _close_out_database_users(self, conn, ident):
605 """Attempt to guarantee a database can be dropped.
606
607 Optional feature which guarantees no connections with our
608 username are attached to the DB we're going to drop.
609
610 This method has caveats; for one, the 'pid' column was named
611 'procpid' prior to Postgresql 9.2. But more critically,
612 prior to 9.2 this operation required superuser permissions,
613 even if the connections we're closing are under the same username
614 as us. In more recent versions this restriction has been
615 lifted for same-user connections.
616
617 """
618 if conn.dialect.server_version_info >= (9, 2):
619 conn.execute(
620 sqlalchemy.text(
621 "SELECT pg_terminate_backend(pid) "
622 "FROM pg_stat_activity "
623 "WHERE usename=current_user AND "
624 "pid != pg_backend_pid() AND "
625 "datname=:dname"
626 ),
627 {'dname': ident},
628 )
629
630
631 def _random_ident():
632 return ''.join(random.choice(string.ascii_lowercase) for i in range(10))
633
634
635 Backend._setup()