alexa_media_player: Possible Solution for HTTP2 blocking operation
Describe the bug
A blocking operation was detected in the http2_connect() function in the alexa_media integration. Specifically, the function load_verify_locations was being called inside the event loop, which caused performance issues and blocked other tasks.
To Reproduce
- Integrate the Alexa Media Player into Home Assistant.
- Reboot.
- Watch for the warning message related to blocking calls in the logs.
Expected behavior
The http2_connect() function should complete without blocking the event loop, allowing the system to handle multiple tasks concurrently without performance issues.
System details
- Home Assistant version: Core: 2024.9.1 Frontend: 20240906.0
- alexa_media version: 4.12.12
- alexapy version: 1.29.2
- Is Amazon 2FA/2SV enabled (y/n): y
- Amazon Domain: amazon.de
Debug Logs (alexa_media & alexapy)
Please refer to the following error message from the debug logs:
Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7fcbde43ca50>,) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/__init__.py, line 876: http2 = HTTP2EchoClient(
(offender: /usr/local/lib/python3.12/site-packages/httpx/_config.py, line 147: context.load_verify_locations(cafile=cafile))
Additional context
I was able to fix the issue by modifying the http2_connect() function to offload the SSL initialization to a separate thread using hass.async_add_executor_job. Here is the change that fixed the issue:
The Problem:
In Home Assistant, the Alexa Media integration was causing performance issues due to the SSL certificate loading (load_verify_locations) being called inside the event loop. This caused the event loop to block, slowing down the system.
The Solution:
I adjusted the code to ensure that the SSL certificate loading happens in a separate thread, outside the event loop, allowing the system to run smoothly.
Code Changes:
- Offloaded the Blocking Operation: I added the following line to move the SSL initialization into a separate thread using
hass.async_add_executor_job:
await hass.async_add_executor_job(
login_obj.session.context.load_verify_locations, cafile=cafile
)
- Retained the HTTP2 Client Creation: After offloading the SSL operation, the rest of the code for creating and running
HTTP2EchoClientremains unchanged.
Here is the full function after the change:
async def http2_connect() -> Optional[HTTP2EchoClient]:
"""Open HTTP2 Push connection.
This will only attempt one login before failing.
"""
http2: Optional[HTTP2EchoClient] = None
email = login_obj.email
try:
if login_obj.session.closed:
_LOGGER.debug(
"%s: HTTP2 creation aborted. Session is closed.",
hide_email(email),
)
return
# Offloading SSL initialization to a separate thread
await hass.async_add_executor_job(
login_obj.session.context.load_verify_locations, cafile=cafile
)
# Create HTTP2EchoClient
http2 = HTTP2EchoClient(
login_obj,
msg_callback=http2_handler,
open_callback=http2_open_handler,
close_callback=http2_close_handler,
error_callback=http2_error_handler,
loop=hass.loop,
)
_LOGGER.debug("%s: HTTP2 created: %s", hide_email(email), http2)
# Start HTTP2 connection
await http2.async_run()
except AlexapyLoginError as exception_:
_LOGGER.debug(
"%s: Login Error detected from http2: %s",
hide_email(email),
exception_,
)
hass.bus.async_fire(
"alexa_media_relogin_required",
event_data={"email": hide_email(email), "url": login_obj.url},
)
return
except BaseException as exception_: # pylint: disable=broad-except
_LOGGER.debug(
"%s: HTTP2 creation failed: %s", hide_email(email), exception_
)
return
return http2
Since making this change, the warning is no longer appearing.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 5
- Comments: 52 (15 by maintainers)
Yes but I think his basic code is many years old now and I do not know when HA’s util.ssl was added.
I can confirm that making the above change to
__init__.pyhas eliminated one of my 5 warnings:This one is now resolved:
One of my remaining 4 is from custom integration ‘smartthinq_sensors’:
Detected blocking call to load_default_certs with args (<ssl.SSLContext object at 0xffff62e1f050>. I just found a PR that fixes it: Using get_default_context() for ssl context to avoid blocking call #791 I made the code change and that warning is gone:I applied the smartthinq_sensors change to alexalogin.py and resolved another warning.
…
I also made a change in
alexalogin.pyasync def load_cookieusingasyncio.run_coroutine_threadsafe()to executelocalfile.write(cookies_txt):I’m now down to two warnings:
@jamesonuk When I tried it, it became obvious that there cannot be HA dependencies in it. The merge request processing could not find
from homeassistant.util import sslin its build environment.In another github post (I can’t find it now), @bdraco recommended changing ssl.create_default_context as a top level import as those occur at load time in the executor loop. I’ve tried it and it works for me so I have submitted
alexapymerge request !395I installed your
Followed by
alexalogin.pyand yes, it resolves the load verify_locations blocking call but AMP initialization now takes forever but finally does load but I see new errors in HA logs.Failed: login_obj is not definedand then initializing again at which point it loads and is working albeit after the HA startup event has fired and triggered my startup automation, which cannot speak…I left the config entry in place, restored
__init__.py, restarted and the config entry from the failed attempt then initialized correctly.I will try both files a little later…
@danielbrunt57
I have found another issue: The HTTP/2 connection status isn’t updated properly. I asked ChatGPT to write the following:
Here’s an improved version of the response, incorporating your feedback about the importance of jitter handling and focusing more on points 1 and 2:
Issues and Solutions Related to the HTTP/2 Connection in
__init__.pyAfter analyzing the
__init__.pyfile, I’ve identified key problems that explain why the HTTP/2 connection status isn’t updated properly and why it fails to reopen. Here’s a breakdown:1. HTTP/2 Connection Status Not Updating Properly
When the HTTP/2 connection closes, the status in Home Assistant is set to
None:This causes the
should_pollproperty to returnTrue, indicating that polling should be enabled, as the system is no longer using an HTTP/2 push connection:However, if the connection is not properly reopened, the
http2value remainsNone, causing persistent polling, which isn’t ideal for real-time updates like Alexa reminders.2. Reconnection Fails Due to Incomplete Error Handling
The logic to reopen the HTTP/2 connection after it closes is handled by the
http2_close_handler(), which attempts to reconnect up to five times:Problem 1: If the reconnection attempts fail, the connection may not be properly reestablished, leaving
http2asNoneindefinitely.Problem 2: The status of the HTTP/2 connection (
http2_enabled) is not updated reliably if the connection fails, preventing the system from properly detecting whether the connection was reestablished.3. Lack of Jitter in Retry Logic
A critical issue is the lack of jitter in the retry logic for reconnecting. The current reconnection logic uses exponential backoff:
While exponential backoff is useful, adding jitter (randomness) to the retry delay would prevent potential “thundering herd” problems, where multiple clients attempt to reconnect simultaneously, leading to network congestion or API rate limits.
Recommendations:
Improve the Reconnection Logic:
Expand Error and Success Logs:
Polling as a Temporary Fallback:
@danielbrunt57
I now solved this problem (hopefully) without a new
homeassistant.util import ssland keep everything compatible to the same time.Please test my (non-HA-exclusive)
alexalogin.pyversion: alexalogin.zipAnd this is your
__init__.py- but with additional logging (see above). init.zipThis is the only warning I get for alexa* (huge list of almost all integrations, but without any details):
Confirmed that I do need the ssl change in alexalogin.py to eliminate the error in addition to offloading the HTTP2EchoClient.
I will try that.
In the meantime, I just tried offloading the entire HTTP2EchoClient and it worked. This currently is in addition to the ssl change I made in alexalogin.py, which I will try without changing it (alexalogin.py). I have no warnings and HHTP2 is connected.
What’s your take on this approach??
You mean cookiejar.py? https://github.com/alandtse/alexa_media_player/issues/2520
I just now successfully eliminated the last two warnings!!! I’ve been chasing the wrong code for I don’t know how many hours now!
This fixes them… Change (~line 380)
to:
and ~line 735:
to:
I tried all possible workarounds here, but only the HTTP2 blocking warning disappeared.
init.py.txt
Here are the relevant libraries and modules responsible for the reported blocking call error:
aiohttp:aiohttptriggers blocking operations during SSL connection initialization, particularly when loading certificates withload_verify_locations.ssl(part of the Python standard library):load_verify_locationsfunction in thessllibrary is responsible for loading certificate files. This operation is blocking and is internally called byaiohttpto verify SSL connections.certifi:aiohttpto specify the path to SSL certificates, which can lead to blocking operations.AlexaLogin(from thealexapylibrary):AlexaLoginobject and its login function indirectly cause blocking SSL calls, as they rely onaiohttpsessions.alexapy:aiohttpfor HTTP requests, which can trigger blocking SSL initialization.Summary of Responsible Libraries:
load_verify_locations).ssl.alexapy) – Indirectly responsible as it utilizesaiohttp.Primary Cause:
aiohttpand thessllibrary, specifically the call toload_verify_locationsduring SSL initialization.I just did a little bit of digging and I think the root cause is https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexalogin.py#L100 it should probably be addressed there (probably having an SSL context created and reused here)