client_session.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. # Copyright 2017 MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Logical sessions for ordering sequential operations.
  15. Requires MongoDB 3.6.
  16. .. versionadded:: 3.6
  17. Causally Consistent Reads
  18. =========================
  19. .. code-block:: python
  20. with client.start_session(causal_consistency=True) as session:
  21. collection = client.db.collection
  22. collection.update_one({'_id': 1}, {'$set': {'x': 10}}, session=session)
  23. secondary_c = collection.with_options(
  24. read_preference=ReadPreference.SECONDARY)
  25. # A secondary read waits for replication of the write.
  26. secondary_c.find_one({'_id': 1}, session=session)
  27. If `causal_consistency` is True (the default), read operations that use
  28. the session are causally after previous read and write operations. Using a
  29. causally consistent session, an application can read its own writes and is
  30. guaranteed monotonic reads, even when reading from replica set secondaries.
  31. .. mongodoc:: causal-consistency
  32. .. _transactions-ref:
  33. Transactions
  34. ============
  35. .. versionadded:: 3.7
  36. MongoDB 4.0 adds support for transactions on replica set primaries. A
  37. transaction is associated with a :class:`ClientSession`. To start a transaction
  38. on a session, use :meth:`ClientSession.start_transaction` in a with-statement.
  39. Then, execute an operation within the transaction by passing the session to the
  40. operation:
  41. .. code-block:: python
  42. orders = client.db.orders
  43. inventory = client.db.inventory
  44. with client.start_session() as session:
  45. with session.start_transaction():
  46. orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
  47. inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}},
  48. {"$inc": {"qty": -100}}, session=session)
  49. Upon normal completion of ``with session.start_transaction()`` block, the
  50. transaction automatically calls :meth:`ClientSession.commit_transaction`.
  51. If the block exits with an exception, the transaction automatically calls
  52. :meth:`ClientSession.abort_transaction`.
  53. In general, multi-document transactions only support read/write (CRUD)
  54. operations on existing collections. However, MongoDB 4.4 adds support for
  55. creating collections and indexes with some limitations, including an
  56. insert operation that would result in the creation of a new collection.
  57. For a complete description of all the supported and unsupported operations
  58. see the `MongoDB server's documentation for transactions
  59. <http://dochub.mongodb.org/core/transactions>`_.
  60. A session may only have a single active transaction at a time, multiple
  61. transactions on the same session can be executed in sequence.
  62. Sharded Transactions
  63. ^^^^^^^^^^^^^^^^^^^^
  64. .. versionadded:: 3.9
  65. PyMongo 3.9 adds support for transactions on sharded clusters running MongoDB
  66. >=4.2. Sharded transactions have the same API as replica set transactions.
  67. When running a transaction against a sharded cluster, the session is
  68. pinned to the mongos server selected for the first operation in the
  69. transaction. All subsequent operations that are part of the same transaction
  70. are routed to the same mongos server. When the transaction is completed, by
  71. running either commitTransaction or abortTransaction, the session is unpinned.
  72. .. mongodoc:: transactions
  73. .. _snapshot-reads-ref:
  74. Snapshot Reads
  75. ==============
  76. .. versionadded:: 3.12
  77. MongoDB 5.0 adds support for snapshot reads. Snapshot reads are requested by
  78. passing the ``snapshot`` option to
  79. :meth:`~pymongo.mongo_client.MongoClient.start_session`.
  80. If ``snapshot`` is True, all read operations that use this session read data
  81. from the same snapshot timestamp. The server chooses the latest
  82. majority-committed snapshot timestamp when executing the first read operation
  83. using the session. Subsequent reads on this session read from the same
  84. snapshot timestamp. Snapshot reads are also supported when reading from
  85. replica set secondaries.
  86. .. code-block:: python
  87. # Each read using this session reads data from the same point in time.
  88. with client.start_session(snapshot=True) as session:
  89. order = orders.find_one({"sku": "abc123"}, session=session)
  90. inventory = inventory.find_one({"sku": "abc123"}, session=session)
  91. Snapshot Reads Limitations
  92. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  93. Snapshot reads sessions are incompatible with ``causal_consistency=True``.
  94. Only the following read operations are supported in a snapshot reads session:
  95. - :meth:`~pymongo.collection.Collection.find`
  96. - :meth:`~pymongo.collection.Collection.find_one`
  97. - :meth:`~pymongo.collection.Collection.aggregate`
  98. - :meth:`~pymongo.collection.Collection.count_documents`
  99. - :meth:`~pymongo.collection.Collection.distinct` (on unsharded collections)
  100. Classes
  101. =======
  102. """
  103. import collections
  104. import uuid
  105. from bson.binary import Binary
  106. from bson.int64 import Int64
  107. from bson.py3compat import abc, integer_types
  108. from bson.son import SON
  109. from bson.timestamp import Timestamp
  110. from pymongo import monotonic
  111. from pymongo.cursor import _SocketManager
  112. from pymongo.errors import (ConfigurationError,
  113. ConnectionFailure,
  114. InvalidOperation,
  115. OperationFailure,
  116. PyMongoError,
  117. WTimeoutError)
  118. from pymongo.helpers import _RETRYABLE_ERROR_CODES
  119. from pymongo.read_concern import ReadConcern
  120. from pymongo.read_preferences import ReadPreference, _ServerMode
  121. from pymongo.server_type import SERVER_TYPE
  122. from pymongo.write_concern import WriteConcern
  123. class SessionOptions(object):
  124. """Options for a new :class:`ClientSession`.
  125. :Parameters:
  126. - `causal_consistency` (optional): If True, read operations are causally
  127. ordered within the session. Defaults to True when the ``snapshot``
  128. option is ``False``.
  129. - `default_transaction_options` (optional): The default
  130. TransactionOptions to use for transactions started on this session.
  131. - `snapshot` (optional): If True, then all reads performed using this
  132. session will read from the same snapshot. This option is incompatible
  133. with ``causal_consistency=True``. Defaults to ``False``.
  134. .. versionchanged:: 3.12
  135. Added the ``snapshot`` parameter.
  136. """
  137. def __init__(self,
  138. causal_consistency=None,
  139. default_transaction_options=None,
  140. snapshot=False):
  141. if snapshot:
  142. if causal_consistency:
  143. raise ConfigurationError('snapshot reads do not support '
  144. 'causal_consistency=True')
  145. causal_consistency = False
  146. elif causal_consistency is None:
  147. causal_consistency = True
  148. self._causal_consistency = causal_consistency
  149. if default_transaction_options is not None:
  150. if not isinstance(default_transaction_options, TransactionOptions):
  151. raise TypeError(
  152. "default_transaction_options must be an instance of "
  153. "pymongo.client_session.TransactionOptions, not: %r" %
  154. (default_transaction_options,))
  155. self._default_transaction_options = default_transaction_options
  156. self._snapshot = snapshot
  157. @property
  158. def causal_consistency(self):
  159. """Whether causal consistency is configured."""
  160. return self._causal_consistency
  161. @property
  162. def default_transaction_options(self):
  163. """The default TransactionOptions to use for transactions started on
  164. this session.
  165. .. versionadded:: 3.7
  166. """
  167. return self._default_transaction_options
  168. @property
  169. def snapshot(self):
  170. """Whether snapshot reads are configured.
  171. .. versionadded:: 3.12
  172. """
  173. return self._snapshot
  174. class TransactionOptions(object):
  175. """Options for :meth:`ClientSession.start_transaction`.
  176. :Parameters:
  177. - `read_concern` (optional): The
  178. :class:`~pymongo.read_concern.ReadConcern` to use for this transaction.
  179. If ``None`` (the default) the :attr:`read_preference` of
  180. the :class:`MongoClient` is used.
  181. - `write_concern` (optional): The
  182. :class:`~pymongo.write_concern.WriteConcern` to use for this
  183. transaction. If ``None`` (the default) the :attr:`read_preference` of
  184. the :class:`MongoClient` is used.
  185. - `read_preference` (optional): The read preference to use. If
  186. ``None`` (the default) the :attr:`read_preference` of this
  187. :class:`MongoClient` is used. See :mod:`~pymongo.read_preferences`
  188. for options. Transactions which read must use
  189. :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
  190. - `max_commit_time_ms` (optional): The maximum amount of time to allow a
  191. single commitTransaction command to run. This option is an alias for
  192. maxTimeMS option on the commitTransaction command. If ``None`` (the
  193. default) maxTimeMS is not used.
  194. .. versionchanged:: 3.9
  195. Added the ``max_commit_time_ms`` option.
  196. .. versionadded:: 3.7
  197. """
  198. def __init__(self, read_concern=None, write_concern=None,
  199. read_preference=None, max_commit_time_ms=None):
  200. self._read_concern = read_concern
  201. self._write_concern = write_concern
  202. self._read_preference = read_preference
  203. self._max_commit_time_ms = max_commit_time_ms
  204. if read_concern is not None:
  205. if not isinstance(read_concern, ReadConcern):
  206. raise TypeError("read_concern must be an instance of "
  207. "pymongo.read_concern.ReadConcern, not: %r" %
  208. (read_concern,))
  209. if write_concern is not None:
  210. if not isinstance(write_concern, WriteConcern):
  211. raise TypeError("write_concern must be an instance of "
  212. "pymongo.write_concern.WriteConcern, not: %r" %
  213. (write_concern,))
  214. if not write_concern.acknowledged:
  215. raise ConfigurationError(
  216. "transactions do not support unacknowledged write concern"
  217. ": %r" % (write_concern,))
  218. if read_preference is not None:
  219. if not isinstance(read_preference, _ServerMode):
  220. raise TypeError("%r is not valid for read_preference. See "
  221. "pymongo.read_preferences for valid "
  222. "options." % (read_preference,))
  223. if max_commit_time_ms is not None:
  224. if not isinstance(max_commit_time_ms, integer_types):
  225. raise TypeError(
  226. "max_commit_time_ms must be an integer or None")
  227. @property
  228. def read_concern(self):
  229. """This transaction's :class:`~pymongo.read_concern.ReadConcern`."""
  230. return self._read_concern
  231. @property
  232. def write_concern(self):
  233. """This transaction's :class:`~pymongo.write_concern.WriteConcern`."""
  234. return self._write_concern
  235. @property
  236. def read_preference(self):
  237. """This transaction's :class:`~pymongo.read_preferences.ReadPreference`.
  238. """
  239. return self._read_preference
  240. @property
  241. def max_commit_time_ms(self):
  242. """The maxTimeMS to use when running a commitTransaction command.
  243. .. versionadded:: 3.9
  244. """
  245. return self._max_commit_time_ms
  246. def _validate_session_write_concern(session, write_concern):
  247. """Validate that an explicit session is not used with an unack'ed write.
  248. Returns the session to use for the next operation.
  249. """
  250. if session:
  251. if write_concern is not None and not write_concern.acknowledged:
  252. # For unacknowledged writes without an explicit session,
  253. # drivers SHOULD NOT use an implicit session. If a driver
  254. # creates an implicit session for unacknowledged writes
  255. # without an explicit session, the driver MUST NOT send the
  256. # session ID.
  257. if session._implicit:
  258. return None
  259. else:
  260. raise ConfigurationError(
  261. 'Explicit sessions are incompatible with '
  262. 'unacknowledged write concern: %r' % (
  263. write_concern,))
  264. return session
  265. class _TransactionContext(object):
  266. """Internal transaction context manager for start_transaction."""
  267. def __init__(self, session):
  268. self.__session = session
  269. def __enter__(self):
  270. return self
  271. def __exit__(self, exc_type, exc_val, exc_tb):
  272. if self.__session.in_transaction:
  273. if exc_val is None:
  274. self.__session.commit_transaction()
  275. else:
  276. self.__session.abort_transaction()
  277. class _TxnState(object):
  278. NONE = 1
  279. STARTING = 2
  280. IN_PROGRESS = 3
  281. COMMITTED = 4
  282. COMMITTED_EMPTY = 5
  283. ABORTED = 6
  284. class _Transaction(object):
  285. """Internal class to hold transaction information in a ClientSession."""
  286. def __init__(self, opts, client):
  287. self.opts = opts
  288. self.state = _TxnState.NONE
  289. self.sharded = False
  290. self.pinned_address = None
  291. self.sock_mgr = None
  292. self.recovery_token = None
  293. self.attempt = 0
  294. self.client = client
  295. def active(self):
  296. return self.state in (_TxnState.STARTING, _TxnState.IN_PROGRESS)
  297. def starting(self):
  298. return self.state == _TxnState.STARTING
  299. @property
  300. def pinned_conn(self):
  301. if self.active() and self.sock_mgr:
  302. return self.sock_mgr.sock
  303. return None
  304. def pin(self, server, sock_info):
  305. self.sharded = True
  306. self.pinned_address = server.description.address
  307. if server.description.server_type == SERVER_TYPE.LoadBalancer:
  308. sock_info.pin_txn()
  309. self.sock_mgr = _SocketManager(sock_info, False)
  310. def unpin(self):
  311. self.pinned_address = None
  312. if self.sock_mgr:
  313. self.sock_mgr.close()
  314. self.sock_mgr = None
  315. def reset(self):
  316. self.unpin()
  317. self.state = _TxnState.NONE
  318. self.sharded = False
  319. self.recovery_token = None
  320. self.attempt = 0
  321. def __del__(self):
  322. if self.sock_mgr:
  323. # Reuse the cursor closing machinery to return the socket to the
  324. # pool soon.
  325. self.client._close_cursor_soon(0, None, self.sock_mgr)
  326. self.sock_mgr = None
  327. def _reraise_with_unknown_commit(exc):
  328. """Re-raise an exception with the UnknownTransactionCommitResult label."""
  329. exc._add_error_label("UnknownTransactionCommitResult")
  330. raise
  331. def _max_time_expired_error(exc):
  332. """Return true if exc is a MaxTimeMSExpired error."""
  333. return isinstance(exc, OperationFailure) and exc.code == 50
  334. # From the transactions spec, all the retryable writes errors plus
  335. # WriteConcernFailed.
  336. _UNKNOWN_COMMIT_ERROR_CODES = _RETRYABLE_ERROR_CODES | frozenset([
  337. 64, # WriteConcernFailed
  338. 50, # MaxTimeMSExpired
  339. ])
  340. # From the Convenient API for Transactions spec, with_transaction must
  341. # halt retries after 120 seconds.
  342. # This limit is non-configurable and was chosen to be twice the 60 second
  343. # default value of MongoDB's `transactionLifetimeLimitSeconds` parameter.
  344. _WITH_TRANSACTION_RETRY_TIME_LIMIT = 120
  345. def _within_time_limit(start_time):
  346. """Are we within the with_transaction retry limit?"""
  347. return monotonic.time() - start_time < _WITH_TRANSACTION_RETRY_TIME_LIMIT
  348. class ClientSession(object):
  349. """A session for ordering sequential operations.
  350. :class:`ClientSession` instances are **not thread-safe or fork-safe**.
  351. They can only be used by one thread or process at a time. A single
  352. :class:`ClientSession` cannot be used to run multiple operations
  353. concurrently.
  354. Should not be initialized directly by application developers - to create a
  355. :class:`ClientSession`, call
  356. :meth:`~pymongo.mongo_client.MongoClient.start_session`.
  357. """
  358. def __init__(self, client, server_session, options, authset, implicit):
  359. # A MongoClient, a _ServerSession, a SessionOptions, and a set.
  360. self._client = client
  361. self._server_session = server_session
  362. self._options = options
  363. self._authset = authset
  364. self._cluster_time = None
  365. self._operation_time = None
  366. self._snapshot_time = None
  367. # Is this an implicitly created session?
  368. self._implicit = implicit
  369. self._transaction = _Transaction(None, client)
  370. def end_session(self):
  371. """Finish this session. If a transaction has started, abort it.
  372. It is an error to use the session after the session has ended.
  373. """
  374. self._end_session(lock=True)
  375. def _end_session(self, lock):
  376. if self._server_session is not None:
  377. try:
  378. if self.in_transaction:
  379. self.abort_transaction()
  380. # It's possible we're still pinned here when the transaction
  381. # is in the committed state when the session is discarded.
  382. self._unpin()
  383. finally:
  384. self._client._return_server_session(self._server_session, lock)
  385. self._server_session = None
  386. def _check_ended(self):
  387. if self._server_session is None:
  388. raise InvalidOperation("Cannot use ended session")
  389. def __enter__(self):
  390. return self
  391. def __exit__(self, exc_type, exc_val, exc_tb):
  392. self._end_session(lock=True)
  393. @property
  394. def client(self):
  395. """The :class:`~pymongo.mongo_client.MongoClient` this session was
  396. created from.
  397. """
  398. return self._client
  399. @property
  400. def options(self):
  401. """The :class:`SessionOptions` this session was created with."""
  402. return self._options
  403. @property
  404. def session_id(self):
  405. """A BSON document, the opaque server session identifier."""
  406. self._check_ended()
  407. return self._server_session.session_id
  408. @property
  409. def cluster_time(self):
  410. """The cluster time returned by the last operation executed
  411. in this session.
  412. """
  413. return self._cluster_time
  414. @property
  415. def operation_time(self):
  416. """The operation time returned by the last operation executed
  417. in this session.
  418. """
  419. return self._operation_time
  420. def _inherit_option(self, name, val):
  421. """Return the inherited TransactionOption value."""
  422. if val:
  423. return val
  424. txn_opts = self.options.default_transaction_options
  425. val = txn_opts and getattr(txn_opts, name)
  426. if val:
  427. return val
  428. return getattr(self.client, name)
  429. def with_transaction(self, callback, read_concern=None, write_concern=None,
  430. read_preference=None, max_commit_time_ms=None):
  431. """Execute a callback in a transaction.
  432. This method starts a transaction on this session, executes ``callback``
  433. once, and then commits the transaction. For example::
  434. def callback(session):
  435. orders = session.client.db.orders
  436. inventory = session.client.db.inventory
  437. orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
  438. inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}},
  439. {"$inc": {"qty": -100}}, session=session)
  440. with client.start_session() as session:
  441. session.with_transaction(callback)
  442. To pass arbitrary arguments to the ``callback``, wrap your callable
  443. with a ``lambda`` like this::
  444. def callback(session, custom_arg, custom_kwarg=None):
  445. # Transaction operations...
  446. with client.start_session() as session:
  447. session.with_transaction(
  448. lambda s: callback(s, "custom_arg", custom_kwarg=1))
  449. In the event of an exception, ``with_transaction`` may retry the commit
  450. or the entire transaction, therefore ``callback`` may be invoked
  451. multiple times by a single call to ``with_transaction``. Developers
  452. should be mindful of this possiblity when writing a ``callback`` that
  453. modifies application state or has any other side-effects.
  454. Note that even when the ``callback`` is invoked multiple times,
  455. ``with_transaction`` ensures that the transaction will be committed
  456. at-most-once on the server.
  457. The ``callback`` should not attempt to start new transactions, but
  458. should simply run operations meant to be contained within a
  459. transaction. The ``callback`` should also not commit the transaction;
  460. this is handled automatically by ``with_transaction``. If the
  461. ``callback`` does commit or abort the transaction without error,
  462. however, ``with_transaction`` will return without taking further
  463. action.
  464. :class:`ClientSession` instances are **not thread-safe or fork-safe**.
  465. Consequently, the ``callback`` must not attempt to execute multiple
  466. operations concurrently.
  467. When ``callback`` raises an exception, ``with_transaction``
  468. automatically aborts the current transaction. When ``callback`` or
  469. :meth:`~ClientSession.commit_transaction` raises an exception that
  470. includes the ``"TransientTransactionError"`` error label,
  471. ``with_transaction`` starts a new transaction and re-executes
  472. the ``callback``.
  473. When :meth:`~ClientSession.commit_transaction` raises an exception with
  474. the ``"UnknownTransactionCommitResult"`` error label,
  475. ``with_transaction`` retries the commit until the result of the
  476. transaction is known.
  477. This method will cease retrying after 120 seconds has elapsed. This
  478. timeout is not configurable and any exception raised by the
  479. ``callback`` or by :meth:`ClientSession.commit_transaction` after the
  480. timeout is reached will be re-raised. Applications that desire a
  481. different timeout duration should not use this method.
  482. :Parameters:
  483. - `callback`: The callable ``callback`` to run inside a transaction.
  484. The callable must accept a single argument, this session. Note,
  485. under certain error conditions the callback may be run multiple
  486. times.
  487. - `read_concern` (optional): The
  488. :class:`~pymongo.read_concern.ReadConcern` to use for this
  489. transaction.
  490. - `write_concern` (optional): The
  491. :class:`~pymongo.write_concern.WriteConcern` to use for this
  492. transaction.
  493. - `read_preference` (optional): The read preference to use for this
  494. transaction. If ``None`` (the default) the :attr:`read_preference`
  495. of this :class:`Database` is used. See
  496. :mod:`~pymongo.read_preferences` for options.
  497. :Returns:
  498. The return value of the ``callback``.
  499. .. versionadded:: 3.9
  500. """
  501. start_time = monotonic.time()
  502. while True:
  503. self.start_transaction(
  504. read_concern, write_concern, read_preference,
  505. max_commit_time_ms)
  506. try:
  507. ret = callback(self)
  508. except Exception as exc:
  509. if self.in_transaction:
  510. self.abort_transaction()
  511. if (isinstance(exc, PyMongoError) and
  512. exc.has_error_label("TransientTransactionError") and
  513. _within_time_limit(start_time)):
  514. # Retry the entire transaction.
  515. continue
  516. raise
  517. if not self.in_transaction:
  518. # Assume callback intentionally ended the transaction.
  519. return ret
  520. while True:
  521. try:
  522. self.commit_transaction()
  523. except PyMongoError as exc:
  524. if (exc.has_error_label("UnknownTransactionCommitResult")
  525. and _within_time_limit(start_time)
  526. and not _max_time_expired_error(exc)):
  527. # Retry the commit.
  528. continue
  529. if (exc.has_error_label("TransientTransactionError") and
  530. _within_time_limit(start_time)):
  531. # Retry the entire transaction.
  532. break
  533. raise
  534. # Commit succeeded.
  535. return ret
  536. def start_transaction(self, read_concern=None, write_concern=None,
  537. read_preference=None, max_commit_time_ms=None):
  538. """Start a multi-statement transaction.
  539. Takes the same arguments as :class:`TransactionOptions`.
  540. .. versionchanged:: 3.9
  541. Added the ``max_commit_time_ms`` option.
  542. .. versionadded:: 3.7
  543. """
  544. self._check_ended()
  545. if self.options.snapshot:
  546. raise InvalidOperation("Transactions are not supported in "
  547. "snapshot sessions")
  548. if self.in_transaction:
  549. raise InvalidOperation("Transaction already in progress")
  550. read_concern = self._inherit_option("read_concern", read_concern)
  551. write_concern = self._inherit_option("write_concern", write_concern)
  552. read_preference = self._inherit_option(
  553. "read_preference", read_preference)
  554. if max_commit_time_ms is None:
  555. opts = self.options.default_transaction_options
  556. if opts:
  557. max_commit_time_ms = opts.max_commit_time_ms
  558. self._transaction.opts = TransactionOptions(
  559. read_concern, write_concern, read_preference, max_commit_time_ms)
  560. self._transaction.reset()
  561. self._transaction.state = _TxnState.STARTING
  562. self._start_retryable_write()
  563. return _TransactionContext(self)
  564. def commit_transaction(self):
  565. """Commit a multi-statement transaction.
  566. .. versionadded:: 3.7
  567. """
  568. self._check_ended()
  569. state = self._transaction.state
  570. if state is _TxnState.NONE:
  571. raise InvalidOperation("No transaction started")
  572. elif state in (_TxnState.STARTING, _TxnState.COMMITTED_EMPTY):
  573. # Server transaction was never started, no need to send a command.
  574. self._transaction.state = _TxnState.COMMITTED_EMPTY
  575. return
  576. elif state is _TxnState.ABORTED:
  577. raise InvalidOperation(
  578. "Cannot call commitTransaction after calling abortTransaction")
  579. elif state is _TxnState.COMMITTED:
  580. # We're explicitly retrying the commit, move the state back to
  581. # "in progress" so that in_transaction returns true.
  582. self._transaction.state = _TxnState.IN_PROGRESS
  583. try:
  584. self._finish_transaction_with_retry("commitTransaction")
  585. except ConnectionFailure as exc:
  586. # We do not know if the commit was successfully applied on the
  587. # server or if it satisfied the provided write concern, set the
  588. # unknown commit error label.
  589. exc._remove_error_label("TransientTransactionError")
  590. _reraise_with_unknown_commit(exc)
  591. except WTimeoutError as exc:
  592. # We do not know if the commit has satisfied the provided write
  593. # concern, add the unknown commit error label.
  594. _reraise_with_unknown_commit(exc)
  595. except OperationFailure as exc:
  596. if exc.code not in _UNKNOWN_COMMIT_ERROR_CODES:
  597. # The server reports errorLabels in the case.
  598. raise
  599. # We do not know if the commit was successfully applied on the
  600. # server or if it satisfied the provided write concern, set the
  601. # unknown commit error label.
  602. _reraise_with_unknown_commit(exc)
  603. finally:
  604. self._transaction.state = _TxnState.COMMITTED
  605. def abort_transaction(self):
  606. """Abort a multi-statement transaction.
  607. .. versionadded:: 3.7
  608. """
  609. self._check_ended()
  610. state = self._transaction.state
  611. if state is _TxnState.NONE:
  612. raise InvalidOperation("No transaction started")
  613. elif state is _TxnState.STARTING:
  614. # Server transaction was never started, no need to send a command.
  615. self._transaction.state = _TxnState.ABORTED
  616. return
  617. elif state is _TxnState.ABORTED:
  618. raise InvalidOperation("Cannot call abortTransaction twice")
  619. elif state in (_TxnState.COMMITTED, _TxnState.COMMITTED_EMPTY):
  620. raise InvalidOperation(
  621. "Cannot call abortTransaction after calling commitTransaction")
  622. try:
  623. self._finish_transaction_with_retry("abortTransaction")
  624. except (OperationFailure, ConnectionFailure):
  625. # The transactions spec says to ignore abortTransaction errors.
  626. pass
  627. finally:
  628. self._transaction.state = _TxnState.ABORTED
  629. self._unpin()
  630. def _finish_transaction_with_retry(self, command_name):
  631. """Run commit or abort with one retry after any retryable error.
  632. :Parameters:
  633. - `command_name`: Either "commitTransaction" or "abortTransaction".
  634. """
  635. def func(session, sock_info, retryable):
  636. return self._finish_transaction(sock_info, command_name)
  637. return self._client._retry_internal(True, func, self, None)
  638. def _finish_transaction(self, sock_info, command_name):
  639. self._transaction.attempt += 1
  640. opts = self._transaction.opts
  641. wc = opts.write_concern
  642. cmd = SON([(command_name, 1)])
  643. if command_name == "commitTransaction":
  644. if opts.max_commit_time_ms:
  645. cmd['maxTimeMS'] = opts.max_commit_time_ms
  646. # Transaction spec says that after the initial commit attempt,
  647. # subsequent commitTransaction commands should be upgraded to use
  648. # w:"majority" and set a default value of 10 seconds for wtimeout.
  649. if self._transaction.attempt > 1:
  650. wc_doc = wc.document
  651. wc_doc["w"] = "majority"
  652. wc_doc.setdefault("wtimeout", 10000)
  653. wc = WriteConcern(**wc_doc)
  654. if self._transaction.recovery_token:
  655. cmd['recoveryToken'] = self._transaction.recovery_token
  656. return self._client.admin._command(
  657. sock_info,
  658. cmd,
  659. session=self,
  660. write_concern=wc,
  661. parse_write_concern_error=True)
  662. def _advance_cluster_time(self, cluster_time):
  663. """Internal cluster time helper."""
  664. if self._cluster_time is None:
  665. self._cluster_time = cluster_time
  666. elif cluster_time is not None:
  667. if cluster_time["clusterTime"] > self._cluster_time["clusterTime"]:
  668. self._cluster_time = cluster_time
  669. def advance_cluster_time(self, cluster_time):
  670. """Update the cluster time for this session.
  671. :Parameters:
  672. - `cluster_time`: The
  673. :data:`~pymongo.client_session.ClientSession.cluster_time` from
  674. another `ClientSession` instance.
  675. """
  676. if not isinstance(cluster_time, abc.Mapping):
  677. raise TypeError(
  678. "cluster_time must be a subclass of collections.Mapping")
  679. if not isinstance(cluster_time.get("clusterTime"), Timestamp):
  680. raise ValueError("Invalid cluster_time")
  681. self._advance_cluster_time(cluster_time)
  682. def _advance_operation_time(self, operation_time):
  683. """Internal operation time helper."""
  684. if self._operation_time is None:
  685. self._operation_time = operation_time
  686. elif operation_time is not None:
  687. if operation_time > self._operation_time:
  688. self._operation_time = operation_time
  689. def advance_operation_time(self, operation_time):
  690. """Update the operation time for this session.
  691. :Parameters:
  692. - `operation_time`: The
  693. :data:`~pymongo.client_session.ClientSession.operation_time` from
  694. another `ClientSession` instance.
  695. """
  696. if not isinstance(operation_time, Timestamp):
  697. raise TypeError("operation_time must be an instance "
  698. "of bson.timestamp.Timestamp")
  699. self._advance_operation_time(operation_time)
  700. def _process_response(self, reply):
  701. """Process a response to a command that was run with this session."""
  702. self._advance_cluster_time(reply.get('$clusterTime'))
  703. self._advance_operation_time(reply.get('operationTime'))
  704. if self._options.snapshot and self._snapshot_time is None:
  705. if 'cursor' in reply:
  706. ct = reply['cursor'].get('atClusterTime')
  707. else:
  708. ct = reply.get('atClusterTime')
  709. self._snapshot_time = ct
  710. if self.in_transaction and self._transaction.sharded:
  711. recovery_token = reply.get('recoveryToken')
  712. if recovery_token:
  713. self._transaction.recovery_token = recovery_token
  714. @property
  715. def has_ended(self):
  716. """True if this session is finished."""
  717. return self._server_session is None
  718. @property
  719. def in_transaction(self):
  720. """True if this session has an active multi-statement transaction.
  721. .. versionadded:: 3.10
  722. """
  723. return self._transaction.active()
  724. @property
  725. def _starting_transaction(self):
  726. """True if this session is starting a multi-statement transaction.
  727. """
  728. return self._transaction.starting()
  729. @property
  730. def _pinned_address(self):
  731. """The mongos address this transaction was created on."""
  732. if self._transaction.active():
  733. return self._transaction.pinned_address
  734. return None
  735. @property
  736. def _pinned_connection(self):
  737. """The connection this transaction was started on."""
  738. return self._transaction.pinned_conn
  739. def _pin(self, server, sock_info):
  740. """Pin this session to the given Server or to the given connection."""
  741. self._transaction.pin(server, sock_info)
  742. def _unpin(self):
  743. """Unpin this session from any pinned Server."""
  744. self._transaction.unpin()
  745. def _txn_read_preference(self):
  746. """Return read preference of this transaction or None."""
  747. if self.in_transaction:
  748. return self._transaction.opts.read_preference
  749. return None
  750. def _apply_to(self, command, is_retryable, read_preference, sock_info):
  751. self._check_ended()
  752. if self.options.snapshot:
  753. self._update_read_concern(command, sock_info)
  754. self._server_session.last_use = monotonic.time()
  755. command['lsid'] = self._server_session.session_id
  756. if is_retryable:
  757. command['txnNumber'] = self._server_session.transaction_id
  758. return
  759. if self.in_transaction:
  760. if read_preference != ReadPreference.PRIMARY:
  761. raise InvalidOperation(
  762. 'read preference in a transaction must be primary, not: '
  763. '%r' % (read_preference,))
  764. if self._transaction.state == _TxnState.STARTING:
  765. # First command begins a new transaction.
  766. self._transaction.state = _TxnState.IN_PROGRESS
  767. command['startTransaction'] = True
  768. if self._transaction.opts.read_concern:
  769. rc = self._transaction.opts.read_concern.document
  770. if rc:
  771. command['readConcern'] = rc
  772. self._update_read_concern(command, sock_info)
  773. command['txnNumber'] = self._server_session.transaction_id
  774. command['autocommit'] = False
  775. def _start_retryable_write(self):
  776. self._check_ended()
  777. self._server_session.inc_transaction_id()
  778. def _update_read_concern(self, cmd, sock_info):
  779. if (self.options.causal_consistency
  780. and self.operation_time is not None):
  781. cmd.setdefault('readConcern', {})[
  782. 'afterClusterTime'] = self.operation_time
  783. if self.options.snapshot:
  784. if sock_info.max_wire_version < 13:
  785. raise ConfigurationError(
  786. 'Snapshot reads require MongoDB 5.0 or later')
  787. rc = cmd.setdefault('readConcern', {})
  788. rc['level'] = 'snapshot'
  789. if self._snapshot_time is not None:
  790. rc['atClusterTime'] = self._snapshot_time
  791. class _ServerSession(object):
  792. def __init__(self, generation):
  793. # Ensure id is type 4, regardless of CodecOptions.uuid_representation.
  794. self.session_id = {'id': Binary(uuid.uuid4().bytes, 4)}
  795. self.last_use = monotonic.time()
  796. self._transaction_id = 0
  797. self.dirty = False
  798. self.generation = generation
  799. def mark_dirty(self):
  800. """Mark this session as dirty.
  801. A server session is marked dirty when a command fails with a network
  802. error. Dirty sessions are later discarded from the server session pool.
  803. """
  804. self.dirty = True
  805. def timed_out(self, session_timeout_minutes):
  806. idle_seconds = monotonic.time() - self.last_use
  807. # Timed out if we have less than a minute to live.
  808. return idle_seconds > (session_timeout_minutes - 1) * 60
  809. @property
  810. def transaction_id(self):
  811. """Positive 64-bit integer."""
  812. return Int64(self._transaction_id)
  813. def inc_transaction_id(self):
  814. self._transaction_id += 1
  815. class _ServerSessionPool(collections.deque):
  816. """Pool of _ServerSession objects.
  817. This class is not thread-safe, access it while holding the Topology lock.
  818. """
  819. def __init__(self, *args, **kwargs):
  820. super(_ServerSessionPool, self).__init__(*args, **kwargs)
  821. self.generation = 0
  822. def reset(self):
  823. self.generation += 1
  824. self.clear()
  825. def pop_all(self):
  826. ids = []
  827. while self:
  828. ids.append(self.pop().session_id)
  829. return ids
  830. def get_server_session(self, session_timeout_minutes):
  831. # Although the Driver Sessions Spec says we only clear stale sessions
  832. # in return_server_session, PyMongo can't take a lock when returning
  833. # sessions from a __del__ method (like in Cursor.__die), so it can't
  834. # clear stale sessions there. In case many sessions were returned via
  835. # __del__, check for stale sessions here too.
  836. self._clear_stale(session_timeout_minutes)
  837. # The most recently used sessions are on the left.
  838. while self:
  839. s = self.popleft()
  840. if not s.timed_out(session_timeout_minutes):
  841. return s
  842. return _ServerSession(self.generation)
  843. def return_server_session(self, server_session, session_timeout_minutes):
  844. if session_timeout_minutes is not None:
  845. self._clear_stale(session_timeout_minutes)
  846. if server_session.timed_out(session_timeout_minutes):
  847. return
  848. self.return_server_session_no_lock(server_session)
  849. def return_server_session_no_lock(self, server_session):
  850. # Discard sessions from an old pool to avoid duplicate sessions in the
  851. # child process after a fork.
  852. if (server_session.generation == self.generation and
  853. not server_session.dirty):
  854. self.appendleft(server_session)
  855. def _clear_stale(self, session_timeout_minutes):
  856. # Clear stale sessions. The least recently used are on the right.
  857. while self:
  858. if self[-1].timed_out(session_timeout_minutes):
  859. self.pop()
  860. else:
  861. # The remaining sessions also haven't timed out.
  862. break