script.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # -*- coding: utf-8 -*-
  2. """
  3. Script Condition - Führt Python-Script aus und prüft Rückgabewert.
  4. """
  5. import asyncio
  6. import os
  7. import sys
  8. from typing import Any
  9. from trixy_core.scheduler.condition.base import Condition
  10. class ScriptCondition(Condition):
  11. """
  12. Führt ein Python-Script aus und prüft den Rückgabewert.
  13. Das Script kann:
  14. - Einen Boolean zurückgeben (True/False)
  15. - Einen Wert zurückgeben der mit expected verglichen wird
  16. - exit(0) für True, exit(1) für False
  17. Beispiel:
  18. ```python
  19. # check_temperature.py
  20. import requests
  21. temp = requests.get("http://sensor/temp").json()["value"]
  22. return temp > 20 # oder: exit(0 if temp > 20 else 1)
  23. ```
  24. ScriptCondition("scripts/check_temperature.py")
  25. ScriptCondition("scripts/get_value.py", expected=42)
  26. """
  27. def __init__(
  28. self,
  29. script_path: str | None = None,
  30. script_code: str | None = None,
  31. expected: Any = True,
  32. timeout_seconds: float = 30.0,
  33. pass_context: bool = False,
  34. name: str | None = None,
  35. invert: bool = False,
  36. ):
  37. """
  38. Initialisiert die Condition.
  39. Args:
  40. script_path: Pfad zum Python-Script
  41. script_code: Inline Python-Code (alternativ zu script_path)
  42. expected: Erwarteter Rückgabewert (default: True)
  43. timeout_seconds: Timeout für Script-Ausführung
  44. pass_context: Kontext als Variable 'context' verfügbar machen
  45. name: Condition-Name
  46. invert: Ergebnis invertieren
  47. """
  48. super().__init__(name, invert)
  49. if not script_path and not script_code:
  50. raise ValueError("script_path oder script_code muss angegeben werden")
  51. self._script_path = script_path
  52. self._script_code = script_code
  53. self._expected = expected
  54. self._timeout_seconds = timeout_seconds
  55. self._pass_context = pass_context
  56. @property
  57. def script_path(self) -> str | None:
  58. """Script-Pfad."""
  59. return self._script_path
  60. @property
  61. def expected(self) -> Any:
  62. """Erwarteter Wert."""
  63. return self._expected
  64. def _get_script_code(self) -> str:
  65. """Lädt Script-Code."""
  66. if self._script_code:
  67. return self._script_code
  68. if self._script_path and os.path.isfile(self._script_path):
  69. with open(self._script_path, "r", encoding="utf-8") as f:
  70. return f.read()
  71. raise FileNotFoundError(f"Script nicht gefunden: {self._script_path}")
  72. def _evaluate(self, context: dict) -> bool:
  73. """Führt Script aus und prüft Ergebnis."""
  74. try:
  75. code = self._get_script_code()
  76. # Globale Variablen für Script
  77. script_globals = {
  78. "__builtins__": __builtins__,
  79. "__name__": "__script__",
  80. "__file__": self._script_path or "<inline>",
  81. }
  82. # Kontext verfügbar machen
  83. if self._pass_context:
  84. script_globals["context"] = context
  85. # Lokale Variablen
  86. script_locals: dict[str, Any] = {}
  87. # Script ausführen
  88. exec(code, script_globals, script_locals)
  89. # Rückgabewert suchen
  90. # 1. Explizite 'result' Variable
  91. if "result" in script_locals:
  92. result = script_locals["result"]
  93. # 2. Funktion 'check()' oder 'evaluate()'
  94. elif "check" in script_locals and callable(script_locals["check"]):
  95. result = script_locals["check"]()
  96. elif "evaluate" in script_locals and callable(script_locals["evaluate"]):
  97. result = script_locals["evaluate"]()
  98. # 3. Funktion 'main()'
  99. elif "main" in script_locals and callable(script_locals["main"]):
  100. result = script_locals["main"]()
  101. else:
  102. # Kein expliziter Rückgabewert = True (Script lief durch)
  103. result = True
  104. # Vergleich
  105. if self._expected is True:
  106. return bool(result)
  107. elif self._expected is False:
  108. return not bool(result)
  109. else:
  110. return result == self._expected
  111. except SystemExit as e:
  112. # exit(0) = True, exit(1) = False
  113. exit_code = e.code if e.code is not None else 0
  114. return exit_code == 0
  115. except Exception as e:
  116. from trixy_core.utils.debug import perror
  117. perror(f"Script-Fehler: {e}")
  118. return False
  119. def to_dict(self) -> dict:
  120. """Konvertiert zu Dictionary."""
  121. return {
  122. **self._base_dict(),
  123. "script_path": self._script_path,
  124. "script_code": self._script_code,
  125. "expected": self._expected,
  126. "timeout_seconds": self._timeout_seconds,
  127. "pass_context": self._pass_context,
  128. }
  129. @classmethod
  130. def from_dict(cls, data: dict) -> "ScriptCondition":
  131. """Erstellt Condition aus Dictionary."""
  132. return cls(
  133. script_path=data.get("script_path"),
  134. script_code=data.get("script_code"),
  135. expected=data.get("expected", True),
  136. timeout_seconds=data.get("timeout_seconds", 30.0),
  137. pass_context=data.get("pass_context", False),
  138. name=data.get("name"),
  139. invert=data.get("invert", False),
  140. )
  141. class AsyncScriptCondition(Condition):
  142. """
  143. Führt ein async Python-Script aus.
  144. Beispiel:
  145. ```python
  146. # async_check.py
  147. import aiohttp
  148. async def check():
  149. async with aiohttp.ClientSession() as session:
  150. async with session.get("http://api/status") as resp:
  151. data = await resp.json()
  152. return data["status"] == "ok"
  153. ```
  154. """
  155. def __init__(
  156. self,
  157. script_path: str | None = None,
  158. script_code: str | None = None,
  159. expected: Any = True,
  160. timeout_seconds: float = 30.0,
  161. name: str | None = None,
  162. invert: bool = False,
  163. ):
  164. """
  165. Initialisiert die Condition.
  166. Args:
  167. script_path: Pfad zum Python-Script
  168. script_code: Inline Python-Code
  169. expected: Erwarteter Rückgabewert
  170. timeout_seconds: Timeout
  171. name: Condition-Name
  172. invert: Ergebnis invertieren
  173. """
  174. super().__init__(name, invert)
  175. if not script_path and not script_code:
  176. raise ValueError("script_path oder script_code muss angegeben werden")
  177. self._script_path = script_path
  178. self._script_code = script_code
  179. self._expected = expected
  180. self._timeout_seconds = timeout_seconds
  181. def _evaluate(self, context: dict) -> bool:
  182. """Führt async Script aus."""
  183. try:
  184. # Event-Loop holen oder erstellen
  185. try:
  186. loop = asyncio.get_running_loop()
  187. # Wir sind bereits in einem Loop - synchron ausführen
  188. return self._evaluate_sync(context)
  189. except RuntimeError:
  190. # Kein laufender Loop - neuen erstellen
  191. return asyncio.run(self._evaluate_async(context))
  192. except Exception as e:
  193. from trixy_core.utils.debug import perror
  194. perror(f"Async Script-Fehler: {e}")
  195. return False
  196. def _evaluate_sync(self, context: dict) -> bool:
  197. """Synchrone Evaluation (Fallback)."""
  198. # Nutze reguläre ScriptCondition
  199. sync_cond = ScriptCondition(
  200. script_path=self._script_path,
  201. script_code=self._script_code,
  202. expected=self._expected,
  203. )
  204. return sync_cond._evaluate(context)
  205. async def _evaluate_async(self, context: dict) -> bool:
  206. """Asynchrone Evaluation."""
  207. code = self._get_script_code()
  208. script_globals = {
  209. "__builtins__": __builtins__,
  210. "asyncio": asyncio,
  211. "context": context,
  212. }
  213. script_locals: dict[str, Any] = {}
  214. exec(code, script_globals, script_locals)
  215. # Async Funktion suchen
  216. check_fn = None
  217. for name in ["check", "evaluate", "main"]:
  218. if name in script_locals and asyncio.iscoroutinefunction(script_locals[name]):
  219. check_fn = script_locals[name]
  220. break
  221. if check_fn:
  222. result = await asyncio.wait_for(
  223. check_fn(),
  224. timeout=self._timeout_seconds,
  225. )
  226. else:
  227. result = script_locals.get("result", True)
  228. if self._expected is True:
  229. return bool(result)
  230. elif self._expected is False:
  231. return not bool(result)
  232. else:
  233. return result == self._expected
  234. def _get_script_code(self) -> str:
  235. """Lädt Script-Code."""
  236. if self._script_code:
  237. return self._script_code
  238. if self._script_path and os.path.isfile(self._script_path):
  239. with open(self._script_path, "r", encoding="utf-8") as f:
  240. return f.read()
  241. raise FileNotFoundError(f"Script nicht gefunden: {self._script_path}")
  242. def to_dict(self) -> dict:
  243. """Konvertiert zu Dictionary."""
  244. return {
  245. **self._base_dict(),
  246. "script_path": self._script_path,
  247. "script_code": self._script_code,
  248. "expected": self._expected,
  249. "timeout_seconds": self._timeout_seconds,
  250. }
  251. @classmethod
  252. def from_dict(cls, data: dict) -> "AsyncScriptCondition":
  253. """Erstellt Condition aus Dictionary."""
  254. return cls(
  255. script_path=data.get("script_path"),
  256. script_code=data.get("script_code"),
  257. expected=data.get("expected", True),
  258. timeout_seconds=data.get("timeout_seconds", 30.0),
  259. name=data.get("name"),
  260. invert=data.get("invert", False),
  261. )