scheduler.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. # -*- coding: utf-8 -*-
  2. """
  3. Scheduler - Hauptklasse für Job-Scheduling.
  4. """
  5. import asyncio
  6. import json
  7. import os
  8. from dataclasses import dataclass, field
  9. from datetime import datetime, timedelta
  10. from pathlib import Path
  11. from typing import Any, Callable, TYPE_CHECKING
  12. from trixy_core.scheduler.job import ScheduledJob, JobConfig, JobState, JobResult
  13. from trixy_core.scheduler.trigger.base import Trigger, TriggerContext
  14. from trixy_core.scheduler.trigger.cron import CronTrigger
  15. from trixy_core.scheduler.trigger.interval import IntervalTrigger
  16. from trixy_core.scheduler.trigger.datetime_trigger import DateTimeTrigger
  17. from trixy_core.scheduler.trigger.event import EventTrigger
  18. from trixy_core.scheduler.trigger.composite import AndTrigger, OrTrigger
  19. from trixy_core.scheduler.condition.base import Condition
  20. from trixy_core.scheduler.condition.time import (
  21. TimeRangeCondition, DayOfWeekCondition, DateRangeCondition,
  22. )
  23. from trixy_core.scheduler.condition.activity import (
  24. RecentActivityCondition, ActivityCountCondition,
  25. )
  26. from trixy_core.scheduler.condition.sensor import (
  27. ComparisonOperator, SensorThresholdCondition, SensorChangeCondition,
  28. )
  29. from trixy_core.scheduler.condition.state import (
  30. StateCondition, BooleanCondition, ExistsCondition,
  31. )
  32. from trixy_core.scheduler.condition.composite import (
  33. AndCondition, OrCondition, NotCondition, XorCondition,
  34. )
  35. from trixy_core.scheduler.condition.script import (
  36. ScriptCondition, AsyncScriptCondition,
  37. )
  38. from trixy_core.scheduler.condition.file_value import (
  39. JsonValueCondition, IniValueCondition, YamlValueCondition,
  40. TomlValueCondition, EnvFileValueCondition,
  41. )
  42. from trixy_core.scheduler.condition.expression import (
  43. ExpressionCondition, LambdaCondition,
  44. )
  45. from trixy_core.scheduler.action.base import Action, ActionResult
  46. from trixy_core.scheduler.action.event import EmitEventAction, MultiEventAction
  47. from trixy_core.scheduler.action.callback import CallbackAction, MethodAction
  48. from trixy_core.scheduler.action.command import CommandAction, ScriptAction
  49. if TYPE_CHECKING:
  50. from trixy_core.events import EventManager
  51. @dataclass
  52. class SchedulerConfig:
  53. """Konfiguration für den Scheduler."""
  54. # Intervalle
  55. tick_interval_seconds: float = 1.0 # Prüfintervall
  56. cleanup_interval_seconds: float = 3600 # History-Cleanup
  57. # Job-Persistierung
  58. jobs_directory: str = "./cron" # Verzeichnis für Job-Dateien
  59. auto_load: bool = True # Jobs beim Start laden
  60. auto_save: bool = True # Jobs bei Änderungen speichern
  61. # Limits
  62. max_concurrent_jobs: int = 10 # Maximale parallele Jobs
  63. max_history_per_job: int = 100 # History-Einträge pro Job
  64. # Defaults für Jobs
  65. default_timeout_seconds: float = 60.0
  66. default_max_retries: int = 3
  67. # Event-Integration
  68. emit_job_events: bool = True # Events bei Job-Ausführung emittieren
  69. class Scheduler:
  70. """
  71. Scheduler für Job-Ausführung.
  72. Lädt und speichert Jobs als JSON-Dateien in ./cron/*.json.
  73. """
  74. # Trigger-Registry für Deserialisierung
  75. TRIGGER_TYPES: dict[str, type] = {
  76. "CronTrigger": CronTrigger,
  77. "IntervalTrigger": IntervalTrigger,
  78. "DateTimeTrigger": DateTimeTrigger,
  79. "EventTrigger": EventTrigger,
  80. "AndTrigger": AndTrigger,
  81. "OrTrigger": OrTrigger,
  82. }
  83. # Condition-Registry für Deserialisierung
  84. CONDITION_TYPES: dict[str, type] = {
  85. "TimeRangeCondition": TimeRangeCondition,
  86. "DayOfWeekCondition": DayOfWeekCondition,
  87. "DateRangeCondition": DateRangeCondition,
  88. "RecentActivityCondition": RecentActivityCondition,
  89. "ActivityCountCondition": ActivityCountCondition,
  90. "SensorThresholdCondition": SensorThresholdCondition,
  91. "SensorChangeCondition": SensorChangeCondition,
  92. "StateCondition": StateCondition,
  93. "BooleanCondition": BooleanCondition,
  94. "ExistsCondition": ExistsCondition,
  95. "AndCondition": AndCondition,
  96. "OrCondition": OrCondition,
  97. "NotCondition": NotCondition,
  98. "XorCondition": XorCondition,
  99. # Script
  100. "ScriptCondition": ScriptCondition,
  101. "AsyncScriptCondition": AsyncScriptCondition,
  102. # File Value
  103. "JsonValueCondition": JsonValueCondition,
  104. "IniValueCondition": IniValueCondition,
  105. "YamlValueCondition": YamlValueCondition,
  106. "TomlValueCondition": TomlValueCondition,
  107. "EnvFileValueCondition": EnvFileValueCondition,
  108. # Expression
  109. "ExpressionCondition": ExpressionCondition,
  110. # LambdaCondition kann nicht aus JSON geladen werden
  111. }
  112. # Action-Registry für Deserialisierung
  113. ACTION_TYPES: dict[str, type] = {
  114. "EmitEventAction": EmitEventAction,
  115. "MultiEventAction": MultiEventAction,
  116. "CommandAction": CommandAction,
  117. "ScriptAction": ScriptAction,
  118. # CallbackAction und MethodAction können nicht aus JSON geladen werden
  119. }
  120. def __init__(
  121. self,
  122. config: SchedulerConfig | None = None,
  123. event_manager: "EventManager | None" = None,
  124. ):
  125. """
  126. Initialisiert den Scheduler.
  127. Args:
  128. config: Scheduler-Konfiguration
  129. event_manager: EventManager für Events
  130. """
  131. self._config = config or SchedulerConfig()
  132. self._event_manager = event_manager
  133. # Jobs
  134. self._jobs: dict[str, ScheduledJob] = {}
  135. self._running_jobs: set[str] = set()
  136. # Zustand
  137. self._running = False
  138. self._task: asyncio.Task | None = None
  139. self._context: dict[str, Any] = {}
  140. # Callbacks
  141. self._job_callbacks: list[Callable[[ScheduledJob, JobResult], None]] = []
  142. # Verzeichnis erstellen
  143. self._ensure_directory()
  144. def _ensure_directory(self) -> None:
  145. """Stellt sicher, dass das Jobs-Verzeichnis existiert."""
  146. jobs_dir = Path(self._config.jobs_directory)
  147. jobs_dir.mkdir(parents=True, exist_ok=True)
  148. @property
  149. def config(self) -> SchedulerConfig:
  150. """Scheduler-Konfiguration."""
  151. return self._config
  152. @property
  153. def is_running(self) -> bool:
  154. """Prüft ob Scheduler läuft."""
  155. return self._running
  156. @property
  157. def jobs(self) -> dict[str, ScheduledJob]:
  158. """Alle Jobs."""
  159. return dict(self._jobs)
  160. @property
  161. def job_count(self) -> int:
  162. """Anzahl Jobs."""
  163. return len(self._jobs)
  164. @property
  165. def running_jobs(self) -> set[str]:
  166. """Aktuell laufende Jobs."""
  167. return self._running_jobs.copy()
  168. @property
  169. def context(self) -> dict[str, Any]:
  170. """Aktueller Kontext."""
  171. return dict(self._context)
  172. # === Context Management ===
  173. def set_context(self, key: str, value: Any) -> None:
  174. """Setzt Kontext-Variable."""
  175. self._context[key] = value
  176. def update_context(self, data: dict[str, Any]) -> None:
  177. """Aktualisiert Kontext."""
  178. self._context.update(data)
  179. def clear_context(self) -> None:
  180. """Löscht Kontext."""
  181. self._context.clear()
  182. # === Job Management ===
  183. def add_job(
  184. self,
  185. job: ScheduledJob,
  186. save: bool | None = None,
  187. ) -> str:
  188. """
  189. Fügt Job hinzu.
  190. Args:
  191. job: ScheduledJob
  192. save: Als JSON speichern (default: auto_save)
  193. Returns:
  194. Job-ID
  195. """
  196. self._jobs[job.job_id] = job
  197. # Speichern
  198. if save is None:
  199. save = self._config.auto_save
  200. if save:
  201. self._save_job(job)
  202. return job.job_id
  203. def create_job(
  204. self,
  205. trigger: Trigger,
  206. actions: list[Action] | Action,
  207. conditions: list[Condition] | None = None,
  208. config: JobConfig | None = None,
  209. job_id: str | None = None,
  210. save: bool | None = None,
  211. ) -> ScheduledJob:
  212. """
  213. Erstellt und fügt Job hinzu.
  214. Args:
  215. trigger: Trigger für den Job
  216. actions: Action(s) für den Job
  217. conditions: Optionale Conditions
  218. config: Job-Konfiguration
  219. job_id: Job-ID (wird generiert wenn None)
  220. save: Als JSON speichern
  221. Returns:
  222. ScheduledJob
  223. """
  224. if isinstance(actions, Action):
  225. actions = [actions]
  226. job = ScheduledJob(
  227. job_id=job_id,
  228. trigger=trigger,
  229. conditions=conditions,
  230. actions=actions,
  231. config=config,
  232. )
  233. self.add_job(job, save=save)
  234. return job
  235. def get_job(self, job_id: str) -> ScheduledJob | None:
  236. """Holt Job nach ID."""
  237. return self._jobs.get(job_id)
  238. def remove_job(
  239. self,
  240. job_id: str,
  241. delete_file: bool = True,
  242. ) -> bool:
  243. """
  244. Entfernt Job.
  245. Args:
  246. job_id: Job-ID
  247. delete_file: JSON-Datei löschen
  248. Returns:
  249. True wenn entfernt
  250. """
  251. if job_id not in self._jobs:
  252. return False
  253. del self._jobs[job_id]
  254. if delete_file:
  255. self._delete_job_file(job_id)
  256. return True
  257. def enable_job(self, job_id: str) -> bool:
  258. """Aktiviert Job."""
  259. job = self._jobs.get(job_id)
  260. if job:
  261. job.enable()
  262. if self._config.auto_save:
  263. self._save_job(job)
  264. return True
  265. return False
  266. def disable_job(self, job_id: str) -> bool:
  267. """Deaktiviert Job."""
  268. job = self._jobs.get(job_id)
  269. if job:
  270. job.disable()
  271. if self._config.auto_save:
  272. self._save_job(job)
  273. return True
  274. return False
  275. # === Callbacks ===
  276. def on_job_executed(
  277. self,
  278. callback: Callable[[ScheduledJob, JobResult], None],
  279. ) -> None:
  280. """Registriert Callback für Job-Ausführung."""
  281. self._job_callbacks.append(callback)
  282. # === Persistence ===
  283. def _get_job_path(self, job_id: str) -> Path:
  284. """Gibt Pfad zur Job-Datei zurück."""
  285. # Dateiname: job_id.json (Sonderzeichen ersetzen)
  286. safe_id = "".join(c if c.isalnum() or c in "-_" else "_" for c in job_id)
  287. return Path(self._config.jobs_directory) / f"{safe_id}.json"
  288. def _save_job(self, job: ScheduledJob) -> bool:
  289. """
  290. Speichert Job als JSON-Datei.
  291. Args:
  292. job: Zu speichernder Job
  293. Returns:
  294. True wenn erfolgreich
  295. """
  296. try:
  297. path = self._get_job_path(job.job_id)
  298. data = job.to_dict()
  299. with open(path, "w", encoding="utf-8") as f:
  300. json.dump(data, f, indent=2, ensure_ascii=False)
  301. return True
  302. except Exception as e:
  303. from trixy_core.utils.debug import perror
  304. perror(f"Fehler beim Speichern von Job {job.job_id}: {e}")
  305. return False
  306. def _delete_job_file(self, job_id: str) -> bool:
  307. """Löscht Job-Datei."""
  308. try:
  309. path = self._get_job_path(job_id)
  310. if path.exists():
  311. path.unlink()
  312. return True
  313. except Exception:
  314. return False
  315. def _load_job_from_dict(self, data: dict) -> ScheduledJob | None:
  316. """
  317. Lädt Job aus Dictionary.
  318. Args:
  319. data: Job-Daten
  320. Returns:
  321. ScheduledJob oder None bei Fehler
  322. """
  323. try:
  324. # Trigger laden
  325. trigger = None
  326. if data.get("trigger"):
  327. trigger = self._load_trigger(data["trigger"])
  328. # Conditions laden
  329. conditions = []
  330. for cond_data in data.get("conditions", []):
  331. condition = self._load_condition(cond_data)
  332. if condition:
  333. conditions.append(condition)
  334. # Actions laden
  335. actions = []
  336. for action_data in data.get("actions", []):
  337. action = self._load_action(action_data)
  338. if action:
  339. actions.append(action)
  340. # Config laden
  341. config_data = data.get("config", {})
  342. config = JobConfig(
  343. name=data.get("name", ""),
  344. description=data.get("description", ""),
  345. max_runs=config_data.get("max_runs", 0),
  346. max_failures=config_data.get("max_failures", 3),
  347. timeout_seconds=config_data.get("timeout_seconds", 60.0),
  348. priority=config_data.get("priority", 0),
  349. tags=config_data.get("tags", []),
  350. enabled=data.get("enabled", True),
  351. )
  352. # Job erstellen
  353. job = ScheduledJob(
  354. job_id=data.get("job_id"),
  355. trigger=trigger,
  356. conditions=conditions,
  357. actions=actions,
  358. config=config,
  359. )
  360. return job
  361. except Exception as e:
  362. from trixy_core.utils.debug import perror
  363. perror(f"Fehler beim Laden von Job: {e}")
  364. return None
  365. def _load_trigger(self, data: dict) -> Trigger | None:
  366. """Lädt Trigger aus Dictionary."""
  367. trigger_type = data.get("type")
  368. trigger_class = self.TRIGGER_TYPES.get(trigger_type)
  369. if not trigger_class:
  370. return None
  371. if hasattr(trigger_class, "from_dict"):
  372. return trigger_class.from_dict(data)
  373. return None
  374. def _load_condition(self, data: dict) -> Condition | None:
  375. """Lädt Condition aus Dictionary."""
  376. cond_type = data.get("type")
  377. cond_class = self.CONDITION_TYPES.get(cond_type)
  378. if not cond_class:
  379. return None
  380. if hasattr(cond_class, "from_dict"):
  381. return cond_class.from_dict(data)
  382. return None
  383. def _load_action(self, data: dict) -> Action | None:
  384. """Lädt Action aus Dictionary."""
  385. action_type = data.get("type")
  386. action_class = self.ACTION_TYPES.get(action_type)
  387. if not action_class:
  388. return None
  389. if hasattr(action_class, "from_dict"):
  390. return action_class.from_dict(data)
  391. return None
  392. def load_jobs(self) -> int:
  393. """
  394. Lädt alle Jobs aus dem Jobs-Verzeichnis.
  395. Returns:
  396. Anzahl geladener Jobs
  397. """
  398. jobs_dir = Path(self._config.jobs_directory)
  399. loaded = 0
  400. if not jobs_dir.exists():
  401. return 0
  402. for file_path in jobs_dir.glob("*.json"):
  403. try:
  404. with open(file_path, "r", encoding="utf-8") as f:
  405. data = json.load(f)
  406. job = self._load_job_from_dict(data)
  407. if job:
  408. self._jobs[job.job_id] = job
  409. loaded += 1
  410. except Exception as e:
  411. from trixy_core.utils.debug import perror
  412. perror(f"Fehler beim Laden von {file_path}: {e}")
  413. return loaded
  414. def save_all_jobs(self) -> int:
  415. """
  416. Speichert alle Jobs.
  417. Returns:
  418. Anzahl gespeicherter Jobs
  419. """
  420. saved = 0
  421. for job in self._jobs.values():
  422. if self._save_job(job):
  423. saved += 1
  424. return saved
  425. # === Execution ===
  426. async def start(self) -> None:
  427. """Startet den Scheduler."""
  428. if self._running:
  429. return
  430. # Jobs laden
  431. if self._config.auto_load:
  432. loaded = self.load_jobs()
  433. from trixy_core.utils.debug import pinfo
  434. pinfo(f"Scheduler: {loaded} Jobs geladen")
  435. self._running = True
  436. self._task = asyncio.create_task(self._run_loop())
  437. async def stop(self) -> None:
  438. """Stoppt den Scheduler."""
  439. self._running = False
  440. if self._task:
  441. self._task.cancel()
  442. try:
  443. await self._task
  444. except asyncio.CancelledError:
  445. pass
  446. self._task = None
  447. # Laufende Jobs abwarten
  448. while self._running_jobs:
  449. await asyncio.sleep(0.1)
  450. async def _run_loop(self) -> None:
  451. """Hauptschleife des Schedulers."""
  452. while self._running:
  453. try:
  454. await self._tick()
  455. except Exception as e:
  456. from trixy_core.utils.debug import perror
  457. perror(f"Scheduler-Fehler: {e}")
  458. await asyncio.sleep(self._config.tick_interval_seconds)
  459. async def _tick(self) -> None:
  460. """Ein Tick des Schedulers."""
  461. now = datetime.now()
  462. context = TriggerContext(
  463. current_time=now,
  464. )
  465. # Jobs prüfen
  466. for job in list(self._jobs.values()):
  467. if not job.is_runnable:
  468. continue
  469. if job.job_id in self._running_jobs:
  470. continue
  471. # Max concurrent prüfen
  472. if len(self._running_jobs) >= self._config.max_concurrent_jobs:
  473. break
  474. # Trigger prüfen
  475. if job.trigger and job.trigger.should_fire(context):
  476. # Conditions prüfen
  477. if job.should_run_now(self._context):
  478. asyncio.create_task(self._execute_job(job))
  479. async def _execute_job(self, job: ScheduledJob) -> None:
  480. """Führt einen Job aus."""
  481. self._running_jobs.add(job.job_id)
  482. start_time = datetime.now()
  483. try:
  484. # Job-Status setzen
  485. job._state = JobState.RUNNING
  486. # Event emittieren
  487. if self._config.emit_job_events and self._event_manager:
  488. await self._event_manager.emit("scheduler_job_started", {
  489. "job_id": job.job_id,
  490. "job_name": job.name,
  491. })
  492. # Kontext für Actions
  493. action_context = {
  494. **self._context,
  495. "job_id": job.job_id,
  496. "job_name": job.name,
  497. "event_manager": self._event_manager,
  498. "current_time": start_time,
  499. }
  500. # Actions ausführen
  501. results = []
  502. error = None
  503. for action in job.actions:
  504. if not action.is_enabled:
  505. continue
  506. try:
  507. result = await action.execute(action_context)
  508. results.append(result)
  509. if not result.success:
  510. error = result.error
  511. break
  512. except Exception as e:
  513. error = str(e)
  514. break
  515. # Trigger markieren
  516. if job.trigger:
  517. job.trigger.fire()
  518. # Job-Ergebnis
  519. end_time = datetime.now()
  520. job_result = JobResult(
  521. job_id=job.job_id,
  522. success=error is None,
  523. start_time=start_time,
  524. end_time=end_time,
  525. result=results,
  526. error=error,
  527. condition_results=job.check_conditions(self._context),
  528. )
  529. # Job aktualisieren
  530. job.record_run(job_result)
  531. # Speichern
  532. if self._config.auto_save:
  533. self._save_job(job)
  534. # Callbacks
  535. for callback in self._job_callbacks:
  536. try:
  537. callback(job, job_result)
  538. except Exception:
  539. pass
  540. # Event emittieren
  541. if self._config.emit_job_events and self._event_manager:
  542. await self._event_manager.emit("scheduler_job_completed", {
  543. "job_id": job.job_id,
  544. "job_name": job.name,
  545. "success": job_result.success,
  546. "duration_ms": job_result.duration_ms,
  547. "error": error,
  548. })
  549. except Exception as e:
  550. from trixy_core.utils.debug import perror
  551. perror(f"Fehler bei Job {job.job_id}: {e}")
  552. job._state = JobState.FAILED
  553. finally:
  554. self._running_jobs.discard(job.job_id)
  555. # === Event Handling ===
  556. async def on_event(self, event_name: str, event_data: dict | None = None) -> None:
  557. """
  558. Wird aufgerufen wenn ein Event eintrifft.
  559. Für Jobs mit EventTrigger.
  560. """
  561. context = TriggerContext(
  562. current_time=datetime.now(),
  563. event_name=event_name,
  564. event_data=event_data,
  565. )
  566. for job in list(self._jobs.values()):
  567. if not job.is_runnable:
  568. continue
  569. if job.job_id in self._running_jobs:
  570. continue
  571. # Nur EventTrigger oder Composite mit EventTrigger
  572. trigger = job.trigger
  573. if not trigger:
  574. continue
  575. if isinstance(trigger, EventTrigger):
  576. if trigger.on_event(event_name, event_data):
  577. if job.should_run_now(self._context):
  578. asyncio.create_task(self._execute_job(job))
  579. # === Statistics ===
  580. def get_statistics(self) -> dict:
  581. """Gibt Scheduler-Statistiken zurück."""
  582. enabled = sum(1 for j in self._jobs.values() if j.is_enabled)
  583. total_runs = sum(j.run_count for j in self._jobs.values())
  584. total_failures = sum(j.failure_count for j in self._jobs.values())
  585. return {
  586. "total_jobs": len(self._jobs),
  587. "enabled_jobs": enabled,
  588. "running_jobs": len(self._running_jobs),
  589. "total_runs": total_runs,
  590. "total_failures": total_failures,
  591. "is_running": self._running,
  592. }