task-scheduler-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scheduler_mcp/__init__.py +84 -0
- scheduler_mcp/__main__.py +16 -0
- scheduler_mcp/_mcpb.yaml +36 -0
- scheduler_mcp/cli.py +225 -0
- scheduler_mcp/executor/__init__.py +12 -0
- scheduler_mcp/executor/base.py +35 -0
- scheduler_mcp/executor/mock.py +30 -0
- scheduler_mcp/executor/process.py +73 -0
- scheduler_mcp/models/__init__.py +14 -0
- scheduler_mcp/models/job.py +137 -0
- scheduler_mcp/models/schedule.py +77 -0
- scheduler_mcp/scheduler/__init__.py +19 -0
- scheduler_mcp/scheduler/calculator.py +195 -0
- scheduler_mcp/scheduler/parser.py +92 -0
- scheduler_mcp/server.py +178 -0
- scheduler_mcp/services/__init__.py +48 -0
- scheduler_mcp/services/job_service.py +239 -0
- scheduler_mcp/services/launchagent.py +195 -0
- scheduler_mcp/services/service_manager.py +40 -0
- scheduler_mcp/services/systemd.py +170 -0
- scheduler_mcp/services/windows.py +223 -0
- scheduler_mcp/storage/__init__.py +12 -0
- scheduler_mcp/storage/base.py +37 -0
- scheduler_mcp/storage/file.py +111 -0
- scheduler_mcp/storage/memory.py +49 -0
- task_scheduler_mcp-0.1.0.dist-info/METADATA +382 -0
- task_scheduler_mcp-0.1.0.dist-info/RECORD +29 -0
- task_scheduler_mcp-0.1.0.dist-info/WHEEL +4 -0
- task_scheduler_mcp-0.1.0.dist-info/entry_points.txt +5 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Scheduler MCP - A cross-platform job scheduler conforming to SOLID principles and OOP."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Optional
|
|
5
|
+
|
|
6
|
+
from .executor.base import ExecutionResult, JobExecutor
|
|
7
|
+
from .executor.mock import MockJobExecutor
|
|
8
|
+
from .executor.process import SubprocessJobExecutor
|
|
9
|
+
from .models.job import Job, JobStatus, current_iso_time, generate_job_id
|
|
10
|
+
from .models.schedule import CronExpression, ScheduleConfig, ScheduleType
|
|
11
|
+
from .scheduler.calculator import (
|
|
12
|
+
CronStrategy,
|
|
13
|
+
ImmediateStrategy,
|
|
14
|
+
IntervalStrategy,
|
|
15
|
+
NextRunCalculator,
|
|
16
|
+
NextRunStrategy,
|
|
17
|
+
)
|
|
18
|
+
from .scheduler.parser import ScheduleParser
|
|
19
|
+
from .server import create_server, mcp
|
|
20
|
+
from .services.job_service import JobService
|
|
21
|
+
from .storage.base import JobRepository
|
|
22
|
+
from .storage.file import FileJobRepository, get_default_storage_path
|
|
23
|
+
from .storage.memory import InMemoryJobRepository
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
# Backward compatibility helpers
|
|
28
|
+
_default_parser = ScheduleParser()
|
|
29
|
+
_default_calculator = NextRunCalculator()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_schedule(schedule: Optional[str]) -> dict[str, Any]:
|
|
33
|
+
"""Parse schedule string (backward compatibility helper)."""
|
|
34
|
+
return _default_parser.parse(schedule).to_dict()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def calculate_next_run(schedule: dict[str, Any]) -> Optional[str]:
|
|
38
|
+
"""Calculate next run ISO string (backward compatibility helper)."""
|
|
39
|
+
return _default_calculator.calculate_iso(schedule)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _generate_job_id() -> str:
|
|
43
|
+
"""Generate job ID (backward compatibility helper)."""
|
|
44
|
+
return generate_job_id()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_storage_path() -> Path:
|
|
48
|
+
"""Get storage path (backward compatibility helper)."""
|
|
49
|
+
return get_default_storage_path()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get_jobs_dir() -> Path:
|
|
53
|
+
"""Get jobs dir (backward compatibility helper)."""
|
|
54
|
+
return get_default_storage_path()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
__all__ = [
|
|
58
|
+
"mcp",
|
|
59
|
+
"create_server",
|
|
60
|
+
"Job",
|
|
61
|
+
"JobStatus",
|
|
62
|
+
"ScheduleConfig",
|
|
63
|
+
"ScheduleType",
|
|
64
|
+
"CronExpression",
|
|
65
|
+
"JobRepository",
|
|
66
|
+
"InMemoryJobRepository",
|
|
67
|
+
"FileJobRepository",
|
|
68
|
+
"JobExecutor",
|
|
69
|
+
"SubprocessJobExecutor",
|
|
70
|
+
"MockJobExecutor",
|
|
71
|
+
"ExecutionResult",
|
|
72
|
+
"ScheduleParser",
|
|
73
|
+
"NextRunCalculator",
|
|
74
|
+
"NextRunStrategy",
|
|
75
|
+
"ImmediateStrategy",
|
|
76
|
+
"IntervalStrategy",
|
|
77
|
+
"CronStrategy",
|
|
78
|
+
"JobService",
|
|
79
|
+
"parse_schedule",
|
|
80
|
+
"calculate_next_run",
|
|
81
|
+
"_generate_job_id",
|
|
82
|
+
"get_storage_path",
|
|
83
|
+
"get_jobs_dir",
|
|
84
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Package entry point for python -m scheduler_mcp."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from scheduler_mcp.server import mcp
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main() -> None:
|
|
8
|
+
"""Run the MCP server in stdio mode."""
|
|
9
|
+
try:
|
|
10
|
+
mcp.run(transport="stdio", show_banner=False)
|
|
11
|
+
except (KeyboardInterrupt, SystemExit):
|
|
12
|
+
sys.exit(0)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
if __name__ == "__main__":
|
|
16
|
+
main()
|
scheduler_mcp/_mcpb.yaml
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# MCPB Bundle Configuration
|
|
2
|
+
# This defines how the scheduler server is packaged for different platforms
|
|
3
|
+
|
|
4
|
+
name: "scheduler-mcp"
|
|
5
|
+
version: "0.1.0"
|
|
6
|
+
|
|
7
|
+
# Target platforms
|
|
8
|
+
targets:
|
|
9
|
+
linux:
|
|
10
|
+
distro: "any"
|
|
11
|
+
|
|
12
|
+
mac:
|
|
13
|
+
arch: ["x64", "arm64"]
|
|
14
|
+
|
|
15
|
+
windows:
|
|
16
|
+
arch: ["x64", "arm64"]
|
|
17
|
+
|
|
18
|
+
# Build configuration
|
|
19
|
+
build:
|
|
20
|
+
entrypoint: "scheduler_mcp:__main__"
|
|
21
|
+
|
|
22
|
+
# Dependencies to bundle
|
|
23
|
+
deps:
|
|
24
|
+
- fastmcp
|
|
25
|
+
- mcp
|
|
26
|
+
|
|
27
|
+
# Platform-specific configurations
|
|
28
|
+
platforms:
|
|
29
|
+
linux:
|
|
30
|
+
interpreter: python3
|
|
31
|
+
|
|
32
|
+
mac:
|
|
33
|
+
interpreter: python3.13+
|
|
34
|
+
|
|
35
|
+
windows:
|
|
36
|
+
interpreter: python3.13+
|
scheduler_mcp/cli.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Command-line interface for the scheduler MCP server."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import signal
|
|
7
|
+
import sys
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from .models.job import JobStatus
|
|
11
|
+
from .server import mcp
|
|
12
|
+
from .services.job_service import JobService
|
|
13
|
+
from .services.service_manager import get_platform_service_manager
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@click.group()
|
|
17
|
+
@click.version_option(version="0.1.0")
|
|
18
|
+
def main() -> None:
|
|
19
|
+
"""Scheduler MCP Server - A cross-platform job scheduling tool."""
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@main.command(name="start")
|
|
24
|
+
def start() -> None:
|
|
25
|
+
"""Start the MCP server in stdio mode."""
|
|
26
|
+
try:
|
|
27
|
+
mcp.run(transport="stdio", show_banner=False)
|
|
28
|
+
except (KeyboardInterrupt, SystemExit):
|
|
29
|
+
sys.exit(0)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@main.command(name="ui")
|
|
33
|
+
@click.option("--port", "-p", default=5173, type=int, help="Port for the Inspector UI (default: 5173)")
|
|
34
|
+
def ui_cmd(port: int) -> None:
|
|
35
|
+
"""Launch the interactive MCP Inspector Web UI in your browser."""
|
|
36
|
+
import shutil
|
|
37
|
+
import subprocess
|
|
38
|
+
|
|
39
|
+
npx_bin = shutil.which("npx")
|
|
40
|
+
if not npx_bin:
|
|
41
|
+
click.secho("Error: 'npx' is required to launch the MCP Inspector web UI.", fg="red")
|
|
42
|
+
click.echo("Install Node.js (https://nodejs.org) or run:")
|
|
43
|
+
click.echo(" fastmcp dev inspector scheduler_mcp/server.py:mcp")
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
click.secho(f"🚀 Launching MCP Inspector Web UI (port: {port})...", fg="green")
|
|
47
|
+
cmd = [npx_bin, "@modelcontextprotocol/inspector", "scheduler-mcp", "start"]
|
|
48
|
+
try:
|
|
49
|
+
subprocess.run(cmd)
|
|
50
|
+
except KeyboardInterrupt:
|
|
51
|
+
click.echo("\nMCP Inspector stopped.")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@main.command(name="create")
|
|
55
|
+
@click.argument("task")
|
|
56
|
+
@click.option("--schedule", "-s", default=None, help="Cron expression (e.g. '0 9 * * *') or interval ('every hour')")
|
|
57
|
+
@click.option("--disabled", "-d", is_flag=True, help="Create job in paused state")
|
|
58
|
+
def create_cmd(task: str, schedule: str | None, disabled: bool) -> None:
|
|
59
|
+
"""Create a new scheduled job."""
|
|
60
|
+
service = JobService()
|
|
61
|
+
job = service.create_job(task=task, schedule=schedule, enabled=not disabled)
|
|
62
|
+
click.secho(f"Job created successfully! [ID: {job.id}]", fg="green", bold=True)
|
|
63
|
+
click.echo(json.dumps(job.to_dict(), indent=2))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@main.command(name="list")
|
|
67
|
+
@click.option("--status", "-s", type=click.Choice(["pending", "running", "completed", "failed", "paused"], case_sensitive=False), help="Filter by status")
|
|
68
|
+
@click.option("--enabled-only", "-e", is_flag=True, help="Show only enabled jobs")
|
|
69
|
+
def list_cmd(status: str | None, enabled_only: bool) -> None:
|
|
70
|
+
"""List all scheduled jobs."""
|
|
71
|
+
service = JobService()
|
|
72
|
+
jobs = service.list_jobs(filter_status=status, enabled_only=enabled_only)
|
|
73
|
+
if not jobs:
|
|
74
|
+
click.echo("No jobs found.")
|
|
75
|
+
return
|
|
76
|
+
|
|
77
|
+
click.echo(f"Found {len(jobs)} job(s):")
|
|
78
|
+
for job in jobs:
|
|
79
|
+
click.secho(f"[{job.id}] {job.task}", bold=True)
|
|
80
|
+
click.echo(f" Status: {job.status.value} | Enabled: {job.enabled}")
|
|
81
|
+
click.echo(f" Schedule: {job.schedule.type.value}")
|
|
82
|
+
if job.next_run_at:
|
|
83
|
+
click.echo(f" Next run: {job.next_run_at}")
|
|
84
|
+
click.echo("")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@main.command(name="status")
|
|
88
|
+
def status_cmd() -> None:
|
|
89
|
+
"""Show scheduler summary status."""
|
|
90
|
+
service = JobService()
|
|
91
|
+
stats = service.get_status()
|
|
92
|
+
click.echo(json.dumps(stats, indent=2))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@main.command(name="run")
|
|
96
|
+
@click.argument("job_id")
|
|
97
|
+
@click.option("--force", "-f", is_flag=True, help="Force execution even if paused")
|
|
98
|
+
def run_cmd(job_id: str, force: bool) -> None:
|
|
99
|
+
"""Execute a job immediately."""
|
|
100
|
+
service = JobService()
|
|
101
|
+
result = asyncio.run(service.run_job(job_id=job_id, force=force))
|
|
102
|
+
click.echo(json.dumps(result, indent=2))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@main.command(name="delete")
|
|
106
|
+
@click.argument("job_id")
|
|
107
|
+
def delete_cmd(job_id: str) -> None:
|
|
108
|
+
"""Delete a job by ID."""
|
|
109
|
+
service = JobService()
|
|
110
|
+
deleted = service.delete_job(job_id)
|
|
111
|
+
if deleted:
|
|
112
|
+
click.secho(f"Job {job_id} deleted successfully.", fg="green")
|
|
113
|
+
else:
|
|
114
|
+
click.secho(f"Job {job_id} not found.", fg="red")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@main.command(name="daemon")
|
|
118
|
+
@click.option("--interval", "-i", default=1.0, type=float, help="Poll interval in seconds")
|
|
119
|
+
def daemon_cmd(interval: float) -> None:
|
|
120
|
+
"""Run the continuous scheduler background daemon to execute scheduled jobs."""
|
|
121
|
+
service = JobService()
|
|
122
|
+
stop_event = asyncio.Event()
|
|
123
|
+
|
|
124
|
+
def handle_stop(sig: int, frame: object) -> None:
|
|
125
|
+
click.echo(f"\nReceived signal {sig}. Stopping scheduler daemon gracefully...")
|
|
126
|
+
stop_event.set()
|
|
127
|
+
|
|
128
|
+
signal.signal(signal.SIGINT, handle_stop)
|
|
129
|
+
signal.signal(signal.SIGTERM, handle_stop)
|
|
130
|
+
|
|
131
|
+
click.secho(f"🚀 Scheduler daemon started (polling every {interval}s). Press Ctrl+C to exit.", fg="green")
|
|
132
|
+
asyncio.run(service.start_daemon(poll_interval=interval, stop_event=stop_event))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@main.group(name="service")
|
|
136
|
+
def service_group() -> None:
|
|
137
|
+
"""Manage background service (LaunchAgent on macOS / systemd on Linux)."""
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@service_group.command(name="install")
|
|
142
|
+
@click.option("--executable", "-e", default=None, help="Explicit path to scheduler-mcp executable")
|
|
143
|
+
@click.option("--working-dir", "-w", default=None, help="Working directory for the service")
|
|
144
|
+
def service_install(executable: str | None, working_dir: str | None) -> None:
|
|
145
|
+
"""Install and enable background service to auto-start scheduler on user login."""
|
|
146
|
+
manager, platform_name = get_platform_service_manager()
|
|
147
|
+
import platform
|
|
148
|
+
import shutil
|
|
149
|
+
sys_name = platform.system().lower()
|
|
150
|
+
if sys_name not in ("darwin", "linux", "windows"):
|
|
151
|
+
click.secho(f"Background service is not supported on {platform.system()}.", fg="yellow")
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
# Determine executable
|
|
155
|
+
exec_path = executable
|
|
156
|
+
if not exec_path:
|
|
157
|
+
project_root = Path(__file__).parent.parent.resolve()
|
|
158
|
+
candidate_bin_nix = project_root / ".venv" / "bin" / "scheduler-mcp"
|
|
159
|
+
candidate_bin_win = project_root / ".venv" / "Scripts" / "scheduler-mcp.exe"
|
|
160
|
+
if candidate_bin_win.exists():
|
|
161
|
+
exec_path = str(candidate_bin_win)
|
|
162
|
+
elif candidate_bin_nix.exists():
|
|
163
|
+
exec_path = str(candidate_bin_nix)
|
|
164
|
+
else:
|
|
165
|
+
which_path = shutil.which("scheduler-mcp")
|
|
166
|
+
exec_path = which_path if which_path else sys.executable
|
|
167
|
+
|
|
168
|
+
cwd = working_dir or str(Path(__file__).parent.parent.resolve())
|
|
169
|
+
success, msg = manager.install(executable_path=exec_path, working_dir=cwd, auto_start=True)
|
|
170
|
+
if success:
|
|
171
|
+
click.secho(f"✅ {msg}", fg="green")
|
|
172
|
+
click.echo(f"The scheduler daemon is now configured to start automatically ({platform_name}).")
|
|
173
|
+
else:
|
|
174
|
+
click.secho(f"❌ {msg}", fg="red")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@service_group.command(name="uninstall")
|
|
178
|
+
def service_uninstall() -> None:
|
|
179
|
+
"""Stop and remove the background service."""
|
|
180
|
+
manager, platform_name = get_platform_service_manager()
|
|
181
|
+
success, msg = manager.uninstall()
|
|
182
|
+
if success:
|
|
183
|
+
click.secho(f"✅ {msg}", fg="green")
|
|
184
|
+
else:
|
|
185
|
+
click.secho(f"❌ {msg}", fg="red")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@service_group.command(name="start")
|
|
189
|
+
def service_start() -> None:
|
|
190
|
+
"""Start the registered background service."""
|
|
191
|
+
manager, platform_name = get_platform_service_manager()
|
|
192
|
+
success, msg = manager.start()
|
|
193
|
+
if success:
|
|
194
|
+
click.secho(f"✅ Background service started ({platform_name}).", fg="green")
|
|
195
|
+
else:
|
|
196
|
+
click.secho(f"❌ {msg}", fg="red")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@service_group.command(name="stop")
|
|
200
|
+
def service_stop() -> None:
|
|
201
|
+
"""Stop the running background service."""
|
|
202
|
+
manager, platform_name = get_platform_service_manager()
|
|
203
|
+
success, msg = manager.stop()
|
|
204
|
+
if success:
|
|
205
|
+
click.secho(f"✅ Background service stopped ({platform_name}).", fg="green")
|
|
206
|
+
else:
|
|
207
|
+
click.secho(f"❌ {msg}", fg="red")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@service_group.command(name="status")
|
|
211
|
+
def service_status() -> None:
|
|
212
|
+
"""Check the status of the background service."""
|
|
213
|
+
manager, platform_name = get_platform_service_manager()
|
|
214
|
+
info = manager.status()
|
|
215
|
+
click.echo(json.dumps(info, indent=2))
|
|
216
|
+
if info.get("running"):
|
|
217
|
+
click.secho(f"● Service is ACTIVE (PID: {info.get('pid')})", fg="green", bold=True)
|
|
218
|
+
elif info.get("installed"):
|
|
219
|
+
click.secho("○ Service is INSTALLED but not currently running.", fg="yellow", bold=True)
|
|
220
|
+
else:
|
|
221
|
+
click.secho("⨯ Service is NOT INSTALLED.", fg="red", bold=True)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
if __name__ == "__main__":
|
|
225
|
+
main()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Executor package exports."""
|
|
2
|
+
|
|
3
|
+
from .base import ExecutionResult, JobExecutor
|
|
4
|
+
from .mock import MockJobExecutor
|
|
5
|
+
from .process import SubprocessJobExecutor
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"JobExecutor",
|
|
9
|
+
"ExecutionResult",
|
|
10
|
+
"SubprocessJobExecutor",
|
|
11
|
+
"MockJobExecutor",
|
|
12
|
+
]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Abstract executor interface and execution models."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class ExecutionResult:
|
|
10
|
+
"""Outcome of a job task execution."""
|
|
11
|
+
|
|
12
|
+
success: bool
|
|
13
|
+
exit_code: int
|
|
14
|
+
output: str
|
|
15
|
+
error: Optional[str] = None
|
|
16
|
+
duration_seconds: float = 0.0
|
|
17
|
+
|
|
18
|
+
def to_dict(self) -> dict:
|
|
19
|
+
"""Convert result to dictionary representation."""
|
|
20
|
+
return {
|
|
21
|
+
"success": self.success,
|
|
22
|
+
"exit_code": self.exit_code,
|
|
23
|
+
"output": self.output,
|
|
24
|
+
"error": self.error,
|
|
25
|
+
"duration_seconds": round(self.duration_seconds, 3),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class JobExecutor(ABC):
|
|
30
|
+
"""Abstract base class for executing job tasks."""
|
|
31
|
+
|
|
32
|
+
@abstractmethod
|
|
33
|
+
async def execute(self, task: str, timeout: Optional[float] = None) -> ExecutionResult:
|
|
34
|
+
"""Execute a task and return the execution result."""
|
|
35
|
+
pass
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Mock executor for deterministic testing."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from .base import ExecutionResult, JobExecutor
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MockJobExecutor(JobExecutor):
|
|
9
|
+
"""Mock job executor with configurable responses."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
default_success: bool = True,
|
|
14
|
+
default_output: str = "Mock execution completed",
|
|
15
|
+
default_exit_code: int = 0,
|
|
16
|
+
) -> None:
|
|
17
|
+
self.default_success = default_success
|
|
18
|
+
self.default_output = default_output
|
|
19
|
+
self.default_exit_code = default_exit_code
|
|
20
|
+
self.executed_tasks: list[str] = []
|
|
21
|
+
|
|
22
|
+
async def execute(self, task: str, timeout: Optional[float] = None) -> ExecutionResult:
|
|
23
|
+
self.executed_tasks.append(task)
|
|
24
|
+
return ExecutionResult(
|
|
25
|
+
success=self.default_success,
|
|
26
|
+
exit_code=self.default_exit_code,
|
|
27
|
+
output=self.default_output,
|
|
28
|
+
error=None if self.default_success else "Mock execution error",
|
|
29
|
+
duration_seconds=0.01,
|
|
30
|
+
)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Process-based job executor executing tasks in asynchronous subprocesses."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from .base import ExecutionResult, JobExecutor
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SubprocessJobExecutor(JobExecutor):
|
|
11
|
+
"""Executes tasks as system commands using asynchronous subprocesses."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, default_timeout: float = 300.0) -> None:
|
|
14
|
+
self.default_timeout = default_timeout
|
|
15
|
+
|
|
16
|
+
async def execute(self, task: str, timeout: Optional[float] = None) -> ExecutionResult:
|
|
17
|
+
"""Execute the task in a shell subprocess."""
|
|
18
|
+
effective_timeout = timeout if timeout is not None else self.default_timeout
|
|
19
|
+
start_time = time.time()
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
process = await asyncio.create_subprocess_shell(
|
|
23
|
+
task,
|
|
24
|
+
stdout=asyncio.subprocess.PIPE,
|
|
25
|
+
stderr=asyncio.subprocess.PIPE,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
stdout_bytes, stderr_bytes = await asyncio.wait_for(
|
|
30
|
+
process.communicate(), timeout=effective_timeout
|
|
31
|
+
)
|
|
32
|
+
except asyncio.TimeoutError:
|
|
33
|
+
try:
|
|
34
|
+
process.kill()
|
|
35
|
+
await process.wait()
|
|
36
|
+
except ProcessLookupError:
|
|
37
|
+
pass
|
|
38
|
+
duration = time.time() - start_time
|
|
39
|
+
return ExecutionResult(
|
|
40
|
+
success=False,
|
|
41
|
+
exit_code=-1,
|
|
42
|
+
output="",
|
|
43
|
+
error=f"Job execution timed out after {effective_timeout}s",
|
|
44
|
+
duration_seconds=duration,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
duration = time.time() - start_time
|
|
48
|
+
stdout_str = stdout_bytes.decode("utf-8", errors="replace").strip()
|
|
49
|
+
stderr_str = stderr_bytes.decode("utf-8", errors="replace").strip()
|
|
50
|
+
exit_code = process.returncode or 0
|
|
51
|
+
success = exit_code == 0
|
|
52
|
+
|
|
53
|
+
combined_output = stdout_str
|
|
54
|
+
if stderr_str:
|
|
55
|
+
combined_output = f"{stdout_str}\n{stderr_str}".strip() if stdout_str else stderr_str
|
|
56
|
+
|
|
57
|
+
return ExecutionResult(
|
|
58
|
+
success=success,
|
|
59
|
+
exit_code=exit_code,
|
|
60
|
+
output=combined_output or ("Executed successfully" if success else "Command failed"),
|
|
61
|
+
error=stderr_str if not success else None,
|
|
62
|
+
duration_seconds=duration,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
except Exception as exc:
|
|
66
|
+
duration = time.time() - start_time
|
|
67
|
+
return ExecutionResult(
|
|
68
|
+
success=False,
|
|
69
|
+
exit_code=1,
|
|
70
|
+
output="",
|
|
71
|
+
error=f"Execution error: {exc}",
|
|
72
|
+
duration_seconds=duration,
|
|
73
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Models package initialization."""
|
|
2
|
+
|
|
3
|
+
from .job import Job, JobStatus, current_iso_time, generate_job_id
|
|
4
|
+
from .schedule import CronExpression, ScheduleConfig, ScheduleType
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Job",
|
|
8
|
+
"JobStatus",
|
|
9
|
+
"ScheduleConfig",
|
|
10
|
+
"ScheduleType",
|
|
11
|
+
"CronExpression",
|
|
12
|
+
"generate_job_id",
|
|
13
|
+
"current_iso_time",
|
|
14
|
+
]
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Job domain model and lifecycle management."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
from .schedule import ScheduleConfig, ScheduleType
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class JobStatus(str, Enum):
|
|
13
|
+
"""Job status states."""
|
|
14
|
+
|
|
15
|
+
PENDING = "pending"
|
|
16
|
+
RUNNING = "running"
|
|
17
|
+
COMPLETED = "completed"
|
|
18
|
+
FAILED = "failed"
|
|
19
|
+
PAUSED = "paused"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def generate_job_id() -> str:
|
|
23
|
+
"""Generate an 8-character unique job ID."""
|
|
24
|
+
return str(uuid.uuid4())[:8]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def current_iso_time() -> str:
|
|
28
|
+
"""Return the current UTC time in ISO format."""
|
|
29
|
+
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Job:
|
|
34
|
+
"""Domain model representing a scheduled or ad-hoc executable job."""
|
|
35
|
+
|
|
36
|
+
id: str = field(default_factory=generate_job_id)
|
|
37
|
+
task: str = ""
|
|
38
|
+
schedule: ScheduleConfig = field(default_factory=ScheduleConfig)
|
|
39
|
+
enabled: bool = True
|
|
40
|
+
created_at: str = field(default_factory=current_iso_time)
|
|
41
|
+
updated_at: str = field(default_factory=current_iso_time)
|
|
42
|
+
last_run_at: Optional[str] = None
|
|
43
|
+
next_run_at: Optional[str] = None
|
|
44
|
+
status: JobStatus = JobStatus.PENDING
|
|
45
|
+
last_exit_code: Optional[int] = None
|
|
46
|
+
last_output: Optional[str] = None
|
|
47
|
+
|
|
48
|
+
def mark_started(self) -> None:
|
|
49
|
+
"""Mark job execution as started."""
|
|
50
|
+
now = current_iso_time()
|
|
51
|
+
self.status = JobStatus.RUNNING
|
|
52
|
+
self.last_run_at = now
|
|
53
|
+
self.updated_at = now
|
|
54
|
+
|
|
55
|
+
def mark_completed(
|
|
56
|
+
self,
|
|
57
|
+
output: str,
|
|
58
|
+
exit_code: int = 0,
|
|
59
|
+
next_run: Optional[str] = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Mark job execution as successfully completed."""
|
|
62
|
+
now = current_iso_time()
|
|
63
|
+
self.status = JobStatus.COMPLETED
|
|
64
|
+
self.last_output = output
|
|
65
|
+
self.last_exit_code = exit_code
|
|
66
|
+
self.next_run_at = next_run
|
|
67
|
+
self.updated_at = now
|
|
68
|
+
|
|
69
|
+
def mark_failed(
|
|
70
|
+
self,
|
|
71
|
+
error_output: str,
|
|
72
|
+
exit_code: int = 1,
|
|
73
|
+
next_run: Optional[str] = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Mark job execution as failed."""
|
|
76
|
+
now = current_iso_time()
|
|
77
|
+
self.status = JobStatus.FAILED
|
|
78
|
+
self.last_output = error_output
|
|
79
|
+
self.last_exit_code = exit_code
|
|
80
|
+
self.next_run_at = next_run
|
|
81
|
+
self.updated_at = now
|
|
82
|
+
|
|
83
|
+
def pause(self) -> None:
|
|
84
|
+
"""Pause the job."""
|
|
85
|
+
self.enabled = False
|
|
86
|
+
self.status = JobStatus.PAUSED
|
|
87
|
+
self.updated_at = current_iso_time()
|
|
88
|
+
|
|
89
|
+
def resume(self, next_run: Optional[str] = None) -> None:
|
|
90
|
+
"""Resume the job."""
|
|
91
|
+
self.enabled = True
|
|
92
|
+
self.status = JobStatus.PENDING
|
|
93
|
+
if next_run is not None:
|
|
94
|
+
self.next_run_at = next_run
|
|
95
|
+
self.updated_at = current_iso_time()
|
|
96
|
+
|
|
97
|
+
def to_dict(self) -> dict[str, Any]:
|
|
98
|
+
"""Serialize job to dictionary for API/storage."""
|
|
99
|
+
return {
|
|
100
|
+
"id": self.id,
|
|
101
|
+
"task": self.task,
|
|
102
|
+
"schedule": self.schedule.to_dict() if isinstance(self.schedule, ScheduleConfig) else self.schedule,
|
|
103
|
+
"enabled": self.enabled,
|
|
104
|
+
"created_at": self.created_at,
|
|
105
|
+
"updated_at": self.updated_at,
|
|
106
|
+
"last_run_at": self.last_run_at,
|
|
107
|
+
"next_run_at": self.next_run_at,
|
|
108
|
+
"status": self.status.value if isinstance(self.status, JobStatus) else str(self.status),
|
|
109
|
+
"last_exit_code": self.last_exit_code,
|
|
110
|
+
"last_output": self.last_output,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def from_dict(cls, data: dict[str, Any]) -> "Job":
|
|
115
|
+
"""Instantiate Job domain model from dictionary."""
|
|
116
|
+
raw_status = data.get("status", JobStatus.PENDING.value)
|
|
117
|
+
try:
|
|
118
|
+
status = JobStatus(raw_status)
|
|
119
|
+
except ValueError:
|
|
120
|
+
status = JobStatus.PENDING
|
|
121
|
+
|
|
122
|
+
raw_schedule = data.get("schedule", {})
|
|
123
|
+
schedule = ScheduleConfig.from_dict(raw_schedule) if isinstance(raw_schedule, dict) else ScheduleConfig()
|
|
124
|
+
|
|
125
|
+
return cls(
|
|
126
|
+
id=data.get("id", generate_job_id()),
|
|
127
|
+
task=data.get("task", ""),
|
|
128
|
+
schedule=schedule,
|
|
129
|
+
enabled=data.get("enabled", True),
|
|
130
|
+
created_at=data.get("created_at", current_iso_time()),
|
|
131
|
+
updated_at=data.get("updated_at", current_iso_time()),
|
|
132
|
+
last_run_at=data.get("last_run_at"),
|
|
133
|
+
next_run_at=data.get("next_run_at"),
|
|
134
|
+
status=status,
|
|
135
|
+
last_exit_code=data.get("last_exit_code"),
|
|
136
|
+
last_output=data.get("last_output"),
|
|
137
|
+
)
|