From 89429789233e5909b1421d4bc6f763a1a2e58720 Mon Sep 17 00:00:00 2001 From: Marco D'Aleo Date: Fri, 2 Oct 2026 14:31:44 +0100 Subject: [PATCH] Add cron next-run display and speed up timer lookup --- README.md | 2 +- docs/cli.md | 10 ++- docs/cron.md | 9 ++ docs/security-model.md | 2 +- pyproject.toml | 2 +- src/schedls/backends/cron.py | 1 - src/schedls/backends/systemd.py | 33 ++++++- src/schedls/cronexpr.py | 140 ++++++++++++++++++++++++++++++ src/schedls/operations/inspect.py | 32 ++++++- tests/unit/test_cronexpr.py | 45 ++++++++++ tests/unit/test_operations.py | 66 ++++++++++++++ 11 files changed, 328 insertions(+), 14 deletions(-) create mode 100644 src/schedls/cronexpr.py create mode 100644 tests/unit/test_cronexpr.py diff --git a/README.md b/README.md index 7b5d9b1..b2e82fd 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ daemon, not a queue, and not a replacement scheduler. $ schedls NAME SCHEDULE NEXT BACKEND SCOPE STATUS backup daily at 02:00 tomorrow 02:00 systemd user waiting -cleanup 0 4 * * 0 — cron user active +cleanup 0 4 * * 0 Sun 04:00 cron user active logrotate daily — systemd system waiting ``` diff --git a/docs/cli.md b/docs/cli.md index 4ddc754..3f4020a 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -54,9 +54,13 @@ written to stderr as `Note:` lines. $ schedls show backup ``` -Shows one job in detail: status, backend and scope, whether schedls manages it, -the schedule, the next and previous runs, the command, the source paths, and any -systemd extras (persistent, jitter, accuracy, working directory, environment). +Shows one job in a field-oriented view: status, backend and scope, whether +schedls manages it, the schedule, next and previous runs, the command, source +paths, and any systemd extras (persistent, jitter, accuracy, working directory, +environment). Human-readable cron next runs are calculated in the host's local +timezone; cron previous runs and results remain unavailable because cron +exposes no per-job execution history. To preserve the JSON document contract, +cron `next_run` remains `null` in `--json` output. ### `new NAME` diff --git a/docs/cron.md b/docs/cron.md index f59ee73..92ec992 100644 --- a/docs/cron.md +++ b/docs/cron.md @@ -35,6 +35,15 @@ Periodic directories only contribute executable, run-parts-style file names. Every unrelated line is preserved exactly. `schedls` does not reformat, sort, normalize, or rewrite crontab content it did not create. +## Run times + +For five-field expressions and calendar nicknames, schedls calculates the next +cron occurrence in the host's local timezone for human-readable output. +`@reboot` has no wall-clock next run. Cron does not expose per-entry execution +history, so previous run times and results are shown as unavailable rather than +guessed. To keep the stable JSON document contract, cron `next_run` remains +`null` in `--json` output. + ## Managed blocks Jobs created by `schedls` in the current user's crontab live in a delimited diff --git a/docs/security-model.md b/docs/security-model.md index 0ad288b..5db313f 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -113,6 +113,6 @@ in CI. ## Availability, privacy -`0.2.0` requires `systemd-analyze` to create or validate calendar expressions +`0.3.0` requires `systemd-analyze` to create or validate calendar expressions and refuses the operation if it is unavailable. `schedls` makes no network requests and collects no telemetry. diff --git a/pyproject.toml b/pyproject.toml index b4ea1f0..23d77b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "schedls" -version = "0.2.0" +version = "0.3.0" description = "Inspect and manage Linux scheduled jobs" authors = [ { name = "Marco D'Aleo", email = "marco@marcodaleo.com" } diff --git a/src/schedls/backends/cron.py b/src/schedls/backends/cron.py index 8d9ea39..c5f851e 100644 --- a/src/schedls/backends/cron.py +++ b/src/schedls/backends/cron.py @@ -382,7 +382,6 @@ class CronBackend(SchedulerBackend): schedule=Schedule(ScheduleKind.CRON, (job_line.expression or "") if job_line else ""), command=Command(argv=(), raw=job_line.command if job_line else ""), source=JobSource("current user's crontab", line=block.begin_index), - next_run=None, last_run=None, cron=CronDetails( expression=job_line.expression if job_line else None, diff --git a/src/schedls/backends/systemd.py b/src/schedls/backends/systemd.py index 5ae61b1..21223e4 100644 --- a/src/schedls/backends/systemd.py +++ b/src/schedls/backends/systemd.py @@ -77,6 +77,9 @@ class SystemdBackend(SchedulerBackend): def __init__(self, runner: CommandRunner) -> None: self.runner = runner + self._manager_ok: dict[Scope, bool] = {} + self._user_lingering_checked = False + self._user_lingering: bool | None = None # -- capability detection ------------------------------------------------- @@ -87,7 +90,10 @@ class SystemdBackend(SchedulerBackend): return self.runner.has("systemd-analyze") def manager_ok(self, scope: Scope) -> bool: + if scope in self._manager_ok: + return self._manager_ok[scope] if not self.has_systemctl(): + self._manager_ok[scope] = False return False try: completed = self.runner.run( @@ -96,14 +102,19 @@ class SystemdBackend(SchedulerBackend): check=False, ) except OperationalError: + self._manager_ok[scope] = False return False state = completed.stdout.strip() - return state not in {"", "offline", "unknown"} + self._manager_ok[scope] = state not in {"", "offline", "unknown"} + return self._manager_ok[scope] def available(self) -> bool: return self.has_systemctl() and (self.manager_ok(Scope.USER) or self.manager_ok(Scope.SYSTEM)) def user_lingering(self) -> bool | None: + if self._user_lingering_checked: + return self._user_lingering + self._user_lingering_checked = True if not self.runner.has("loginctl"): return None try: @@ -116,7 +127,8 @@ class SystemdBackend(SchedulerBackend): return None if completed.returncode != 0: return None - return completed.stdout.strip().endswith("yes") + self._user_lingering = completed.stdout.strip().endswith("yes") + return self._user_lingering # -- calendar validation -------------------------------------------------- @@ -171,6 +183,20 @@ class SystemdBackend(SchedulerBackend): jobs.append(job) return jobs + def find(self, name: str) -> ScheduledJob | None: + """Look up a timer directly instead of discovering every timer.""" + candidates = (f"schedls-{name}.timer", f"{name}.timer") + for scope in (Scope.USER, Scope.SYSTEM): + if not self.manager_ok(scope): + continue + for unit in candidates: + if not is_safe_unit_name(unit): + continue + job = self._build_job(unit, scope) + if job is not None and job.name == name: + return job + return None + def _list_timer_units(self, scope: Scope) -> list[str]: units: list[str] = [] seen: set[str] = set() @@ -212,6 +238,7 @@ class SystemdBackend(SchedulerBackend): service_unit = None service_fragment = None service_sections = None + service_props: dict[str, str] = {} if service_unit: service_props = self._show(service_unit, scope) service_fragment = service_props.get("FragmentPath") or None @@ -227,7 +254,7 @@ class SystemdBackend(SchedulerBackend): command = _command_from_service(service_sections) next_run = parse_systemd_timestamp(properties.get("NextElapseUSecRealtime", "")) last_run = parse_systemd_timestamp(properties.get("LastTriggerUSec", "")) - last_result = properties.get("Result") or None + last_result = service_props.get("Result") or properties.get("Result") or None details = SystemdDetails( timer_unit=unit, diff --git a/src/schedls/cronexpr.py b/src/schedls/cronexpr.py new file mode 100644 index 0000000..67b1c4d --- /dev/null +++ b/src/schedls/cronexpr.py @@ -0,0 +1,140 @@ +"""Calculate upcoming occurrences for the cron syntax schedls accepts.""" + +from __future__ import annotations + +from datetime import UTC, date, datetime, time, timedelta, tzinfo +from zoneinfo import ZoneInfo + +_NICKNAMES = { + "@yearly": "0 0 1 1 *", + "@annually": "0 0 1 1 *", + "@monthly": "0 0 1 * *", + "@weekly": "0 0 * * 0", + "@daily": "0 0 * * *", + "@midnight": "0 0 * * *", + "@hourly": "0 * * * *", +} +_MONTHS = { + "jan": 1, + "feb": 2, + "mar": 3, + "apr": 4, + "may": 5, + "jun": 6, + "jul": 7, + "aug": 8, + "sep": 9, + "oct": 10, + "nov": 11, + "dec": 12, +} +_WEEKDAYS = {"sun": 0, "mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat": 6} + + +def next_occurrence(expression: str, *, after: datetime | None = None) -> datetime | None: + """Return the next local occurrence, or ``None`` when it cannot be known. + + ``@reboot`` and unsupported foreign expressions have no calculable + wall-clock next occurrence. + """ + expression = expression.lower() + if expression == "@reboot": + return None + expression = _NICKNAMES.get(expression, expression) + try: + minute_text, hour_text, dom_text, month_text, dow_text = expression.split() + minutes, _ = _field_values(minute_text, 0, 59) + hours, _ = _field_values(hour_text, 0, 23) + days, dom_any = _field_values(dom_text, 1, 31) + months, _ = _field_values(month_text, 1, 12, aliases=_MONTHS) + weekdays, dow_any = _field_values(dow_text, 0, 7, aliases=_WEEKDAYS) + except ValueError: + return None + + weekdays = {value % 7 for value in weekdays} + reference = after or datetime.now(_local_timezone()) + if reference.tzinfo is None: + raise ValueError("after must include a timezone") + zone = reference.tzinfo + reference = reference.astimezone(zone) + times = [(hour, minute) for hour in sorted(hours) for minute in sorted(minutes)] + + # Gregorian leap days can be eight years apart across a non-leap century. + for offset in range(9 * 366): + candidate_date = reference.date() + timedelta(days=offset) + if not _date_matches(candidate_date, months, days, weekdays, dom_any=dom_any, dow_any=dow_any): + continue + for hour, minute in times: + candidate = datetime.combine(candidate_date, time(hour, minute), tzinfo=zone) + if not _is_real_local_time(candidate, zone) or candidate <= reference: + continue + return candidate + return None + + +def _field_values( + field: str, + low: int, + high: int, + *, + aliases: dict[str, int] | None = None, +) -> tuple[set[int], bool]: + values: set[int] = set() + unrestricted = field == "*" + for part in field.split(","): + base, separator, step_text = part.partition("/") + step = int(step_text) if separator else 1 + if step < 1: + raise ValueError("invalid step") + if base == "*": + start, end = low, high + elif "-" in base: + start_text, end_text = base.split("-", 1) + start = _field_value(start_text, aliases) + end = _field_value(end_text, aliases) + else: + start = end = _field_value(base, aliases) + if not (low <= start <= high and low <= end <= high and start <= end): + raise ValueError("field out of range") + values.update(range(start, end + 1, step)) + return values, unrestricted + + +def _field_value(value: str, aliases: dict[str, int] | None) -> int: + if aliases and value in aliases: + return aliases[value] + return int(value) + + +def _date_matches( + candidate: date, + months: set[int], + days: set[int], + weekdays: set[int], + *, + dom_any: bool, + dow_any: bool, +) -> bool: + if candidate.month not in months: + return False + dom_matches = candidate.day in days + cron_weekday = (candidate.weekday() + 1) % 7 + dow_matches = cron_weekday in weekdays + if dom_any: + return dow_matches + if dow_any: + return dom_matches + return dom_matches or dow_matches + + +def _is_real_local_time(candidate: datetime, zone: tzinfo) -> bool: + normalized = candidate.astimezone(UTC).astimezone(zone) + return normalized.replace(tzinfo=None) == candidate.replace(tzinfo=None) + + +def _local_timezone() -> tzinfo: + try: + with open("/etc/localtime", "rb") as handle: + return ZoneInfo.from_file(handle) + except (OSError, ValueError): + return datetime.now().astimezone().tzinfo or UTC diff --git a/src/schedls/operations/inspect.py b/src/schedls/operations/inspect.py index 4576cc6..17373a0 100644 --- a/src/schedls/operations/inspect.py +++ b/src/schedls/operations/inspect.py @@ -4,8 +4,10 @@ from __future__ import annotations import os from collections.abc import Sequence +from datetime import datetime from ..backends.base import SchedulerBackend +from ..cronexpr import next_occurrence from ..errors import SchedlsError from ..models import Backend, ScheduledJob, Scope from ..output import Output, jobs_document @@ -76,7 +78,8 @@ def render_list(output: Output, jobs: Sequence[ScheduledJob], warnings: Sequence else: rows = [] for job in jobs: - next_text = format_short(job.next_run, utc=output.utc) if job.next_run else "—" + next_run = _next_run(job) + next_text = format_short(next_run, utc=output.utc) if next_run else "—" rows.append( [ job.name, @@ -89,7 +92,7 @@ def render_list(output: Output, jobs: Sequence[ScheduledJob], warnings: Sequence ) output.table(["NAME", "SCHEDULE", "NEXT", "BACKEND", "SCOPE", "STATUS"], rows) for warning in warnings: - output.diagnostic(f"Note: {warning}") + output.diagnostic(f"\nNote: {warning}") def render_show(output: Output, job: ScheduledJob) -> None: @@ -109,9 +112,10 @@ def render_show(output: Output, job: ScheduledJob) -> None: for expression in job.schedule.expressions: output.key_values([("OnCalendar", expression)]) output.line() - output.key_values([("Next", output.job_datetime(job.next_run) or "unknown")]) + next_run = _next_run(job) + output.key_values([("Next", output.job_datetime(next_run) or _next_unavailable(job))]) output.line() - previous = output.job_datetime(job.last_run) or "unknown" + previous = output.job_datetime(job.last_run) or _previous_unavailable(job) if job.last_result: previous = f"{previous}\nresult: {job.last_result}" output.key_values([("Previous", previous)]) @@ -156,3 +160,23 @@ def _backend_label(job: ScheduledJob) -> str: if job.backend is Backend.SYSTEMD: return f"systemd {job.scope.value} timer" return "cron" + + +def _next_unavailable(job: ScheduledJob) -> str: + if job.backend is Backend.CRON and job.schedule.expression.lower() == "@reboot": + return "unavailable (@reboot has no wall-clock next run)" + return "unavailable" + + +def _next_run(job: ScheduledJob) -> datetime | None: + if job.next_run is not None: + return job.next_run + if job.backend is Backend.CRON: + return next_occurrence(job.schedule.expression) + return None + + +def _previous_unavailable(job: ScheduledJob) -> str: + if job.backend is Backend.CRON: + return "unavailable (cron does not provide per-job history)" + return "unavailable" diff --git a/tests/unit/test_cronexpr.py b/tests/unit/test_cronexpr.py new file mode 100644 index 0000000..bf01463 --- /dev/null +++ b/tests/unit/test_cronexpr.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from zoneinfo import ZoneInfo + +from schedls.cronexpr import next_occurrence + + +def test_next_occurrence_for_hourly_schedule() -> None: + after = datetime(2026, 10, 2, 12, 17, 30, tzinfo=UTC) + + assert next_occurrence("17 * * * *", after=after) == datetime(2026, 10, 2, 13, 17, tzinfo=UTC) + + +def test_next_occurrence_uses_cron_day_of_month_or_weekday() -> None: + after = datetime(2026, 10, 12, 12, 0, tzinfo=UTC) + + assert next_occurrence("0 0 13 * fri", after=after) == datetime(2026, 10, 13, 0, 0, tzinfo=UTC) + + +def test_next_occurrence_treats_day_steps_as_restricted() -> None: + after = datetime(2026, 10, 2, 12, 0, tzinfo=UTC) + + assert next_occurrence("0 0 */2 * *", after=after) == datetime(2026, 10, 3, 0, 0, tzinfo=UTC) + assert next_occurrence("0 0 * * */2", after=after) == datetime(2026, 10, 3, 0, 0, tzinfo=UTC) + + +def test_next_occurrence_supports_nicknames_and_reboot() -> None: + after = datetime(2026, 10, 2, 12, 0, tzinfo=UTC) + + assert next_occurrence("@daily", after=after) == datetime(2026, 10, 3, 0, 0, tzinfo=UTC) + assert next_occurrence("@reboot", after=after) is None + + +def test_next_occurrence_skips_nonexistent_local_time() -> None: + london = ZoneInfo("Europe/London") + after = datetime(2026, 3, 29, 0, 0, tzinfo=london) + + assert next_occurrence("30 1 * * *", after=after) == datetime(2026, 3, 30, 1, 30, tzinfo=london) + + +def test_next_occurrence_handles_long_leap_day_gap() -> None: + after = datetime(2096, 3, 1, 0, 0, tzinfo=UTC) + + assert next_occurrence("0 0 29 2 *", after=after) == datetime(2104, 2, 29, 0, 0, tzinfo=UTC) diff --git a/tests/unit/test_operations.py b/tests/unit/test_operations.py index 655e368..5dc8e27 100644 --- a/tests/unit/test_operations.py +++ b/tests/unit/test_operations.py @@ -15,6 +15,7 @@ from schedls.interact import Interaction from schedls.models import ( Backend, Command, + CronDetails, JobSource, JobSpec, Schedule, @@ -72,6 +73,45 @@ def test_render_show() -> None: assert "systemd user timer" in text +def test_render_show_explains_unavailable_cron_history() -> None: + job = ScheduledJob( + name="cron-1", + backend=Backend.CRON, + scope=Scope.USER, + managed=False, + enabled=None, + schedule=Schedule(ScheduleKind.CRON, "0 2 * * *"), + command=Command(raw="/usr/bin/backup"), + source=JobSource("current user's crontab", line=1), + cron=CronDetails(expression="0 2 * * *", line=1), + ) + output, stream = _output() + + inspect_ops.render_show(output, job) + + assert "Previous unavailable (cron does not provide per-job history)" in stream.getvalue() + + +def test_render_show_keeps_cron_next_run_null_in_json() -> None: + job = ScheduledJob( + name="cron-1", + backend=Backend.CRON, + scope=Scope.USER, + managed=False, + enabled=None, + schedule=Schedule(ScheduleKind.CRON, "0 2 * * *"), + command=Command(raw="/usr/bin/backup"), + source=JobSource("current user's crontab", line=1), + cron=CronDetails(expression="0 2 * * *", line=1), + ) + output, stream = _output() + output.json_mode = True + + inspect_ops.render_show(output, job) + + assert '"next_run": null' in stream.getvalue() + + def test_filter_jobs() -> None: jobs = [_job(), _job("other")] assert inspect_ops.filter_jobs(jobs, managed=True) == jobs @@ -216,6 +256,32 @@ def test_systemd_backend_discovery_parses_units() -> None: assert job.command.argv == ("/usr/local/bin/backup", "/srv/data") assert job.enabled is True assert job.next_run is not None + assert job.last_result == "success" + + +def test_systemd_find_uses_direct_lookup_and_cached_manager_check() -> None: + def systemctl(argv, _input): + if "is-system-running" in argv: + return ("running\n", "") + if "show" in argv: + unit = argv[argv.index("show") + 1] + if unit == "schedls-backup.timer": + return ("LoadState=not-found\n", "") + if unit == "backup.timer": + return ("LoadState=loaded\nUnitFileState=enabled\n", "") + return ("", "") + + runner = FakeRunner(handlers={"systemctl": systemctl}, available={"systemctl"}) + backend = SystemdBackend(runner) + + assert backend.available() is True + job = backend.find("backup") + + assert job is not None + assert job.name == "backup" + calls = [argv for argv, _, _ in runner.calls] + assert sum("is-system-running" in argv for argv in calls) == 1 + assert not any("list-unit-files" in argv or "list-units" in argv for argv in calls) def test_plan_update_refuses_unmanaged() -> None: