Drop the API connection after a connection error in Mikrotik (#194990)

This commit is contained in:
Simone Chemelli
2026-11-28 11:14:54 +01:00
committed by GitHub
parent 3d1fc7fb66
commit c372ee916f
3 changed files with 84 additions and 16 deletions
@@ -193,7 +193,7 @@ async def async_unload_entry(
) -> None:
"""Unload a config entry."""
await hass.config_entries.async_unload_platforms_or_raise(config_entry, PLATFORMS)
await hass.async_add_executor_job(config_entry.runtime_data.api.api.close)
await hass.async_add_executor_job(config_entry.runtime_data.api.disconnect)
async def async_remove_config_entry_device(
@@ -1,5 +1,6 @@
"""The Mikrotik router class."""
from contextlib import suppress
from datetime import timedelta
import ssl
from typing import Any, override
@@ -65,7 +66,7 @@ class MikrotikData:
"""Initialize the Mikrotik Client."""
self.hass = hass
self.config_entry = config_entry
self.api = api
self.api: librouteros.Api | None = api
self._host: str = self.config_entry.data[CONF_HOST]
self.all_devices: dict[str, dict[str, Any]] = {}
self.devices: dict[str, Device] = {}
@@ -341,20 +342,35 @@ class MikrotikData:
with mikrotik_config_entry_errors(
suppress_errors=suppress_errors, during_setup=during_setup
):
if self.api is not None:
try:
return list(self.api(cmd, **(params or {})))
except CONNECTION_ERRORS as err:
LOGGER.debug(
"Mikrotik %s - connection dropped (%s), reconnecting",
self._host,
err,
)
self.disconnect()
self.api = get_api(dict(self.config_entry.data))
try:
if params:
return list(self.api(cmd, **params))
return list(self.api(cmd))
except CONNECTION_ERRORS as err:
LOGGER.debug(
"Mikrotik %s - connection dropped (%s), reconnecting",
self._host,
err,
)
self.api = get_api(dict(self.config_entry.data))
if params:
return list(self.api(cmd, **params))
return list(self.api(cmd))
return list(self.api(cmd, **(params or {})))
except CONNECTION_ERRORS:
self.disconnect()
raise
def disconnect(self) -> None:
"""Close the connection to the Mikrotik API.
A reply cut off by a connection error stays unread on the socket and
would be read as the reply to the next command, so the connection is
never reused after one.
"""
if self.api is None:
return
with suppress(*CONNECTION_ERRORS):
self.api.close()
self.api = None
class MikrotikDataUpdateCoordinator(DataUpdateCoordinator[None]):
+53 -1
View File
@@ -24,10 +24,11 @@ from homeassistant.components.mikrotik.const import (
INTERFACE,
MIKROTIK_SERVICES,
PING,
RESOURCE,
ROUTERBOARD,
)
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import CONF_VERIFY_SSL
from homeassistant.const import CONF_VERIFY_SSL, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
device_registry as dr,
@@ -50,10 +51,13 @@ from .const import (
INTERFACE_DATA,
MOCK_DATA,
ROUTERBOARD_DATA,
SYSTEM_DATA,
TEST_SERIAL_NUMBER,
WLAN1_INTERFACE,
)
CPU_USAGE_ENTITY_ID = "sensor.mikrotik_cpu_usage"
_BASE_COMMAND_RESPONSES: dict[str, list[dict[str, Any]]] = {
MIKROTIK_SERVICES[IDENTITY]: [{"name": "Mikrotik"}]
}
@@ -301,6 +305,54 @@ async def test_hub_reconnect_error_during_refresh_raises_update_failed(
assert isinstance(coordinator.last_exception, UpdateFailed)
@pytest.mark.parametrize(
"reconnect",
[
pytest.param({"side_effect": OSError()}, id="reconnect_fails"),
pytest.param(
{"return_value": MagicMock(side_effect=ConnectionClosed())},
id="retry_fails",
),
],
)
async def test_failed_reconnect_discards_dropped_connection(
hass: HomeAssistant,
mock_api: MagicMock,
mock_config_entry: MockConfigEntryFactory,
freezer: FrozenDateTimeFactory,
reconnect: dict[str, Any],
) -> None:
"""Test a dropped connection is never reused once the reconnect fails.
A reply cut off by the drop stays unread on the old socket, so reusing it
would hand every following command the reply of an earlier one.
"""
responses = _BASE_COMMAND_RESPONSES | {MIKROTIK_SERVICES[RESOURCE]: SYSTEM_DATA}
entry = mock_config_entry()
await setup_integration(hass, entry, command_responses=responses)
assert hass.states.get(CPU_USAGE_ENTITY_ID).state == "15"
mock_api.side_effect = ConnectionClosed()
with patch("librouteros.connect", **reconnect):
freezer.tick(timedelta(seconds=10))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(CPU_USAGE_ENTITY_ID).state == STATE_UNAVAILABLE
mock_api.close.assert_called_once()
new_api = MagicMock(side_effect=lambda cmd, **params: responses.get(cmd, []))
with patch("librouteros.connect", return_value=new_api) as mock_connect:
freezer.tick(timedelta(seconds=10))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(CPU_USAGE_ENTITY_ID).state == "15"
mock_connect.assert_called_once()
mock_api.close.assert_called_once()
async def test_connection_dropped_during_refresh_reconnects_and_succeeds(
hass: HomeAssistant,
mock_api: MagicMock,