plugin_manager.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. # -*- coding: utf-8 -*-
  2. """
  3. PluginManager für das dynamische Laden und Verwalten von Plugins.
  4. """
  5. import importlib.util
  6. import json
  7. import sys
  8. from pathlib import Path
  9. from typing import Type, TYPE_CHECKING
  10. from trixy_core.plugins.trixy_plugin import TrixyPlugin
  11. from trixy_core.utils.debug import pinfo, pdebug, perror, pwarn
  12. if TYPE_CHECKING:
  13. from trixy_core.application import IApplication
  14. # Lazy import für Intent-System (verhindert zirkuläre Imports)
  15. _intent_registry = None
  16. _discover_handlers = None
  17. def _get_intent_registry():
  18. """Gibt die IntentRegistry-Instanz zurück (lazy loading)."""
  19. global _intent_registry
  20. if _intent_registry is None:
  21. from trixy_core.nlp.intent_registry import IntentRegistry
  22. _intent_registry = IntentRegistry.get_instance()
  23. return _intent_registry
  24. def _get_discover_handlers():
  25. """Gibt die discover_intent_handlers Funktion zurück (lazy loading)."""
  26. global _discover_handlers
  27. if _discover_handlers is None:
  28. from trixy_core.nlp.decorators import discover_intent_handlers
  29. _discover_handlers = discover_intent_handlers
  30. return _discover_handlers
  31. class PluginManager:
  32. """
  33. Verwaltet das Laden, Aktivieren und Deaktivieren von Plugins.
  34. Plugins werden aus dem konfigurierten Verzeichnis geladen.
  35. Jedes Plugin muss in einem eigenen Unterverzeichnis liegen
  36. mit einer main.py und optionaler config.json.
  37. """
  38. DEFAULT_DIRECTORY = "plugins"
  39. def __init__(
  40. self,
  41. application: "IApplication",
  42. directory: str | Path = DEFAULT_DIRECTORY
  43. ) -> None:
  44. """
  45. Initialisiert den PluginManager.
  46. Args:
  47. application: Referenz zur Hauptanwendung
  48. directory: Plugin-Verzeichnis
  49. """
  50. self._application = application
  51. self._directory = Path(directory)
  52. self._plugins: dict[str, TrixyPlugin] = {}
  53. self._failed_plugins: dict[str, str] = {} # Name -> Fehler
  54. @property
  55. def count(self) -> int:
  56. """Anzahl geladener Plugins."""
  57. return len(self._plugins)
  58. @property
  59. def enabled_count(self) -> int:
  60. """Anzahl aktivierter Plugins."""
  61. return sum(1 for p in self._plugins.values() if p.is_enabled())
  62. def get(self, name: str) -> TrixyPlugin | None:
  63. """
  64. Gibt ein Plugin nach Namen zurück.
  65. Args:
  66. name: Plugin-Name
  67. Returns:
  68. Plugin oder None
  69. """
  70. return self._plugins.get(name)
  71. def get_all(self) -> list[TrixyPlugin]:
  72. """Gibt alle geladenen Plugins zurück."""
  73. return list(self._plugins.values())
  74. def get_enabled(self) -> list[TrixyPlugin]:
  75. """Gibt alle aktivierten Plugins zurück."""
  76. return [p for p in self._plugins.values() if p.is_enabled()]
  77. def get_failed(self) -> dict[str, str]:
  78. """Gibt fehlgeschlagene Plugins mit Fehlern zurück."""
  79. return self._failed_plugins.copy()
  80. async def load_all(self) -> int:
  81. """
  82. Lädt alle Plugins aus dem Plugin-Verzeichnis.
  83. Returns:
  84. Anzahl erfolgreich geladener Plugins
  85. """
  86. if not self._directory.exists():
  87. self._directory.mkdir(parents=True, exist_ok=True)
  88. pinfo(f"Plugin-Verzeichnis erstellt: {self._directory}")
  89. return 0
  90. loaded = 0
  91. for plugin_dir in self._directory.iterdir():
  92. if not plugin_dir.is_dir():
  93. continue
  94. if plugin_dir.name.startswith("_") or plugin_dir.name.startswith("."):
  95. continue
  96. if await self.load(plugin_dir.name):
  97. loaded += 1
  98. pinfo(f"{loaded} Plugins geladen")
  99. return loaded
  100. async def load(self, name: str) -> bool:
  101. """
  102. Lädt ein einzelnes Plugin.
  103. Args:
  104. name: Name des Plugin-Verzeichnisses
  105. Returns:
  106. True bei Erfolg
  107. """
  108. plugin_dir = self._directory / name
  109. main_file = plugin_dir / "main.py"
  110. config_file = plugin_dir / "config.json"
  111. if not plugin_dir.exists():
  112. perror(f"Plugin-Verzeichnis nicht gefunden: {plugin_dir}")
  113. self._failed_plugins[name] = "Verzeichnis nicht gefunden"
  114. return False
  115. if not main_file.exists():
  116. perror(f"main.py nicht gefunden in: {plugin_dir}")
  117. self._failed_plugins[name] = "main.py nicht gefunden"
  118. return False
  119. try:
  120. # Konfiguration laden
  121. config = {}
  122. if config_file.exists():
  123. with open(config_file, "r", encoding="utf-8") as f:
  124. config = json.load(f)
  125. # Plugin-Modul laden
  126. spec = importlib.util.spec_from_file_location(
  127. f"trixy_plugins.{name}",
  128. main_file
  129. )
  130. if spec is None or spec.loader is None:
  131. raise ImportError(f"Kann Plugin-Spec nicht erstellen: {name}")
  132. module = importlib.util.module_from_spec(spec)
  133. sys.modules[spec.name] = module
  134. spec.loader.exec_module(module)
  135. # Plugin-Klasse finden
  136. plugin_class = self._find_plugin_class(module)
  137. if plugin_class is None:
  138. raise ImportError(f"Keine TrixyPlugin-Unterklasse gefunden in: {name}")
  139. # Prüfen ob Plugin aktiviert ist
  140. is_enabled = config.get("enabled", True)
  141. # Plugin instanziieren
  142. plugin = plugin_class(
  143. application=self._application,
  144. plugin_path=plugin_dir,
  145. config=config
  146. )
  147. # enabled-Status setzen
  148. plugin.enabled = is_enabled
  149. # Nur on_load und on_enable aufrufen wenn Plugin aktiviert ist
  150. if is_enabled:
  151. await plugin.on_load()
  152. plugin._loaded = True
  153. # Event-Handler registrieren
  154. if hasattr(self._application, "events"):
  155. self._application.events.register_object(plugin)
  156. # Intent-Handler registrieren
  157. self._register_intent_handlers(plugin)
  158. # on_enable aufrufen
  159. await plugin.on_enable()
  160. else:
  161. plugin._loaded = False
  162. self._plugins[plugin.name] = plugin
  163. self._failed_plugins.pop(name, None)
  164. if is_enabled:
  165. pinfo(f"Plugin geladen und aktiviert: {plugin.name} v{plugin.VERSION}")
  166. else:
  167. pdebug(f"Plugin registriert (deaktiviert): {plugin.name}")
  168. return True
  169. except Exception as e:
  170. error_msg = str(e)
  171. perror(f"Fehler beim Laden von Plugin '{name}': {error_msg}")
  172. self._failed_plugins[name] = error_msg
  173. return False
  174. def _find_plugin_class(self, module: object) -> Type[TrixyPlugin] | None:
  175. """Findet die Plugin-Klasse in einem Modul."""
  176. for attr_name in dir(module):
  177. if attr_name.startswith("_"):
  178. continue
  179. attr = getattr(module, attr_name)
  180. if (
  181. isinstance(attr, type) and
  182. issubclass(attr, TrixyPlugin) and
  183. attr is not TrixyPlugin
  184. ):
  185. return attr
  186. return None
  187. def _register_intent_handlers(self, plugin: TrixyPlugin) -> int:
  188. """
  189. Registriert alle Intent-Handler eines Plugins.
  190. Durchsucht das Plugin nach @intent dekorierten Methoden
  191. und registriert diese in der IntentRegistry.
  192. Args:
  193. plugin: Plugin-Instanz
  194. Returns:
  195. Anzahl registrierter Intents
  196. """
  197. try:
  198. discover_handlers = _get_discover_handlers()
  199. registry = _get_intent_registry()
  200. handlers = discover_handlers(plugin)
  201. count = 0
  202. for intent_name, handler, metadata in handlers:
  203. from trixy_core.nlp.intent_registry import IntentDefinition, IntentSlot
  204. # Intent-Definition erstellen
  205. intent_def = IntentDefinition(
  206. name=intent_name,
  207. handler=handler,
  208. plugin_name=plugin.name,
  209. slots=metadata.get("slots", {}),
  210. examples=metadata.get("examples", []),
  211. description=metadata.get("description", ""),
  212. priority=metadata.get("priority", 0),
  213. enabled=True,
  214. )
  215. if registry.register(intent_def):
  216. count += 1
  217. pdebug(f"Intent registriert: {intent_name} (Plugin: {plugin.name})")
  218. if count > 0:
  219. pinfo(f"{count} Intent(s) registriert für Plugin: {plugin.name}")
  220. return count
  221. except Exception as e:
  222. perror(f"Fehler beim Registrieren von Intent-Handlern für '{plugin.name}': {e}")
  223. return 0
  224. def _unregister_intent_handlers(self, plugin: TrixyPlugin) -> int:
  225. """
  226. Entfernt alle Intent-Handler eines Plugins.
  227. Args:
  228. plugin: Plugin-Instanz
  229. Returns:
  230. Anzahl entfernter Intents
  231. """
  232. try:
  233. registry = _get_intent_registry()
  234. count = registry.unregister_plugin(plugin.name)
  235. if count > 0:
  236. pdebug(f"{count} Intent(s) entfernt für Plugin: {plugin.name}")
  237. return count
  238. except Exception as e:
  239. perror(f"Fehler beim Entfernen von Intent-Handlern für '{plugin.name}': {e}")
  240. return 0
  241. async def unload(self, name: str) -> bool:
  242. """
  243. Entlädt ein Plugin.
  244. Args:
  245. name: Plugin-Name
  246. Returns:
  247. True bei Erfolg
  248. """
  249. plugin = self._plugins.get(name)
  250. if plugin is None:
  251. pwarn(f"Plugin nicht geladen: {name}")
  252. return False
  253. try:
  254. # Intent-Handler entfernen
  255. self._unregister_intent_handlers(plugin)
  256. # Event-Handler entfernen
  257. if hasattr(self._application, "events"):
  258. self._application.events.unregister_object(plugin)
  259. # on_unload aufrufen
  260. await plugin.on_unload()
  261. del self._plugins[name]
  262. # Modul aus sys.modules entfernen
  263. module_name = f"trixy_plugins.{name}"
  264. if module_name in sys.modules:
  265. del sys.modules[module_name]
  266. pinfo(f"Plugin entladen: {name}")
  267. return True
  268. except Exception as e:
  269. perror(f"Fehler beim Entladen von Plugin '{name}': {e}")
  270. return False
  271. async def reload(self, name: str) -> bool:
  272. """
  273. Lädt ein Plugin neu.
  274. Args:
  275. name: Plugin-Name
  276. Returns:
  277. True bei Erfolg
  278. """
  279. if name in self._plugins:
  280. await self.unload(name)
  281. return await self.load(name)
  282. async def enable(self, name: str) -> bool:
  283. """
  284. Aktiviert ein Plugin.
  285. Args:
  286. name: Plugin-Name
  287. Returns:
  288. True bei Erfolg
  289. """
  290. plugin = self._plugins.get(name)
  291. if plugin is None:
  292. pwarn(f"Plugin nicht geladen: {name}")
  293. return False
  294. if plugin.is_enabled():
  295. return True
  296. try:
  297. plugin.enabled = True
  298. # on_load aufrufen falls noch nicht geschehen
  299. # (bei Plugins die beim Start deaktiviert waren)
  300. if not hasattr(plugin, "_loaded") or not plugin._loaded:
  301. await plugin.on_load()
  302. plugin._loaded = True
  303. # Event-Handler registrieren
  304. if hasattr(self._application, "events"):
  305. self._application.events.register_object(plugin)
  306. # Intent-Handler registrieren
  307. self._register_intent_handlers(plugin)
  308. await plugin.on_enable()
  309. pinfo(f"Plugin aktiviert: {name}")
  310. return True
  311. except Exception as e:
  312. perror(f"Fehler beim Aktivieren von Plugin '{name}': {e}")
  313. plugin.enabled = False
  314. return False
  315. async def disable(self, name: str) -> bool:
  316. """
  317. Deaktiviert ein Plugin.
  318. Args:
  319. name: Plugin-Name
  320. Returns:
  321. True bei Erfolg
  322. """
  323. plugin = self._plugins.get(name)
  324. if plugin is None:
  325. pwarn(f"Plugin nicht geladen: {name}")
  326. return False
  327. if not plugin.is_enabled():
  328. return True
  329. try:
  330. await plugin.on_disable()
  331. plugin.enabled = False
  332. pinfo(f"Plugin deaktiviert: {name}")
  333. return True
  334. except Exception as e:
  335. perror(f"Fehler beim Deaktivieren von Plugin '{name}': {e}")
  336. return False
  337. async def unload_all(self) -> int:
  338. """
  339. Entlädt alle Plugins.
  340. Returns:
  341. Anzahl entladener Plugins
  342. """
  343. count = 0
  344. for name in list(self._plugins.keys()):
  345. if await self.unload(name):
  346. count += 1
  347. return count
  348. def __contains__(self, name: str) -> bool:
  349. """Prüft, ob ein Plugin geladen ist."""
  350. return name in self._plugins
  351. def __getitem__(self, name: str) -> TrixyPlugin:
  352. """Gibt ein Plugin nach Namen zurück."""
  353. if name not in self._plugins:
  354. raise KeyError(f"Plugin nicht gefunden: {name}")
  355. return self._plugins[name]
  356. def __iter__(self):
  357. """Iterator über alle Plugins."""
  358. return iter(self._plugins.values())
  359. def __len__(self) -> int:
  360. """Anzahl geladener Plugins."""
  361. return len(self._plugins)