"""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/`` 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 `` prints `` - ``; 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)