|
| 1 | +# Copyright 2021-present 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 | + |
| 15 | +"""Test the Load Balancer unified spec tests.""" |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import asyncio |
| 19 | +import gc |
| 20 | +import os |
| 21 | +import pathlib |
| 22 | +import sys |
| 23 | +import threading |
| 24 | +from asyncio import Event |
| 25 | +from test.asynchronous.helpers import ConcurrentRunner, ExceptionCatchingTask |
| 26 | + |
| 27 | +import pytest |
| 28 | + |
| 29 | +sys.path[0:0] = [""] |
| 30 | + |
| 31 | +from test.asynchronous import AsyncIntegrationTest, async_client_context, unittest |
| 32 | +from test.asynchronous.unified_format import generate_test_classes |
| 33 | +from test.utils import ( |
| 34 | + async_get_pool, |
| 35 | + async_wait_until, |
| 36 | + create_async_event, |
| 37 | +) |
| 38 | + |
| 39 | +from pymongo.asynchronous.helpers import anext |
| 40 | + |
| 41 | +_IS_SYNC = False |
| 42 | + |
| 43 | +pytestmark = pytest.mark.load_balancer |
| 44 | + |
| 45 | +# Location of JSON test specifications. |
| 46 | +if _IS_SYNC: |
| 47 | + _TEST_PATH = os.path.join(pathlib.Path(__file__).resolve().parent, "load_balancer") |
| 48 | +else: |
| 49 | + _TEST_PATH = os.path.join(pathlib.Path(__file__).resolve().parent.parent, "load_balancer") |
| 50 | + |
| 51 | +# Generate unified tests. |
| 52 | +globals().update(generate_test_classes(_TEST_PATH, module=__name__)) |
| 53 | + |
| 54 | + |
| 55 | +class TestLB(AsyncIntegrationTest): |
| 56 | + RUN_ON_LOAD_BALANCER = True |
| 57 | + RUN_ON_SERVERLESS = True |
| 58 | + |
| 59 | + async def test_connections_are_only_returned_once(self): |
| 60 | + if "PyPy" in sys.version: |
| 61 | + # Tracked in PYTHON-3011 |
| 62 | + self.skipTest("Test is flaky on PyPy") |
| 63 | + pool = await async_get_pool(self.client) |
| 64 | + n_conns = len(pool.conns) |
| 65 | + await self.db.test.find_one({}) |
| 66 | + self.assertEqual(len(pool.conns), n_conns) |
| 67 | + await (await self.db.test.aggregate([{"$limit": 1}])).to_list() |
| 68 | + self.assertEqual(len(pool.conns), n_conns) |
| 69 | + |
| 70 | + @async_client_context.require_load_balancer |
| 71 | + async def test_unpin_committed_transaction(self): |
| 72 | + client = await self.async_rs_client() |
| 73 | + pool = await async_get_pool(client) |
| 74 | + coll = client[self.db.name].test |
| 75 | + async with client.start_session() as session: |
| 76 | + async with await session.start_transaction(): |
| 77 | + self.assertEqual(pool.active_sockets, 0) |
| 78 | + await coll.insert_one({}, session=session) |
| 79 | + self.assertEqual(pool.active_sockets, 1) # Pinned. |
| 80 | + self.assertEqual(pool.active_sockets, 1) # Still pinned. |
| 81 | + self.assertEqual(pool.active_sockets, 0) # Unpinned. |
| 82 | + |
| 83 | + @async_client_context.require_failCommand_fail_point |
| 84 | + async def test_cursor_gc(self): |
| 85 | + async def create_resource(coll): |
| 86 | + cursor = coll.find({}, batch_size=3) |
| 87 | + await anext(cursor) |
| 88 | + return cursor |
| 89 | + |
| 90 | + await self._test_no_gc_deadlock(create_resource) |
| 91 | + |
| 92 | + @async_client_context.require_failCommand_fail_point |
| 93 | + async def test_command_cursor_gc(self): |
| 94 | + async def create_resource(coll): |
| 95 | + cursor = await coll.aggregate([], batchSize=3) |
| 96 | + await anext(cursor) |
| 97 | + return cursor |
| 98 | + |
| 99 | + await self._test_no_gc_deadlock(create_resource) |
| 100 | + |
| 101 | + async def _test_no_gc_deadlock(self, create_resource): |
| 102 | + client = await self.async_rs_client() |
| 103 | + pool = await async_get_pool(client) |
| 104 | + coll = client[self.db.name].test |
| 105 | + await coll.insert_many([{} for _ in range(10)]) |
| 106 | + self.assertEqual(pool.active_sockets, 0) |
| 107 | + # Cause the initial find attempt to fail to induce a reference cycle. |
| 108 | + args = { |
| 109 | + "mode": {"times": 1}, |
| 110 | + "data": { |
| 111 | + "failCommands": ["find", "aggregate"], |
| 112 | + "closeConnection": True, |
| 113 | + }, |
| 114 | + } |
| 115 | + async with self.fail_point(args): |
| 116 | + resource = await create_resource(coll) |
| 117 | + if async_client_context.load_balancer: |
| 118 | + self.assertEqual(pool.active_sockets, 1) # Pinned. |
| 119 | + |
| 120 | + task = PoolLocker(pool) |
| 121 | + await task.start() |
| 122 | + self.assertTrue(await task.wait(task.locked, 5), "timed out") |
| 123 | + # Garbage collect the resource while the pool is locked to ensure we |
| 124 | + # don't deadlock. |
| 125 | + del resource |
| 126 | + # On PyPy it can take a few rounds to collect the cursor. |
| 127 | + for _ in range(3): |
| 128 | + gc.collect() |
| 129 | + task.unlock.set() |
| 130 | + await task.join(5) |
| 131 | + self.assertFalse(task.is_alive()) |
| 132 | + self.assertIsNone(task.exc) |
| 133 | + |
| 134 | + await async_wait_until(lambda: pool.active_sockets == 0, "return socket") |
| 135 | + # Run another operation to ensure the socket still works. |
| 136 | + await coll.delete_many({}) |
| 137 | + |
| 138 | + @async_client_context.require_transactions |
| 139 | + async def test_session_gc(self): |
| 140 | + client = await self.async_rs_client() |
| 141 | + pool = await async_get_pool(client) |
| 142 | + session = client.start_session() |
| 143 | + await session.start_transaction() |
| 144 | + await client.test_session_gc.test.find_one({}, session=session) |
| 145 | + # Cleanup the transaction left open on the server unless we're |
| 146 | + # testing serverless which does not support killSessions. |
| 147 | + if not async_client_context.serverless: |
| 148 | + self.addAsyncCleanup(self.client.admin.command, "killSessions", [session.session_id]) |
| 149 | + if async_client_context.load_balancer: |
| 150 | + self.assertEqual(pool.active_sockets, 1) # Pinned. |
| 151 | + |
| 152 | + task = PoolLocker(pool) |
| 153 | + await task.start() |
| 154 | + self.assertTrue(await task.wait(task.locked, 5), "timed out") |
| 155 | + # Garbage collect the session while the pool is locked to ensure we |
| 156 | + # don't deadlock. |
| 157 | + del session |
| 158 | + # On PyPy it can take a few rounds to collect the session. |
| 159 | + for _ in range(3): |
| 160 | + gc.collect() |
| 161 | + task.unlock.set() |
| 162 | + await task.join(5) |
| 163 | + self.assertFalse(task.is_alive()) |
| 164 | + self.assertIsNone(task.exc) |
| 165 | + |
| 166 | + await async_wait_until(lambda: pool.active_sockets == 0, "return socket") |
| 167 | + # Run another operation to ensure the socket still works. |
| 168 | + await client[self.db.name].test.delete_many({}) |
| 169 | + |
| 170 | + |
| 171 | +class PoolLocker(ExceptionCatchingTask): |
| 172 | + def __init__(self, pool): |
| 173 | + super().__init__(target=self.lock_pool) |
| 174 | + self.pool = pool |
| 175 | + self.daemon = True |
| 176 | + self.locked = create_async_event() |
| 177 | + self.unlock = create_async_event() |
| 178 | + |
| 179 | + async def lock_pool(self): |
| 180 | + async with self.pool.lock: |
| 181 | + self.locked.set() |
| 182 | + # Wait for the unlock flag. |
| 183 | + unlock_pool = await self.wait(self.unlock, 10) |
| 184 | + if not unlock_pool: |
| 185 | + raise Exception("timed out waiting for unlock signal: deadlock?") |
| 186 | + |
| 187 | + async def wait(self, event: Event, timeout: int): |
| 188 | + if _IS_SYNC: |
| 189 | + return event.wait(timeout) # type: ignore[call-arg] |
| 190 | + else: |
| 191 | + try: |
| 192 | + await asyncio.wait_for(event.wait(), timeout=timeout) |
| 193 | + except asyncio.TimeoutError: |
| 194 | + return False |
| 195 | + return True |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + unittest.main() |
0 commit comments