You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

515 lines
15KB

  1. # sqlalchemy/pool.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Pool implementation classes.
  8. """
  9. import traceback
  10. import weakref
  11. from .base import _AsyncConnDialect
  12. from .base import _ConnectionFairy
  13. from .base import _ConnectionRecord
  14. from .base import Pool
  15. from .. import exc
  16. from .. import util
  17. from ..util import chop_traceback
  18. from ..util import queue as sqla_queue
  19. from ..util import threading
  20. class QueuePool(Pool):
  21. """A :class:`_pool.Pool`
  22. that imposes a limit on the number of open connections.
  23. :class:`.QueuePool` is the default pooling implementation used for
  24. all :class:`_engine.Engine` objects, unless the SQLite dialect is in use.
  25. """
  26. _is_asyncio = False
  27. _queue_class = sqla_queue.Queue
  28. def __init__(
  29. self,
  30. creator,
  31. pool_size=5,
  32. max_overflow=10,
  33. timeout=30.0,
  34. use_lifo=False,
  35. **kw
  36. ):
  37. r"""
  38. Construct a QueuePool.
  39. :param creator: a callable function that returns a DB-API
  40. connection object, same as that of :paramref:`_pool.Pool.creator`.
  41. :param pool_size: The size of the pool to be maintained,
  42. defaults to 5. This is the largest number of connections that
  43. will be kept persistently in the pool. Note that the pool
  44. begins with no connections; once this number of connections
  45. is requested, that number of connections will remain.
  46. ``pool_size`` can be set to 0 to indicate no size limit; to
  47. disable pooling, use a :class:`~sqlalchemy.pool.NullPool`
  48. instead.
  49. :param max_overflow: The maximum overflow size of the
  50. pool. When the number of checked-out connections reaches the
  51. size set in pool_size, additional connections will be
  52. returned up to this limit. When those additional connections
  53. are returned to the pool, they are disconnected and
  54. discarded. It follows then that the total number of
  55. simultaneous connections the pool will allow is pool_size +
  56. `max_overflow`, and the total number of "sleeping"
  57. connections the pool will allow is pool_size. `max_overflow`
  58. can be set to -1 to indicate no overflow limit; no limit
  59. will be placed on the total number of concurrent
  60. connections. Defaults to 10.
  61. :param timeout: The number of seconds to wait before giving up
  62. on returning a connection. Defaults to 30.0. This can be a float
  63. but is subject to the limitations of Python time functions which
  64. may not be reliable in the tens of milliseconds.
  65. :param use_lifo: use LIFO (last-in-first-out) when retrieving
  66. connections instead of FIFO (first-in-first-out). Using LIFO, a
  67. server-side timeout scheme can reduce the number of connections used
  68. during non-peak periods of use. When planning for server-side
  69. timeouts, ensure that a recycle or pre-ping strategy is in use to
  70. gracefully handle stale connections.
  71. .. versionadded:: 1.3
  72. .. seealso::
  73. :ref:`pool_use_lifo`
  74. :ref:`pool_disconnects`
  75. :param \**kw: Other keyword arguments including
  76. :paramref:`_pool.Pool.recycle`, :paramref:`_pool.Pool.echo`,
  77. :paramref:`_pool.Pool.reset_on_return` and others are passed to the
  78. :class:`_pool.Pool` constructor.
  79. """
  80. Pool.__init__(self, creator, **kw)
  81. self._pool = self._queue_class(pool_size, use_lifo=use_lifo)
  82. self._overflow = 0 - pool_size
  83. self._max_overflow = max_overflow
  84. self._timeout = timeout
  85. self._overflow_lock = threading.Lock()
  86. def _do_return_conn(self, conn):
  87. try:
  88. self._pool.put(conn, False)
  89. except sqla_queue.Full:
  90. try:
  91. conn.close()
  92. finally:
  93. self._dec_overflow()
  94. def _do_get(self):
  95. use_overflow = self._max_overflow > -1
  96. try:
  97. wait = use_overflow and self._overflow >= self._max_overflow
  98. return self._pool.get(wait, self._timeout)
  99. except sqla_queue.Empty:
  100. # don't do things inside of "except Empty", because when we say
  101. # we timed out or can't connect and raise, Python 3 tells
  102. # people the real error is queue.Empty which it isn't.
  103. pass
  104. if use_overflow and self._overflow >= self._max_overflow:
  105. if not wait:
  106. return self._do_get()
  107. else:
  108. raise exc.TimeoutError(
  109. "QueuePool limit of size %d overflow %d reached, "
  110. "connection timed out, timeout %0.2f"
  111. % (self.size(), self.overflow(), self._timeout),
  112. code="3o7r",
  113. )
  114. if self._inc_overflow():
  115. try:
  116. return self._create_connection()
  117. except:
  118. with util.safe_reraise():
  119. self._dec_overflow()
  120. else:
  121. return self._do_get()
  122. def _inc_overflow(self):
  123. if self._max_overflow == -1:
  124. self._overflow += 1
  125. return True
  126. with self._overflow_lock:
  127. if self._overflow < self._max_overflow:
  128. self._overflow += 1
  129. return True
  130. else:
  131. return False
  132. def _dec_overflow(self):
  133. if self._max_overflow == -1:
  134. self._overflow -= 1
  135. return True
  136. with self._overflow_lock:
  137. self._overflow -= 1
  138. return True
  139. def recreate(self):
  140. self.logger.info("Pool recreating")
  141. return self.__class__(
  142. self._creator,
  143. pool_size=self._pool.maxsize,
  144. max_overflow=self._max_overflow,
  145. pre_ping=self._pre_ping,
  146. use_lifo=self._pool.use_lifo,
  147. timeout=self._timeout,
  148. recycle=self._recycle,
  149. echo=self.echo,
  150. logging_name=self._orig_logging_name,
  151. reset_on_return=self._reset_on_return,
  152. _dispatch=self.dispatch,
  153. dialect=self._dialect,
  154. )
  155. def dispose(self):
  156. while True:
  157. try:
  158. conn = self._pool.get(False)
  159. conn.close()
  160. except sqla_queue.Empty:
  161. break
  162. self._overflow = 0 - self.size()
  163. self.logger.info("Pool disposed. %s", self.status())
  164. def status(self):
  165. return (
  166. "Pool size: %d Connections in pool: %d "
  167. "Current Overflow: %d Current Checked out "
  168. "connections: %d"
  169. % (
  170. self.size(),
  171. self.checkedin(),
  172. self.overflow(),
  173. self.checkedout(),
  174. )
  175. )
  176. def size(self):
  177. return self._pool.maxsize
  178. def timeout(self):
  179. return self._timeout
  180. def checkedin(self):
  181. return self._pool.qsize()
  182. def overflow(self):
  183. return self._overflow
  184. def checkedout(self):
  185. return self._pool.maxsize - self._pool.qsize() + self._overflow
  186. class AsyncAdaptedQueuePool(QueuePool):
  187. _is_asyncio = True
  188. _queue_class = sqla_queue.AsyncAdaptedQueue
  189. _dialect = _AsyncConnDialect()
  190. class FallbackAsyncAdaptedQueuePool(AsyncAdaptedQueuePool):
  191. _queue_class = sqla_queue.FallbackAsyncAdaptedQueue
  192. class NullPool(Pool):
  193. """A Pool which does not pool connections.
  194. Instead it literally opens and closes the underlying DB-API connection
  195. per each connection open/close.
  196. Reconnect-related functions such as ``recycle`` and connection
  197. invalidation are not supported by this Pool implementation, since
  198. no connections are held persistently.
  199. """
  200. def status(self):
  201. return "NullPool"
  202. def _do_return_conn(self, conn):
  203. conn.close()
  204. def _do_get(self):
  205. return self._create_connection()
  206. def recreate(self):
  207. self.logger.info("Pool recreating")
  208. return self.__class__(
  209. self._creator,
  210. recycle=self._recycle,
  211. echo=self.echo,
  212. logging_name=self._orig_logging_name,
  213. reset_on_return=self._reset_on_return,
  214. pre_ping=self._pre_ping,
  215. _dispatch=self.dispatch,
  216. dialect=self._dialect,
  217. )
  218. def dispose(self):
  219. pass
  220. class SingletonThreadPool(Pool):
  221. """A Pool that maintains one connection per thread.
  222. Maintains one connection per each thread, never moving a connection to a
  223. thread other than the one which it was created in.
  224. .. warning:: the :class:`.SingletonThreadPool` will call ``.close()``
  225. on arbitrary connections that exist beyond the size setting of
  226. ``pool_size``, e.g. if more unique **thread identities**
  227. than what ``pool_size`` states are used. This cleanup is
  228. non-deterministic and not sensitive to whether or not the connections
  229. linked to those thread identities are currently in use.
  230. :class:`.SingletonThreadPool` may be improved in a future release,
  231. however in its current status it is generally used only for test
  232. scenarios using a SQLite ``:memory:`` database and is not recommended
  233. for production use.
  234. Options are the same as those of :class:`_pool.Pool`, as well as:
  235. :param pool_size: The number of threads in which to maintain connections
  236. at once. Defaults to five.
  237. :class:`.SingletonThreadPool` is used by the SQLite dialect
  238. automatically when a memory-based database is used.
  239. See :ref:`sqlite_toplevel`.
  240. """
  241. _is_asyncio = False
  242. def __init__(self, creator, pool_size=5, **kw):
  243. Pool.__init__(self, creator, **kw)
  244. self._conn = threading.local()
  245. self._fairy = threading.local()
  246. self._all_conns = set()
  247. self.size = pool_size
  248. def recreate(self):
  249. self.logger.info("Pool recreating")
  250. return self.__class__(
  251. self._creator,
  252. pool_size=self.size,
  253. recycle=self._recycle,
  254. echo=self.echo,
  255. pre_ping=self._pre_ping,
  256. logging_name=self._orig_logging_name,
  257. reset_on_return=self._reset_on_return,
  258. _dispatch=self.dispatch,
  259. dialect=self._dialect,
  260. )
  261. def dispose(self):
  262. """Dispose of this pool."""
  263. for conn in self._all_conns:
  264. try:
  265. conn.close()
  266. except Exception:
  267. # pysqlite won't even let you close a conn from a thread
  268. # that didn't create it
  269. pass
  270. self._all_conns.clear()
  271. def _cleanup(self):
  272. while len(self._all_conns) >= self.size:
  273. c = self._all_conns.pop()
  274. c.close()
  275. def status(self):
  276. return "SingletonThreadPool id:%d size: %d" % (
  277. id(self),
  278. len(self._all_conns),
  279. )
  280. def _do_return_conn(self, conn):
  281. pass
  282. def _do_get(self):
  283. try:
  284. c = self._conn.current()
  285. if c:
  286. return c
  287. except AttributeError:
  288. pass
  289. c = self._create_connection()
  290. self._conn.current = weakref.ref(c)
  291. if len(self._all_conns) >= self.size:
  292. self._cleanup()
  293. self._all_conns.add(c)
  294. return c
  295. def connect(self):
  296. # vendored from Pool to include the now removed use_threadlocal
  297. # behavior
  298. try:
  299. rec = self._fairy.current()
  300. except AttributeError:
  301. pass
  302. else:
  303. if rec is not None:
  304. return rec._checkout_existing()
  305. return _ConnectionFairy._checkout(self, self._fairy)
  306. def _return_conn(self, record):
  307. try:
  308. del self._fairy.current
  309. except AttributeError:
  310. pass
  311. self._do_return_conn(record)
  312. class StaticPool(Pool):
  313. """A Pool of exactly one connection, used for all requests.
  314. Reconnect-related functions such as ``recycle`` and connection
  315. invalidation (which is also used to support auto-reconnect) are only
  316. partially supported right now and may not yield good results.
  317. """
  318. @util.memoized_property
  319. def connection(self):
  320. return _ConnectionRecord(self)
  321. def status(self):
  322. return "StaticPool"
  323. def dispose(self):
  324. if (
  325. "connection" in self.__dict__
  326. and self.connection.connection is not None
  327. ):
  328. self.connection.close()
  329. del self.__dict__["connection"]
  330. def recreate(self):
  331. self.logger.info("Pool recreating")
  332. return self.__class__(
  333. creator=self._creator,
  334. recycle=self._recycle,
  335. reset_on_return=self._reset_on_return,
  336. pre_ping=self._pre_ping,
  337. echo=self.echo,
  338. logging_name=self._orig_logging_name,
  339. _dispatch=self.dispatch,
  340. dialect=self._dialect,
  341. )
  342. def _transfer_from(self, other_static_pool):
  343. # used by the test suite to make a new engine / pool without
  344. # losing the state of an existing SQLite :memory: connection
  345. self._invoke_creator = (
  346. lambda crec: other_static_pool.connection.connection
  347. )
  348. def _create_connection(self):
  349. raise NotImplementedError()
  350. def _do_return_conn(self, conn):
  351. pass
  352. def _do_get(self):
  353. rec = self.connection
  354. if rec._is_hard_or_soft_invalidated():
  355. del self.__dict__["connection"]
  356. rec = self.connection
  357. return rec
  358. class AssertionPool(Pool):
  359. """A :class:`_pool.Pool` that allows at most one checked out connection at
  360. any given time.
  361. This will raise an exception if more than one connection is checked out
  362. at a time. Useful for debugging code that is using more connections
  363. than desired.
  364. """
  365. def __init__(self, *args, **kw):
  366. self._conn = None
  367. self._checked_out = False
  368. self._store_traceback = kw.pop("store_traceback", True)
  369. self._checkout_traceback = None
  370. Pool.__init__(self, *args, **kw)
  371. def status(self):
  372. return "AssertionPool"
  373. def _do_return_conn(self, conn):
  374. if not self._checked_out:
  375. raise AssertionError("connection is not checked out")
  376. self._checked_out = False
  377. assert conn is self._conn
  378. def dispose(self):
  379. self._checked_out = False
  380. if self._conn:
  381. self._conn.close()
  382. def recreate(self):
  383. self.logger.info("Pool recreating")
  384. return self.__class__(
  385. self._creator,
  386. echo=self.echo,
  387. pre_ping=self._pre_ping,
  388. recycle=self._recycle,
  389. reset_on_return=self._reset_on_return,
  390. logging_name=self._orig_logging_name,
  391. _dispatch=self.dispatch,
  392. dialect=self._dialect,
  393. )
  394. def _do_get(self):
  395. if self._checked_out:
  396. if self._checkout_traceback:
  397. suffix = " at:\n%s" % "".join(
  398. chop_traceback(self._checkout_traceback)
  399. )
  400. else:
  401. suffix = ""
  402. raise AssertionError("connection is already checked out" + suffix)
  403. if not self._conn:
  404. self._conn = self._create_connection()
  405. self._checked_out = True
  406. if self._store_traceback:
  407. self._checkout_traceback = traceback.format_stack()
  408. return self._conn