From 0ef66202e1e91cc6330d81980c3a78dc38676bb9 Mon Sep 17 00:00:00 2001 From: Ingmar Steen Date: Fri, 30 Sep 2022 17:28:17 +0200 Subject: [PATCH 1/2] Close connection when _fill_free_pool is cancelled. Cancelling _fill_free_pool before a new connection is added to self._free prevents it from being cleaned up which causes a lingering connection and eventually the postgresql server running out of sockets. --- aiopg/pool.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/aiopg/pool.py b/aiopg/pool.py index 4d6015c6..9d0cf5e7 100644 --- a/aiopg/pool.py +++ b/aiopg/pool.py @@ -347,6 +347,9 @@ async def _fill_free_pool(self, override_min: bool) -> None: # raise exception if pool is closing self._free.append(conn) self._cond.notify() + except asyncio.CancelledError: + conn.close() + raise finally: self._acquiring -= 1 if self._free: @@ -369,6 +372,9 @@ async def _fill_free_pool(self, override_min: bool) -> None: # raise exception if pool is closing self._free.append(conn) self._cond.notify() + except asyncio.CancelledError: + conn.close() + raise finally: self._acquiring -= 1 From 1f39c7c36b0e8376f6d55f4c14f12352dec9b6c3 Mon Sep 17 00:00:00 2001 From: Ingmar Steen Date: Fri, 30 Sep 2022 17:35:45 +0200 Subject: [PATCH 2/2] Guard against the unlikely event conn will not be set. --- aiopg/pool.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/aiopg/pool.py b/aiopg/pool.py index 9d0cf5e7..1b6e58c0 100644 --- a/aiopg/pool.py +++ b/aiopg/pool.py @@ -332,6 +332,7 @@ async def _fill_free_pool(self, override_min: bool) -> None: while self.size < self.minsize: self._acquiring += 1 + conn = None try: conn = await connect( self._dsn, @@ -348,7 +349,8 @@ async def _fill_free_pool(self, override_min: bool) -> None: self._free.append(conn) self._cond.notify() except asyncio.CancelledError: - conn.close() + if conn is not None: + conn.close() raise finally: self._acquiring -= 1 @@ -357,6 +359,7 @@ async def _fill_free_pool(self, override_min: bool) -> None: if override_min and (not self.maxsize or self.size < self.maxsize): self._acquiring += 1 + conn = None try: conn = await connect( self._dsn, @@ -373,7 +376,8 @@ async def _fill_free_pool(self, override_min: bool) -> None: self._free.append(conn) self._cond.notify() except asyncio.CancelledError: - conn.close() + if conn is not None: + conn.close() raise finally: self._acquiring -= 1