Move core service from core to components (#5787)

* Move core servcie from core to components

* add new handler for signals/exception

* Static persistent id

* Move unittest

* fix coro/callback

* Add more unittest for new services

* Address comments

* Update __init__.py
This commit is contained in:
Pascal Vizeli authored and Paulus Schoutsen committed 2017-02-08 09:17:52 -08:00
1 parent 08efe2bf6d
commit 3f82ef64a1
6 files changed
+165 -102

No files matched your search

+49 -10
View File
@@ -12,14 +12,19 @@ import itertools as it
import logging
import homeassistant.core as ha
import homeassistant.config as conf_util
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.service import extract_entity_ids
from homeassistant.loader import get_component
from homeassistant.const import (
ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE)
ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE,
SERVICE_HOMEASSISTANT_STOP, SERVICE_HOMEASSISTANT_RESTART,
RESTART_EXIT_CODE)
_LOGGER = logging.getLogger(__name__)
SERVICE_RELOAD_CORE_CONFIG = 'reload_core_config'
SERVICE_CHECK_CONFIG = 'check_config'
def is_on(hass, entity_id=None):
@@ -75,6 +80,21 @@ def toggle(hass, entity_id=None, **service_data):
hass.services.call(ha.DOMAIN, SERVICE_TOGGLE, service_data)
def stop(hass):
"""Stop Home Assistant."""
hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_STOP)
def restart(hass):
"""Stop Home Assistant."""
hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_RESTART)
def check_config(hass):
"""Check the config files."""
hass.services.call(ha.DOMAIN, SERVICE_CHECK_CONFIG)
def reload_core_config(hass):
"""Reload the core config."""
hass.services.call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG)
@@ -84,7 +104,7 @@ def reload_core_config(hass):
def async_setup(hass, config):
"""Setup general services related to Home Assistant."""
@asyncio.coroutine
def handle_turn_service(service):
def async_handle_turn_service(service):
"""Method to handle calls to homeassistant.turn_on/off."""
entity_ids = extract_entity_ids(hass, service)
@@ -122,18 +142,37 @@ def async_setup(hass, config):
yield from asyncio.wait(tasks, loop=hass.loop)
hass.services.async_register(
ha.DOMAIN, SERVICE_TURN_OFF, handle_turn_service)
ha.DOMAIN, SERVICE_TURN_OFF, async_handle_turn_service)
hass.services.async_register(
ha.DOMAIN, SERVICE_TURN_ON, handle_turn_service)
ha.DOMAIN, SERVICE_TURN_ON, async_handle_turn_service)
hass.services.async_register(
ha.DOMAIN, SERVICE_TOGGLE, handle_turn_service)
ha.DOMAIN, SERVICE_TOGGLE, async_handle_turn_service)
@asyncio.coroutine
def handle_reload_config(call):
"""Service handler for reloading core config."""
from homeassistant.exceptions import HomeAssistantError
from homeassistant import config as conf_util
def async_handle_core_service(call):
"""Service handler for handling core services."""
if call.service == SERVICE_HOMEASSISTANT_STOP:
hass.async_add_job(hass.async_stop())
return
try:
yield from conf_util.async_check_ha_config_file(hass)
except HomeAssistantError:
return
if call.service == SERVICE_HOMEASSISTANT_RESTART:
hass.async_add_job(hass.async_stop(RESTART_EXIT_CODE))
hass.services.async_register(
ha.DOMAIN, SERVICE_HOMEASSISTANT_STOP, async_handle_core_service)
hass.services.async_register(
ha.DOMAIN, SERVICE_HOMEASSISTANT_RESTART, async_handle_core_service)
hass.services.async_register(
ha.DOMAIN, SERVICE_CHECK_CONFIG, async_handle_core_service)
@asyncio.coroutine
def async_handle_reload_config(call):
"""Service handler for reloading core config."""
try:
conf = yield from conf_util.async_hass_config_yaml(hass)
except HomeAssistantError as err:
@@ -144,6 +183,6 @@ def async_setup(hass, config):
hass, conf.get(ha.DOMAIN) or {})
hass.services.async_register(
ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG, handle_reload_config)
ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG, async_handle_reload_config)
return True
+29
View File
@@ -3,7 +3,9 @@ import asyncio
from collections import OrderedDict
import logging
import os
import re
import shutil
import sys
# pylint: disable=unused-import
from typing import Any, List, Tuple # NOQA
@@ -453,3 +455,30 @@ def merge_packages_customize(core_customize, packages):
conf = schema(pkg)
cust.extend(conf.get(CONF_CORE, {}).get(CONF_CUSTOMIZE, []))
return cust
@asyncio.coroutine
def async_check_ha_config_file(hass):
"""Check if HA config file valid.
This method is a coroutine.
"""
import homeassistant.components.persistent_notification as pn
proc = yield from asyncio.create_subprocess_exec(
sys.argv[0],
'--script',
'check_config',
stdout=asyncio.subprocess.PIPE)
# Wait for the subprocess exit
(stdout_data, dummy) = yield from proc.communicate()
result = yield from proc.wait()
if result:
content = re.sub(r'\033\[[^m]*m', '', str(stdout_data, 'utf-8'))
# Put error cleaned from color codes in the error log so it
# will be visible at the UI.
_LOGGER.error(content)
pn.async_create(
hass, "Config error. See dev-info panel for details.",
"Config validating", "{0}.check_config".format(CONF_CORE))
raise HomeAssistantError("Invalid config")
+10 -54
View File
@@ -26,8 +26,7 @@ from homeassistant.const import (
ATTR_SERVICE_CALL_ID, ATTR_SERVICE_DATA, EVENT_CALL_SERVICE,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
EVENT_SERVICE_EXECUTED, EVENT_SERVICE_REGISTERED, EVENT_STATE_CHANGED,
EVENT_TIME_CHANGED, MATCH_ALL, RESTART_EXIT_CODE,
SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, __version__)
EVENT_TIME_CHANGED, MATCH_ALL, RESTART_EXIT_CODE, __version__)
from homeassistant.exceptions import (
HomeAssistantError, InvalidEntityFormatError, ShuttingDown)
from homeassistant.util.async import (
@@ -137,7 +136,7 @@ class HomeAssistant(object):
_LOGGER.info("Starting Home Assistant core loop")
self.loop.run_forever()
except KeyboardInterrupt:
self.loop.call_soon(self._async_stop_handler)
self.loop.create_task(self.async_stop())
self.loop.run_forever()
finally:
self.loop.close()
@@ -149,26 +148,23 @@ class HomeAssistant(object):
This method is a coroutine.
"""
_LOGGER.info("Starting Home Assistant")
self.state = CoreState.starting
# Register the restart/stop event
self.services.async_register(
DOMAIN, SERVICE_HOMEASSISTANT_STOP, self._async_stop_handler)
self.services.async_register(
DOMAIN, SERVICE_HOMEASSISTANT_RESTART, self._async_restart_handler)
# Setup signal handling
if sys.platform != 'win32':
def _async_signal_handle(exit_code):
"""Wrap signal handling."""
self.async_add_job(self.async_stop(exit_code))
try:
self.loop.add_signal_handler(
signal.SIGTERM, self._async_stop_handler)
signal.SIGTERM, _async_signal_handle, 0)
except ValueError:
_LOGGER.warning("Could not bind to SIGTERM")
try:
self.loop.add_signal_handler(
signal.SIGHUP, self._async_restart_handler)
signal.SIGHUP, _async_signal_handle, RESTART_EXIT_CODE)
except ValueError:
_LOGGER.warning("Could not bind to SIGHUP")
@@ -283,7 +279,7 @@ class HomeAssistant(object):
run_coroutine_threadsafe(self.async_stop(), self.loop)
@asyncio.coroutine
def async_stop(self) -> None:
def async_stop(self, exit_code=0) -> None:
"""Stop Home Assistant and shuts down all threads.
This method is a coroutine.
@@ -306,6 +302,7 @@ class HomeAssistant(object):
logging.getLogger('').removeHandler(handler)
yield from handler.async_close(blocking=True)
self.exit_code = exit_code
self.loop.stop()
# pylint: disable=no-self-use
@@ -324,47 +321,6 @@ class HomeAssistant(object):
_LOGGER.error("Error doing job: %s", context['message'], **kwargs)
@callback
def _async_stop_handler(self, *args):
"""Stop Home Assistant."""
self.exit_code = 0
self.loop.create_task(self.async_stop())
@asyncio.coroutine
def _async_check_config_and_restart(self):
"""Restart Home Assistant if config is valid.
This method is a coroutine.
"""
proc = yield from asyncio.create_subprocess_exec(
sys.argv[0],
'--script',
'check_config',
stdout=asyncio.subprocess.PIPE)
# Wait for the subprocess exit
(stdout_data, dummy) = yield from proc.communicate()
result = yield from proc.wait()
if result:
_LOGGER.error("check_config failed. Not restarting.")
content = re.sub(r'\033\[[^m]*m', '', str(stdout_data, 'utf-8'))
# Put error cleaned from color codes in the error log so it
# will be visible at the UI.
_LOGGER.error(content)
yield from self.services.async_call(
'persistent_notification', 'create', {
'message': 'Config error. See dev-info panel for details.',
'title': 'Restarting',
'notification_id': '{}.restart'.format(DOMAIN)})
return
self.exit_code = RESTART_EXIT_CODE
yield from self.async_stop()
@callback
def _async_restart_handler(self, *args):
"""Restart Home Assistant."""
self.loop.create_task(self._async_check_config_and_restart())
class EventOrigin(enum.Enum):
"""Represent the origin of an event."""