mirror of
https://github.com/home-assistant/core.git
synced 2025-07-23 13:17:32 +00:00
Prevent ping integration from blocking startup (#38504)
This commit is contained in:
parent
3fdec7946c
commit
a91f5b7192
@ -636,6 +636,7 @@ omit =
|
|||||||
homeassistant/components/picotts/tts.py
|
homeassistant/components/picotts/tts.py
|
||||||
homeassistant/components/piglow/light.py
|
homeassistant/components/piglow/light.py
|
||||||
homeassistant/components/pilight/*
|
homeassistant/components/pilight/*
|
||||||
|
homeassistant/components/ping/const.py
|
||||||
homeassistant/components/ping/binary_sensor.py
|
homeassistant/components/ping/binary_sensor.py
|
||||||
homeassistant/components/ping/device_tracker.py
|
homeassistant/components/ping/device_tracker.py
|
||||||
homeassistant/components/pioneer/media_player.py
|
homeassistant/components/pioneer/media_player.py
|
||||||
|
@ -10,9 +10,13 @@ import voluptuous as vol
|
|||||||
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
|
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
|
||||||
from homeassistant.const import CONF_HOST, CONF_NAME
|
from homeassistant.const import CONF_HOST, CONF_NAME
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
|
from homeassistant.util.process import kill_subprocess
|
||||||
|
|
||||||
|
from .const import PING_TIMEOUT
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
ATTR_ROUND_TRIP_TIME_AVG = "round_trip_time_avg"
|
ATTR_ROUND_TRIP_TIME_AVG = "round_trip_time_avg"
|
||||||
ATTR_ROUND_TRIP_TIME_MAX = "round_trip_time_max"
|
ATTR_ROUND_TRIP_TIME_MAX = "round_trip_time_max"
|
||||||
ATTR_ROUND_TRIP_TIME_MDEV = "round_trip_time_mdev"
|
ATTR_ROUND_TRIP_TIME_MDEV = "round_trip_time_mdev"
|
||||||
@ -20,12 +24,14 @@ ATTR_ROUND_TRIP_TIME_MIN = "round_trip_time_min"
|
|||||||
|
|
||||||
CONF_PING_COUNT = "count"
|
CONF_PING_COUNT = "count"
|
||||||
|
|
||||||
DEFAULT_NAME = "Ping Binary sensor"
|
DEFAULT_NAME = "Ping"
|
||||||
DEFAULT_PING_COUNT = 5
|
DEFAULT_PING_COUNT = 5
|
||||||
DEFAULT_DEVICE_CLASS = "connectivity"
|
DEFAULT_DEVICE_CLASS = "connectivity"
|
||||||
|
|
||||||
SCAN_INTERVAL = timedelta(minutes=5)
|
SCAN_INTERVAL = timedelta(minutes=5)
|
||||||
|
|
||||||
|
PARALLEL_UPDATES = 0
|
||||||
|
|
||||||
PING_MATCHER = re.compile(
|
PING_MATCHER = re.compile(
|
||||||
r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)\/(?P<mdev>\d+.\d+)"
|
r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)\/(?P<mdev>\d+.\d+)"
|
||||||
)
|
)
|
||||||
@ -39,17 +45,19 @@ WIN32_PING_MATCHER = re.compile(r"(?P<min>\d+)ms.+(?P<max>\d+)ms.+(?P<avg>\d+)ms
|
|||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||||
{
|
{
|
||||||
vol.Required(CONF_HOST): cv.string,
|
vol.Required(CONF_HOST): cv.string,
|
||||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
vol.Optional(CONF_NAME): cv.string,
|
||||||
vol.Optional(CONF_PING_COUNT, default=DEFAULT_PING_COUNT): cv.positive_int,
|
vol.Optional(CONF_PING_COUNT, default=DEFAULT_PING_COUNT): vol.Range(
|
||||||
|
min=1, max=100
|
||||||
|
),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||||
"""Set up the Ping Binary sensor."""
|
"""Set up the Ping Binary sensor."""
|
||||||
name = config.get(CONF_NAME)
|
host = config[CONF_HOST]
|
||||||
host = config.get(CONF_HOST)
|
count = config[CONF_PING_COUNT]
|
||||||
count = config.get(CONF_PING_COUNT)
|
name = config.get(CONF_NAME, f"{DEFAULT_NAME} {host}")
|
||||||
|
|
||||||
add_entities([PingBinarySensor(name, PingData(host, count))], True)
|
add_entities([PingBinarySensor(name, PingData(host, count))], True)
|
||||||
|
|
||||||
@ -129,7 +137,7 @@ class PingData:
|
|||||||
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
out = pinger.communicate()
|
out = pinger.communicate(timeout=self._count + PING_TIMEOUT)
|
||||||
_LOGGER.debug("Output is %s", str(out))
|
_LOGGER.debug("Output is %s", str(out))
|
||||||
if sys.platform == "win32":
|
if sys.platform == "win32":
|
||||||
match = WIN32_PING_MATCHER.search(str(out).split("\n")[-1])
|
match = WIN32_PING_MATCHER.search(str(out).split("\n")[-1])
|
||||||
@ -142,6 +150,9 @@ class PingData:
|
|||||||
match = PING_MATCHER.search(str(out).split("\n")[-1])
|
match = PING_MATCHER.search(str(out).split("\n")[-1])
|
||||||
rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups()
|
rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups()
|
||||||
return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev}
|
return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev}
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
kill_subprocess(pinger)
|
||||||
|
return False
|
||||||
except (subprocess.CalledProcessError, AttributeError):
|
except (subprocess.CalledProcessError, AttributeError):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
3
homeassistant/components/ping/const.py
Normal file
3
homeassistant/components/ping/const.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
"""Tracks devices by sending a ICMP echo request (ping)."""
|
||||||
|
|
||||||
|
PING_TIMEOUT = 3
|
@ -14,9 +14,13 @@ from homeassistant.components.device_tracker.const import (
|
|||||||
SOURCE_TYPE_ROUTER,
|
SOURCE_TYPE_ROUTER,
|
||||||
)
|
)
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
|
from homeassistant.util.process import kill_subprocess
|
||||||
|
|
||||||
|
from .const import PING_TIMEOUT
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PARALLEL_UPDATES = 0
|
||||||
CONF_PING_COUNT = "count"
|
CONF_PING_COUNT = "count"
|
||||||
|
|
||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||||
@ -47,8 +51,12 @@ class Host:
|
|||||||
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
pinger.communicate()
|
pinger.communicate(timeout=1 + PING_TIMEOUT)
|
||||||
return pinger.returncode == 0
|
return pinger.returncode == 0
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
kill_subprocess(pinger)
|
||||||
|
return False
|
||||||
|
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
12
homeassistant/util/process.py
Normal file
12
homeassistant/util/process.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
"""Util to handle processes."""
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
|
||||||
|
def kill_subprocess(process: subprocess.Popen) -> None:
|
||||||
|
"""Force kill a subprocess and wait for it to exit."""
|
||||||
|
process.kill()
|
||||||
|
process.communicate()
|
||||||
|
process.wait()
|
||||||
|
|
||||||
|
del process
|
26
tests/util/test_process.py
Normal file
26
tests/util/test_process.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
"""Test process util."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from homeassistant.util import process
|
||||||
|
|
||||||
|
|
||||||
|
async def test_kill_process():
|
||||||
|
"""Test killing a process."""
|
||||||
|
sleeper = subprocess.Popen(
|
||||||
|
"sleep 1000",
|
||||||
|
shell=True, # nosec # shell by design
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
pid = sleeper.pid
|
||||||
|
|
||||||
|
assert os.kill(pid, 0) is None
|
||||||
|
|
||||||
|
process.kill_subprocess(sleeper)
|
||||||
|
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
os.kill(pid, 0)
|
Loading…
x
Reference in New Issue
Block a user