sioncronaich 0.1.2__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.
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.3
2
+ Name: sioncronaich
3
+ Version: 0.1.2
4
+ Summary: Capture stdout, stderr and exit codes from cron jobs and view them in a web UI
5
+ Author: Adam Cuthbert
6
+ Author-email: Adam Cuthbert <54388772+ac3673@users.noreply.github.com>
7
+ Requires-Dist: pydantic>=2
8
+ Requires-Dist: requests>=2.32
9
+ Requires-Dist: click>=8.1
10
+ Requires-Dist: fastapi>=0.111 ; extra == 'server'
11
+ Requires-Dist: uvicorn[standard]>=0.29 ; extra == 'server'
12
+ Requires-Dist: jinja2>=3.1 ; extra == 'server'
13
+ Requires-Dist: pyyaml>=6.0 ; extra == 'server'
14
+ Requires-Python: >=3.12
15
+ Provides-Extra: server
16
+ Description-Content-Type: text/markdown
17
+
18
+
19
+ <p align="center">
20
+ <img width="350" height="150" src="img/sioncronaich.jpeg" alt='sioncronaich'>
21
+ </p>
22
+
23
+ <p align="center"><strong>sioncronaich</strong> <em>- A lightweight cron-job monitoring tool written in Python - from Gaelic "to synchronise, to chronicle"</em></p>
24
+
25
+
26
+ `sioncronaich` wraps any shell command, captures its **stdout**, **stderr** and **exit code**,
27
+ then POSTs the result to the sioncronaich web app, which stores everything in a local SQLite
28
+ database and renders it in a simple web dashboard.
29
+
30
+ ---
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ # From source with uv:
36
+ git clone <repo>
37
+ cd sioncronaich
38
+ uv sync
39
+ ```
40
+
41
+ ---
42
+
43
+ ## Quick start
44
+
45
+ ### 1 — Start the web app
46
+
47
+ ```bash
48
+ uv run uvicorn --factory sioncronaich.app:create_app --host 127.0.0.1 --port 8716
49
+ ```
50
+
51
+ Pass `--host`, `--port`, and any other server options directly to uvicorn.
52
+ See `uvicorn --help` for the full list.
53
+
54
+ The app reads the following environment variables:
55
+
56
+ | Environment variable | Default | Purpose |
57
+ |---|---|---|
58
+ | `SIONCRONAICH_DB` | `~/.local/share/sioncronaich/jobs.db` | SQLite database path |
59
+ | `LOG_CONFIG` | *(unset — logs to stderr at INFO)* | Path to a YAML logging config file |
60
+
61
+ ### 2 — Wrap a command
62
+
63
+ ```bash
64
+ sioncronaich --name "daily-backup" -- /usr/local/bin/backup.sh --full
65
+ ```
66
+
67
+ The wrapper exits with **the same exit code** as the wrapped command, so
68
+ existing cron alerting is unaffected. If posting to the web app fails, the
69
+ error is printed to stderr but the exit code is still that of the wrapped job.
70
+
71
+ ```
72
+ Usage: sioncronaich [OPTIONS] COMMAND...
73
+
74
+ Options:
75
+ --name TEXT Human-readable label for this job [required]
76
+ --endpoint TEXT URL of the POST /jobs endpoint
77
+ [default: http://127.0.0.1:8716/jobs]
78
+ --timeout INT HTTP request timeout in seconds [default: 10]
79
+ ```
80
+
81
+ ### 3 — Add to crontab
82
+
83
+ ```crontab
84
+ # m h dom mon dow command
85
+ 0 3 * * * sioncronaich --name daily-backup -- /usr/local/bin/backup.sh
86
+ */5 * * * * sioncronaich --name health-check -- /usr/local/bin/check.sh
87
+ ```
88
+
89
+ ### 4 — View the dashboard
90
+
91
+ Open **http://127.0.0.1:8716** in a browser for a colour-coded table of recent
92
+ job runs. stdout / stderr are available in collapsible panels.
93
+
94
+ The raw JSON API is also available:
95
+
96
+ | Method | Path | Description |
97
+ |---|---|---|
98
+ | `POST` | `/jobs` | Ingest a new job result (used by `sioncronaich`) |
99
+ | `GET` | `/jobs` | List job results as JSON (newest first) |
100
+ | `GET` | `/` | HTML dashboard |
101
+
102
+ Interactive API docs are served at **http://127.0.0.1:8716/docs**.
103
+
104
+ ---
105
+
106
+ ## Project layout
107
+
108
+ ```
109
+ src/sioncronaich/
110
+ ├── __init__.py version
111
+ ├── config.py env var helpers (db_path, configure_logging)
112
+ ├── models.py Pydantic models (JobResultCreate, JobResult)
113
+ ├── db.py SQLite CRUD helpers
114
+ ├── app.py FastAPI application
115
+ ├── script.py sioncronaich CLI wrapper
116
+ └── templates/
117
+ └── index.html Jinja2 dashboard template
118
+ logging.yaml default logging configuration
119
+ pyproject.toml
120
+ README.md
121
+ ```
122
+
123
+ ---
124
+
125
+ ## Logging
126
+
127
+ By default the app logs to stderr at INFO level. To use a custom logging
128
+ configuration, point `LOG_CONFIG` at a YAML file in the standard
129
+ [`logging.config.dictConfig`](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema)
130
+ format. A ready-to-use example is provided at `logging.yaml`:
131
+
132
+ ```bash
133
+ LOG_CONFIG=logging.yaml uv run uvicorn --factory sioncronaich.app:create_app
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Development
139
+
140
+ ```bash
141
+ uv sync --extra dev --extra server
142
+ pytest
143
+ ```
@@ -0,0 +1,126 @@
1
+
2
+ <p align="center">
3
+ <img width="350" height="150" src="img/sioncronaich.jpeg" alt='sioncronaich'>
4
+ </p>
5
+
6
+ <p align="center"><strong>sioncronaich</strong> <em>- A lightweight cron-job monitoring tool written in Python - from Gaelic "to synchronise, to chronicle"</em></p>
7
+
8
+
9
+ `sioncronaich` wraps any shell command, captures its **stdout**, **stderr** and **exit code**,
10
+ then POSTs the result to the sioncronaich web app, which stores everything in a local SQLite
11
+ database and renders it in a simple web dashboard.
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ # From source with uv:
19
+ git clone <repo>
20
+ cd sioncronaich
21
+ uv sync
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Quick start
27
+
28
+ ### 1 — Start the web app
29
+
30
+ ```bash
31
+ uv run uvicorn --factory sioncronaich.app:create_app --host 127.0.0.1 --port 8716
32
+ ```
33
+
34
+ Pass `--host`, `--port`, and any other server options directly to uvicorn.
35
+ See `uvicorn --help` for the full list.
36
+
37
+ The app reads the following environment variables:
38
+
39
+ | Environment variable | Default | Purpose |
40
+ |---|---|---|
41
+ | `SIONCRONAICH_DB` | `~/.local/share/sioncronaich/jobs.db` | SQLite database path |
42
+ | `LOG_CONFIG` | *(unset — logs to stderr at INFO)* | Path to a YAML logging config file |
43
+
44
+ ### 2 — Wrap a command
45
+
46
+ ```bash
47
+ sioncronaich --name "daily-backup" -- /usr/local/bin/backup.sh --full
48
+ ```
49
+
50
+ The wrapper exits with **the same exit code** as the wrapped command, so
51
+ existing cron alerting is unaffected. If posting to the web app fails, the
52
+ error is printed to stderr but the exit code is still that of the wrapped job.
53
+
54
+ ```
55
+ Usage: sioncronaich [OPTIONS] COMMAND...
56
+
57
+ Options:
58
+ --name TEXT Human-readable label for this job [required]
59
+ --endpoint TEXT URL of the POST /jobs endpoint
60
+ [default: http://127.0.0.1:8716/jobs]
61
+ --timeout INT HTTP request timeout in seconds [default: 10]
62
+ ```
63
+
64
+ ### 3 — Add to crontab
65
+
66
+ ```crontab
67
+ # m h dom mon dow command
68
+ 0 3 * * * sioncronaich --name daily-backup -- /usr/local/bin/backup.sh
69
+ */5 * * * * sioncronaich --name health-check -- /usr/local/bin/check.sh
70
+ ```
71
+
72
+ ### 4 — View the dashboard
73
+
74
+ Open **http://127.0.0.1:8716** in a browser for a colour-coded table of recent
75
+ job runs. stdout / stderr are available in collapsible panels.
76
+
77
+ The raw JSON API is also available:
78
+
79
+ | Method | Path | Description |
80
+ |---|---|---|
81
+ | `POST` | `/jobs` | Ingest a new job result (used by `sioncronaich`) |
82
+ | `GET` | `/jobs` | List job results as JSON (newest first) |
83
+ | `GET` | `/` | HTML dashboard |
84
+
85
+ Interactive API docs are served at **http://127.0.0.1:8716/docs**.
86
+
87
+ ---
88
+
89
+ ## Project layout
90
+
91
+ ```
92
+ src/sioncronaich/
93
+ ├── __init__.py version
94
+ ├── config.py env var helpers (db_path, configure_logging)
95
+ ├── models.py Pydantic models (JobResultCreate, JobResult)
96
+ ├── db.py SQLite CRUD helpers
97
+ ├── app.py FastAPI application
98
+ ├── script.py sioncronaich CLI wrapper
99
+ └── templates/
100
+ └── index.html Jinja2 dashboard template
101
+ logging.yaml default logging configuration
102
+ pyproject.toml
103
+ README.md
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Logging
109
+
110
+ By default the app logs to stderr at INFO level. To use a custom logging
111
+ configuration, point `LOG_CONFIG` at a YAML file in the standard
112
+ [`logging.config.dictConfig`](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema)
113
+ format. A ready-to-use example is provided at `logging.yaml`:
114
+
115
+ ```bash
116
+ LOG_CONFIG=logging.yaml uv run uvicorn --factory sioncronaich.app:create_app
117
+ ```
118
+
119
+ ---
120
+
121
+ ## Development
122
+
123
+ ```bash
124
+ uv sync --extra dev --extra server
125
+ pytest
126
+ ```
@@ -0,0 +1,110 @@
1
+ [project]
2
+ name = "sioncronaich"
3
+ version = "0.1.2"
4
+ description = "Capture stdout, stderr and exit codes from cron jobs and view them in a web UI"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Adam Cuthbert", email = "54388772+ac3673@users.noreply.github.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "pydantic>=2",
12
+ "requests>=2.32",
13
+ "click>=8.1",
14
+ ]
15
+
16
+ [project.scripts]
17
+ sioncronaich = "sioncronaich.script:main"
18
+
19
+ [project.optional-dependencies]
20
+ server = [
21
+ "fastapi>=0.111",
22
+ "uvicorn[standard]>=0.29",
23
+ "jinja2>=3.1",
24
+ "pyyaml>=6.0",
25
+ ]
26
+
27
+ [dependency-groups]
28
+ dev = [
29
+ "commitizen>=4.11.0",
30
+ "mypy>=1.10",
31
+ "types-pyyaml>=6.0",
32
+ "types-requests>=2.32",
33
+ "genbadge[coverage]>=1.1",
34
+ "httpxyz>=0.30",
35
+ "prek>=0.2.27",
36
+ "pytest>=8",
37
+ "pytest-asyncio>=1.0",
38
+ "pytest-cov>=7.0.0",
39
+ "ruff>=0.11",
40
+ ]
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.11.7,<0.12.0"]
44
+ build-backend = "uv_build"
45
+
46
+ [tool.ruff]
47
+ line-length = 96
48
+ fix = true
49
+ target-version = "py312"
50
+ output-format = "concise"
51
+
52
+ [tool.ruff.lint]
53
+ select = [
54
+ "A", # flake8-builtins
55
+ "ARG", # flake8-unused-arguments
56
+ "B", # flake8-bugbear
57
+ "C4", # flake8-comprehensions
58
+ "C90", # mccabe
59
+ "DTZ", # flake8-datetimez
60
+ "E", # pycodestyle error
61
+ "F", # pyflakes
62
+ "FAST", # fastapi
63
+ "I", # isort
64
+ "PT", # flake8-pytest-style
65
+ "PTH", # flake8-use-pathlib
66
+ "RUF", # Ruff-specific rules
67
+ "SIM", # flake8-simplify
68
+ "UP", # pyupgrade
69
+ "W", # pycodestyle warning
70
+ ]
71
+ ignore = [
72
+ "B008", # function-call-in-default-argument
73
+ "E501", # line-too-long, handled by the formatter
74
+ "PT011", # pytest-raises-too-broad
75
+ "PTH201", # path-constructor-current-directory
76
+ ]
77
+
78
+ [tool.ruff.lint.per-file-ignores]
79
+ "tests/*.py" = [
80
+ "ANN201", # missing-return-type-undocumented-public-function
81
+ ]
82
+
83
+ [tool.ruff.lint.mccabe]
84
+ max-complexity = 12
85
+
86
+ [tool.mypy]
87
+ show_column_numbers = true
88
+
89
+ [tool.pytest.ini_options]
90
+ asyncio_mode = "auto"
91
+ log_cli = true
92
+ log_level = "DEBUG"
93
+ log_format = "%(asctime)s.%(msecs).03d | %(name)s | %(levelname)s: %(message)s"
94
+ log_date_format = "%Y-%m-%d %H:%M:%S"
95
+ addopts = [
96
+ "--cov=sioncronaich",
97
+ "--cov-report=term-missing",
98
+ ]
99
+
100
+ [tool.commitizen]
101
+ name = "cz_conventional_commits"
102
+ tag_format = "v$version"
103
+ update_changelog_on_bump = true
104
+ changelog_incremental = true
105
+ changelog_file = "CHANGELOG.md"
106
+ changelog_template = "changelog.md.j2"
107
+ version_provider = "uv"
108
+ version_files = [
109
+ "src/sioncronaich/__init__.py:__version__",
110
+ ]
@@ -0,0 +1,3 @@
1
+ """sioncronaich — cron job output capture and monitoring."""
2
+
3
+ __version__ = "0.1.2"
@@ -0,0 +1,101 @@
1
+ """FastAPI web application — job ingest endpoint and HTML dashboard."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import AsyncGenerator
7
+ from contextlib import asynccontextmanager
8
+ from pathlib import Path
9
+
10
+ from fastapi import FastAPI, Request, Response
11
+ from fastapi.responses import HTMLResponse
12
+ from fastapi.templating import Jinja2Templates
13
+
14
+ from sioncronaich import __version__
15
+ from sioncronaich.config import configure_logging, db_path
16
+ from sioncronaich.db import get_jobs, init_db, insert_job
17
+ from sioncronaich.models import JobResult, JobResultCreate
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _TEMPLATES_DIR = Path(__file__).parent / "templates"
22
+
23
+
24
+ @asynccontextmanager
25
+ async def _lifespan(_app: FastAPI) -> AsyncGenerator[None, None]:
26
+ """Configure logging and ensure the database schema exists when the server starts."""
27
+ configure_logging()
28
+ resolved = init_db(db_path())
29
+ logger.info("Database ready at %s", resolved)
30
+ yield
31
+
32
+
33
+ app = FastAPI(
34
+ title="sioncronaich",
35
+ description="Cron job output capture and monitoring",
36
+ version=__version__,
37
+ lifespan=_lifespan,
38
+ )
39
+
40
+ templates = Jinja2Templates(directory=str(_TEMPLATES_DIR))
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # API routes
45
+ # ---------------------------------------------------------------------------
46
+
47
+
48
+ @app.post("/jobs", response_model=JobResult, status_code=201)
49
+ def create_job(job: JobResultCreate) -> JobResult:
50
+ """Receive and persist a single job result from the sioncronaich script."""
51
+ logger.info("Received job result: %s (exit_code=%s)", job.job_name, job.exit_code)
52
+ return insert_job(job, db_path=db_path())
53
+
54
+
55
+ @app.get("/jobs", response_model=list[JobResult])
56
+ def list_jobs(limit: int = 200, offset: int = 0) -> list[JobResult]:
57
+ """Return job results as JSON (newest first)."""
58
+ return get_jobs(limit=limit, offset=offset, db_path=db_path())
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # HTML dashboard
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ @app.get("/", response_class=HTMLResponse)
67
+ def dashboard(request: Request, limit: int = 200, offset: int = 0) -> Response:
68
+ """Render an HTML table of recent job results."""
69
+ jobs = get_jobs(limit=limit, offset=offset, db_path=db_path())
70
+ return templates.TemplateResponse(
71
+ request,
72
+ "index.html",
73
+ {
74
+ "jobs": jobs,
75
+ "limit": limit,
76
+ "offset": offset,
77
+ },
78
+ )
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Entry point
83
+ # ---------------------------------------------------------------------------
84
+
85
+
86
+ def create_app() -> FastAPI:
87
+ """App factory — used with ``uvicorn --factory sioncronaich.app:create_app``."""
88
+ return app
89
+
90
+
91
+ if __name__ == "__main__": # pragma: no cover
92
+ import argparse
93
+
94
+ import uvicorn
95
+
96
+ parser = argparse.ArgumentParser(description="Run the sioncronaich web app.")
97
+ parser.add_argument("--host", default="127.0.0.1", help="Bind address (default: 127.0.0.1)")
98
+ parser.add_argument("--port", type=int, default=8716, help="Bind port (default: 8716)")
99
+ args = parser.parse_args()
100
+
101
+ uvicorn.run("sioncronaich.app:create_app", host=args.host, port=args.port, factory=True)
@@ -0,0 +1,40 @@
1
+ """Environment-based configuration for the sioncronaich server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import logging.config
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+
12
+
13
+ def db_path() -> Path | None:
14
+ """Return the database path from ``SIONCRONAICH_DB``, or ``None`` for the default."""
15
+ raw = os.environ.get("SIONCRONAICH_DB")
16
+ return Path(raw) if raw else None
17
+
18
+
19
+ def configure_logging() -> None:
20
+ """Load logging configuration from the file named in ``LOG_CONFIG``.
21
+
22
+ Falls back to a sensible default if the variable is unset or the file
23
+ does not exist.
24
+ """
25
+ log_config_path = os.environ.get("LOG_CONFIG")
26
+
27
+ if log_config_path:
28
+ path = Path(log_config_path)
29
+ if not path.is_file():
30
+ raise FileNotFoundError(f"LOG_CONFIG points to a non-existent file: {path}")
31
+ with path.open(encoding="utf-8") as fh:
32
+ config = yaml.safe_load(fh)
33
+ logging.config.dictConfig(config)
34
+ else:
35
+ # Minimal default: INFO to stderr
36
+ logging.basicConfig(
37
+ format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
38
+ datefmt="%Y-%m-%d %H:%M:%S",
39
+ level=logging.INFO,
40
+ )
@@ -0,0 +1,133 @@
1
+ """SQLite persistence layer for job results."""
2
+
3
+ import sqlite3
4
+ from collections.abc import Generator
5
+ from contextlib import contextmanager
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+
9
+ from sioncronaich.models import JobResult, JobResultCreate
10
+
11
+ _CREATE_TABLE = """
12
+ CREATE TABLE IF NOT EXISTS job_results (
13
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ job_name TEXT NOT NULL,
15
+ hostname TEXT NOT NULL,
16
+ command TEXT NOT NULL,
17
+ stdout TEXT NOT NULL,
18
+ stderr TEXT NOT NULL,
19
+ exit_code INTEGER NOT NULL,
20
+ started_at TEXT NOT NULL,
21
+ finished_at TEXT NOT NULL
22
+ );
23
+ """
24
+
25
+
26
+ def _default_db_path() -> Path:
27
+ base = Path.home() / ".local" / "share" / "sioncronaich"
28
+ base.mkdir(parents=True, exist_ok=True)
29
+ return base / "jobs.db"
30
+
31
+
32
+ @contextmanager
33
+ def _connect(db_path: Path) -> Generator[sqlite3.Connection, None, None]:
34
+ conn = sqlite3.connect(db_path)
35
+ conn.row_factory = sqlite3.Row
36
+ try:
37
+ yield conn
38
+ conn.commit()
39
+ except Exception: # pragma: no cover
40
+ conn.rollback()
41
+ raise
42
+ finally:
43
+ conn.close()
44
+
45
+
46
+ def init_db(db_path: Path | None = None) -> Path:
47
+ """Create the database schema if it does not already exist.
48
+
49
+ Returns the resolved path to the database file.
50
+ """
51
+ resolved = db_path or _default_db_path()
52
+ with _connect(resolved) as conn:
53
+ conn.execute(_CREATE_TABLE)
54
+ return resolved
55
+
56
+
57
+ def insert_job(job: JobResultCreate, db_path: Path | None = None) -> JobResult:
58
+ """Persist a new job result and return it with its assigned *id*."""
59
+ resolved = db_path or _default_db_path()
60
+ with _connect(resolved) as conn:
61
+ cursor = conn.execute(
62
+ """
63
+ INSERT INTO job_results
64
+ (job_name, hostname, command, stdout, stderr, exit_code, started_at, finished_at)
65
+ VALUES
66
+ (:job_name, :hostname, :command, :stdout, :stderr, :exit_code, :started_at, :finished_at)
67
+ """,
68
+ {
69
+ "job_name": job.job_name,
70
+ "hostname": job.hostname,
71
+ "command": job.command,
72
+ "stdout": job.stdout,
73
+ "stderr": job.stderr,
74
+ "exit_code": job.exit_code,
75
+ "started_at": job.started_at.isoformat(),
76
+ "finished_at": job.finished_at.isoformat(),
77
+ },
78
+ )
79
+ row_id: int = cursor.lastrowid # type: ignore[assignment]
80
+
81
+ return JobResult(
82
+ id=row_id,
83
+ job_name=job.job_name,
84
+ hostname=job.hostname,
85
+ command=job.command,
86
+ stdout=job.stdout,
87
+ stderr=job.stderr,
88
+ exit_code=job.exit_code,
89
+ started_at=job.started_at,
90
+ finished_at=job.finished_at,
91
+ )
92
+
93
+
94
+ def _parse_dt(value: str) -> datetime:
95
+ dt = datetime.fromisoformat(value)
96
+ if dt.tzinfo is None:
97
+ dt = dt.replace(tzinfo=UTC)
98
+ return dt
99
+
100
+
101
+ def get_jobs(
102
+ *,
103
+ limit: int = 200,
104
+ offset: int = 0,
105
+ db_path: Path | None = None,
106
+ ) -> list[JobResult]:
107
+ """Return the most-recent *limit* job results, newest first."""
108
+ resolved = db_path or _default_db_path()
109
+ with _connect(resolved) as conn:
110
+ rows = conn.execute(
111
+ """
112
+ SELECT id, job_name, hostname, command, stdout, stderr, exit_code, started_at, finished_at
113
+ FROM job_results
114
+ ORDER BY id DESC
115
+ LIMIT :limit OFFSET :offset
116
+ """,
117
+ {"limit": limit, "offset": offset},
118
+ ).fetchall()
119
+
120
+ return [
121
+ JobResult(
122
+ id=row["id"],
123
+ job_name=row["job_name"],
124
+ hostname=row["hostname"],
125
+ command=row["command"],
126
+ stdout=row["stdout"],
127
+ stderr=row["stderr"],
128
+ exit_code=row["exit_code"],
129
+ started_at=_parse_dt(row["started_at"]),
130
+ finished_at=_parse_dt(row["finished_at"]),
131
+ )
132
+ for row in rows
133
+ ]
@@ -0,0 +1,36 @@
1
+ """Shared Pydantic models used by both the script and the web app."""
2
+
3
+ from datetime import datetime
4
+
5
+ from pydantic import BaseModel, computed_field
6
+
7
+
8
+ class JobResultCreate(BaseModel):
9
+ """Payload posted by the sioncronaich script after a job finishes."""
10
+
11
+ job_name: str
12
+ hostname: str
13
+ command: str
14
+ stdout: str
15
+ stderr: str
16
+ exit_code: int
17
+ started_at: datetime
18
+ finished_at: datetime
19
+
20
+ @computed_field # type: ignore[misc]
21
+ @property
22
+ def duration_seconds(self) -> float:
23
+ return (self.finished_at - self.started_at).total_seconds()
24
+
25
+
26
+ class JobResult(JobResultCreate):
27
+ """A job result as stored in (and returned from) the database."""
28
+
29
+ id: int
30
+
31
+ @computed_field # type: ignore[misc]
32
+ @property
33
+ def succeeded(self) -> bool:
34
+ return self.exit_code == 0
35
+
36
+ model_config = {"from_attributes": True}
@@ -0,0 +1,112 @@
1
+ """sioncronaich -- wrap a command, capture its output, and POST the result."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shlex
6
+ import socket
7
+ import subprocess
8
+ import sys
9
+ from datetime import UTC, datetime
10
+
11
+ import click
12
+ import requests
13
+
14
+ from sioncronaich.models import JobResultCreate
15
+
16
+
17
+ def _now() -> datetime:
18
+ return datetime.now(tz=UTC)
19
+
20
+
21
+ def _run_command(command: tuple[str, ...]) -> tuple[str, str, int, datetime, datetime]:
22
+ """Execute *command* via the system shell, capture output and return
23
+ (stdout, stderr, exit_code, started_at, finished_at).
24
+
25
+ Running via the shell allows shell built-ins (cd, export, …) and
26
+ operators (&&, ||, ;, pipes) to work as expected.
27
+ """
28
+ started_at = _now()
29
+ # shlex.join() produces POSIX quoting for sh; Windows cmd.exe needs plain joining
30
+ shell_cmd = " ".join(command) if sys.platform == "win32" else shlex.join(command)
31
+ result = subprocess.run(
32
+ shell_cmd,
33
+ shell=True,
34
+ capture_output=True,
35
+ text=True,
36
+ )
37
+ finished_at = _now()
38
+ return result.stdout, result.stderr, result.returncode, started_at, finished_at
39
+
40
+
41
+ def _post_result(endpoint: str, payload: JobResultCreate, timeout: int) -> None:
42
+ """POST the job result to the sioncronaich web app.
43
+
44
+ Failures are printed to stderr but never raise -- the wrapped job's exit
45
+ code should not be affected by a reporting error.
46
+ """
47
+ try:
48
+ response = requests.post(
49
+ endpoint,
50
+ data=payload.model_dump_json(),
51
+ headers={"Content-Type": "application/json"},
52
+ timeout=timeout,
53
+ )
54
+ response.raise_for_status()
55
+ except requests.RequestException as exc:
56
+ click.echo(f"sioncronaich: failed to post result to {endpoint!r}: {exc}", err=True)
57
+
58
+
59
+ @click.command(
60
+ context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
61
+ help=(
62
+ "Wrap COMMAND, capture its stdout/stderr/exit-code and POST the result "
63
+ "to a sioncronaich web app. All arguments after -- are treated as the "
64
+ "command to run.\n\n"
65
+ "Example (crontab):\n\n"
66
+ " 0 3 * * * sioncronaich --name daily-backup --endpoint http://mon:8716/jobs -- /usr/local/bin/backup.sh"
67
+ ),
68
+ )
69
+ @click.option(
70
+ "--name",
71
+ required=True,
72
+ help="Human-readable label for this job (e.g. 'daily-backup').",
73
+ )
74
+ @click.option(
75
+ "--endpoint",
76
+ default="http://127.0.0.1:8716/jobs",
77
+ show_default=True,
78
+ help="URL of the sioncronaich POST /jobs endpoint.",
79
+ )
80
+ @click.option(
81
+ "--timeout",
82
+ default=10,
83
+ show_default=True,
84
+ help="HTTP request timeout in seconds when posting the result.",
85
+ )
86
+ @click.argument("command", nargs=-1, type=click.UNPROCESSED, required=True)
87
+ def main(
88
+ name: str,
89
+ endpoint: str,
90
+ timeout: int,
91
+ command: tuple[str, ...],
92
+ ) -> None:
93
+ stdout, stderr, exit_code, started_at, finished_at = _run_command(command)
94
+
95
+ payload = JobResultCreate(
96
+ job_name=name,
97
+ hostname=socket.gethostname(),
98
+ command=" ".join(command),
99
+ stdout=stdout,
100
+ stderr=stderr,
101
+ exit_code=exit_code,
102
+ started_at=started_at,
103
+ finished_at=finished_at,
104
+ )
105
+
106
+ _post_result(endpoint, payload, timeout)
107
+
108
+ sys.exit(exit_code)
109
+
110
+
111
+ if __name__ == "__main__": # pragma: no cover
112
+ main()
@@ -0,0 +1,224 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>sioncronaich — cron job monitor</title>
7
+ <style>
8
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
9
+
10
+ body {
11
+ font-family: ui-monospace, "Cascadia Code", "Fira Mono", monospace;
12
+ background: #0f1117;
13
+ color: #e2e8f0;
14
+ padding: 2rem;
15
+ }
16
+
17
+ h1 {
18
+ font-size: 1.5rem;
19
+ margin-bottom: 0.25rem;
20
+ color: #a78bfa;
21
+ letter-spacing: 0.05em;
22
+ }
23
+
24
+ .subtitle {
25
+ font-size: 0.8rem;
26
+ color: #64748b;
27
+ margin-bottom: 1.5rem;
28
+ }
29
+
30
+ .table-wrapper {
31
+ overflow-x: auto;
32
+ border-radius: 0.5rem;
33
+ border: 1px solid #1e293b;
34
+ }
35
+
36
+ table {
37
+ width: 100%;
38
+ border-collapse: collapse;
39
+ font-size: 0.82rem;
40
+ }
41
+
42
+ thead {
43
+ background: #1e293b;
44
+ }
45
+
46
+ th {
47
+ padding: 0.65rem 0.9rem;
48
+ text-align: left;
49
+ color: #94a3b8;
50
+ font-weight: 600;
51
+ white-space: nowrap;
52
+ border-bottom: 1px solid #334155;
53
+ }
54
+
55
+ tbody tr {
56
+ border-bottom: 1px solid #1e293b;
57
+ transition: background 0.1s;
58
+ }
59
+
60
+ tbody tr:last-child { border-bottom: none; }
61
+ tbody tr:hover { background: #1a2235; }
62
+
63
+ td {
64
+ padding: 0.55rem 0.9rem;
65
+ vertical-align: top;
66
+ color: #cbd5e1;
67
+ }
68
+
69
+ .badge {
70
+ display: inline-block;
71
+ padding: 0.15rem 0.55rem;
72
+ border-radius: 9999px;
73
+ font-size: 0.75rem;
74
+ font-weight: 700;
75
+ letter-spacing: 0.03em;
76
+ }
77
+ .badge-ok { background: #14532d; color: #4ade80; }
78
+ .badge-err { background: #450a0a; color: #f87171; }
79
+
80
+ .cmd {
81
+ color: #e2e8f0;
82
+ max-width: 28ch;
83
+ overflow: hidden;
84
+ text-overflow: ellipsis;
85
+ white-space: nowrap;
86
+ }
87
+
88
+ .dur { color: #7dd3fc; }
89
+ .ts { color: #64748b; white-space: nowrap; }
90
+
91
+ details { margin-top: 0.1rem; }
92
+
93
+ summary {
94
+ cursor: pointer;
95
+ color: #7c3aed;
96
+ font-size: 0.75rem;
97
+ user-select: none;
98
+ list-style: none;
99
+ }
100
+ summary::-webkit-details-marker { display: none; }
101
+ summary::before { content: "▶ "; font-size: 0.6rem; }
102
+ details[open] summary::before { content: "▼ "; }
103
+
104
+ pre {
105
+ margin-top: 0.4rem;
106
+ padding: 0.6rem 0.8rem;
107
+ background: #0a0e17;
108
+ border: 1px solid #1e293b;
109
+ border-radius: 0.35rem;
110
+ white-space: pre-wrap;
111
+ word-break: break-all;
112
+ max-height: 18rem;
113
+ overflow-y: auto;
114
+ font-size: 0.78rem;
115
+ color: #94a3b8;
116
+ min-width: 30ch;
117
+ }
118
+
119
+ .empty {
120
+ text-align: center;
121
+ padding: 3rem;
122
+ color: #334155;
123
+ font-size: 0.9rem;
124
+ }
125
+
126
+ .pagination {
127
+ margin-top: 1.2rem;
128
+ display: flex;
129
+ gap: 0.75rem;
130
+ align-items: center;
131
+ font-size: 0.8rem;
132
+ color: #64748b;
133
+ }
134
+
135
+ .pagination a {
136
+ color: #a78bfa;
137
+ text-decoration: none;
138
+ padding: 0.25rem 0.6rem;
139
+ border: 1px solid #334155;
140
+ border-radius: 0.3rem;
141
+ }
142
+ .pagination a:hover { background: #1e293b; }
143
+ </style>
144
+ </head>
145
+ <body>
146
+
147
+ <h1>sioncronaich</h1>
148
+ <p class="subtitle">cron job output monitor &mdash; showing {{ jobs | length }} result(s)</p>
149
+
150
+ <div class="table-wrapper">
151
+ <table>
152
+ <thead>
153
+ <tr>
154
+ <th>#</th>
155
+ <th>Job</th>
156
+ <th>Host</th>
157
+ <th>Status</th>
158
+ <th>Command</th>
159
+ <th>Duration</th>
160
+ <th>Started (UTC)</th>
161
+ <th>stdout</th>
162
+ <th>stderr</th>
163
+ </tr>
164
+ </thead>
165
+ <tbody>
166
+ {% if jobs %}
167
+ {% for job in jobs %}
168
+ <tr>
169
+ <td class="ts">{{ job.id }}</td>
170
+ <td>{{ job.job_name }}</td>
171
+ <td>{{ job.hostname }}</td>
172
+ <td>
173
+ {% if job.succeeded %}
174
+ <span class="badge badge-ok">OK&nbsp;(0)</span>
175
+ {% else %}
176
+ <span class="badge badge-err">ERR&nbsp;({{ job.exit_code }})</span>
177
+ {% endif %}
178
+ </td>
179
+ <td><span class="cmd" title="{{ job.command }}">{{ job.command }}</span></td>
180
+ <td class="dur">{{ "%.3f"|format(job.duration_seconds) }}s</td>
181
+ <td class="ts">{{ job.started_at.strftime("%Y-%m-%d %H:%M:%S") }}</td>
182
+ <td>
183
+ {% if job.stdout %}
184
+ <details>
185
+ <summary>show stdout</summary>
186
+ <pre>{{ job.stdout }}</pre>
187
+ </details>
188
+ {% else %}
189
+ <span style="color:#334155">(empty)</span>
190
+ {% endif %}
191
+ </td>
192
+ <td>
193
+ {% if job.stderr %}
194
+ <details>
195
+ <summary>show stderr</summary>
196
+ <pre>{{ job.stderr }}</pre>
197
+ </details>
198
+ {% else %}
199
+ <span style="color:#334155">(empty)</span>
200
+ {% endif %}
201
+ </td>
202
+ </tr>
203
+ {% endfor %}
204
+ {% else %}
205
+ <tr>
206
+ <td colspan="8" class="empty">No job results yet — run <code>sioncronaich-run</code> to capture your first job.</td>
207
+ </tr>
208
+ {% endif %}
209
+ </tbody>
210
+ </table>
211
+ </div>
212
+
213
+ <div class="pagination">
214
+ {% if offset > 0 %}
215
+ <a href="/?limit={{ limit }}&offset={{ [offset - limit, 0] | max }}">&larr; newer</a>
216
+ {% endif %}
217
+ <span>offset {{ offset }}, limit {{ limit }}</span>
218
+ {% if jobs | length == limit %}
219
+ <a href="/?limit={{ limit }}&offset={{ offset + limit }}">older &rarr;</a>
220
+ {% endif %}
221
+ </div>
222
+
223
+ </body>
224
+ </html>