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

  1. Integrate the Alexa Media Player into Home Assistant.
  2. Reboot.
  3. 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:

  1. 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
)
  1. Retained the HTTP2 Client Creation: After offloading the SSL operation, the rest of the code for creating and running HTTP2EchoClient remains 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)

Most upvoted comments

Based on Alen’s documentation, Alexapy was “was originally designed for alexa_media_player”. However, I think this also implies that its approach has since evolved to be more general and applicable beyond just Home Assistant.

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__.py has eliminated one of my 5 warnings:

Logger: homeassistant.util.loop
Source: util/loop.py:136
First occurred: 10:41:41 PM (5 occurrences)
Last logged: 10:41:51 PM

This one is now resolved:

Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0xffff322c5750>,) 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)), please create a bug report

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:

Detected blocking call to load_default_certs with args (<ssl.SSLContext object at 0xffff48ce1ed0>, <Purpose.SERVER_AUTH: _ASN1Object(nid=129, shortname=‘serverAuth’, longname=‘TLS Web Server Authentication’, oid=‘1.3.6.1.5.5.7.3.1’)>) inside the event loop by custom integration ‘smartthinq_sensors’ at custom_components/smartthinq_sensors/wideq/core_async.py, line 149: context = ssl.create_default_context() (offender: /usr/local/lib/python3.12/ssl.py, line 713: context.load_default_certs(purpose)), please create a bug report

I applied the smartthinq_sensors change to alexalogin.py and resolved another warning.

"""Python Package for controlling Alexa devices (echo dot, etc) programmatically.

SPDX-License-Identifier: Apache-2.0

Login class.

This file could not have been written without referencing MIT code from https://github.com/Apollon77/alexa-remote.

For more details about this api, please refer to the documentation at
https://gitlab.com/keatontaylor/alexapy
"""

import asyncio
import base64
from binascii import Error
import datetime
import hashlib
from homeassistant.util.ssl import get_default_context
from http.cookies import Morsel, SimpleCookie

…

    def __init__(
        self,
        url: str,
        email: str,
        password: str,
        outputpath: Callable[[str], str],
        debug: bool = False,
        otp_secret: str = "",
        oauth: Optional[dict[Any, Any]] = None,
        uuid: Optional[str] = None,
        oauth_login: bool = True,
    ) -> None:
        # pylint: disable=too-many-arguments,import-outside-toplevel
        """Set up initial connection and log in."""
#        import ssl

#        import certifi

        oauth = oauth or {}
        self._hass_domain: str = "alexa_media"
        self._prefix: str = "https://alexa."
        self._url: str = url
        self._email: str = email
        self._password: str = password
        self._session: Optional[aiohttp.ClientSession] = None
        self._ssl = get_default_context()
#        self._ssl = ssl.create_default_context(
#            purpose=ssl.Purpose.SERVER_AUTH, cafile=certifi.where()
#        )
        self._headers: dict[str, str] = {}

I also made a change in alexalogin.py async def load_cookie using asyncio.run_coroutine_threadsafe() to execute localfile.write(cookies_txt):

    async def load_cookie(self, cookies_txt: str = "") -> Optional[dict[str, str]]:
        # pylint: disable=import-outside-toplevel
        """Load cookie from disk."""
        from collections import defaultdict
        import http.cookiejar

        from requests.cookies import RequestsCookieJar

        cookies: Optional[
            Union[RequestsCookieJar, http.cookiejar.MozillaCookieJar]
        ] = None
        return_cookies = {}
        numcookies: int = 0
        loaded: bool = False
        if self._cookiefile:
            if cookies_txt:
                _LOGGER.debug(
                    "Saving passed in cookie to %s\n%s",
                    self._cookiefile[0],
                    repr(cookies_txt),
                )
                async with aiofiles.open(self._cookiefile[0], mode="w") as localfile:
                    try:
                        asyncio.run_coroutine_threadsafe(localfile.write(cookies_txt), loop)
                    except (OSError, EOFError, TypeError, AttributeError) as ex:
                        _LOGGER.debug(
                            "Error saving passed in cookie to %s: %s",
                            self._cookiefile[0],
                            EXCEPTION_TEMPLATE.format(type(ex).__name__, ex.args),
                        )

I’m now down to two warnings:

Logger: homeassistant.util.loop
Source: util/loop.py:136
First occurred: 7:09:08 PM (2 occurrences)
Last logged: 7:09:11 PM

Detected blocking call to open with args (PosixPath('/config/.storage/alexa_media.daniel@brunt.ca.pickle'),) 
inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/__init__.py, 
line 372: await login.login(cookies=await login.load_cookie()) 
(offender: /usr/local/lib/python3.12/site-packages/aiohttp/cookiejar.py, 
line 118: with file_path.open(mode="rb") as f:), 
please create a bug report at https://github.com/alandtse/alexa_media_player/issues 
For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#open 

Traceback (most recent call last): File "<frozen runpy>", 
line 198, in _run_module_as_main File "<frozen runpy>", 
line 88, in _run_code File "/usr/src/homeassistant/homeassistant/__main__.py", 
line 223, in <module> sys.exit(main()) File "/usr/src/homeassistant/homeassistant/__main__.py", 
line 209, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", 
line 189, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.12/asyncio/base_events.py", 
line 674, in run_until_complete self.run_forever() File "/usr/local/lib/python3.12/asyncio/base_events.py", 
line 641, in run_forever self._run_once() File "/usr/local/lib/python3.12/asyncio/base_events.py", 
line 1990, in _run_once handle._run() File "/usr/local/lib/python3.12/asyncio/events.py", 
line 88, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/config_entries.py", 
line 752, in async_setup_locked await self.async_setup(hass, integration=integration) File "/usr/src/homeassistant/homeassistant/config_entries.py",
 line 604, in async_setup result = await component.async_setup_entry(hass, self) File "/config/custom_components/alexa_media/__init__.py", 
line 372, in async_setup_entry await login.login(cookies=await login.load_cookie())
Detected blocking call to open with args (PosixPath('/config/.storage/alexa_media.daniel@brunt.ca.pickle'),) 
inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/__init__.py, 
line 372: await login.login(cookies=await login.load_cookie()) 
(offender: /usr/local/lib/python3.12/site-packages/aiohttp/cookiejar.py, 
line 113: with file_path.open(mode="wb") as f:), 
please create a bug report at https://github.com/alandtse/alexa_media_player/issues 
For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#open 

Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", 
line 88, in _run_code File "/usr/src/homeassistant/homeassistant/__main__.py", 
line 223, in <module> sys.exit(main()) File "/usr/src/homeassistant/homeassistant/__main__.py", 
line 209, in main exit_code = runner.run(runtime_conf) File "/usr/src/homeassistant/homeassistant/runner.py", 
line 189, in run return loop.run_until_complete(setup_and_run_hass(runtime_config)) File "/usr/local/lib/python3.12/asyncio/base_events.py", 
line 674, in run_until_complete self.run_forever() File "/usr/local/lib/python3.12/asyncio/base_events.py", 
line 641, in run_forever self._run_once() File "/usr/local/lib/python3.12/asyncio/base_events.py", 
line 1990, in _run_once handle._run() File "/usr/local/lib/python3.12/asyncio/events.py", 
line 88, in _run self._context.run(self._callback, *self._args) File "/usr/src/homeassistant/homeassistant/config_entries.py", 
line 752, in async_setup_locked await self.async_setup(hass, integration=integration) File "/usr/src/homeassistant/homeassistant/config_entries.py", 
line 604, in async_setup result = await component.async_setup_entry(hass, self) File "/config/custom_components/alexa_media/__init__.py", 
line 372, in async_setup_entry await login.login(cookies=await login.load_cookie())

Remember alexpy is not necessarily just HA so there shouldn’t really be an HA dependencies in there.

@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 ssl in 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 alexapy merge request !395

I installed your alexalogin.py and 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. image Followed by Failed: login_obj is not defined and 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__.py

After analyzing the __init__.py file, 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:

hass.data[DATA_ALEXAMEDIA]["accounts"][email]["http2"] = None

This causes the should_poll property to return True, indicating that polling should be enabled, as the system is no longer using an HTTP/2 push connection:

@property
def should_poll(self):
    return not (self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._account]["http2"])

However, if the connection is not properly reopened, the http2 value remains None, 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:

while errors < 5 and not (http2_enabled):
    _LOGGER.debug(
        "%s: HTTP2 push closed; reconnect #%i in %is",
        hide_email(email),
        errors,
        delay,
    )
    http2_enabled = hass.data[DATA_ALEXAMEDIA]["accounts"][email]["http2"] = (
        await http2_connect()
    )
    errors = hass.data[DATA_ALEXAMEDIA]["accounts"][email]["http2error"] = (
        hass.data[DATA_ALEXAMEDIA]["accounts"][email]["http2error"] + 1
    )
    delay = 5 * 2**errors
    await asyncio.sleep(delay)
  • Problem 1: If the reconnection attempts fail, the connection may not be properly reestablished, leaving http2 as None indefinitely.

  • 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:

delay = 5 * 2**errors
await asyncio.sleep(delay)

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:

  1. Improve the Reconnection Logic:

    • Add jitter to the retry logic to avoid simultaneous reconnection attempts by multiple clients, which could lead to rate-limiting or connection failures. For example, instead of a fixed delay, you can use a random factor:
    import random
    delay = 5 * 2**errors + random.uniform(0, 1)
    await asyncio.sleep(delay)
    
    • Reduce the maximum delay in the exponential backoff to ensure faster retries when the connection fails repeatedly.
  2. Expand Error and Success Logs:

    • Add detailed logging for each reconnection attempt, including whether it was successful. This will help in tracking when the connection is lost and when it’s reestablished. For example:
    if http2_enabled:
        _LOGGER.info("HTTP2 reconnected successfully for %s", hide_email(email))
    else:
        _LOGGER.error("HTTP2 reconnection failed for %s on attempt #%i", hide_email(email), errors)
    
  3. Polling as a Temporary Fallback:

    • While polling can act as a temporary fallback mechanism when HTTP/2 fails, it’s more important to ensure that HTTP/2 reconnects reliably. Relying solely on polling would lead to slower updates and higher resource usage, which is why jitter and more robust reconnection attempts are critical.

@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.py version: alexalogin.zip

And this is your __init__.py - but with additional logging (see above). init.zip

This is the only warning I get for alexa* (huge list of almost all integrations, but without any details): image

Confirmed that I do need the ssl change in alexalogin.py to eliminate the error in addition to offloading the HTTP2EchoClient.

        """Set up initial connection and log in."""
#        import ssl
        from homeassistant.util import ssl

        import certifi

        oauth = oauth or {}
        self._hass_domain: str = "alexa_media"
        self._prefix: str = "https://alexa."
        self._url: str = url
        self._email: str = email
        self._password: str = password
        self._session: Optional[aiohttp.ClientSession] = None
#        self._ssl = ssl.create_default_context(
#            purpose=ssl.Purpose.SERVER_AUTH, cafile=certifi.where()
#        )
        self._ssl = ssl.get_default_context()

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.

# Offloading SSL initialization to a separate thread
#            await hass.async_add_executor_job(
#                login_obj.session.context.load_verify_locations, cafile=cafile
#            )
            msg_callback=http2_handler,
            open_callback=http2_open_handler
            close_callback=http2_close_handler
            error_callback=http2_error_handler
            loop=hass.loop
            http2 = await hass.async_add_executor_job(
                HTTP2EchoClient,
                login_obj,
                msg_callback,
                open_callback,
                close_callback,
                error_callback,
                loop,
            )               

            # 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,
#            )

What’s your take on this approach??

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)

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)

                        cookie_jar.load(cookiefile)

to:

                        await self.async_add_executor_job(
                            cookie_jar.load, cookiefile
                        )

and ~line 735:

                    cookie_jar.save(self._cookiefile[0])

to:

                    await self.async_add_executor_job(
                        cookie_jar.save, self._cookiefile[0]
                    )

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)

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:

  1. aiohttp:

    • Used for HTTP requests and session management.
    • Cause: The SSL handling within aiohttp triggers blocking operations during SSL connection initialization, particularly when loading certificates with load_verify_locations.
  2. ssl (part of the Python standard library):

    • Cause: The load_verify_locations function in the ssl library is responsible for loading certificate files. This operation is blocking and is internally called by aiohttp to verify SSL connections.
  3. certifi:

    • Provides certificate files.
    • Cause: This library is used by aiohttp to specify the path to SSL certificates, which can lead to blocking operations.
  4. AlexaLogin (from the alexapy library):

    • Used for authentication with Amazon Alexa.
    • Cause: The instantiation of the AlexaLogin object and its login function indirectly cause blocking SSL calls, as they rely on aiohttp sessions.
  5. alexapy:

    • The primary library for interacting with Alexa APIs.
    • Cause: This library uses aiohttp for HTTP requests, which can trigger blocking SSL initialization.

Summary of Responsible Libraries:

  1. aiohttp – For HTTP and SSL connections (responsible for the blocking SSL initialization).
  2. ssl – Python’s standard library for SSL handling (the actual blocking occurs via load_verify_locations).
  3. certifi – Provides SSL certificates that are loaded by ssl.
  4. AlexaLogin (from alexapy) – Indirectly responsible as it utilizes aiohttp.

Primary Cause:

  • The direct cause is the combination of aiohttp and the ssl library, specifically the call to load_verify_locations during 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)