Example #1
0
def async_setup_component(hass: core.HomeAssistant,
                          domain: str,
                          config: Optional[Dict] = None) -> bool:
    """Setup a component and all its dependencies.

    This method is a coroutine.
    """
    if domain in hass.config.components:
        _LOGGER.debug('Component %s already set up.', domain)
        return True

    if not loader.PREPARED:
        yield from hass.loop.run_in_executor(None, loader.prepare, hass)

    if config is None:
        config = defaultdict(dict)

    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        _async_persistent_notification(hass, domain, True)
        return False

    for component in components:
        res = yield from _async_setup_component(hass, component, config)
        if not res:
            _LOGGER.error('Component %s failed to setup', component)
            _async_persistent_notification(hass, component, True)
            return False

    return True
Example #2
0
def setup_component(hass, domain, config=None):
    """ Setup a component and all its dependencies. """

    if domain in hass.config.components:
        return True

    _ensure_loader_prepared(hass)

    if config is None:
        config = defaultdict(dict)

    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        return False

    for component in components:
        if component in hass.config.components:
            continue

        if not _setup_component(hass, component, config):
            return False

    return True
def setup_component(hass: core.HomeAssistant,
                    domain: str,
                    config: Optional[Dict] = None) -> bool:
    """Setup a component and all its dependencies."""
    if domain in hass.config.components:
        _LOGGER.debug('Component %s already set up.', domain)
        return True

    _ensure_loader_prepared(hass)

    if config is None:
        config = defaultdict(dict)

    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        return False

    for component in components:
        if not _setup_component(hass, component, config):
            _LOGGER.error('Component %s failed to setup', component)
            return False

    return True
Example #4
0
def setup_component(hass, domain, config=None):
    """ Setup a component and all its dependencies. """

    if domain in hass.config.components:
        return True

    _ensure_loader_prepared(hass)

    if config is None:
        config = defaultdict(dict)

    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        return False

    for component in components:
        if component in hass.config.components:
            continue

        if not _setup_component(hass, component, config):
            return False

    return True
Example #5
0
def async_setup_component(hass: core.HomeAssistant, domain: str,
                          config: Optional[Dict]=None) -> bool:
    """Setup a component and all its dependencies.

    This method is a coroutine.
    """
    if domain in hass.config.components:
        _LOGGER.debug('Component %s already set up.', domain)
        return True

    if not loader.PREPARED:
        yield from hass.loop.run_in_executor(None, loader.prepare, hass)

    if config is None:
        config = {}

    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        _async_persistent_notification(hass, domain, True)
        return False

    for component in components:
        res = yield from _async_setup_component(hass, component, config)
        if not res:
            _LOGGER.error('Component %s failed to setup', component)
            _async_persistent_notification(hass, component, True)
            return False

    return True
    def test_load_order_component(self):
        """Test if we can get the proper load order of components."""
        loader.set_component('mod1', MockModule('mod1'))
        loader.set_component('mod2', MockModule('mod2', ['mod1']))
        loader.set_component('mod3', MockModule('mod3', ['mod2']))

        self.assertEqual(
            ['mod1', 'mod2', 'mod3'], loader.load_order_component('mod3'))

        # Create circular dependency
        loader.set_component('mod1', MockModule('mod1', ['mod3']))

        self.assertEqual([], loader.load_order_component('mod3'))

        # Depend on non-existing component
        loader.set_component('mod1', MockModule('mod1', ['nonexisting']))

        self.assertEqual([], loader.load_order_component('mod1'))

        # Try to get load order for non-existing component
        self.assertEqual([], loader.load_order_component('mod1'))
    def test_load_order_component(self):
        """Test if we can get the proper load order of components."""
        loader.set_component('mod1', MockModule('mod1'))
        loader.set_component('mod2', MockModule('mod2', ['mod1']))
        loader.set_component('mod3', MockModule('mod3', ['mod2']))

        self.assertEqual(['mod1', 'mod2', 'mod3'],
                         loader.load_order_component('mod3'))

        # Create circular dependency
        loader.set_component('mod1', MockModule('mod1', ['mod3']))

        self.assertEqual([], loader.load_order_component('mod3'))

        # Depend on non-existing component
        loader.set_component('mod1', MockModule('mod1', ['nonexisting']))

        self.assertEqual([], loader.load_order_component('mod1'))

        # Try to get load order for non-existing component
        self.assertEqual([], loader.load_order_component('mod1'))
Example #8
0
def setup_component(hass: core.HomeAssistant, domain: str,
                    config: Optional[Dict]=None) -> bool:
    """Setup a component and all its dependencies."""
    if domain in hass.config.components:
        return True

    _ensure_loader_prepared(hass)

    if config is None:
        config = defaultdict(dict)

    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        return False

    for component in components:
        if not _setup_component(hass, component, config):
            return False

    return True
Example #9
0
async def _async_setup_component(hass: core.HomeAssistant, domain: str,
                                 config) -> bool:
    """Set up a component for Home Assistant.

    This method is a coroutine.
    """
    def log_error(msg, link=True):
        """Log helper."""
        _LOGGER.error("Setup failed for %s: %s", domain, msg)
        async_notify_setup_error(hass, domain, link)

    component = loader.get_component(hass, domain)

    if not component:
        log_error("Component not found.", False)
        return False

    # Validate no circular dependencies
    components = loader.load_order_component(hass, domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        log_error("Unable to resolve component or dependencies.")
        return False

    processed_config = \
        conf_util.async_process_component_config(hass, config, domain)

    if processed_config is None:
        log_error("Invalid config.")
        return False

    try:
        await async_process_deps_reqs(hass, config, domain, component)
    except HomeAssistantError as err:
        log_error(str(err))
        return False

    start = timer()
    _LOGGER.info("Setting up %s", domain)

    if hasattr(component, 'PLATFORM_SCHEMA'):
        # Entity components have their own warning
        warn_task = None
    else:
        warn_task = hass.loop.call_later(
            SLOW_SETUP_WARNING, _LOGGER.warning,
            "Setup of %s is taking over %s seconds.", domain,
            SLOW_SETUP_WARNING)

    try:
        if hasattr(component, 'async_setup'):
            result = await component.async_setup(  # type: ignore
                hass, processed_config)
        else:
            result = await hass.async_add_job(component.setup, hass,
                                              processed_config)  # type: ignore
    except Exception:  # pylint: disable=broad-except
        _LOGGER.exception("Error during setup of component %s", domain)
        async_notify_setup_error(hass, domain, True)
        return False
    finally:
        end = timer()
        if warn_task:
            warn_task.cancel()
    _LOGGER.info("Setup of domain %s took %.1f seconds.", domain, end - start)

    if result is False:
        log_error("Component failed to initialize.")
        return False
    elif result is not True:
        log_error("Component did not return boolean if setup was successful. "
                  "Disabling component.")
        loader.set_component(hass, domain, None)
        return False

    for entry in hass.config_entries.async_entries(domain):
        await entry.async_setup(hass, component=component)

    hass.config.components.add(component.DOMAIN)  # type: ignore

    # Cleanup
    if domain in hass.data[DATA_SETUP]:
        hass.data[DATA_SETUP].pop(domain)

    hass.bus.async_fire(
        EVENT_COMPONENT_LOADED,
        {ATTR_COMPONENT: component.DOMAIN}  # type: ignore
    )

    return True
Example #10
0
def _async_setup_component(hass: core.HomeAssistant, domain: str,
                           config) -> bool:
    """Set up a component for Home Assistant.

    This method is a coroutine.
    """
    def log_error(msg, link=True):
        """Log helper."""
        _LOGGER.error("Setup failed for %s: %s", domain, msg)
        async_notify_setup_error(hass, domain, link)

    component = loader.get_component(domain)

    if not component:
        log_error("Component not found.", False)
        return False

    # Validate no circular dependencies
    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        log_error("Unable to resolve component or dependencies.")
        return False

    processed_config = \
        conf_util.async_process_component_config(hass, config, domain)

    if processed_config is None:
        log_error("Invalid config.")
        return False

    if not hass.config.skip_pip and hasattr(component, 'REQUIREMENTS'):
        req_success = yield from _async_process_requirements(
            hass, domain, component.REQUIREMENTS)
        if not req_success:
            log_error("Could not install all requirements.")
            return False

    if hasattr(component, 'DEPENDENCIES'):
        dep_success = yield from _async_process_dependencies(
            hass, config, domain, component.DEPENDENCIES)

        if not dep_success:
            log_error("Could not setup all dependencies.")
            return False

    async_comp = hasattr(component, 'async_setup')

    _LOGGER.info("Setting up %s", domain)
    warn_task = hass.loop.call_later(SLOW_SETUP_WARNING, _LOGGER.warning,
                                     "Setup of %s is taking over %s seconds.",
                                     domain, SLOW_SETUP_WARNING)

    try:
        if async_comp:
            result = yield from component.async_setup(hass, processed_config)
        else:
            result = yield from hass.loop.run_in_executor(
                None, component.setup, hass, processed_config)
    except Exception:  # pylint: disable=broad-except
        _LOGGER.exception("Error during setup of component %s", domain)
        async_notify_setup_error(hass, domain, True)
        return False
    finally:
        warn_task.cancel()

    if result is False:
        log_error("Component failed to initialize.")
        return False
    elif result is not True:
        log_error("Component did not return boolean if setup was successful. "
                  "Disabling component.")
        loader.set_component(domain, None)
        return False

    hass.config.components.add(component.DOMAIN)

    # Cleanup
    if domain in hass.data[DATA_SETUP]:
        hass.data[DATA_SETUP].pop(domain)

    hass.bus.async_fire(EVENT_COMPONENT_LOADED,
                        {ATTR_COMPONENT: component.DOMAIN})

    return True
Example #11
0
def _async_setup_component(hass: core.HomeAssistant,
                           domain: str, config) -> bool:
    """Set up a component for Home Assistant.

    This method is a coroutine.
    """
    def log_error(msg, link=True):
        """Log helper."""
        _LOGGER.error("Setup failed for %s: %s", domain, msg)
        async_notify_setup_error(hass, domain, link)

    component = loader.get_component(domain)

    if not component:
        log_error("Component not found.", False)
        return False

    # Validate no circular dependencies
    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        log_error("Unable to resolve component or dependencies.")
        return False

    processed_config = \
        conf_util.async_process_component_config(hass, config, domain)

    if processed_config is None:
        log_error("Invalid config.")
        return False

    try:
        yield from async_process_deps_reqs(hass, config, domain, component)
    except HomeAssistantError as err:
        log_error(str(err))
        return False

    start = timer()
    _LOGGER.info("Setting up %s", domain)

    if hasattr(component, 'PLATFORM_SCHEMA'):
        # Entity components have their own warning
        warn_task = None
    else:
        warn_task = hass.loop.call_later(
            SLOW_SETUP_WARNING, _LOGGER.warning,
            "Setup of %s is taking over %s seconds.",
            domain, SLOW_SETUP_WARNING)

    try:
        if hasattr(component, 'async_setup'):
            result = yield from component.async_setup(hass, processed_config)
        else:
            result = yield from hass.async_add_job(
                component.setup, hass, processed_config)
    except Exception:  # pylint: disable=broad-except
        _LOGGER.exception("Error during setup of component %s", domain)
        async_notify_setup_error(hass, domain, True)
        return False
    finally:
        end = timer()
        if warn_task:
            warn_task.cancel()
    _LOGGER.info("Setup of domain %s took %.1f seconds.", domain, end - start)

    if result is False:
        log_error("Component failed to initialize.")
        return False
    elif result is not True:
        log_error("Component did not return boolean if setup was successful. "
                  "Disabling component.")
        loader.set_component(domain, None)
        return False

    for entry in hass.config_entries.async_entries(domain):
        yield from entry.async_setup(hass, component=component)

    hass.config.components.add(component.DOMAIN)

    # Cleanup
    if domain in hass.data[DATA_SETUP]:
        hass.data[DATA_SETUP].pop(domain)

    hass.bus.async_fire(
        EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN}
    )

    return True
Example #12
0
def _async_setup_component(hass: core.HomeAssistant,
                           domain: str, config) -> bool:
    """Setup a component for Home Assistant.

    This method is a coroutine.

    hass: Home Assistant instance.
    domain: Domain of component to setup.
    config: The Home Assistant configuration.
    """
    def log_error(msg, link=True):
        """Log helper."""
        _LOGGER.error('Setup failed for %s: %s', domain, msg)
        async_notify_setup_error(hass, domain, link)

    component = loader.get_component(domain)

    if not component:
        log_error('Component not found.', False)
        return False

    # Validate no circular dependencies
    components = loader.load_order_component(domain)

    # OrderedSet is empty if component or dependencies could not be resolved
    if not components:
        log_error('Unable to resolve component or dependencies.')
        return False

    processed_config = \
        conf_util.async_process_component_config(hass, config, domain)

    if processed_config is None:
        log_error('Invalid config.')
        return False

    if not hass.config.skip_pip and hasattr(component, 'REQUIREMENTS'):
        req_success = yield from _async_process_requirements(
            hass, domain, component.REQUIREMENTS)
        if not req_success:
            log_error('Could not install all requirements.')
            return False

    if hasattr(component, 'DEPENDENCIES'):
        dep_success = yield from _async_process_dependencies(
            hass, config, domain, component.DEPENDENCIES)

        if not dep_success:
            log_error('Could not setup all dependencies.')
            return False

    async_comp = hasattr(component, 'async_setup')

    _LOGGER.info("Setting up %s", domain)
    warn_task = hass.loop.call_later(
        SLOW_SETUP_WARNING, _LOGGER.warning,
        'Setup of %s is taking over %s seconds.', domain, SLOW_SETUP_WARNING)

    try:
        if async_comp:
            result = yield from component.async_setup(hass, processed_config)
        else:
            result = yield from hass.loop.run_in_executor(
                None, component.setup, hass, processed_config)
    except Exception:  # pylint: disable=broad-except
        _LOGGER.exception('Error during setup of component %s', domain)
        async_notify_setup_error(hass, domain, True)
        return False
    finally:
        warn_task.cancel()

    if result is False:
        log_error('Component failed to initialize.')
        return False
    elif result is not True:
        log_error('Component did not return boolean if setup was successful. '
                  'Disabling component.')
        loader.set_component(domain, None)
        return False

    hass.config.components.add(component.DOMAIN)

    # cleanup
    if domain in hass.data[DATA_SETUP]:
        hass.data[DATA_SETUP].pop(domain)

    hass.bus.async_fire(
        EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN}
    )

    return True