initial manager work
This commit is contained in:
1 parent
08af01dd11
commit
7aadfbc175
15 files changed
+217
-80
No files matched your search
@@ -2,6 +2,7 @@ from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from src.logger import get_logger
|
||||
from ...utils import extract_files
|
||||
|
||||
from ..db import AutomationDBConnection, DBError
|
||||
from ..loader import load_automation_path
|
||||
@@ -17,30 +18,37 @@ class AutomationEventHandler(BaseFileEventHandler):
|
||||
def __init__(self, automation_file: Path, automation_db_path: Path, **kwrgs) -> None:
|
||||
self.__automation_file = automation_file.absolute()
|
||||
self.__automation_db = AutomationDBConnection(automation_db_path)
|
||||
self.__loaded_automations: Optional[List[ExtenededAutomationData]] = None
|
||||
super().__init__(**kwrgs)
|
||||
|
||||
def should_reload(self, p: Path) -> bool:
|
||||
return p.absolute() == self.__automation_file
|
||||
def reload_file(self, file_path: Optional[Path], deleted: bool):
|
||||
if file_path is None:
|
||||
file_path = self.__automation_file
|
||||
|
||||
def reload_file(self):
|
||||
automations = list(load_automation_path(self.__automation_file))
|
||||
self.__automation_db.upsert_automations(automations)
|
||||
self.__loaded_automations = automations
|
||||
self.clear_automations(file_path)
|
||||
|
||||
if not deleted:
|
||||
automations = list(load_automation_path(file_path))
|
||||
self.__automation_db.upsert_automations(automations)
|
||||
|
||||
def clear_automations(self, file_path: Path):
|
||||
if file_path.is_dir():
|
||||
for f in extract_files(file_path):
|
||||
self.__automation_db.delete_automations_in_source_file(f)
|
||||
else:
|
||||
self.__automation_db.delete_automations_in_source_file(file_path)
|
||||
|
||||
def handle_failure(self, error: Exception):
|
||||
logger.error(error)
|
||||
if isinstance(error, DBError):
|
||||
logger.warning(f"Failed to reload {self.__automation_file} due to {error}")
|
||||
logger.warning(f"Failed to reload {self.__automation_file} due to {repr(error)}")
|
||||
else:
|
||||
logger.warning(f"Failed to load {self.__automation_file} due to {error}")
|
||||
if self.__loaded_automations is not None:
|
||||
try:
|
||||
self.__automation_db.delete_automations(self.__loaded_automations)
|
||||
except DBError as err:
|
||||
raise FailedDeletion(
|
||||
f"failed to flush automations from database for the invalid file {self.__automation_file} due to {err}"
|
||||
) from err
|
||||
logger.warning(f"Failed to load {self.__automation_file} due to {repr(error)}")
|
||||
try:
|
||||
self.clear_automations(self.__automation_file)
|
||||
except DBError as err:
|
||||
raise FailedDeletion(
|
||||
f"failed to flush automations from database for the invalid file {self.__automation_file} due to {repr(err)}"
|
||||
) from err
|
||||
|
||||
|
||||
class AutomationFileWatcher(BaseWatcher):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import abc
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
import nest_asyncio
|
||||
|
||||
from threading import Event
|
||||
@@ -20,12 +21,9 @@ class BaseFileEventHandler(FileSystemEventHandler, abc.ABC):
|
||||
self.event_loaded = event_loaded
|
||||
self.event_errored = event_errored
|
||||
super().__init__()
|
||||
asyncio.run(self._reload_file())
|
||||
asyncio.run(self._reload_file(None, False))
|
||||
|
||||
def should_reload(self, p: Path) -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
def reload_file(self):
|
||||
def reload_file(self, file_path: Optional[Path], deleted: bool):
|
||||
raise NotImplementedError
|
||||
|
||||
def handle_failure(self, error: Exception):
|
||||
@@ -33,9 +31,9 @@ class BaseFileEventHandler(FileSystemEventHandler, abc.ABC):
|
||||
raise error from error
|
||||
|
||||
@throttle(seconds=60)
|
||||
def _reload_file(self):
|
||||
def _reload_file(self, file_path: Optional[Path], deleted: bool):
|
||||
try:
|
||||
self.reload_file()
|
||||
self.reload_file(file_path, deleted)
|
||||
except Exception as err:
|
||||
self.event_errored.set()
|
||||
self.handle_failure(err)
|
||||
@@ -43,15 +41,12 @@ class BaseFileEventHandler(FileSystemEventHandler, abc.ABC):
|
||||
|
||||
def on_modified(self, event: FileSystemEvent):
|
||||
logger.info(f"on_modified: {event.event_type} path : {event.src_path}")
|
||||
if self.should_reload(Path(event.src_path)):
|
||||
asyncio.run(self._reload_file())
|
||||
asyncio.run(self._reload_file(Path(event.src_path), False))
|
||||
|
||||
def on_created(self, event: FileSystemEvent):
|
||||
logger.info(f"on_created: {event.event_type} path : {event.src_path}")
|
||||
if self.should_reload(Path(event.src_path)):
|
||||
asyncio.run(self._reload_file())
|
||||
asyncio.run(self._reload_file(Path(event.src_path), False))
|
||||
|
||||
def on_deleted(self, event: FileSystemEvent):
|
||||
logger.info(f"on_deleted: {event.event_type} path : {event.src_path}")
|
||||
if self.should_reload(Path(event.src_path)):
|
||||
asyncio.run(self._reload_file())
|
||||
asyncio.run(self._reload_file(Path(event.src_path), True))
|
||||
@@ -22,13 +22,14 @@ class BaseWatcher(Observer, abc.ABC, Generic[BaseFileEventHandlerT]):
|
||||
self.__event_errored = Event()
|
||||
Observer.__init__(self)
|
||||
self.handler: Optional[BaseFileEventHandlerT] = None
|
||||
self.name = f"{self.__class__.__name__}-{self.file_path}-{self.name}"
|
||||
|
||||
def start(self):
|
||||
self.handler = self.get_handler(
|
||||
event_errored=self.__event_errored,
|
||||
event_loaded=self.__event_file_loaded,
|
||||
)
|
||||
self.schedule(self.handler, self.file_path)
|
||||
self.schedule(self.handler, self.file_path, recursive=self.file_path.is_dir())
|
||||
return super().start()
|
||||
|
||||
def get_handler(self, event_loaded: Event, event_errored: Event) -> BaseFileEventHandlerT:
|
||||
@@ -51,6 +52,14 @@ class BaseWatcher(Observer, abc.ABC, Generic[BaseFileEventHandlerT]):
|
||||
if self.handler is not None:
|
||||
self._post_stop(self.handler)
|
||||
|
||||
@property
|
||||
def is_loaded(self):
|
||||
return self.__event_file_loaded.is_set()
|
||||
|
||||
@property
|
||||
def is_errored(self):
|
||||
return self.__event_errored.is_set()
|
||||
|
||||
def wait_until_next_reload(self, reset_after: bool = False, *, timeout: int = 5):
|
||||
self.__event_file_loaded.wait(timeout)
|
||||
if reset_after:
|
||||
|
||||
@@ -21,16 +21,20 @@ class ConfigEventHandler(BaseFileEventHandler):
|
||||
def __init__(self, config_path: Path, db_path: Path, **kwargs) -> None:
|
||||
self.__db = AutomationDBConnection(db_path)
|
||||
self.__config_path = config_path
|
||||
self.__hass_config = HassConfig(self.__config_path)
|
||||
self.__hass_config = HassConfig(self.__config_path.parent)
|
||||
self.__automation_watchers: List[AutomationFileWatcher] = []
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def should_reload(self, p: Path) -> bool:
|
||||
return p.absolute() == self.__config_path
|
||||
|
||||
def reload_file(self):
|
||||
def reload_file(self, file_path: Path, deleted: bool):
|
||||
if file_path is None:
|
||||
file_path = self.__config_path
|
||||
if file_path.absolute() != self.__config_path:
|
||||
return
|
||||
self.clear_automation_watchers()
|
||||
self.__db.reset()
|
||||
if deleted:
|
||||
logger.error("Could not detect your configuration.yaml file, was is deleted?")
|
||||
return
|
||||
for p in extract_automation_paths(self.__hass_config):
|
||||
watcher = AutomationFileWatcher(automation_file=p, automation_db_path=self.__db.db_file)
|
||||
watcher.start()
|
||||
|
||||
Reference in new issue
Block a user