HAMusicAssistantJukebox icon indicating copy to clipboard operation
HAMusicAssistantJukebox copied to clipboard

Detecting blocking I/O operations in event loop (shutil and open) in music_assistant_jukebox

Open ragne1d opened this issue 1 year ago • 4 comments

Home Assistant is warning that the music_assistant_jukebox integration is performing blocking disk I/O calls directly in the main asyncio event loop. This can degrade performance and lead to warnings like:

  • Detected blocking call to open with args ('/config/www/jukebox/jukebox.html', 'wb') inside the event loop by custom integration 'music_assistant_jukebox' at custom_components/music_assistant_jukebox/init.py, line 120: shutil.copy2(src_file, dst_file)

Similar warnings appear for shutil.rmtree, shutil.copytree, and other open calls in:

custom_components/music_assistant_jukebox/init.py custom_components/music_assistant_jukebox/image.py

Home Assistant 2025.7.2 detects these blocking calls and logs them under homeassistant.util.loop. According to the Home Assistant developer docs on blocking I/O, all disk operations must be offloaded to the executor.

Expected behavior: All file operations (shutil.copy2, shutil.copytree, shutil.rmtree, open) should be executed in an executor thread to avoid blocking the main asyncio loop. No warnings about blocking calls should appear in the Home Assistant log.

ragne1d avatar Jul 15 '25 10:07 ragne1d

Open to advice/suggestions on how to offload these to 'the executor'.

DJS91 avatar Jul 22 '25 02:07 DJS91

https://github.com/DJS91/HAMusicAssistantJukebox/issues/40

see https://developers.home-assistant.io/docs/asyncio_blocking_operations/

jonwaland avatar Jul 24 '25 07:07 jonwaland

Suggested code from google Gemini for the image.py changes

I make no comment on the validity of the changes, but the feedback from Gemini on what to do, was educational if nothing else ((https://g.co/gemini/share/ee445c126d91)) :

"""Image platform for music_assistant_jukebox."""
from __future__ import annotations

import os
from datetime import datetime

from homeassistant.components.image import ImageEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN, LOGGER

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up image entities based on a config entry."""
    entities = [
        JukeboxInternalQRCode(hass, entry),
        JukeboxExternalQRCode(hass, entry),
    ]
    async_add_entities(entities)

class JukeboxBaseMixin:
    """Mixin for common device info."""

    @property
    def device_info(self) -> DeviceInfo:
        """Return device info."""
        return DeviceInfo(
            identifiers={(DOMAIN, "jukebox")},
            name="Music Assistant Jukebox",
            manufacturer="DJS91 and TheOddPirate",
            model="Jukebox Controller",
            configuration_url="http://homeassistant.local:8123/local/jukebox/jukebox.html"
        )

class JukeboxInternalQRCode(JukeboxBaseMixin, ImageEntity):
    """Representation of the Jukebox Internal QR Code."""

    _attr_has_entity_name = True
    _attr_name = "Internal Access QR Code"
    _attr_unique_id = f"{DOMAIN}_internal_qr"

    def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
        """Initialize the image entity."""
        self.hass = hass
        self.entry = entry
        super().__init__(hass)
        self._attr_content_type = "image/png"
        self._image_path = hass.config.path("www/jukebox/internal_url_qr.png")
        self._attr_entity_picture = "/local/jukebox/internal_url_qr.png"
        self._image = None

    async def async_image(self) -> bytes | None:
        """Return bytes of image."""
        await self._async_load_image()
        return self._image

    async def _async_load_image(self) -> None:
        """Load the image asynchronously and set attributes."""
        if not os.path.exists(self._image_path):
            self._attr_available = False
            self._image = None
            return

        try:
            # Offload the blocking file read to a thread pool
            image_data = await self.hass.async_add_executor_job(
                self._read_image_file, self._image_path
            )
            self._image = image_data
            self._attr_available = True
            self._attr_image_last_updated = datetime.fromtimestamp(os.path.getmtime(self._image_path))
        except Exception as err:
            LOGGER.error("Error reading image file %s: %s", self._image_path, err)
            self._attr_available = False
            self._image = None

    def _read_image_file(self, path: str) -> bytes:
        """Read the image file in a separate thread."""
        with open(path, "rb") as image_file:
            return image_file.read()

    @property
    def state(self) -> str:
        """Return state of image."""
        return "available" if self._attr_available else "unavailable"

class JukeboxExternalQRCode(JukeboxBaseMixin, ImageEntity):
    """Representation of the Jukebox External QR Code."""

    _attr_has_entity_name = True
    _attr_name = "External Access QR Code"
    _attr_unique_id = f"{DOMAIN}_external_qr"

    def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
        """Initialize the image entity."""
        self.hass = hass
        self.entry = entry
        super().__init__(hass)
        self._attr_content_type = "image/png"
        self._image_path = hass.config.path("www/jukebox/external_url_qr.png")
        self._attr_entity_picture = "/local/jukebox/external_url_qr.png"
        self._image = None

    async def async_image(self) -> bytes | None:
        """Return bytes of image."""
        await self._async_load_image()
        return self._image

    async def _async_load_image(self) -> None:
        """Load the image asynchronously and set attributes."""
        if not os.path.exists(self._image_path):
            self._attr_available = False
            self._image = None
            return

        try:
            # Offload the blocking file read to a thread pool
            image_data = await self.hass.async_add_executor_job(
                self._read_image_file, self._image_path
            )
            self._image = image_data
            self._attr_available = True
            self._attr_image_last_updated = datetime.fromtimestamp(os.path.getmtime(self._image_path))
        except Exception as err:
            LOGGER.error("Error reading image file %s: %s", self._image_path, err)
            self._attr_available = False
            self._image = None

    def _read_image_file(self, path: str) -> bytes:
        """Read the image file in a separate thread."""
        with open(path, "rb") as image_file:
            return image_file.read()

    @property
    def state(self) -> str:
        """Return state of image."""
        return "available" if self._attr_available else "unavailable"

jonwaland avatar Sep 09 '25 07:09 jonwaland

Hey All, This project is now deprecated and will be archived.

Party mode with much of the same features (but much better) has been developed as a native plugin in the latest Music assistant beta and will be released soon.

You can read about it here and test it for yourself in the latest beta build. https://beta.music-assistant.io/plugins/party-mode/

DJS91 avatar Mar 11 '26 23:03 DJS91