From ff5f1ce8a4495e01c4858bc2484f99e2cc022e52 Mon Sep 17 00:00:00 2001 From: Shane Harvey Date: Thu, 13 Dec 2018 12:04:03 -0800 Subject: [PATCH] PYTHON-1704 Close periodic task thread when client is closed (#389) --- pymongo/mongo_client.py | 11 +++++------ test/test_client.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/pymongo/mongo_client.py b/pymongo/mongo_client.py index 06bc14eca..866e24f72 100644 --- a/pymongo/mongo_client.py +++ b/pymongo/mongo_client.py @@ -1030,8 +1030,9 @@ class MongoClient(common.BaseObject): session_ids = self._topology.pop_all_sessions() if session_ids: self._end_sessions(session_ids) - # Run _process_periodic_tasks to send pending killCursor requests - # before closing the topology. + # Stop the periodic task thread and then run _process_periodic_tasks + # to send pending killCursor requests before closing the topology. + self._kill_cursors_executor.close() self._process_periodic_tasks() self._topology.close() @@ -1071,6 +1072,8 @@ class MongoClient(common.BaseObject): launches the connection process in the background. """ self._topology.open() + with self.__lock: + self._kill_cursors_executor.open() return self._topology @contextlib.contextmanager @@ -1136,10 +1139,6 @@ class MongoClient(common.BaseObject): - `address` (optional): Optional address when sending a message to a specific server, used for getMore. """ - with self.__lock: - # If needed, restart kill-cursors thread after a fork. - self._kill_cursors_executor.open() - topology = self._get_topology() if address: server = topology.select_server_by_address(address) diff --git a/test/test_client.py b/test/test_client.py index 60deae7b4..fed05facc 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -640,6 +640,23 @@ class TestClient(IntegrationTest): self.client._process_periodic_tasks() self.assertFalse(self.client._topology._opened) + def test_close_stops_kill_cursors_thread(self): + client = rs_client() + client.test.test.find_one() + self.assertFalse(client._kill_cursors_executor._stopped) + + # Closing the client should stop the thread. + client.close() + self.assertTrue(client._kill_cursors_executor._stopped) + + # Reusing the closed client should restart the thread. + client.admin.command('isMaster') + self.assertFalse(client._kill_cursors_executor._stopped) + + # Again, closing the client should stop the thread. + client.close() + self.assertTrue(client._kill_cursors_executor._stopped) + def test_bad_uri(self): with self.assertRaises(InvalidURI): MongoClient("http://localhost")