Prevent ping integration from blocking startup (#38504)

This commit is contained in:
J. Nick Koston 2020-08-05 00:43:35 -10:00 committed by GitHub
parent 3fdec7946c
commit a91f5b7192
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 69 additions and 8 deletions

View File

@ -636,6 +636,7 @@ omit =
homeassistant/components/picotts/tts.py
homeassistant/components/piglow/light.py
homeassistant/components/pilight/*
homeassistant/components/ping/const.py
homeassistant/components/ping/binary_sensor.py
homeassistant/components/ping/device_tracker.py
homeassistant/components/pioneer/media_player.py

View File

@ -10,9 +10,13 @@ import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import CONF_HOST, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.util.process import kill_subprocess
from .const import PING_TIMEOUT
_LOGGER = logging.getLogger(__name__)
ATTR_ROUND_TRIP_TIME_AVG = "round_trip_time_avg"
ATTR_ROUND_TRIP_TIME_MAX = "round_trip_time_max"
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"
DEFAULT_NAME = "Ping Binary sensor"
DEFAULT_NAME = "Ping"
DEFAULT_PING_COUNT = 5
DEFAULT_DEVICE_CLASS = "connectivity"
SCAN_INTERVAL = timedelta(minutes=5)
PARALLEL_UPDATES = 0
PING_MATCHER = re.compile(
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(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PING_COUNT, default=DEFAULT_PING_COUNT): cv.positive_int,
vol.Optional(CONF_NAME): cv.string,
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):
"""Set up the Ping Binary sensor."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
count = config.get(CONF_PING_COUNT)
host = config[CONF_HOST]
count = config[CONF_PING_COUNT]
name = config.get(CONF_NAME, f"{DEFAULT_NAME} {host}")
add_entities([PingBinarySensor(name, PingData(host, count))], True)
@ -129,7 +137,7 @@ class PingData:
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
try:
out = pinger.communicate()
out = pinger.communicate(timeout=self._count + PING_TIMEOUT)
_LOGGER.debug("Output is %s", str(out))
if sys.platform == "win32":
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])
rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups()
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):
return False

View File

@ -0,0 +1,3 @@
"""Tracks devices by sending a ICMP echo request (ping)."""
PING_TIMEOUT = 3

View File

@ -14,9 +14,13 @@ from homeassistant.components.device_tracker.const import (
SOURCE_TYPE_ROUTER,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.process import kill_subprocess
from .const import PING_TIMEOUT
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
CONF_PING_COUNT = "count"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
@ -47,8 +51,12 @@ class Host:
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
)
try:
pinger.communicate()
pinger.communicate(timeout=1 + PING_TIMEOUT)
return pinger.returncode == 0
except subprocess.TimeoutExpired:
kill_subprocess(pinger)
return False
except subprocess.CalledProcessError:
return False

View 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

View 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)