From 761acd6ad6da5775ce8171313810eaa3738d97c6 Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Wed, 9 Oct 2024 19:21:05 +0200 Subject: [PATCH] Recreate aiohttp session on connectivity check It seems to actually get a proper connectivity check run, we need a new vanilla ClientSession() object. --- supervisor/coresys.py | 18 +++++++++++++----- supervisor/supervisor.py | 2 ++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/supervisor/coresys.py b/supervisor/coresys.py index bc95df9cbb1..5a36df05cc2 100644 --- a/supervisor/coresys.py +++ b/supervisor/coresys.py @@ -63,7 +63,7 @@ def __init__(self): # External objects self._loop: asyncio.BaseEventLoop = asyncio.get_running_loop() - self._websession: aiohttp.ClientSession = aiohttp.ClientSession() + self._websession = None # Global objects self._config: CoreConfig = CoreConfig() @@ -96,10 +96,8 @@ def __init__(self): self._bus: Bus | None = None self._mounts: MountManager | None = None - # Set default header for aiohttp - self._websession._default_headers = MappingProxyType( - {aiohttp.hdrs.USER_AGENT: SERVER_SOFTWARE} - ) + # Setup aiohttp session + self.create_websession() # Task factory attributes self._set_task_context: list[Callable[[Context], Context]] = [] @@ -548,6 +546,16 @@ def run_in_executor( return self.loop.run_in_executor(None, funct, *args) + def create_websession(self) -> None: + """Create a new aiohttp session.""" + if self._websession: + self.create_task(self._websession.close()) + + # Create session and set default header for aiohttp + self._websession: aiohttp.ClientSession = aiohttp.ClientSession( + headers=MappingProxyType({aiohttp.hdrs.USER_AGENT: SERVER_SOFTWARE}) + ) + def _create_context(self) -> Context: """Create a new context for a task.""" context = copy_context() diff --git a/supervisor/supervisor.py b/supervisor/supervisor.py index 126cf739de8..082962930ce 100644 --- a/supervisor/supervisor.py +++ b/supervisor/supervisor.py @@ -274,6 +274,8 @@ async def check_connectivity(self): "https://checkonline.home-assistant.io/online.txt", timeout=timeout ) except (ClientError, TimeoutError): + # Need to recreate the websession to avoid stale connection checks + self.coresys.create_websession() self.connectivity = False else: self.connectivity = True