feat(scheduled-jobs): scheduled jobs through PosixScheduledJobsMixin (#32)
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Failing after 26s
driver / test (3.13) (pull_request) Failing after 15s
driver / test (3.12) (pull_request) Failing after 17s
driver / lowest (pull_request) Failing after 16s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Failing after 35s
CI / driver (pull_request) Failing after 1m6s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Failing after 26s
driver / test (3.13) (pull_request) Failing after 15s
driver / test (3.12) (pull_request) Failing after 17s
driver / lowest (pull_request) Failing after 16s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Failing after 35s
CI / driver (pull_request) Failing after 1m6s
driver / publish (pull_request) Skipped
get_scheduled_jobs reads every crontab in /etc/crontabs in one round trip as root, with the time zone from UCI and each crontab's package from opkg; manage_scheduled_job enables, disables or runs one now; put_ and delete_scheduled_job write and remove an application's own job as marked lines in the user's crontab. BusyBox crond has no /etc/crontab, cron.d, run-parts, anacron or systemd, so none is read. OpenWrt's BusyBox differs from what the POSIX mixin assumes, so a few steps are the driver's own: - crontab -l says only "can't open" for a missing crontab, as for an unreadable one: the file is read directly, a missing one is empty, and one that cannot be read is never written. - crontab FILE exits 0 when it could not write: every write is read back. - cron is enabled and restarted after each write; OpenWrt does not start crond while /etc/crontabs is empty. - crond has no special times: aliases are written as five fields and @reboot is refused. - crond hands the whole command to sh and takes only SHELL and PATH from the crontab, so a run now does the same (% is no stdin). - there is no su and no timeout before 25.x: another user's job runs through start-stop-daemon -c, and the run is bounded by timeout only where the router has it. Every write changes only the job's own line, so the reboot failback line in /etc/crontabs/root stays as it is. Requires napalm-device-types 4.26.0. Closes #32
This commit is contained in:
1 parent
0380350a4c
commit
eeeb46121f
6 files changed
+630
-3
No files matched your search
@@ -47,6 +47,7 @@ from napalm_openwrt.lldp_agent import OpenWrtLldpAgentMixin
|
||||
from napalm_openwrt.lldp_mixin import OpenWrtLLDPMixin
|
||||
from napalm_openwrt.packages_mixin import OpenWrtPackageMixin
|
||||
from napalm_openwrt.routing_mixin import OpenWrtRoutingMixin
|
||||
from napalm_openwrt.scheduled_jobs_mixin import OpenWrtScheduledJobsMixin
|
||||
from napalm_openwrt.system_mixin import _RC_MARKER, OpenWrtSystemMixin, _split_status
|
||||
from napalm_openwrt.vlan_mixin import OpenWrtVLANMixin
|
||||
from napalm_openwrt.wireless_mixin import OpenWrtWirelessMixin
|
||||
@@ -77,6 +78,7 @@ class OpenWrtDriver(
|
||||
OpenWrtSystemMixin,
|
||||
OpenWrtPackageMixin,
|
||||
OpenWrtRoutingMixin,
|
||||
OpenWrtScheduledJobsMixin,
|
||||
ListeningSocketsMixin,
|
||||
SnmpAgentMixin,
|
||||
OpenWrtLldpAgentMixin,
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Scheduled jobs on OpenWrt: BusyBox crond and the crontabs in ``/etc/crontabs`` (#32).
|
||||
|
||||
napalm-device-types' :class:`~napalm_device_types.PosixScheduledJobsMixin` does the
|
||||
work; this mixin tells it what an OpenWrt router has and what its BusyBox lacks.
|
||||
|
||||
**What there is.** BusyBox crond reads ``/etc/crontabs/<user>`` and nothing else:
|
||||
no ``/etc/crontab``, no ``cron.d``, no run-parts, no anacron, no systemd. An
|
||||
application's own job is two marked lines in the user's crontab. After every write
|
||||
the cron service is enabled and restarted -- OpenWrt does not start crond at boot
|
||||
while ``/etc/crontabs`` is empty.
|
||||
|
||||
**What BusyBox does differently** (as OpenWrt builds it, 21.02 to 25.x):
|
||||
|
||||
* ``crontab -l`` says only "can't open" for a crontab that is not there, the same as
|
||||
for one that cannot be read; the file is read directly instead, and a missing one
|
||||
is empty. ``crontab FILE`` exits 0 when it could not write: every write is read
|
||||
back.
|
||||
* crond has no special times (``FEATURE_CROND_SPECIAL_TIMES`` is off): ``@daily``
|
||||
and the other aliases are written as their five fields, ``@reboot`` is refused.
|
||||
* crond hands the whole command to ``sh -c`` -- ``%`` means nothing -- and of the
|
||||
crontab's variables takes only ``SHELL`` and ``PATH``; a run now does the same.
|
||||
* There is no ``stat``, ``cksum``, ``install`` or ``su``, and ``timeout`` only from
|
||||
25.x on. Only the crontabs are written, through ``crontab``; another user's job
|
||||
runs through ``start-stop-daemon -c``; a run is bounded by ``timeout`` where the
|
||||
router has it, else by the channel's wait.
|
||||
|
||||
Every command goes over an SSH exec channel (``run_command``), so ash's
|
||||
512-character limit on a typed line does not apply; dropbear takes 9000.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import ClassVar
|
||||
|
||||
from napalm_device_types import PosixScheduledJobsMixin
|
||||
from napalm_device_types._crontab import CronLine
|
||||
from napalm_device_types._scheduled_reading import Reading
|
||||
from napalm_device_types.cron import ALIASES, is_reboot
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
RUN_TIMEOUT,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobResultDict,
|
||||
ScheduledJobSpecDict,
|
||||
)
|
||||
|
||||
CRONTABS = "/etc/crontabs"
|
||||
INIT_CRON = "/etc/init.d/cron"
|
||||
|
||||
#: LuCI's zone names have spaces where the IANA names have underscores.
|
||||
TIME_ZONE_SH = "uci -q get 'system.@system[0].zonename' | tr ' ' _"
|
||||
|
||||
#: ``opkg search <path>`` prints ``<package> - <version>``; apk-based OpenWrt names none.
|
||||
OWNERS_SH = (
|
||||
"if command -v apk >/dev/null 2>&1; then cat >/dev/null; "
|
||||
"elif command -v opkg >/dev/null 2>&1; then while read -r p; do "
|
||||
"o=$(opkg search \"$p\" 2>/dev/null | sed -n '1s/ - .*//p'); "
|
||||
'[ -z "$o" ] || printf \'%s: %s\\n\' "$o" "$p"; done; '
|
||||
"else cat >/dev/null; fi"
|
||||
)
|
||||
|
||||
#: A user name the run's script may name unquoted (``~user``).
|
||||
_USER = re.compile(r"[A-Za-z_][A-Za-z0-9_.-]*")
|
||||
#: What a run keeps of the job's output.
|
||||
_OUTPUT_LIMIT = 64 * 1024
|
||||
|
||||
|
||||
def _cron_script(line: CronLine) -> str:
|
||||
"""*line*'s command the way BusyBox crond runs it: as the user, from the user's home."""
|
||||
user = line.run_as
|
||||
if not _USER.fullmatch(user):
|
||||
raise ScheduledJobRefused(f"not a user name to run as: {user!r}")
|
||||
env = "".join(
|
||||
f"export {k}={shlex.quote(line.env[k])}; " for k in ("SHELL", "PATH") if k in line.env
|
||||
)
|
||||
return (
|
||||
f"HOME=~{user}; export HOME LOGNAME={user} USER={user}; "
|
||||
f'cd "$HOME" 2>/dev/null || cd /; {env}{line.command}'
|
||||
)
|
||||
|
||||
|
||||
class OpenWrtScheduledJobsMixin(PosixScheduledJobsMixin):
|
||||
"""Scheduled jobs of an OpenWrt router: BusyBox crond's crontabs."""
|
||||
|
||||
CRON_SYSTEM_FILES: ClassVar[tuple[str, ...]] = ()
|
||||
CRON_D_DIRS: ClassVar[tuple[str, ...]] = ()
|
||||
CRON_SPOOL_DIRS: ClassVar[tuple[str, ...]] = (CRONTABS,)
|
||||
RUN_PARTS_DIRS: ClassVar[tuple[tuple[str, str], ...]] = ()
|
||||
#: OpenWrt has no anacron; the reading passes an empty path by.
|
||||
ANACRONTAB: ClassVar[str] = ""
|
||||
OWN_CRON_D_DIR: ClassVar[str | None] = None
|
||||
OWNERS_SH: ClassVar[str] = OWNERS_SH
|
||||
TIME_ZONE_SH: ClassVar[str] = TIME_ZONE_SH
|
||||
CRONTAB_AFTER_WRITE: ClassVar[tuple[str, ...] | None] = (
|
||||
"sh",
|
||||
"-c",
|
||||
f"{INIT_CRON} enable && {INIT_CRON} restart",
|
||||
)
|
||||
|
||||
def _sj_crontab(self, user: str) -> str:
|
||||
"""The crontab of *user* as the file has it; empty when there is none.
|
||||
|
||||
:raises RuntimeError: when it is there and cannot be read -- then nothing is written.
|
||||
"""
|
||||
path = f"{self.CRON_SPOOL_DIRS[0]}/{user}"
|
||||
result = self._sj_root(["sh", "-c", '[ ! -e "$1" ] || cat -- "$1"', "sh", path])
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or f"exit {result.exit_code}"
|
||||
raise RuntimeError(f"cannot read the crontab of {user}: {said}")
|
||||
return result.stdout
|
||||
|
||||
def _sj_write_crontab(self, user: str, text: str) -> None:
|
||||
"""Write through ``crontab``, then read back: BusyBox's exits 0 when it could not."""
|
||||
super()._sj_write_crontab(user, text)
|
||||
if self._sj_crontab(user) != text:
|
||||
raise RuntimeError(f"the crontab of {user} was not written")
|
||||
|
||||
def _sj_as(self, user: str, script: str) -> list[str]:
|
||||
"""*script* run by ``sh`` as *user*; OpenWrt's BusyBox has no ``su``."""
|
||||
if user == "root":
|
||||
return ["sh", "-c", script]
|
||||
# -p /dev/null: no process is "already running" -- only that file is looked at.
|
||||
ssd = ["start-stop-daemon", "-S", "-p", "/dev/null", "-c", user, "-x", "/bin/sh"]
|
||||
return [*ssd, "--", "-c", script]
|
||||
|
||||
def _sj_run(self, job: dict[str, object], reading: Reading) -> ScheduledJobResultDict:
|
||||
"""Run a cron line now as crond would, bounded by ``timeout`` where there is one."""
|
||||
line = self._sj_line(job, self._sj_text(str(job["source"])))
|
||||
argv = shlex.join(self._sj_as(line.run_as, _cron_script(line)))
|
||||
command = (
|
||||
f"if command -v timeout >/dev/null 2>&1; then exec timeout {RUN_TIMEOUT} {argv}; fi; "
|
||||
f"exec {argv}"
|
||||
)
|
||||
result = self.run_command(command, privileged=True, timeout=RUN_TIMEOUT + 30)
|
||||
said = "\n".join(p for p in (result.stdout.strip(), result.stderr.strip()) if p)
|
||||
said = said[-_OUTPUT_LIMIT:]
|
||||
if result.exit_code != 0:
|
||||
return {"success": False, "output": said or f"exit {result.exit_code}"}
|
||||
return {"success": True, "output": said or "ran"}
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Write the application's job; an alias as its five fields, ``@reboot`` refused.
|
||||
|
||||
:raises ScheduledJobRefused: for ``@reboot``: BusyBox crond on OpenWrt has no
|
||||
special times.
|
||||
"""
|
||||
schedule = (spec.get("schedule") or "").strip()
|
||||
if is_reboot(schedule):
|
||||
raise ScheduledJobRefused("BusyBox crond on OpenWrt does not run @reboot")
|
||||
if schedule.lower() in ALIASES:
|
||||
spec = {**spec, "schedule": ALIASES[schedule.lower()]}
|
||||
return super().put_scheduled_job(spec, digest=digest)
|
||||
Reference in new issue
Block a user