2020-07-07 00:58:53 +02:00
|
|
|
"""Run Home Assistant."""
|
2021-03-17 17:34:55 +01:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2020-07-07 00:58:53 +02:00
|
|
|
import asyncio
|
|
|
|
import dataclasses
|
|
|
|
import logging
|
2021-04-18 20:55:51 +02:00
|
|
|
import threading
|
2021-10-19 05:07:51 +02:00
|
|
|
import traceback
|
2021-03-17 17:34:55 +01:00
|
|
|
from typing import Any
|
2020-07-07 00:58:53 +02:00
|
|
|
|
2021-12-23 20:14:47 +01:00
|
|
|
from . import bootstrap
|
|
|
|
from .core import callback
|
|
|
|
from .helpers.frame import warn_use
|
|
|
|
from .util.executor import InterruptibleThreadPoolExecutor
|
|
|
|
from .util.thread import deadlock_safe_shutdown
|
2020-07-07 00:58:53 +02:00
|
|
|
|
2020-08-13 10:12:18 +02:00
|
|
|
#
|
2022-01-30 22:07:07 +01:00
|
|
|
# Some Python versions may have different number of workers by default
|
|
|
|
# than others. In order to be consistent between
|
2020-08-13 10:12:18 +02:00
|
|
|
# supported versions, we need to set max_workers.
|
|
|
|
#
|
|
|
|
# In most cases the workers are not I/O bound, as they
|
|
|
|
# are sleeping/blocking waiting for data from integrations
|
|
|
|
# updating so this number should be higher than the default
|
|
|
|
# use case.
|
|
|
|
#
|
|
|
|
MAX_EXECUTOR_WORKERS = 64
|
2021-09-21 23:35:14 +02:00
|
|
|
TASK_CANCELATION_TIMEOUT = 5
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2020-08-13 10:12:18 +02:00
|
|
|
|
2020-07-07 00:58:53 +02:00
|
|
|
|
|
|
|
@dataclasses.dataclass
|
|
|
|
class RuntimeConfig:
|
|
|
|
"""Class to hold the information for running Home Assistant."""
|
|
|
|
|
|
|
|
config_dir: str
|
|
|
|
skip_pip: bool = False
|
2022-11-30 08:38:52 +01:00
|
|
|
skip_pip_packages: list[str] = dataclasses.field(default_factory=list)
|
2020-07-07 00:58:53 +02:00
|
|
|
safe_mode: bool = False
|
|
|
|
|
|
|
|
verbose: bool = False
|
|
|
|
|
2021-03-17 17:34:55 +01:00
|
|
|
log_rotate_days: int | None = None
|
|
|
|
log_file: str | None = None
|
2020-07-07 00:58:53 +02:00
|
|
|
log_no_color: bool = False
|
|
|
|
|
|
|
|
debug: bool = False
|
|
|
|
open_ui: bool = False
|
|
|
|
|
|
|
|
|
2022-04-28 03:49:54 +02:00
|
|
|
class HassEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
|
2020-07-07 00:58:53 +02:00
|
|
|
"""Event loop policy for Home Assistant."""
|
|
|
|
|
|
|
|
def __init__(self, debug: bool) -> None:
|
|
|
|
"""Init the event loop policy."""
|
|
|
|
super().__init__()
|
|
|
|
self.debug = debug
|
|
|
|
|
|
|
|
@property
|
|
|
|
def loop_name(self) -> str:
|
|
|
|
"""Return name of the loop."""
|
2022-04-28 03:49:54 +02:00
|
|
|
return self._loop_factory.__name__ # type: ignore[no-any-return,attr-defined]
|
2020-07-07 00:58:53 +02:00
|
|
|
|
2020-07-22 17:06:37 +02:00
|
|
|
def new_event_loop(self) -> asyncio.AbstractEventLoop:
|
2020-07-07 00:58:53 +02:00
|
|
|
"""Get the event loop."""
|
2020-07-22 17:06:37 +02:00
|
|
|
loop: asyncio.AbstractEventLoop = super().new_event_loop()
|
2020-07-07 00:58:53 +02:00
|
|
|
loop.set_exception_handler(_async_loop_exception_handler)
|
|
|
|
if self.debug:
|
|
|
|
loop.set_debug(True)
|
|
|
|
|
2021-04-18 20:55:51 +02:00
|
|
|
executor = InterruptibleThreadPoolExecutor(
|
2020-08-13 10:12:18 +02:00
|
|
|
thread_name_prefix="SyncWorker", max_workers=MAX_EXECUTOR_WORKERS
|
|
|
|
)
|
2020-07-07 00:58:53 +02:00
|
|
|
loop.set_default_executor(executor)
|
2022-02-18 08:09:22 +01:00
|
|
|
loop.set_default_executor = warn_use( # type: ignore[assignment]
|
2020-07-07 00:58:53 +02:00
|
|
|
loop.set_default_executor, "sets default executor on the event loop"
|
|
|
|
)
|
|
|
|
return loop
|
|
|
|
|
|
|
|
|
|
|
|
@callback
|
2021-03-17 17:34:55 +01:00
|
|
|
def _async_loop_exception_handler(_: Any, context: dict[str, Any]) -> None:
|
2020-07-07 00:58:53 +02:00
|
|
|
"""Handle all exception inside the core loop."""
|
|
|
|
kwargs = {}
|
2021-10-17 20:08:11 +02:00
|
|
|
if exception := context.get("exception"):
|
2020-07-07 00:58:53 +02:00
|
|
|
kwargs["exc_info"] = (type(exception), exception, exception.__traceback__)
|
|
|
|
|
2021-10-19 05:07:51 +02:00
|
|
|
logger = logging.getLogger(__package__)
|
|
|
|
if source_traceback := context.get("source_traceback"):
|
|
|
|
stack_summary = "".join(traceback.format_list(source_traceback))
|
|
|
|
logger.error(
|
2022-02-18 08:09:22 +01:00
|
|
|
"Error doing job: %s: %s", context["message"], stack_summary, **kwargs # type: ignore[arg-type]
|
2021-10-19 05:07:51 +02:00
|
|
|
)
|
|
|
|
return
|
|
|
|
|
2022-02-18 08:09:22 +01:00
|
|
|
logger.error("Error doing job: %s", context["message"], **kwargs) # type: ignore[arg-type]
|
2020-07-07 00:58:53 +02:00
|
|
|
|
|
|
|
|
2020-08-29 07:59:24 +02:00
|
|
|
async def setup_and_run_hass(runtime_config: RuntimeConfig) -> int:
|
2020-07-07 00:58:53 +02:00
|
|
|
"""Set up Home Assistant and run."""
|
|
|
|
hass = await bootstrap.async_setup_hass(runtime_config)
|
|
|
|
|
|
|
|
if hass is None:
|
|
|
|
return 1
|
|
|
|
|
2021-04-18 20:55:51 +02:00
|
|
|
# threading._shutdown can deadlock forever
|
|
|
|
threading._shutdown = deadlock_safe_shutdown # type: ignore[attr-defined] # pylint: disable=protected-access
|
|
|
|
|
2020-07-07 00:58:53 +02:00
|
|
|
return await hass.async_run()
|
|
|
|
|
|
|
|
|
|
|
|
def run(runtime_config: RuntimeConfig) -> int:
|
|
|
|
"""Run Home Assistant."""
|
|
|
|
asyncio.set_event_loop_policy(HassEventLoopPolicy(runtime_config.debug))
|
2021-09-21 23:35:14 +02:00
|
|
|
# Backport of cpython 3.9 asyncio.run with a _cancel_all_tasks that times out
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
try:
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
return loop.run_until_complete(setup_and_run_hass(runtime_config))
|
|
|
|
finally:
|
|
|
|
try:
|
|
|
|
_cancel_all_tasks_with_timeout(loop, TASK_CANCELATION_TIMEOUT)
|
|
|
|
loop.run_until_complete(loop.shutdown_asyncgens())
|
2022-01-30 22:07:07 +01:00
|
|
|
loop.run_until_complete(loop.shutdown_default_executor())
|
2021-09-21 23:35:14 +02:00
|
|
|
finally:
|
|
|
|
asyncio.set_event_loop(None)
|
|
|
|
loop.close()
|
|
|
|
|
|
|
|
|
|
|
|
def _cancel_all_tasks_with_timeout(
|
|
|
|
loop: asyncio.AbstractEventLoop, timeout: int
|
|
|
|
) -> None:
|
|
|
|
"""Adapted _cancel_all_tasks from python 3.9 with a timeout."""
|
|
|
|
to_cancel = asyncio.all_tasks(loop)
|
|
|
|
if not to_cancel:
|
|
|
|
return
|
|
|
|
|
|
|
|
for task in to_cancel:
|
|
|
|
task.cancel()
|
|
|
|
|
|
|
|
loop.run_until_complete(asyncio.wait(to_cancel, timeout=timeout))
|
|
|
|
|
|
|
|
for task in to_cancel:
|
|
|
|
if task.cancelled():
|
|
|
|
continue
|
|
|
|
if not task.done():
|
|
|
|
_LOGGER.warning(
|
|
|
|
"Task could not be canceled and was still running after shutdown: %s",
|
|
|
|
task,
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
if task.exception() is not None:
|
|
|
|
loop.call_exception_handler(
|
|
|
|
{
|
|
|
|
"message": "unhandled exception during shutdown",
|
|
|
|
"exception": task.exception(),
|
|
|
|
"task": task,
|
|
|
|
}
|
|
|
|
)
|