crontinel 0.2.1__tar.gz
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-0.2.1/LICENSE +21 -0
- crontinel-0.2.1/PKG-INFO +146 -0
- crontinel-0.2.1/README.md +126 -0
- crontinel-0.2.1/pyproject.toml +29 -0
- crontinel-0.2.1/setup.cfg +4 -0
- crontinel-0.2.1/src/crontinel/__init__.py +223 -0
- crontinel-0.2.1/src/crontinel/__main__.py +151 -0
- crontinel-0.2.1/src/crontinel/agent.py +516 -0
- crontinel-0.2.1/src/crontinel.egg-info/PKG-INFO +146 -0
- crontinel-0.2.1/src/crontinel.egg-info/SOURCES.txt +14 -0
- crontinel-0.2.1/src/crontinel.egg-info/dependency_links.txt +1 -0
- crontinel-0.2.1/src/crontinel.egg-info/entry_points.txt +2 -0
- crontinel-0.2.1/src/crontinel.egg-info/requires.txt +10 -0
- crontinel-0.2.1/src/crontinel.egg-info/top_level.txt +1 -0
- crontinel-0.2.1/tests/test_agent.py +486 -0
- crontinel-0.2.1/tests/test_crontinel.py +175 -0
crontinel-0.2.1/LICENSE
ADDED
|
@@ -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.
|
crontinel-0.2.1/PKG-INFO
ADDED
|
@@ -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,126 @@
|
|
|
1
|
+
# crontinel
|
|
2
|
+
|
|
3
|
+
Crontinel monitoring SDK for Python applications. Send cron, queue, and job monitoring events from any Python app.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
# Install directly from GitHub (PyPI publishing pending)
|
|
9
|
+
pip install git+https://github.com/crontinel/python.git
|
|
10
|
+
# or with httpx for async support:
|
|
11
|
+
pip install "crontinel[httpx] @ git+https://github.com/crontinel/python.git"
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Requirements
|
|
15
|
+
|
|
16
|
+
- Python 3.9+
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import os
|
|
22
|
+
|
|
23
|
+
from crontinel import Crontinel
|
|
24
|
+
|
|
25
|
+
client = Crontinel(
|
|
26
|
+
api_key=os.environ["CRONTINEL_API_KEY"],
|
|
27
|
+
app_name="my-worker",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# Report a cron job run
|
|
31
|
+
client.schedule_run(
|
|
32
|
+
command="reports:generate",
|
|
33
|
+
duration_ms=2340,
|
|
34
|
+
exit_code=0,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Report queue worker activity
|
|
38
|
+
client.queue_processed(
|
|
39
|
+
queue="emails",
|
|
40
|
+
processed=12,
|
|
41
|
+
failed=0,
|
|
42
|
+
duration_ms=8901,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# Send a custom alert
|
|
46
|
+
client.event(
|
|
47
|
+
key="disk-space-warning",
|
|
48
|
+
message="Disk usage above 90%",
|
|
49
|
+
state="firing",
|
|
50
|
+
)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Environment variables
|
|
54
|
+
|
|
55
|
+
| Variable | Default | Description |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `CRONTINEL_API_KEY` | — | Your Crontinel API key (required) |
|
|
58
|
+
| `CRONTINEL_API_URL` | `https://app.crontinel.com` | Crontinel SaaS or self-hosted endpoint |
|
|
59
|
+
|
|
60
|
+
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.
|
|
61
|
+
|
|
62
|
+
## Cron / heartbeat submission
|
|
63
|
+
|
|
64
|
+
Use `schedule_run()` when your cron or heartbeat job finishes and you want to submit one monitoring event to Crontinel:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
client.schedule_run(
|
|
68
|
+
command="reports:generate",
|
|
69
|
+
duration_ms=2340,
|
|
70
|
+
exit_code=0,
|
|
71
|
+
)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
If you want the SDK to measure and submit the run automatically, use `monitor_schedule()`:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
result, duration_ms, exit_code = client.monitor_schedule(
|
|
78
|
+
"reports:generate",
|
|
79
|
+
generate_daily_reports,
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Framework integrations
|
|
84
|
+
|
|
85
|
+
### APScheduler
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from apscheduler.schedulers.blocking import BlockingScheduler
|
|
89
|
+
from crontinel import Crontinel
|
|
90
|
+
|
|
91
|
+
client = Crontinel(api_key=os.environ["CRONTINEL_API_KEY"])
|
|
92
|
+
scheduler = BlockingScheduler()
|
|
93
|
+
|
|
94
|
+
@scheduler.scheduled_job("cron", hour=9, minute=0)
|
|
95
|
+
def daily_reports():
|
|
96
|
+
result, ms, code = client.monitor_schedule("daily-reports", send_reports)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Celery
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from crontinel import Crontinel
|
|
103
|
+
from celery.signals import task_success, task_failure
|
|
104
|
+
|
|
105
|
+
client = Crontinel(api_key=os.environ["CRONTINEL_API_KEY"])
|
|
106
|
+
|
|
107
|
+
@task_success.connect
|
|
108
|
+
def on_task_success(task=None, **kwargs):
|
|
109
|
+
client.queue_processed(
|
|
110
|
+
queue=task.name,
|
|
111
|
+
processed=1,
|
|
112
|
+
failed=0,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
@task_failure.connect
|
|
116
|
+
def on_task_failure(task=None, **kwargs):
|
|
117
|
+
client.queue_processed(
|
|
118
|
+
queue=task.name,
|
|
119
|
+
processed=0,
|
|
120
|
+
failed=1,
|
|
121
|
+
)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "crontinel"
|
|
7
|
+
version = "0.2.1"
|
|
8
|
+
description = "Crontinel monitoring SDK for Python applications"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Harun R Rayhan" }]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
crontinel = "crontinel.__main__:main"
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Repository = "https://github.com/crontinel/python"
|
|
19
|
+
Homepage = "https://crontinel.com"
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = ["pytest", "pytest-asyncio"]
|
|
23
|
+
httpx = ["httpx"]
|
|
24
|
+
requests = ["requests"]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
testpaths = ["tests"]
|
|
28
|
+
asyncio_mode = "auto"
|
|
29
|
+
minversion = "7.0"
|
|
@@ -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")
|
|
@@ -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())
|