Call abort() on sockets after close() to prevent dangling sockets (#2231)

This commit is contained in:
Ashley Sommer 2021-09-01 15:14:11 +10:00 committed by GitHub
parent 69c5dde9bf
commit ef4f058a6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 3 deletions

View File

@ -81,13 +81,24 @@ class SanicProtocol(asyncio.Protocol):
self._data_received.clear() self._data_received.clear()
await self._data_received.wait() await self._data_received.wait()
def close(self): def close(self, timeout: Optional[float] = None):
"""
Attempt close the connection.
"""
# Cause a call to connection_lost where further cleanup occurs
if self.transport:
self.transport.close()
if timeout is None:
timeout = self.app.config.GRACEFUL_SHUTDOWN_TIMEOUT
self.loop.call_later(timeout, self.abort)
def abort(self):
""" """
Force close the connection. Force close the connection.
""" """
# Cause a call to connection_lost where further cleanup occurs # Cause a call to connection_lost where further cleanup occurs
if self.transport: if self.transport:
self.transport.close() self.transport.abort()
self.transport = None self.transport = None
# asyncio.Protocol API Callbacks # # asyncio.Protocol API Callbacks #

View File

@ -180,7 +180,7 @@ def serve(
if hasattr(conn, "websocket") and conn.websocket: if hasattr(conn, "websocket") and conn.websocket:
coros.append(conn.websocket.close_connection()) coros.append(conn.websocket.close_connection())
else: else:
conn.close() conn.abort()
_shutdown = asyncio.gather(*coros) _shutdown = asyncio.gather(*coros)
loop.run_until_complete(_shutdown) loop.run_until_complete(_shutdown)