crontinel 0.2.1__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.
- crontinel/__init__.py +223 -0
- crontinel/__main__.py +151 -0
- crontinel/agent.py +516 -0
- crontinel-0.2.1.dist-info/METADATA +146 -0
- crontinel-0.2.1.dist-info/RECORD +9 -0
- crontinel-0.2.1.dist-info/WHEEL +5 -0
- crontinel-0.2.1.dist-info/entry_points.txt +2 -0
- crontinel-0.2.1.dist-info/licenses/LICENSE +21 -0
- crontinel-0.2.1.dist-info/top_level.txt +1 -0
crontinel/__init__.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Crontinel monitoring SDK for Python applications.
|
|
3
|
+
Send cron, queue, and job monitoring events from any Python app.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any, Callable, TypeVar
|
|
11
|
+
|
|
12
|
+
__version__ = "0.2.1"
|
|
13
|
+
|
|
14
|
+
DEFAULT_API_URL = "https://app.crontinel.com"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Crontinel:
|
|
18
|
+
"""
|
|
19
|
+
Crontinel monitoring client.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
api_key: Your Crontinel API key (or set CRONTINEL_API_KEY env var).
|
|
23
|
+
api_url: Crontinel API URL. Defaults to https://app.crontinel.com.
|
|
24
|
+
app_name: Name of this application. Defaults to "python".
|
|
25
|
+
sync: Use ``requests`` if installed, else the standard library. Set ``False`` to use ``httpx``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
api_key: str | None = None,
|
|
31
|
+
api_url: str | None = None,
|
|
32
|
+
app_name: str = "python",
|
|
33
|
+
sync: bool = True,
|
|
34
|
+
):
|
|
35
|
+
self.api_key = api_key or os.environ.get("CRONTINEL_API_KEY")
|
|
36
|
+
if not self.api_key:
|
|
37
|
+
raise ValueError("Crontinel: api_key is required")
|
|
38
|
+
self.api_url = (api_url or os.environ.get("CRONTINEL_API_URL") or DEFAULT_API_URL).rstrip("/")
|
|
39
|
+
self.app_name = app_name
|
|
40
|
+
self.sync = sync
|
|
41
|
+
|
|
42
|
+
def _request(self, method: str, params: dict[str, Any]) -> Any:
|
|
43
|
+
payload = {
|
|
44
|
+
"jsonrpc": "2.0",
|
|
45
|
+
"id": int(time.time() * 1000),
|
|
46
|
+
"method": method,
|
|
47
|
+
"params": params,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
headers = {
|
|
51
|
+
"Content-Type": "application/json",
|
|
52
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
53
|
+
"User-Agent": f"crontinel-python:{__version__}",
|
|
54
|
+
}
|
|
55
|
+
try:
|
|
56
|
+
import requests
|
|
57
|
+
except ImportError:
|
|
58
|
+
requests = None
|
|
59
|
+
|
|
60
|
+
if self.sync and requests is None:
|
|
61
|
+
# No optional HTTP library installed: use the standard library.
|
|
62
|
+
import json
|
|
63
|
+
import urllib.request
|
|
64
|
+
|
|
65
|
+
req = urllib.request.Request(
|
|
66
|
+
f"{self.api_url}/api/mcp", data=json.dumps(payload).encode(), headers=headers, method="POST"
|
|
67
|
+
)
|
|
68
|
+
with urllib.request.urlopen(req, timeout=10) as resp: # raises HTTPError on 4xx/5xx
|
|
69
|
+
data = json.loads(resp.read())
|
|
70
|
+
elif self.sync:
|
|
71
|
+
resp = requests.post(
|
|
72
|
+
f"{self.api_url}/api/mcp",
|
|
73
|
+
json=payload,
|
|
74
|
+
headers={
|
|
75
|
+
"Content-Type": "application/json",
|
|
76
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
77
|
+
"User-Agent": f"crontinel-python:{__version__}",
|
|
78
|
+
},
|
|
79
|
+
timeout=10,
|
|
80
|
+
)
|
|
81
|
+
resp.raise_for_status()
|
|
82
|
+
data = resp.json()
|
|
83
|
+
else:
|
|
84
|
+
try:
|
|
85
|
+
import httpx
|
|
86
|
+
except ImportError:
|
|
87
|
+
raise ImportError("Install crontinel with httpx: pip install 'crontinel[httpx]'")
|
|
88
|
+
with httpx.Client() as client:
|
|
89
|
+
resp = client.post(
|
|
90
|
+
f"{self.api_url}/api/mcp",
|
|
91
|
+
json=payload,
|
|
92
|
+
headers={
|
|
93
|
+
"Content-Type": "application/json",
|
|
94
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
95
|
+
"User-Agent": f"crontinel-python:{__version__}",
|
|
96
|
+
},
|
|
97
|
+
timeout=10,
|
|
98
|
+
)
|
|
99
|
+
resp.raise_for_status()
|
|
100
|
+
data = resp.json()
|
|
101
|
+
|
|
102
|
+
if "error" in data:
|
|
103
|
+
raise RuntimeError(f"Crontinel RPC error: {data['error']}")
|
|
104
|
+
return data.get("result")
|
|
105
|
+
|
|
106
|
+
def schedule_run(
|
|
107
|
+
self,
|
|
108
|
+
command: str,
|
|
109
|
+
duration_ms: int | None = None,
|
|
110
|
+
exit_code: int = 0,
|
|
111
|
+
ran_at: str | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
"""
|
|
114
|
+
Report a scheduled command run.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
command: The command name, e.g. ``"reports:generate"``.
|
|
118
|
+
duration_ms: How long the command took in milliseconds.
|
|
119
|
+
exit_code: 0 for success, 1 for failure.
|
|
120
|
+
ran_at: ISO 8601 timestamp. Defaults to now.
|
|
121
|
+
"""
|
|
122
|
+
self._request("notify/schedule_run", {
|
|
123
|
+
"command": command,
|
|
124
|
+
"duration_ms": duration_ms,
|
|
125
|
+
"exit_code": exit_code,
|
|
126
|
+
"ran_at": ran_at or self._now(),
|
|
127
|
+
"app": self.app_name,
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
def queue_processed(
|
|
131
|
+
self,
|
|
132
|
+
queue: str,
|
|
133
|
+
processed: int = 0,
|
|
134
|
+
failed: int = 0,
|
|
135
|
+
duration_ms: int | None = None,
|
|
136
|
+
ran_at: str | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
"""
|
|
139
|
+
Report queue worker activity.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
queue: Queue name, e.g. ``"emails"``.
|
|
143
|
+
processed: Number of successfully processed jobs.
|
|
144
|
+
failed: Number of failed jobs.
|
|
145
|
+
duration_ms: How long the batch took in milliseconds.
|
|
146
|
+
ran_at: ISO 8601 timestamp. Defaults to now.
|
|
147
|
+
"""
|
|
148
|
+
self._request("notify/queue_processed", {
|
|
149
|
+
"queue": queue,
|
|
150
|
+
"processed": processed,
|
|
151
|
+
"failed": failed,
|
|
152
|
+
"duration_ms": duration_ms,
|
|
153
|
+
"ran_at": ran_at or self._now(),
|
|
154
|
+
"app": self.app_name,
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
def event(
|
|
158
|
+
self,
|
|
159
|
+
key: str,
|
|
160
|
+
message: str,
|
|
161
|
+
state: str = "info",
|
|
162
|
+
metadata: dict[str, Any] | None = None,
|
|
163
|
+
ran_at: str | None = None,
|
|
164
|
+
) -> None:
|
|
165
|
+
"""
|
|
166
|
+
Send a custom alert or informational event.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
key: Alert key, e.g. ``"disk-space-warning"``.
|
|
170
|
+
message: Human-readable message.
|
|
171
|
+
state: ``"firing"``, ``"resolved"``, or ``"info"``.
|
|
172
|
+
metadata: Extra key-value data.
|
|
173
|
+
ran_at: ISO 8601 timestamp. Defaults to now.
|
|
174
|
+
"""
|
|
175
|
+
self._request("notify/event", {
|
|
176
|
+
"key": key,
|
|
177
|
+
"message": message,
|
|
178
|
+
"state": state,
|
|
179
|
+
"metadata": metadata or {},
|
|
180
|
+
"ran_at": ran_at or self._now(),
|
|
181
|
+
"app": self.app_name,
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
def monitor_schedule(
|
|
185
|
+
self,
|
|
186
|
+
command: str,
|
|
187
|
+
fn: Callable[..., T],
|
|
188
|
+
*args: Any,
|
|
189
|
+
**kwargs: Any,
|
|
190
|
+
) -> tuple[T, int, int]:
|
|
191
|
+
"""
|
|
192
|
+
Run ``fn`` and automatically report its outcome as a scheduled command.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
A tuple of ``(result, duration_ms, exit_code)``.
|
|
196
|
+
|
|
197
|
+
Example::
|
|
198
|
+
|
|
199
|
+
client = Crontinel(api_key="...")
|
|
200
|
+
result, ms, code = client.monitor_schedule("my-task", my_task_function)
|
|
201
|
+
"""
|
|
202
|
+
start = time.perf_counter()
|
|
203
|
+
exit_code = 0
|
|
204
|
+
try:
|
|
205
|
+
result = fn(*args, **kwargs)
|
|
206
|
+
except Exception:
|
|
207
|
+
exit_code = 1
|
|
208
|
+
raise
|
|
209
|
+
finally:
|
|
210
|
+
duration_ms = int((time.perf_counter() - start) * 1000)
|
|
211
|
+
try:
|
|
212
|
+
self.schedule_run(command, duration_ms=duration_ms, exit_code=exit_code)
|
|
213
|
+
except Exception:
|
|
214
|
+
pass # Don't fail the caller's job if reporting fails
|
|
215
|
+
return result, duration_ms, exit_code
|
|
216
|
+
|
|
217
|
+
@staticmethod
|
|
218
|
+
def _now() -> str:
|
|
219
|
+
from datetime import datetime, timezone
|
|
220
|
+
return datetime.now(timezone.utc).isoformat()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
T = TypeVar("T")
|
crontinel/__main__.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Crontinel CLI — ``crontinel agent`` daemon command.
|
|
3
|
+
|
|
4
|
+
Usage::
|
|
5
|
+
|
|
6
|
+
crontinel agent Start the agent daemon
|
|
7
|
+
crontinel agent --systemd Print systemd unit file
|
|
8
|
+
crontinel agent --supervisor Print Supervisor config
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
from crontinel import __version__
|
|
18
|
+
from crontinel.agent import Agent
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main(argv: list[str] | None = None) -> int:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
prog="crontinel",
|
|
24
|
+
description="Crontinel monitoring tools.",
|
|
25
|
+
)
|
|
26
|
+
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
27
|
+
|
|
28
|
+
# ── agent ──────────────────────────────────────────────────────────────
|
|
29
|
+
agent_parser = subparsers.add_parser(
|
|
30
|
+
"agent",
|
|
31
|
+
help="Start the Crontinel agent daemon",
|
|
32
|
+
description=(
|
|
33
|
+
"Start the Crontinel agent daemon — connects to "
|
|
34
|
+
"app.crontinel.com via SSE to receive and execute commands."
|
|
35
|
+
),
|
|
36
|
+
)
|
|
37
|
+
agent_parser.add_argument(
|
|
38
|
+
"--systemd",
|
|
39
|
+
action="store_true",
|
|
40
|
+
help="Output a systemd unit file and exit",
|
|
41
|
+
)
|
|
42
|
+
agent_parser.add_argument(
|
|
43
|
+
"--supervisor",
|
|
44
|
+
action="store_true",
|
|
45
|
+
help="Output a Supervisor config and exit",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
args = parser.parse_args(argv)
|
|
49
|
+
|
|
50
|
+
if args.command == "agent":
|
|
51
|
+
return _handle_agent(args)
|
|
52
|
+
else:
|
|
53
|
+
parser.print_help()
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _handle_agent(args: argparse.Namespace) -> int:
|
|
58
|
+
if args.systemd:
|
|
59
|
+
_print_systemd_unit()
|
|
60
|
+
return 0
|
|
61
|
+
if args.supervisor:
|
|
62
|
+
_print_supervisor_config()
|
|
63
|
+
return 0
|
|
64
|
+
|
|
65
|
+
api_key = os.environ.get("CRONTINEL_API_KEY")
|
|
66
|
+
api_url = os.environ.get("CRONTINEL_API_URL")
|
|
67
|
+
app_id = os.environ.get("CRONTINEL_APP_ID")
|
|
68
|
+
|
|
69
|
+
if not api_key:
|
|
70
|
+
print("CRONTINEL_API_KEY is not set.", file=sys.stderr)
|
|
71
|
+
print("", file=sys.stderr)
|
|
72
|
+
print(" export CRONTINEL_API_KEY=your-api-key", file=sys.stderr)
|
|
73
|
+
print(" export CRONTINEL_APP_ID=your-app-slug", file=sys.stderr)
|
|
74
|
+
print(" export CRONTINEL_API_URL=https://app.crontinel.com (optional)", file=sys.stderr)
|
|
75
|
+
print("", file=sys.stderr)
|
|
76
|
+
print("You can also generate a systemd unit or supervisor config:", file=sys.stderr)
|
|
77
|
+
print(" crontinel agent --systemd", file=sys.stderr)
|
|
78
|
+
print(" crontinel agent --supervisor", file=sys.stderr)
|
|
79
|
+
return 1
|
|
80
|
+
|
|
81
|
+
if not app_id:
|
|
82
|
+
print("CRONTINEL_APP_ID is not set.", file=sys.stderr)
|
|
83
|
+
print("", file=sys.stderr)
|
|
84
|
+
print(" export CRONTINEL_APP_ID=your-app-slug", file=sys.stderr)
|
|
85
|
+
print(" (found in app.crontinel.com → Settings → App slug)", file=sys.stderr)
|
|
86
|
+
print("", file=sys.stderr)
|
|
87
|
+
return 1
|
|
88
|
+
|
|
89
|
+
agent = Agent(api_key=api_key, api_url=api_url, app_id=app_id)
|
|
90
|
+
print(f"Crontinel Agent v{__version__}")
|
|
91
|
+
print("--------------------------")
|
|
92
|
+
print()
|
|
93
|
+
print("Starting agent daemon. Press Ctrl+C to stop.")
|
|
94
|
+
print()
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
agent.run()
|
|
98
|
+
except KeyboardInterrupt:
|
|
99
|
+
# Agent handles SIGINT internally; this is a safety net
|
|
100
|
+
pass
|
|
101
|
+
|
|
102
|
+
return 0
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _print_systemd_unit() -> None:
|
|
106
|
+
cwd = os.getcwd()
|
|
107
|
+
user = os.environ.get("USER", "root")
|
|
108
|
+
|
|
109
|
+
print("[Unit]")
|
|
110
|
+
print("Description=Crontinel Agent — remote command execution daemon")
|
|
111
|
+
print("After=network.target")
|
|
112
|
+
print()
|
|
113
|
+
print("[Service]")
|
|
114
|
+
print("Type=simple")
|
|
115
|
+
print(f"User={user}")
|
|
116
|
+
print(f"WorkingDirectory={cwd}")
|
|
117
|
+
print(f"ExecStart={sys.executable} -m crontinel agent")
|
|
118
|
+
print("Restart=always")
|
|
119
|
+
print("RestartSec=5")
|
|
120
|
+
print("TimeoutStopSec=30")
|
|
121
|
+
print("KillSignal=SIGTERM")
|
|
122
|
+
print()
|
|
123
|
+
print("[Install]")
|
|
124
|
+
print("WantedBy=multi-user.target")
|
|
125
|
+
print()
|
|
126
|
+
print("# Save to /etc/systemd/system/crontinel-agent.service")
|
|
127
|
+
print("# Then: sudo systemctl daemon-reload && sudo systemctl enable --now crontinel-agent")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _print_supervisor_config() -> None:
|
|
131
|
+
cwd = os.getcwd()
|
|
132
|
+
user = os.environ.get("USER", "root")
|
|
133
|
+
|
|
134
|
+
print("[program:crontinel-agent]")
|
|
135
|
+
print(f"command={sys.executable} -m crontinel agent")
|
|
136
|
+
print(f"directory={cwd}")
|
|
137
|
+
print(f"user={user}")
|
|
138
|
+
print("autostart=true")
|
|
139
|
+
print("autorestart=true")
|
|
140
|
+
print("startretries=3")
|
|
141
|
+
print("stopwaitsecs=30")
|
|
142
|
+
print("stopsignal=SIGTERM")
|
|
143
|
+
print("stdout_logfile=/var/log/crontinel-agent.log")
|
|
144
|
+
print("stderr_logfile=/var/log/crontinel-agent.err")
|
|
145
|
+
print()
|
|
146
|
+
print("# Save to /etc/supervisor/conf.d/crontinel-agent.conf")
|
|
147
|
+
print("# Then: sudo supervisorctl reread && sudo supervisorctl update && sudo supervisorctl start crontinel-agent")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
sys.exit(main())
|
crontinel/agent.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Crontinel Agent — remote command execution daemon.
|
|
3
|
+
|
|
4
|
+
Polls app.crontinel.com via HTTP for pending commands, executes them,
|
|
5
|
+
and reports results. Uses HTTP polling (registration -> poll -> execute -> report)
|
|
6
|
+
instead of SSE for simplicity and portability.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import fnmatch
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import signal
|
|
16
|
+
import socket
|
|
17
|
+
import ssl
|
|
18
|
+
import subprocess
|
|
19
|
+
import time
|
|
20
|
+
import urllib.parse
|
|
21
|
+
from datetime import datetime, timezone
|
|
22
|
+
from typing import Any, Callable
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
REGISTER_PATH = "/v1/agents/register"
|
|
27
|
+
COMMANDS_PATH = "/v1/agents/{app_id}/commands"
|
|
28
|
+
RESULT_PATH = "/v1/ingest/agent-result"
|
|
29
|
+
HEARTBEAT_PATH = "/v1/agents/heartbeat"
|
|
30
|
+
|
|
31
|
+
POLL_INTERVAL_S = 5
|
|
32
|
+
HEARTBEAT_INTERVAL_S = 60
|
|
33
|
+
MAX_RECONNECT_DELAY_S = 60
|
|
34
|
+
HTTP_TIMEOUT_S = 15
|
|
35
|
+
MAX_COMMAND_OUTPUT = 1_048_576 # 1 MB max output per command
|
|
36
|
+
DEFAULT_API_URL = "https://app.crontinel.com"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Agent:
|
|
40
|
+
"""
|
|
41
|
+
Crontinel agent daemon.
|
|
42
|
+
|
|
43
|
+
Registers with the cloud, then polls for pending commands via HTTP,
|
|
44
|
+
executes them as subprocesses, and reports results back.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
api_key: str | None = None,
|
|
50
|
+
api_url: str | None = None,
|
|
51
|
+
app_id: str | None = None,
|
|
52
|
+
output_writer: Callable[[str], None] | None = None,
|
|
53
|
+
allowed_commands: list[str] | None = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
self.api_key = api_key or os.environ.get("CRONTINEL_API_KEY", "")
|
|
56
|
+
if not self.api_key:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"CRONTINEL_API_KEY is not set. Set it in your environment "
|
|
59
|
+
"or pass it to the constructor."
|
|
60
|
+
)
|
|
61
|
+
self.app_id = app_id or os.environ.get("CRONTINEL_APP_ID", "")
|
|
62
|
+
if not self.app_id:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"CRONTINEL_APP_ID is not set. Set it in your environment "
|
|
65
|
+
"or pass it to the constructor."
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
base_url = (api_url or os.environ.get("CRONTINEL_API_URL") or DEFAULT_API_URL).rstrip("/")
|
|
69
|
+
self.api_url = base_url.rstrip("/api") # strip trailing /api if present
|
|
70
|
+
self.output_writer = output_writer or (lambda msg: print(msg))
|
|
71
|
+
|
|
72
|
+
# Commands received from the cloud are matched against this allowlist
|
|
73
|
+
# (fnmatch-style patterns — "*" wildcard; a pattern with no wildcard
|
|
74
|
+
# matches only that exact command string) before they are ever passed
|
|
75
|
+
# to the shell. If not given explicitly, falls back to the
|
|
76
|
+
# comma-separated CRONTINEL_AGENT_ALLOWED_COMMANDS env var.
|
|
77
|
+
#
|
|
78
|
+
# SECURITY: an empty/unset allowlist means NO commands are permitted.
|
|
79
|
+
# This is a fail-closed default — it does NOT mean "allow everything."
|
|
80
|
+
if allowed_commands is not None:
|
|
81
|
+
self.allowed_commands = list(allowed_commands)
|
|
82
|
+
else:
|
|
83
|
+
env_val = os.environ.get("CRONTINEL_AGENT_ALLOWED_COMMANDS", "")
|
|
84
|
+
self.allowed_commands = [p.strip() for p in env_val.split(",") if p.strip()]
|
|
85
|
+
|
|
86
|
+
self.running = True
|
|
87
|
+
self.last_heartbeat_at = time.time()
|
|
88
|
+
self.started_at = time.time()
|
|
89
|
+
self.reconnect_attempt = 0
|
|
90
|
+
|
|
91
|
+
# ── Public API ─────────────────────────────────────────────────────────────
|
|
92
|
+
|
|
93
|
+
def run(self) -> None:
|
|
94
|
+
"""Start the agent daemon (blocking loop). Press Ctrl+C to stop."""
|
|
95
|
+
self.started_at = time.time()
|
|
96
|
+
self.last_heartbeat_at = self.started_at
|
|
97
|
+
self._install_signal_handlers()
|
|
98
|
+
|
|
99
|
+
self._log(f"Agent starting...")
|
|
100
|
+
self._log(f"Agent ID: {self._agent_id()}")
|
|
101
|
+
self._log(f"App ID: {self.app_id}")
|
|
102
|
+
self._log(f"API URL: {self.api_url}")
|
|
103
|
+
if self.allowed_commands:
|
|
104
|
+
self._log(f"Allowed commands: {len(self.allowed_commands)} pattern(s) configured")
|
|
105
|
+
else:
|
|
106
|
+
self._log("Allowed commands: NONE configured — all commands will be rejected")
|
|
107
|
+
|
|
108
|
+
# Register with the cloud on startup
|
|
109
|
+
self.register()
|
|
110
|
+
|
|
111
|
+
self._log("Agent registered. Starting poll loop...")
|
|
112
|
+
|
|
113
|
+
while self.running:
|
|
114
|
+
try:
|
|
115
|
+
self._poll_once()
|
|
116
|
+
self.reconnect_attempt = 0
|
|
117
|
+
except Exception as exc:
|
|
118
|
+
log.error("Poll error: %s", exc)
|
|
119
|
+
self._log(f"Poll error: {exc}")
|
|
120
|
+
|
|
121
|
+
if not self.running:
|
|
122
|
+
break
|
|
123
|
+
|
|
124
|
+
# Throttle loop
|
|
125
|
+
self._sleep(POLL_INTERVAL_S)
|
|
126
|
+
|
|
127
|
+
self._log("Agent stopped.")
|
|
128
|
+
|
|
129
|
+
def is_configured(self) -> bool:
|
|
130
|
+
"""Whether the agent has an API key and app ID configured."""
|
|
131
|
+
return bool(self.api_key) and bool(self.app_id)
|
|
132
|
+
|
|
133
|
+
# ── Registration ───────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
def register(self) -> None:
|
|
136
|
+
"""Register this agent with the Crontinel cloud."""
|
|
137
|
+
try:
|
|
138
|
+
body = {
|
|
139
|
+
"agent_id": self._agent_id(),
|
|
140
|
+
"agent_name": self._agent_name(),
|
|
141
|
+
"metadata": {
|
|
142
|
+
"python_version": os.environ.get("PYTHON_VERSION", ""),
|
|
143
|
+
"platform": os.name,
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
result = self._http_post(self.api_url + REGISTER_PATH, json_body=body)
|
|
147
|
+
if result is not None:
|
|
148
|
+
self._log(f"Registered: id={result.get('id', 'unknown')}")
|
|
149
|
+
else:
|
|
150
|
+
self._log("Registration response was empty (continuing anyway)")
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
self._log(f"Registration error: {exc} (continuing anyway)")
|
|
153
|
+
|
|
154
|
+
# ── Poll Loop ──────────────────────────────────────────────────────────────
|
|
155
|
+
|
|
156
|
+
def _poll_once(self) -> None:
|
|
157
|
+
"""Single poll iteration: heartbeat check + fetch + execute."""
|
|
158
|
+
self._check_heartbeat()
|
|
159
|
+
|
|
160
|
+
commands = self._fetch_commands()
|
|
161
|
+
|
|
162
|
+
if not commands:
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
self._log(f"Received {len(commands)} command(s)")
|
|
166
|
+
|
|
167
|
+
for cmd in commands:
|
|
168
|
+
if not self.running:
|
|
169
|
+
break
|
|
170
|
+
self._execute_and_report(cmd)
|
|
171
|
+
|
|
172
|
+
def _fetch_commands(self) -> list[dict[str, Any]]:
|
|
173
|
+
"""Poll the cloud for pending commands."""
|
|
174
|
+
url = f"{self.api_url}{COMMANDS_PATH.format(app_id=self.app_id)}"
|
|
175
|
+
try:
|
|
176
|
+
data = self._http_get(url)
|
|
177
|
+
if data is None:
|
|
178
|
+
return []
|
|
179
|
+
return data.get("data", [])
|
|
180
|
+
except Exception as exc:
|
|
181
|
+
self._log(f"Commands fetch error: {exc}")
|
|
182
|
+
return []
|
|
183
|
+
|
|
184
|
+
# ── Execute + Report ───────────────────────────────────────────────────────
|
|
185
|
+
|
|
186
|
+
def _is_command_allowed(self, command: str) -> bool:
|
|
187
|
+
"""
|
|
188
|
+
Check a command string against the configured allowlist.
|
|
189
|
+
|
|
190
|
+
Patterns are fnmatch-style (``*`` wildcard supported; a pattern with
|
|
191
|
+
no wildcard must match the command exactly). An empty/unset
|
|
192
|
+
allowlist means NO commands are permitted — fail-closed default.
|
|
193
|
+
"""
|
|
194
|
+
if not self.allowed_commands:
|
|
195
|
+
return False
|
|
196
|
+
return any(fnmatch.fnmatch(command, pattern) for pattern in self.allowed_commands)
|
|
197
|
+
|
|
198
|
+
def _execute_and_report(self, cmd: dict[str, Any]) -> None:
|
|
199
|
+
"""Execute a command and report the result."""
|
|
200
|
+
trigger_id = str(cmd["id"])
|
|
201
|
+
command_str = cmd["command"]
|
|
202
|
+
|
|
203
|
+
self._log(f"Executing [{trigger_id}]: {command_str}")
|
|
204
|
+
|
|
205
|
+
started_at = datetime.now(timezone.utc)
|
|
206
|
+
start_ms = int(time.time() * 1000)
|
|
207
|
+
|
|
208
|
+
exit_code = 0
|
|
209
|
+
output = ""
|
|
210
|
+
status = "completed"
|
|
211
|
+
error_message: str | None = None
|
|
212
|
+
|
|
213
|
+
# Acknowledge receipt first
|
|
214
|
+
self._report_result(trigger_id=trigger_id, status="acknowledged")
|
|
215
|
+
|
|
216
|
+
if not self._is_command_allowed(command_str):
|
|
217
|
+
error_message = "Command rejected: not in allowlist"
|
|
218
|
+
log.warning(
|
|
219
|
+
"Rejected command [%s]: not in allowlist: %r", trigger_id, command_str
|
|
220
|
+
)
|
|
221
|
+
self._log(f"Command [{trigger_id}] rejected: not in allowlist")
|
|
222
|
+
|
|
223
|
+
finished_at = datetime.now(timezone.utc)
|
|
224
|
+
duration_ms = int(time.time() * 1000) - start_ms
|
|
225
|
+
self._report_result(
|
|
226
|
+
trigger_id=trigger_id,
|
|
227
|
+
status="failed",
|
|
228
|
+
exit_code=-1,
|
|
229
|
+
output=error_message,
|
|
230
|
+
error_message=error_message,
|
|
231
|
+
started_at=started_at.isoformat(),
|
|
232
|
+
finished_at=finished_at.isoformat(),
|
|
233
|
+
duration_ms=duration_ms,
|
|
234
|
+
)
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
env_overrides = cmd.get("payload") or {}
|
|
238
|
+
cmd_timeout = 300
|
|
239
|
+
|
|
240
|
+
env = None
|
|
241
|
+
if env_overrides:
|
|
242
|
+
env = {**os.environ, **env_overrides}
|
|
243
|
+
|
|
244
|
+
try:
|
|
245
|
+
result = subprocess.run(
|
|
246
|
+
command_str,
|
|
247
|
+
shell=True,
|
|
248
|
+
capture_output=True,
|
|
249
|
+
text=True,
|
|
250
|
+
timeout=cmd_timeout,
|
|
251
|
+
env=env,
|
|
252
|
+
)
|
|
253
|
+
exit_code = result.returncode
|
|
254
|
+
output = result.stdout + result.stderr
|
|
255
|
+
if len(output) > MAX_COMMAND_OUTPUT:
|
|
256
|
+
output = output[:MAX_COMMAND_OUTPUT]
|
|
257
|
+
self._log(f"Command [{trigger_id}] output truncated to {MAX_COMMAND_OUTPUT} bytes")
|
|
258
|
+
status = "completed" if exit_code == 0 else "failed"
|
|
259
|
+
except subprocess.TimeoutExpired:
|
|
260
|
+
exit_code = -1
|
|
261
|
+
output = f"Command timed out after {cmd_timeout}s"
|
|
262
|
+
status = "failed"
|
|
263
|
+
error_message = f"Timed out after {cmd_timeout}s"
|
|
264
|
+
self._log(f"Command [{trigger_id}] timed out after {cmd_timeout}s")
|
|
265
|
+
except Exception as exc:
|
|
266
|
+
exit_code = -1
|
|
267
|
+
output = str(exc)
|
|
268
|
+
status = "failed"
|
|
269
|
+
error_message = str(exc)
|
|
270
|
+
self._log(f"Command [{trigger_id}] error: {exc}")
|
|
271
|
+
|
|
272
|
+
finished_at = datetime.now(timezone.utc)
|
|
273
|
+
duration_ms = int(time.time() * 1000) - start_ms
|
|
274
|
+
|
|
275
|
+
self._log(
|
|
276
|
+
f"[{trigger_id}] {status} ({duration_ms}ms, exit {exit_code})"
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
self._report_result(
|
|
280
|
+
trigger_id=trigger_id,
|
|
281
|
+
status=status,
|
|
282
|
+
exit_code=exit_code,
|
|
283
|
+
output=output,
|
|
284
|
+
error_message=error_message,
|
|
285
|
+
started_at=started_at.isoformat(),
|
|
286
|
+
finished_at=finished_at.isoformat(),
|
|
287
|
+
duration_ms=duration_ms,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
def _report_result(
|
|
291
|
+
self,
|
|
292
|
+
trigger_id: str,
|
|
293
|
+
status: str,
|
|
294
|
+
exit_code: int | None = None,
|
|
295
|
+
output: str | None = None,
|
|
296
|
+
error_message: str | None = None,
|
|
297
|
+
started_at: str | None = None,
|
|
298
|
+
finished_at: str | None = None,
|
|
299
|
+
duration_ms: int | None = None,
|
|
300
|
+
) -> None:
|
|
301
|
+
"""Report a command execution result to the cloud."""
|
|
302
|
+
payload: dict[str, Any] = {
|
|
303
|
+
"trigger_id": trigger_id,
|
|
304
|
+
"status": status,
|
|
305
|
+
}
|
|
306
|
+
if exit_code is not None:
|
|
307
|
+
payload["exit_code"] = exit_code
|
|
308
|
+
if output is not None:
|
|
309
|
+
payload["output"] = output
|
|
310
|
+
if error_message is not None:
|
|
311
|
+
payload["error_message"] = error_message
|
|
312
|
+
if started_at is not None:
|
|
313
|
+
payload["started_at"] = started_at
|
|
314
|
+
if finished_at is not None:
|
|
315
|
+
payload["finished_at"] = finished_at
|
|
316
|
+
if duration_ms is not None:
|
|
317
|
+
payload["duration_ms"] = duration_ms
|
|
318
|
+
|
|
319
|
+
try:
|
|
320
|
+
self._http_post(self.api_url + RESULT_PATH, json_body=payload)
|
|
321
|
+
except Exception as exc:
|
|
322
|
+
self._log(f"Result report error: {exc}")
|
|
323
|
+
|
|
324
|
+
# ── Heartbeat ──────────────────────────────────────────────────────────────
|
|
325
|
+
|
|
326
|
+
def _check_heartbeat(self) -> None:
|
|
327
|
+
"""Send a heartbeat if it's due."""
|
|
328
|
+
if (time.time() - self.last_heartbeat_at) >= HEARTBEAT_INTERVAL_S:
|
|
329
|
+
self._send_heartbeat()
|
|
330
|
+
|
|
331
|
+
def _send_heartbeat(self) -> None:
|
|
332
|
+
"""POST a heartbeat to the cloud."""
|
|
333
|
+
self.last_heartbeat_at = time.time()
|
|
334
|
+
uptime = int(time.time() - self.started_at)
|
|
335
|
+
|
|
336
|
+
url = f"{self.api_url}{HEARTBEAT_PATH}"
|
|
337
|
+
try:
|
|
338
|
+
self._http_post(
|
|
339
|
+
url,
|
|
340
|
+
json_body={
|
|
341
|
+
"agent_id": self._agent_id(),
|
|
342
|
+
"metadata": {
|
|
343
|
+
"uptime_seconds": uptime,
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
)
|
|
347
|
+
self._log(f"Heartbeat sent (uptime: {uptime}s)")
|
|
348
|
+
except Exception as exc:
|
|
349
|
+
self._log(f"Heartbeat error: {exc}")
|
|
350
|
+
|
|
351
|
+
# ── HTTP Helpers ───────────────────────────────────────────────────────────
|
|
352
|
+
|
|
353
|
+
def _http_get(self, url: str) -> dict[str, Any] | None:
|
|
354
|
+
"""Low-level HTTP GET with auth."""
|
|
355
|
+
parsed = urllib.parse.urlparse(url)
|
|
356
|
+
host = parsed.hostname
|
|
357
|
+
if not host:
|
|
358
|
+
return None
|
|
359
|
+
scheme = parsed.scheme or "https"
|
|
360
|
+
port = parsed.port or (443 if scheme == "https" else 80)
|
|
361
|
+
path = parsed.path or "/"
|
|
362
|
+
if parsed.query:
|
|
363
|
+
path += "?" + parsed.query
|
|
364
|
+
|
|
365
|
+
request = (
|
|
366
|
+
f"GET {path} HTTP/1.1\r\n"
|
|
367
|
+
f"Host: {host}\r\n"
|
|
368
|
+
f"Authorization: Bearer {self.api_key}\r\n"
|
|
369
|
+
f"Accept: application/json\r\n"
|
|
370
|
+
f"Connection: close\r\n"
|
|
371
|
+
f"User-Agent: crontinel-agent/1.0\r\n"
|
|
372
|
+
f"\r\n"
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
try:
|
|
376
|
+
sock = socket.create_connection((host, port), timeout=HTTP_TIMEOUT_S)
|
|
377
|
+
except OSError as exc:
|
|
378
|
+
self._log(f"HTTP GET connect failed: {exc}")
|
|
379
|
+
return None
|
|
380
|
+
|
|
381
|
+
try:
|
|
382
|
+
if scheme == "https":
|
|
383
|
+
ctx = ssl.create_default_context()
|
|
384
|
+
ctx.check_hostname = True
|
|
385
|
+
ctx.verify_mode = ssl.CERT_REQUIRED
|
|
386
|
+
sock = ctx.wrap_socket(sock, server_hostname=host)
|
|
387
|
+
|
|
388
|
+
sock.sendall(request.encode())
|
|
389
|
+
|
|
390
|
+
response = b""
|
|
391
|
+
while True:
|
|
392
|
+
chunk = sock.recv(8192)
|
|
393
|
+
if not chunk:
|
|
394
|
+
break
|
|
395
|
+
response += chunk
|
|
396
|
+
except (ssl.SSLError, OSError) as exc:
|
|
397
|
+
self._log(f"HTTP GET error: {exc}")
|
|
398
|
+
return None
|
|
399
|
+
finally:
|
|
400
|
+
sock.close()
|
|
401
|
+
|
|
402
|
+
# Parse response
|
|
403
|
+
header_end = response.find(b"\r\n\r\n")
|
|
404
|
+
if header_end == -1:
|
|
405
|
+
return None
|
|
406
|
+
|
|
407
|
+
status_line = response[: response.find(b"\r\n")].decode()
|
|
408
|
+
body = response[header_end + 4 :]
|
|
409
|
+
|
|
410
|
+
parts = status_line.split(None, 2)
|
|
411
|
+
if len(parts) >= 2 and parts[1].startswith("2"):
|
|
412
|
+
if body:
|
|
413
|
+
try:
|
|
414
|
+
return json.loads(body.decode())
|
|
415
|
+
except json.JSONDecodeError:
|
|
416
|
+
pass
|
|
417
|
+
return None
|
|
418
|
+
|
|
419
|
+
def _http_post(
|
|
420
|
+
self, url: str, json_body: dict[str, Any]
|
|
421
|
+
) -> dict[str, Any] | None:
|
|
422
|
+
"""Low-level HTTP POST with JSON body over a fresh socket."""
|
|
423
|
+
parsed = urllib.parse.urlparse(url)
|
|
424
|
+
host = parsed.hostname
|
|
425
|
+
if not host:
|
|
426
|
+
return None
|
|
427
|
+
scheme = parsed.scheme or "https"
|
|
428
|
+
port = parsed.port or (443 if scheme == "https" else 80)
|
|
429
|
+
path = parsed.path or "/"
|
|
430
|
+
|
|
431
|
+
body = json.dumps(json_body).encode()
|
|
432
|
+
request = (
|
|
433
|
+
f"POST {path} HTTP/1.1\r\n"
|
|
434
|
+
f"Host: {host}\r\n"
|
|
435
|
+
f"Authorization: Bearer {self.api_key}\r\n"
|
|
436
|
+
f"Content-Type: application/json\r\n"
|
|
437
|
+
f"Content-Length: {len(body)}\r\n"
|
|
438
|
+
f"Connection: close\r\n"
|
|
439
|
+
f"User-Agent: crontinel-agent/1.0\r\n"
|
|
440
|
+
f"\r\n"
|
|
441
|
+
).encode() + body
|
|
442
|
+
|
|
443
|
+
try:
|
|
444
|
+
sock = socket.create_connection((host, port), timeout=HTTP_TIMEOUT_S)
|
|
445
|
+
except OSError:
|
|
446
|
+
return None
|
|
447
|
+
|
|
448
|
+
try:
|
|
449
|
+
if scheme == "https":
|
|
450
|
+
ctx = ssl.create_default_context()
|
|
451
|
+
ctx.check_hostname = True
|
|
452
|
+
ctx.verify_mode = ssl.CERT_REQUIRED
|
|
453
|
+
sock = ctx.wrap_socket(sock, server_hostname=host)
|
|
454
|
+
|
|
455
|
+
sock.sendall(request)
|
|
456
|
+
|
|
457
|
+
response = b""
|
|
458
|
+
while True:
|
|
459
|
+
chunk = sock.recv(8192)
|
|
460
|
+
if not chunk:
|
|
461
|
+
break
|
|
462
|
+
response += chunk
|
|
463
|
+
except (ssl.SSLError, OSError) as exc:
|
|
464
|
+
log.warning("HTTP POST %s error: %s", path, exc)
|
|
465
|
+
return None
|
|
466
|
+
finally:
|
|
467
|
+
sock.close()
|
|
468
|
+
|
|
469
|
+
# Parse response
|
|
470
|
+
header_end = response.find(b"\r\n\r\n")
|
|
471
|
+
if header_end == -1:
|
|
472
|
+
return None
|
|
473
|
+
|
|
474
|
+
status_line = response[: response.find(b"\r\n")].decode()
|
|
475
|
+
body_data = response[header_end + 4 :]
|
|
476
|
+
|
|
477
|
+
parts = status_line.split(None, 2)
|
|
478
|
+
if len(parts) >= 2 and parts[1].startswith("2"):
|
|
479
|
+
if body_data:
|
|
480
|
+
try:
|
|
481
|
+
return json.loads(body_data.decode())
|
|
482
|
+
except json.JSONDecodeError:
|
|
483
|
+
pass
|
|
484
|
+
return None
|
|
485
|
+
|
|
486
|
+
# ── Signal Handling ────────────────────────────────────────────────────────
|
|
487
|
+
|
|
488
|
+
def _install_signal_handlers(self) -> None:
|
|
489
|
+
"""Install graceful-shutdown signal handlers."""
|
|
490
|
+
|
|
491
|
+
def _shutdown(signum: int, _frame) -> None: # type: ignore[type-arg]
|
|
492
|
+
self._log(f"Received signal {signum}. Shutting down gracefully...")
|
|
493
|
+
self.running = False
|
|
494
|
+
|
|
495
|
+
signal.signal(signal.SIGTERM, _shutdown)
|
|
496
|
+
signal.signal(signal.SIGINT, _shutdown)
|
|
497
|
+
|
|
498
|
+
# ── Helpers ────────────────────────────────────────────────────────────────
|
|
499
|
+
|
|
500
|
+
def _agent_id(self) -> str:
|
|
501
|
+
return socket.gethostname()
|
|
502
|
+
|
|
503
|
+
def _agent_name(self) -> str:
|
|
504
|
+
return f"python-agent:{self._agent_id()}"
|
|
505
|
+
|
|
506
|
+
def _sleep(self, seconds: int) -> None:
|
|
507
|
+
for _ in range(seconds):
|
|
508
|
+
if not self.running:
|
|
509
|
+
break
|
|
510
|
+
time.sleep(1)
|
|
511
|
+
|
|
512
|
+
# ── Logging ────────────────────────────────────────────────────────────────
|
|
513
|
+
|
|
514
|
+
def _log(self, message: str) -> None:
|
|
515
|
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
|
516
|
+
self.output_writer(f"[{ts}] Crontinel Agent: {message}")
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: crontinel
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Crontinel monitoring SDK for Python applications
|
|
5
|
+
Author: Harun R Rayhan
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/crontinel/python
|
|
8
|
+
Project-URL: Homepage, https://crontinel.com
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest; extra == "dev"
|
|
14
|
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
|
15
|
+
Provides-Extra: httpx
|
|
16
|
+
Requires-Dist: httpx; extra == "httpx"
|
|
17
|
+
Provides-Extra: requests
|
|
18
|
+
Requires-Dist: requests; extra == "requests"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# crontinel
|
|
22
|
+
|
|
23
|
+
Crontinel monitoring SDK for Python applications. Send cron, queue, and job monitoring events from any Python app.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
# Install directly from GitHub (PyPI publishing pending)
|
|
29
|
+
pip install git+https://github.com/crontinel/python.git
|
|
30
|
+
# or with httpx for async support:
|
|
31
|
+
pip install "crontinel[httpx] @ git+https://github.com/crontinel/python.git"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Requirements
|
|
35
|
+
|
|
36
|
+
- Python 3.9+
|
|
37
|
+
|
|
38
|
+
## Quick Start
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import os
|
|
42
|
+
|
|
43
|
+
from crontinel import Crontinel
|
|
44
|
+
|
|
45
|
+
client = Crontinel(
|
|
46
|
+
api_key=os.environ["CRONTINEL_API_KEY"],
|
|
47
|
+
app_name="my-worker",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Report a cron job run
|
|
51
|
+
client.schedule_run(
|
|
52
|
+
command="reports:generate",
|
|
53
|
+
duration_ms=2340,
|
|
54
|
+
exit_code=0,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Report queue worker activity
|
|
58
|
+
client.queue_processed(
|
|
59
|
+
queue="emails",
|
|
60
|
+
processed=12,
|
|
61
|
+
failed=0,
|
|
62
|
+
duration_ms=8901,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Send a custom alert
|
|
66
|
+
client.event(
|
|
67
|
+
key="disk-space-warning",
|
|
68
|
+
message="Disk usage above 90%",
|
|
69
|
+
state="firing",
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Environment variables
|
|
74
|
+
|
|
75
|
+
| Variable | Default | Description |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `CRONTINEL_API_KEY` | — | Your Crontinel API key (required) |
|
|
78
|
+
| `CRONTINEL_API_URL` | `https://app.crontinel.com` | Crontinel SaaS or self-hosted endpoint |
|
|
79
|
+
|
|
80
|
+
No dependencies are required: the client uses `requests` if it is installed, otherwise the standard library. Calls go to the MCP endpoint (`/api/mcp`) and carry no outcome metrics; to alert when a job finished but did nothing, send the [HTTP check-in receipt](https://docs.crontinel.com/check-in/recipes/) with a count.
|
|
81
|
+
|
|
82
|
+
## Cron / heartbeat submission
|
|
83
|
+
|
|
84
|
+
Use `schedule_run()` when your cron or heartbeat job finishes and you want to submit one monitoring event to Crontinel:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
client.schedule_run(
|
|
88
|
+
command="reports:generate",
|
|
89
|
+
duration_ms=2340,
|
|
90
|
+
exit_code=0,
|
|
91
|
+
)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
If you want the SDK to measure and submit the run automatically, use `monitor_schedule()`:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
result, duration_ms, exit_code = client.monitor_schedule(
|
|
98
|
+
"reports:generate",
|
|
99
|
+
generate_daily_reports,
|
|
100
|
+
)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Framework integrations
|
|
104
|
+
|
|
105
|
+
### APScheduler
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from apscheduler.schedulers.blocking import BlockingScheduler
|
|
109
|
+
from crontinel import Crontinel
|
|
110
|
+
|
|
111
|
+
client = Crontinel(api_key=os.environ["CRONTINEL_API_KEY"])
|
|
112
|
+
scheduler = BlockingScheduler()
|
|
113
|
+
|
|
114
|
+
@scheduler.scheduled_job("cron", hour=9, minute=0)
|
|
115
|
+
def daily_reports():
|
|
116
|
+
result, ms, code = client.monitor_schedule("daily-reports", send_reports)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Celery
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from crontinel import Crontinel
|
|
123
|
+
from celery.signals import task_success, task_failure
|
|
124
|
+
|
|
125
|
+
client = Crontinel(api_key=os.environ["CRONTINEL_API_KEY"])
|
|
126
|
+
|
|
127
|
+
@task_success.connect
|
|
128
|
+
def on_task_success(task=None, **kwargs):
|
|
129
|
+
client.queue_processed(
|
|
130
|
+
queue=task.name,
|
|
131
|
+
processed=1,
|
|
132
|
+
failed=0,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
@task_failure.connect
|
|
136
|
+
def on_task_failure(task=None, **kwargs):
|
|
137
|
+
client.queue_processed(
|
|
138
|
+
queue=task.name,
|
|
139
|
+
processed=0,
|
|
140
|
+
failed=1,
|
|
141
|
+
)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
crontinel/__init__.py,sha256=gv3vzrGyswu_mXp7r2lT_JgEJeBQRq4q7ixjzJXMa9M,7109
|
|
2
|
+
crontinel/__main__.py,sha256=js1dWK73QU0cj2vuDnvOFPp6PxpP8mDmWZ_h_IEtiKc,4829
|
|
3
|
+
crontinel/agent.py,sha256=xKB_s_VBdez0pTt_f6GJXnTY3GicnNPkw7M37qksUW0,19016
|
|
4
|
+
crontinel-0.2.1.dist-info/licenses/LICENSE,sha256=bYwT5qWZvouhkZoznxHCpvVtKxLEet6OIUJSsF0ISUU,1071
|
|
5
|
+
crontinel-0.2.1.dist-info/METADATA,sha256=_WYDW6tK7cdQSU57imi8vbxe3mTM7VGPL2m5xg3sau0,3505
|
|
6
|
+
crontinel-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
crontinel-0.2.1.dist-info/entry_points.txt,sha256=YkolUowZsmMdVqBXcB2Jc6ufU5XHYxjXWruFlgM6PLM,54
|
|
8
|
+
crontinel-0.2.1.dist-info/top_level.txt,sha256=4OAbN9YjFtphQt9TO_yl_k4mtZBwzXWhG2BfftT3a7Q,10
|
|
9
|
+
crontinel-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Harun R Rayhan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
crontinel
|