diff --git a/napalm_device_types/_scheduled_reading.py b/napalm_device_types/_scheduled_reading.py index 9dba4ef..7e09a4a 100644 --- a/napalm_device_types/_scheduled_reading.py +++ b/napalm_device_types/_scheduled_reading.py @@ -37,7 +37,8 @@ UNIT_PROPERTIES = "Id,ExecStart,User,Result,FragmentPath" _RUN_PARTS_NAME = re.compile(r"^[A-Za-z0-9_-]+$") _SECTION = re.compile(r"^\[([a-z-]+)(?: (.*))?\]$") -_OWNERS_SH = ( +#: Reads definition paths on stdin, prints ``: `` for each a package owns. +OWNERS_SH = ( "if command -v dpkg >/dev/null 2>&1; then xargs dpkg -S 2>/dev/null; " "elif command -v rpm >/dev/null 2>&1; then while read -r p; do " 'o=$(rpm -qf --qf \'%{NAME}\' -- "$p" 2>/dev/null) && printf \'%s: %s\\n\' "$o" "$p"; done; ' @@ -47,6 +48,10 @@ _OWNERS_SH = ( ) +#: Prints the host's time zone: an IANA name, or a path ending in ``zoneinfo/``. +TIME_ZONE_SH = "cat /etc/timezone 2>/dev/null || readlink /etc/localtime 2>/dev/null" + + @dataclass(frozen=True) class Paths: """Where a host keeps its scheduled jobs.""" @@ -58,7 +63,8 @@ class Paths: anacrontab: str script_dir: str systemd_marker: str = "/run/systemd/system" - owners_sh: str = _OWNERS_SH + owners_sh: str = OWNERS_SH + time_zone_sh: str = TIME_ZONE_SH @dataclass @@ -119,7 +125,7 @@ def reading_command(paths: Paths) -> str: parts.append(_files("script", f"{_q(paths.script_dir)}/*")) parts.append(_timers(paths)) parts.append( - "echo '[tz]'; cat /etc/timezone 2>/dev/null || readlink /etc/localtime 2>/dev/null; " + f"echo '[tz]'; {{ {paths.time_zone_sh}; }}; " f"echo '[owners]'; printf '%s\\n' \"$P\" | sed '/^$/d' | {{ {paths.owners_sh}; }}; " "printf '%s%s\\n' SJ_ END" ) diff --git a/napalm_device_types/scheduled_jobs_posix.py b/napalm_device_types/scheduled_jobs_posix.py index 91bfe61..441a198 100644 --- a/napalm_device_types/scheduled_jobs_posix.py +++ b/napalm_device_types/scheduled_jobs_posix.py @@ -29,6 +29,7 @@ command as its user the way cron runs it (``_crontab.run_script``). from __future__ import annotations +import fnmatch import shlex from collections.abc import Sequence from typing import TYPE_CHECKING, ClassVar @@ -45,7 +46,9 @@ from napalm_device_types._crontab import ( without_job, ) from napalm_device_types._scheduled_reading import ( + OWNERS_SH, SCHEDULE_HEADER, + TIME_ZONE_SH, Paths, Reading, parse_reading, @@ -114,6 +117,14 @@ class PosixScheduledJobsMixin(ScheduledJobsMixin): ROOT_GROUP: ClassVar[str] = "root" #: Prints " " of the path appended. STAT_ARGV: ClassVar[tuple[str, ...]] = ("stat", "-c", "%a %U %G", "--") + #: ``install`` and how it makes missing directories (FreeBSD's ``-D`` is a destdir). + INSTALL: ClassVar[tuple[str, ...]] = ("install", "-D") + #: ``sh`` that reads definition paths on stdin and prints ``: ``. + OWNERS_SH: ClassVar[str] = OWNERS_SH + #: ``sh`` that prints the time zone: an IANA name, or a path ending in ``zoneinfo/``. + TIME_ZONE_SH: ClassVar[str] = TIME_ZONE_SH + #: ``fnmatch`` patterns on a job's ``source``: what the platform generates is ``platform``. + PLATFORM_SOURCES: ClassVar[tuple[str, ...]] = () #: Run as root after a user's crontab was written; for a host that keeps it elsewhere too. CRONTAB_AFTER_WRITE: ClassVar[tuple[str, ...] | None] = None @@ -138,13 +149,22 @@ class PosixScheduledJobsMixin(ScheduledJobsMixin): run_parts=self.RUN_PARTS_DIRS, anacrontab=self.ANACRONTAB, script_dir=self.JOB_SCRIPT_DIR, + owners_sh=self.OWNERS_SH, + time_zone_sh=self.TIME_ZONE_SH, ) def _sj_read(self) -> Reading: result = self.run_command( reading_command(self._sj_paths()), privileged=True, timeout=_READ_TIMEOUT ) - return parse_reading(result.stdout) + reading = parse_reading(result.stdout) + for job in reading.jobs: + source = str(job["source"]) + if job["managed_by"] != "application" and any( + fnmatch.fnmatchcase(source, p) for p in self.PLATFORM_SOURCES + ): + job["managed_by"] = "platform" + return reading def get_scheduled_jobs(self) -> ScheduledJobsReadingDict: """Every scheduled job of the host, in one round trip. @@ -184,7 +204,7 @@ class PosixScheduledJobsMixin(ScheduledJobsMixin): staged = self._sj_stage(content) try: self._sj_checked( - ["install", "-D", "-m", mode, "-o", owner, "-g", group, "--", staged, path] + [*self.INSTALL, "-m", mode, "-o", owner, "-g", group, "--", staged, path] ) finally: self.run_command(_command(["rm", "-f", "--", staged]), timeout=30) diff --git a/tests/test_scheduled_jobs_posix.py b/tests/test_scheduled_jobs_posix.py index d1d5200..57d515e 100644 --- a/tests/test_scheduled_jobs_posix.py +++ b/tests/test_scheduled_jobs_posix.py @@ -280,6 +280,22 @@ class TestReading: host.get_scheduled_jobs() +class TestDriverSettings: + def test_what_the_platform_generates(self, root: Path): + host = Host(root) + host.PLATFORM_SOURCES = ("*/cron.d/cert*",) # type: ignore[misc] + certbot = next(j for j in _jobs(host).values() if j["source"].endswith("certbot")) + assert certbot["managed_by"] == "platform" + + def test_the_time_zone_and_owners_commands_are_the_drivers(self, root: Path): + host = Host(root) + host.TIME_ZONE_SH = "echo America/New_York" # type: ignore[misc] + host.OWNERS_SH = "cat >/dev/null" # type: ignore[misc] + reading = host.get_scheduled_jobs() + assert reading["time_zone"] == "America/New_York" + assert {j["managed_by"] for j in reading["jobs"] if j["kind"] == "cron"} == {"admin"} + + class TestParseReading: def test_the_time_zone_from_either_file(self): out = "SJ_BEGIN\n[tz]\n/usr/share/zoneinfo/Europe/Berlin\nSJ_END\n"