Files
napalm-bsd/napalm_bsd/scheduled_jobs.py
T
Christian Manivong 991e07043f
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 13s
driver / test (3.12) (pull_request) Failing after 15s
driver / test (3.13) (pull_request) Failing after 13s
driver / types (pull_request) Failing after 25s
driver / lowest (pull_request) Failing after 19s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Failing after 36s
CI / driver (pull_request) Failing after 1m10s
driver / publish (pull_request) Skipped
feat(scheduled-jobs): FreeBSD and OpenBSD through PosixScheduledJobsMixin (#27)
get_scheduled_jobs reads /etc/crontab and the user crontabs in
/var/cron/tabs, on FreeBSD also both cron.d directories and every
periodic script, in one round trip as root; manage_scheduled_job
enables, disables or runs one now; put_ and delete_scheduled_job write
and remove an application's own job (/etc/cron.d on FreeBSD, marked
lines in the user's crontab on OpenBSD).

A periodic script is what FreeBSD runs daily, weekly, monthly and for
the security run; it does its work only when its periodic.conf knob
says YES, so that knob is its enabled state, written with sysrc to
/etc/periodic.conf. A later periodic.conf that still overrides it is
reported instead of claimed as done. A script whose knob is not known
only runs; one whose knob is off does nothing when run and offers no run.

BSD su takes no shell (FreeBSD's -s is a MAC label) and -m starts
root's own shell, csh on many FreeBSD hosts, so another user's job goes
to /bin/sh on stdin. OpenBSD cron's -n/-q/-s flags are left off when a
line runs now. What the base system ships is platform: FreeBSD's
/etc/crontab and /etc/periodic, OpenBSD's newsyslog and
/etc/daily|weekly|monthly lines, which stay one job each.

get_cron_jobs goes: it read without root and missed cron.d, every other
user and periodic.

Requires napalm-device-types 4.26.0.

Closes #27
2026-11-03 05:53:01 +01:00

105 lines
4.2 KiB
Python

"""Scheduled jobs on FreeBSD and OpenBSD: cron with the BSD paths and tools (#27).
napalm-device-types' ``PosixScheduledJobsMixin`` reads, switches, runs and
writes; this names where the BSDs keep their jobs and what their tools take.
Both read ``/etc/crontab`` and the user crontabs in ``/var/cron/tabs``; neither
has run-parts, anacron or systemd. BSD ``install`` makes no directories (its
``-D`` is a destdir), and BSD ``stat`` takes ``-f``.
**su has no shell option** on FreeBSD (``-s`` is a MAC label there), and ``-m``
starts root's own login shell -- csh on many FreeBSD hosts. So the job's script
goes to ``/bin/sh`` on stdin, and the one word ``su`` hands that shell is
``/bin/sh``, which every shell runs alike. ``HOME``, ``USER`` and ``LOGNAME`` are
the user's, as cron sets them.
A driver may add to the report (:meth:`_sj_extra_command`, FreeBSD's
``periodic``): it runs in the same round trip as root, after the cron report.
"""
from __future__ import annotations
import fnmatch
from dataclasses import replace
from typing import ClassVar
from napalm_device_types import PosixScheduledJobsMixin
from napalm_device_types._scheduled_reading import (
Paths,
Reading,
parse_reading,
reading_command,
)
_READ_TIMEOUT = 120
#: Runs ``$2`` with ``/bin/sh`` as the user ``$1``, from root, the way cron would.
_SU_SH = (
"h=$(awk -F: -v u=\"$1\" '$1 == u { print $6; exit }' /etc/passwd); "
"{ echo 'SHELL=/bin/sh; export SHELL'; printf '%s\\n' \"$2\"; } | "
'HOME="${h:-/}" USER="$1" LOGNAME="$1" su -m "$1" -c /bin/sh'
)
class BsdScheduledJobsMixin(PosixScheduledJobsMixin):
"""Cron on a BSD host; the concrete driver names its cron.d and its tools."""
CRON_SYSTEM_FILES: ClassVar[tuple[str, ...]] = ("/etc/crontab",)
CRON_D_DIRS: ClassVar[tuple[str, ...]] = ()
CRON_SPOOL_DIRS: ClassVar[tuple[str, ...]] = ("/var/cron/tabs",)
RUN_PARTS_DIRS: ClassVar[tuple[tuple[str, str], ...]] = ()
ANACRONTAB: ClassVar[str] = ""
OWN_CRON_D_DIR: ClassVar[str | None] = None
ROOT_GROUP: ClassVar[str] = "wheel"
STAT_ARGV: ClassVar[tuple[str, ...]] = ("stat", "-f", "%Lp %Su %Sg", "--")
INSTALL: ClassVar[tuple[str, ...]] = ("install",)
OWNERS_SH: ClassVar[str] = "cat >/dev/null"
TIME_ZONE_SH: ClassVar[str] = "readlink /etc/localtime 2>/dev/null"
#: Commands the base system puts in a crontab: those lines are ``platform``.
PLATFORM_COMMANDS: ClassVar[tuple[str, ...]] = ()
def _sj_paths(self) -> Paths:
# No BSD runs systemd: never look for its timers, never write one.
return replace(super()._sj_paths(), systemd_marker="")
def _sj_extra_command(self) -> str:
"""``sh`` run after the cron report, in the same round trip; "" for none."""
return ""
def _sj_extra_jobs(self, output: str) -> list[dict[str, object]]:
"""The jobs :meth:`_sj_extra_command` printed.
:raises ValueError: when its part of the report is cut short.
"""
return []
def _sj_platform(self, job: dict[str, object]) -> bool:
if job["managed_by"] == "application":
return False
source = str(job["source"])
return any(fnmatch.fnmatchcase(source, p) for p in self.PLATFORM_SOURCES) or (
job["kind"] == "cron" and job["command"] in self.PLATFORM_COMMANDS
)
def _sj_report(self) -> tuple[Reading, str]:
"""The reading and the report it was parsed from, in one round trip as root."""
command = reading_command(self._sj_paths())
extra = self._sj_extra_command()
if extra:
command = f"{command}; {extra}"
output = self.run_command(command, privileged=True, timeout=_READ_TIMEOUT).stdout
reading = parse_reading(output)
reading.jobs += self._sj_extra_jobs(output)
for job in reading.jobs:
if self._sj_platform(job):
job["managed_by"] = "platform"
return reading, output
def _sj_read(self) -> Reading:
return self._sj_report()[0]
def _sj_as(self, user: str, script: str) -> list[str]:
"""*script* run by ``sh`` as *user*, from root (see the module's docstring)."""
if user == "root":
return ["sh", "-c", script]
return ["sh", "-c", _SU_SH, "sh", user, script]