alexa_media_player: WARNING: Detected blocking call to load_verify_locations with args (,) inside the event loop by custom integration 'alexa_media

Describe the bug

This is not a bug! The warning messages should be addressed though so as to not impact performance in the HA event loop.

To Reproduce

HA 2024.9.x now detects blocking calls (which have always been this way)

Expected behavior

No warning messages

System details

  • Home Assistant version: 2024.9.0
  • alexa_media version (from const.py or HA startup log): 4.12.11
  • alexapy version (from pip show alexapy in homeasssistant container or HA startup log): 1.28.2
  • Is Amazon 2FA/2SV enabled <!—We will not debug login issues if unanswered—> (y/n): y
  • Amazon Domain: amazon.it

Debug Logs (alexa_media & alexapy) 2024-09-04 19:37:06.401 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7f155dedfd50>, ‘/usr/local/lib/python3.12/site-packages/certifi/cacert.pem’, None, None) inside the event loop by custom integration ‘alexa_media’ at custom_components/alexa_media/init.py, line 340: AlexaLogin( (offender: /usr/local/lib/python3.12/ssl.py, line 708: context.load_verify_locations(cafile, capath, cadata)), 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/#load_verify_locations 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/setup.py”, line 165, in async_setup_component result = await _async_setup_component(hass, domain, config) File “/usr/src/homeassistant/homeassistant/setup.py”, line 461, in async_setup_component await asyncio.gather( File “/usr/src/homeassistant/homeassistant/setup.py”, line 463, in <genexpr> create_eager_task( File "/usr/src/homeassistant/homeassistant/util/async.py", line 45, in create_eager_task return Task(coro, loop=loop, name=name, eager_start=True) 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 340, in async_setup_entry AlexaLogin(

2024-09-04 19:37:06.627 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to open with args (PosixPath(‘/config/.storage/alexa_media.XXX@XX.pickle’),) inside the event loop by custom integration ‘alexa_media’ at custom_components/alexa_media/init.py, line 360: 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 360, in async_setup_entry await login.login(cookies=await login.load_cookie())

2024-09-04 19:37:08.988 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to open with args (PosixPath(‘/config/.storage/alexa_media.XXX@XX.pickle’),) inside the event loop by custom integration ‘alexa_media’ at custom_components/alexa_media/init.py, line 360: 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 360, in async_setup_entry await login.login(cookies=await login.load_cookie())

2024-09-04 19:37:09.071 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7f155d069e50>,) inside the event loop by custom integration ‘alexa_media’ at custom_components/alexa_media/init.py, line 875: 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 at https://github.com/alandtse/alexa_media_player/issues For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#load_verify_locations 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 362, in async_setup_entry await setup_alexa(hass, config_entry, login) File “/config/custom_components/alexa_media/init.py”, line 1265, in setup_alexa await http2_connect() File “/config/custom_components/alexa_media/init.py”, line 875, in http2_connect http2 = HTTP2EchoClient(

Additional context

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 19
  • Comments: 35 (2 by maintainers)

Most upvoted comments

The integration has become unusable and useless… the entities are shown as offline and not working anymore. This bug + the bug related to the reauth issue are making this custom component not working anymore.

@stefano This issue is not a bug! It is a warning only! This part of the code has always been this way and it’s only now that HA is checking for these types of blocking calls in the event loop that we (and many other integrations as well, including HA Core native integrations!) are being notified that our code is hindering performance. The loop is only blocked for the duration of the call and therefore only affects the overall performance of HA.

Any plan to fix it?

Is there a “plan”? No, there’s no one at the ship’s helm! There’s only users like you, me, @RogerSelwyn, etc.

I repeat…“Detected blocking call to load_verify_locations” is a WARNING ONLY and has NOTHING WHATSOEVER to do with any issues you might be having! DO NOT POST YOUR ISSUES HERE!

¿Es por esto que de repente tengo dispositivos HA dañados dentro de Alexa? Todos los dispositivos que expongo a Alexa a través del asistente de hogar se muestran como inaccesibles de repente. Y recibo la misma advertencia en los registros. Casi no puedo usar mis comandos de voz

No.

  1. Los dispositivos expuestos desde HA a Alexa no tienen nada que ver con esta integración. Debes consultar tu integración con Amazon Alexa , que se realiza a través de Nabu Casa cloud:o mediante la creación manual de habilidades ( Habilidad de Amazon Alexa Smart Home )
  2. Este problema es solo para mensajes de “advertencia” sobre AMP y son solo eso, ¡una advertencia !

I take this opportunity to thank you for all the help you have given us, selflessly, and for that time which is surely a lot to make the component work, I thank you from the bottom of my heart.

Just had a go at solving the one at line 343. As you say seems easier said than done since it seems like it goes from sync call to AlexaLogin class which then initiates an async call. I’m not knowledgeable enough, I’ll do some digging, because I’ve used hass.async_add_executor_job I think it has moved it outside the loop, and then when it trues to go async inside AlexaLogin it can’t find the loop to start a session from.

Edit: I think AlexaLogin needs to be modified to allow a session to be passed in, which looking at the code would be a fairly easy change. Probably needs a discussion with @alandtse.

same problem for me. If it helps I’ve logged (and closed) a bug with all the info an the log: #2512

Thanks but I already have all the logs. And there are multiple blocking calls beyond just the certs…

I’ll try to take a look when I get a chance. It’ll make a change from adding testing to an integration I created.

How does this affect Alexa Media Player?How does this affect Alexa Media Player?

I am encountering this error during initial configuration of the integration and therefore it cannot be added. My information is the same as above, except for the Amazon domain, which for me is amazon.com

The problem seems resolved with AMP v4.13.5

+1,

Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7f57e11f50>,) inside the event loop by custom integration ‘alexa_media’ at custom_components/alexa_media/init.py, line 922: http2 = HTTP2EchoClient( (offender: /usr/local/lib/python3.12/site-packages/httpx/_config.py, line 149: context.load_verify_locations(cafile=cafile)), please create a bug report at https://github.com/alandtse/alexa_media_player/issues

So now we rely in AI to fix the code?

Analysis by ChatGPT:


Here is a summary of the issues that are outside our scope and why we cannot fix them directly:

1. Blocking SSL operations (load_verify_locations):

  • Issue: The function load_verify_locations is part of Python’s built-in ssl library, which handles SSL context verification.
  • Why we can’t fix it: This function is inherently blocking and resides in the standard Python library, which we cannot modify directly. The problem is that SSL verification is designed to block while verifying certificates, and altering this behavior would require changes at the core Python level or within the ssl library itself.

2. AlexaLogin object lacks ssl_context:

  • Issue: The AlexaLogin object does not expose or provide access to an ssl_context attribute, which prevents us from manually controlling SSL verification processes within this object.
  • Why we can’t fix it: The lack of an ssl_context attribute in the AlexaLogin class is part of its internal design. Since this is a third-party library (alexapy), we do not have control over its internal structure. To resolve this, we’d need either the library maintainers to modify the class or to extend the library ourselves, which is outside the scope of this discussion.

3. SSL operations deeply integrated into third-party libraries:

  • Issue: The SSL verification that causes blocking is handled internally by third-party libraries, such as alexapy (used by alexa_media), which are responsible for making network requests to Amazon’s services.
  • Why we can’t fix it: The SSL verification is part of how these libraries handle secure communication, and altering this would require modifying the internal behavior of the third-party libraries. Since we are users of these libraries and not their maintainers, making such deep changes would be impractical and would likely require submitting requests or pull requests to the library maintainers.

In summary, these issues involve built-in Python behaviors and third-party library structures that we cannot modify directly. To resolve them, contributions or fixes from the maintainers of those libraries would be necessary.

Got the same issue. Has been doing this for a while now.

The integration has become unusable and useless… the entities are shown as offline and not working anymore. This bug + the bug related to the reauth issue are making this custom component not working anymore.

Any plan to fix it?

You are likely to need to wrap the call to the offending function with ‘await hass.async_add_executor_job’, which obviously nee ds to be done from an async function. This will push it outside the executor thread.

If the function call was ‘blockingfunction(param1, param2)’ this would get changed to 'await hass.async_add_executor_job(blockingfunction, param1, param2).

You will need access to hass somewhere, but it’s usually hanging around somewhere.

I’ve tried every which way from Sunday that I can think of to implement that here: alexa_meda/__init__.py

    login: AlexaLogin = hass.data[DATA_ALEXAMEDIA]["accounts"][email].get(
        "login_obj",
        AlexaLogin(
            url=url,
            email=email,
            password=password,
            outputpath=hass.config.path,
            debug=account.get(CONF_DEBUG),
            otp_secret=account.get(CONF_OTPSECRET, ""),
            oauth=account.get(CONF_OAUTH, {}),
            uuid=uuid,
            oauth_login=True,
        ),
    )
    hass.data[DATA_ALEXAMEDIA]["accounts"][email]["login_obj"] = login
    hass.data[DATA_ALEXAMEDIA]["accounts"][email]["last_push_activity"] = 0
    if not hass.data[DATA_ALEXAMEDIA]["accounts"][email]["second_account_index"]:
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, close_alexa_media)
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, complete_startup)
    hass.bus.async_listen("alexa_media_relogin_required", relogin)
    hass.bus.async_listen("alexa_media_relogin_success", login_success)
    try:
        await login.login(cookies=await login.load_cookie())    ## Original ## 
        
        #EXAMPLE result = await hass.async_add_executor_job(blocking_code, "something")
        #EXAMPLE result = await hass.async_add_executor_job(partial(blocking_code_with_kwargs, kwarg=True))

        #await login.login(cookies=await hass.async_add_executor_job(login.load_cookie))
        #loaded_cookie = await hass.async_add_executor_job(login.load_cookie)
        #await hass.async_add_executor_job(partial(login.login, cookies=loaded_cookie))
        #await login.login(cookies=loaded_cookie)
        #await hass.async_add_executor_job(login.login, "cookies=await login.load_cookie()")
        #await hass.async_add_executor_job(partial(login.login, cookies=login.load_cookie))
        #await hass.async_add_executor_job(partial(login.login, cookies=await login.load_cookie()))
        #await hass.async_add_executor_job(partial(blocking_code_with_kwargs, kwarg=True))
        #cookies = await hass.async_add_executor_job(login.load_cookie)
        #result = await hass.async_add_executor_job(login.login,cookies)
        
        if await test_login_status(hass, config_entry, login):
            await setup_alexa(hass, config_entry, login)
            return True
        return False

This is the function in alexapy/alexalogin.py:

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

I think this is one of the blocking calls within load_cookie:

                try:
                    async with aiofiles.open(cookiefile, "rb") as myfile:
                        cookies = pickle.loads(await myfile.read())
                        if self._debug:
                            _LOGGER.debug(
                                "Pickled cookie loaded: %s %s", type(cookies), cookies
                            )

!!! IT’S JUST A WARNING !!! The blocking call has always been there. It’s just that HA Core is becoming smarter about checking for and reporting on these async blocking calls in its ongoing attempts to streamline and keep everything internal running smoothly and quickly.

is it possible to fix it?

Possibly, but I do not know how, or where (alexa_media or alexpy)

It’s all outlined in Blocking operations with asyncio but it’s all pseudo code and trying to figure out exactly what should be changed and how is beyond my current skill level.

You are likely to need to wrap the call to the offending function with ‘await hass.async_add_executor_job’, which obviously nee ds to be done from an async function. This will push it outside the executor thread.

If the function call was ‘blockingfunction(param1, param2)’ this would get changed to 'await hass.async_add_executor_job(blockingfunction, param1, param2).

You will need access to hass somewhere, but it’s usually hanging around somewhere.

!!! IT’S JUST A WARNING !!! The blocking call has always been there. It’s just that HA Core is becoming smarter about checking for and reporting on these async blocking calls in its ongoing attempts to streamline and keep everything internal running smoothly and quickly.

is it possible to fix it?

Possibly, but I do not know how, or where (alexa_media or alexpy)

It’s all outlined in Blocking operations with asyncio but it’s all pseudo code and trying to figure out exactly what should be changed and how is beyond my current skill level.

Experiencing the same issue, it started occurring since the latest update to the integration - before this point the error was not experienced.

Debug Logs (alexa_media & alexapy) 2024-09-04 19:37:06.401 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7f155dedfd50>, ‘/usr/local/lib/python3.12/site-packages/certifi/cacert.pem’, None, None) inside the event loop by custom integration ‘alexa_media’ at custom_components/alexa_media/init.py, line 340: AlexaLogin( (offender: /usr/local/lib/python3.12/ssl.py, line 708: context.load_verify_locations(cafile, capath, cadata)), 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/#load_verify_locations

How does this affect Alexa Media Player?How does this affect Alexa Media Player?