provision.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from sqlalchemy.engine import url as sa_url
  2. from sqlalchemy import text
  3. from sqlalchemy import exc
  4. from sqlalchemy.util import compat
  5. from . import config, engines
  6. import os
  7. import time
  8. import logging
  9. log = logging.getLogger(__name__)
  10. FOLLOWER_IDENT = None
  11. class register(object):
  12. def __init__(self):
  13. self.fns = {}
  14. @classmethod
  15. def init(cls, fn):
  16. return register().for_db("*")(fn)
  17. def for_db(self, dbname):
  18. def decorate(fn):
  19. self.fns[dbname] = fn
  20. return self
  21. return decorate
  22. def __call__(self, cfg, *arg):
  23. if isinstance(cfg, compat.string_types):
  24. url = sa_url.make_url(cfg)
  25. elif isinstance(cfg, sa_url.URL):
  26. url = cfg
  27. else:
  28. url = cfg.db.url
  29. backend = url.get_backend_name()
  30. if backend in self.fns:
  31. return self.fns[backend](cfg, *arg)
  32. else:
  33. return self.fns['*'](cfg, *arg)
  34. def create_follower_db(follower_ident):
  35. for cfg in _configs_for_db_operation():
  36. _create_db(cfg, cfg.db, follower_ident)
  37. def configure_follower(follower_ident):
  38. for cfg in config.Config.all_configs():
  39. _configure_follower(cfg, follower_ident)
  40. def setup_config(db_url, options, file_config, follower_ident):
  41. if follower_ident:
  42. db_url = _follower_url_from_main(db_url, follower_ident)
  43. db_opts = {}
  44. _update_db_opts(db_url, db_opts)
  45. eng = engines.testing_engine(db_url, db_opts)
  46. _post_configure_engine(db_url, eng, follower_ident)
  47. eng.connect().close()
  48. cfg = config.Config.register(eng, db_opts, options, file_config)
  49. if follower_ident:
  50. _configure_follower(cfg, follower_ident)
  51. return cfg
  52. def drop_follower_db(follower_ident):
  53. for cfg in _configs_for_db_operation():
  54. _drop_db(cfg, cfg.db, follower_ident)
  55. def _configs_for_db_operation():
  56. hosts = set()
  57. for cfg in config.Config.all_configs():
  58. cfg.db.dispose()
  59. for cfg in config.Config.all_configs():
  60. url = cfg.db.url
  61. backend = url.get_backend_name()
  62. host_conf = (
  63. backend,
  64. url.username, url.host, url.database)
  65. if host_conf not in hosts:
  66. yield cfg
  67. hosts.add(host_conf)
  68. for cfg in config.Config.all_configs():
  69. cfg.db.dispose()
  70. @register.init
  71. def _create_db(cfg, eng, ident):
  72. raise NotImplementedError("no DB creation routine for cfg: %s" % eng.url)
  73. @register.init
  74. def _drop_db(cfg, eng, ident):
  75. raise NotImplementedError("no DB drop routine for cfg: %s" % eng.url)
  76. @register.init
  77. def _update_db_opts(db_url, db_opts):
  78. pass
  79. @register.init
  80. def _configure_follower(cfg, ident):
  81. pass
  82. @register.init
  83. def _post_configure_engine(url, engine, follower_ident):
  84. pass
  85. @register.init
  86. def _follower_url_from_main(url, ident):
  87. url = sa_url.make_url(url)
  88. url.database = ident
  89. return url
  90. @_update_db_opts.for_db("mssql")
  91. def _mssql_update_db_opts(db_url, db_opts):
  92. db_opts['legacy_schema_aliasing'] = False
  93. @_follower_url_from_main.for_db("sqlite")
  94. def _sqlite_follower_url_from_main(url, ident):
  95. url = sa_url.make_url(url)
  96. if not url.database or url.database == ':memory:':
  97. return url
  98. else:
  99. return sa_url.make_url("sqlite:///%s.db" % ident)
  100. @_post_configure_engine.for_db("sqlite")
  101. def _sqlite_post_configure_engine(url, engine, follower_ident):
  102. from sqlalchemy import event
  103. @event.listens_for(engine, "connect")
  104. def connect(dbapi_connection, connection_record):
  105. # use file DBs in all cases, memory acts kind of strangely
  106. # as an attached
  107. if not follower_ident:
  108. dbapi_connection.execute(
  109. 'ATTACH DATABASE "test_schema.db" AS test_schema')
  110. else:
  111. dbapi_connection.execute(
  112. 'ATTACH DATABASE "%s_test_schema.db" AS test_schema'
  113. % follower_ident)
  114. @_create_db.for_db("postgresql")
  115. def _pg_create_db(cfg, eng, ident):
  116. with eng.connect().execution_options(
  117. isolation_level="AUTOCOMMIT") as conn:
  118. try:
  119. _pg_drop_db(cfg, conn, ident)
  120. except Exception:
  121. pass
  122. currentdb = conn.scalar("select current_database()")
  123. for attempt in range(3):
  124. try:
  125. conn.execute(
  126. "CREATE DATABASE %s TEMPLATE %s" % (ident, currentdb))
  127. except exc.OperationalError as err:
  128. if attempt != 2 and "accessed by other users" in str(err):
  129. time.sleep(.2)
  130. continue
  131. else:
  132. raise
  133. else:
  134. break
  135. @_create_db.for_db("mysql")
  136. def _mysql_create_db(cfg, eng, ident):
  137. with eng.connect() as conn:
  138. try:
  139. _mysql_drop_db(cfg, conn, ident)
  140. except Exception:
  141. pass
  142. conn.execute("CREATE DATABASE %s" % ident)
  143. conn.execute("CREATE DATABASE %s_test_schema" % ident)
  144. conn.execute("CREATE DATABASE %s_test_schema_2" % ident)
  145. @_configure_follower.for_db("mysql")
  146. def _mysql_configure_follower(config, ident):
  147. config.test_schema = "%s_test_schema" % ident
  148. config.test_schema_2 = "%s_test_schema_2" % ident
  149. @_create_db.for_db("sqlite")
  150. def _sqlite_create_db(cfg, eng, ident):
  151. pass
  152. @_drop_db.for_db("postgresql")
  153. def _pg_drop_db(cfg, eng, ident):
  154. with eng.connect().execution_options(
  155. isolation_level="AUTOCOMMIT") as conn:
  156. conn.execute(
  157. text(
  158. "select pg_terminate_backend(pid) from pg_stat_activity "
  159. "where usename=current_user and pid != pg_backend_pid() "
  160. "and datname=:dname"
  161. ), dname=ident)
  162. conn.execute("DROP DATABASE %s" % ident)
  163. @_drop_db.for_db("sqlite")
  164. def _sqlite_drop_db(cfg, eng, ident):
  165. if ident:
  166. os.remove("%s_test_schema.db" % ident)
  167. else:
  168. os.remove("%s.db" % ident)
  169. @_drop_db.for_db("mysql")
  170. def _mysql_drop_db(cfg, eng, ident):
  171. with eng.connect() as conn:
  172. conn.execute("DROP DATABASE %s_test_schema" % ident)
  173. conn.execute("DROP DATABASE %s_test_schema_2" % ident)
  174. conn.execute("DROP DATABASE %s" % ident)
  175. @_create_db.for_db("oracle")
  176. def _oracle_create_db(cfg, eng, ident):
  177. # NOTE: make sure you've run "ALTER DATABASE default tablespace users" or
  178. # similar, so that the default tablespace is not "system"; reflection will
  179. # fail otherwise
  180. with eng.connect() as conn:
  181. conn.execute("create user %s identified by xe" % ident)
  182. conn.execute("create user %s_ts1 identified by xe" % ident)
  183. conn.execute("create user %s_ts2 identified by xe" % ident)
  184. conn.execute("grant dba to %s" % (ident, ))
  185. conn.execute("grant unlimited tablespace to %s" % ident)
  186. conn.execute("grant unlimited tablespace to %s_ts1" % ident)
  187. conn.execute("grant unlimited tablespace to %s_ts2" % ident)
  188. @_configure_follower.for_db("oracle")
  189. def _oracle_configure_follower(config, ident):
  190. config.test_schema = "%s_ts1" % ident
  191. config.test_schema_2 = "%s_ts2" % ident
  192. def _ora_drop_ignore(conn, dbname):
  193. try:
  194. conn.execute("drop user %s cascade" % dbname)
  195. log.info("Reaped db: %s", dbname)
  196. return True
  197. except exc.DatabaseError as err:
  198. log.warning("couldn't drop db: %s", err)
  199. return False
  200. @_drop_db.for_db("oracle")
  201. def _oracle_drop_db(cfg, eng, ident):
  202. with eng.connect() as conn:
  203. # cx_Oracle seems to occasionally leak open connections when a large
  204. # suite it run, even if we confirm we have zero references to
  205. # connection objects.
  206. # while there is a "kill session" command in Oracle,
  207. # it unfortunately does not release the connection sufficiently.
  208. _ora_drop_ignore(conn, ident)
  209. _ora_drop_ignore(conn, "%s_ts1" % ident)
  210. _ora_drop_ignore(conn, "%s_ts2" % ident)
  211. @_update_db_opts.for_db("oracle")
  212. def _oracle_update_db_opts(db_url, db_opts):
  213. db_opts['_retry_on_12516'] = True
  214. def reap_oracle_dbs(eng, idents_file):
  215. log.info("Reaping Oracle dbs...")
  216. with eng.connect() as conn:
  217. with open(idents_file) as file_:
  218. idents = set(line.strip() for line in file_)
  219. log.info("identifiers in file: %s", ", ".join(idents))
  220. to_reap = conn.execute(
  221. "select u.username from all_users u where username "
  222. "like 'TEST_%' and not exists (select username "
  223. "from v$session where username=u.username)")
  224. all_names = set([username.lower() for (username, ) in to_reap])
  225. to_drop = set()
  226. for name in all_names:
  227. if name.endswith("_ts1") or name.endswith("_ts2"):
  228. continue
  229. elif name in idents:
  230. to_drop.add(name)
  231. if "%s_ts1" % name in all_names:
  232. to_drop.add("%s_ts1" % name)
  233. if "%s_ts2" % name in all_names:
  234. to_drop.add("%s_ts2" % name)
  235. dropped = total = 0
  236. for total, username in enumerate(to_drop, 1):
  237. if _ora_drop_ignore(conn, username):
  238. dropped += 1
  239. log.info(
  240. "Dropped %d out of %d stale databases detected", dropped, total)
  241. @_follower_url_from_main.for_db("oracle")
  242. def _oracle_follower_url_from_main(url, ident):
  243. url = sa_url.make_url(url)
  244. url.username = ident
  245. url.password = 'xe'
  246. return url