"""Scheduled jobs on QTS: admin's crontab in ``/etc/config``, BusyBox crond, no systemd. napalm-device-types' :class:`~napalm_device_types.PosixScheduledJobsMixin` reaches this driver through ``LinuxDriver`` with Debian's paths. On QTS they are wrong: * **The crontab that survives a boot is** ``/etc/config/crontab``: admin's (uid 0), no user field, on the configuration partition. ``/etc`` is in RAM; ``/etc/crontab`` is at most a link to it. crond runs a copy in its spool, which QTS rebuilds from that file on every boot -- a change made only through ``crontab`` is gone after one. * **BusyBox crond** reads its spool and nothing else: no ``/etc/crontab``, no cron.d, no run-parts or anacron, and QTS has no systemd. Other users' crontabs live in the spool only, in RAM, and are read and switched as they are. * **The firmware writes its own lines** into the same file. They are ``platform``, recognised by :data:`QTS_PLATFORM_COMMANDS`, and only run: QTS's scripts and UI keep those lines, and whether they leave one switched off alone needs a real box (#13). A write puts the new text into ``/etc/config/crontab`` with ``cp`` (the file keeps its inode, mode and owner, and a link to it stays one), then loads it with ``crontab /etc/config/crontab`` and restarts crond, as QNAP says to. """ from __future__ import annotations import fnmatch import re import shlex from typing import ClassVar from napalm_device_types import ( PosixScheduledJobsMixin, ScheduledJobRefused, ScheduledJobResultDict, ScheduledJobSpecDict, job_digest, ) from napalm_device_types._crontab import run_script from napalm_device_types._scheduled_reading import Reading, parse_reading from napalm_device_types.scheduled_jobs import RUN_TIMEOUT from napalm_device_types.scheduled_jobs_posix import _result #: The commands stock QTS 4 and 5 write into ``/etc/config/crontab``, as ``fnmatch`` #: patterns on the whole command; arguments may follow. Conservative on purpose: a line #: that is not listed is the admin's. Taken from stock crontabs as published; to be #: checked against a harvested one (#13). QTS_PLATFORM_COMMANDS = ( "/sbin/hwclock -s", "/sbin/vs_refresh", "/sbin/clean_reset_pwd", "/sbin/clean_upload_file", "/sbin/notice_log_tool *", "/sbin/qfstrim", "/sbin/qpkg_cli --check_license *", "/usr/bin/power_clean *", "/etc/init.d/nss2_dusg.sh", "/etc/init.d/storage_usage.sh", "/etc/init.d/backup_conf.sh", "/etc/init.d/ImRd.sh bgThGen", "/bin/rm -rf /mnt/HDA_ROOT/twonkymedia/twonky-*", ) #: A second command on the line: then it is not the firmware's line alone. _SEPARATOR = re.compile(r";|\||&&|`|\$\(|(?&])&(?!>)") #: ``sh -c`` script: runs ``"$@"`` (after the limit, ``$1``) for at most ``$1`` seconds and #: exits as it did. Sleep and kill only -- QTS's BusyBox has no ``timeout`` to rely on. BOUNDED_RUN = ( 't=$1; shift; "$@" & p=$!; ' '( i=0; while [ "$i" -lt "$t" ] && kill -0 "$p" 2>/dev/null; do sleep 1; i=$((i+1)); done; ' 'kill "$p" 2>/dev/null ) /dev/null 2>&1 & ' 'wait "$p"' ) #: QTS keeps its time zone in uLinux.conf; only an IANA name is taken from there. _TIME_ZONE_SH = ( "getcfg System 'Time Zone' 2>/dev/null" " | grep '^[A-Za-z_][A-Za-z_]*/[A-Za-z0-9_+/-][A-Za-z0-9_+/-]*$'; " "readlink /etc/localtime 2>/dev/null" ) def is_platform_command(command: str) -> bool: """Whether *command* is one QTS's firmware writes into its crontab, and nothing more.""" command = command.strip() if _SEPARATOR.search(command): return False return any( fnmatch.fnmatchcase(command, p) or fnmatch.fnmatchcase(command, f"{p} *") for p in QTS_PLATFORM_COMMANDS ) class QtsScheduledJobsMixin(PosixScheduledJobsMixin): """The POSIX scheduled jobs, on QTS's paths and BusyBox userland.""" #: BusyBox crond reads none of these, and QTS has no run-parts. CRON_SYSTEM_FILES: ClassVar[tuple[str, ...]] = () CRON_D_DIRS: ClassVar[tuple[str, ...]] = () RUN_PARTS_DIRS: ClassVar[tuple[tuple[str, str], ...]] = () #: crond's spool, in RAM: other users' crontabs, and the copy of admin's. CRON_SPOOL_DIRS: ClassVar[tuple[str, ...]] = ("/var/spool/cron/crontabs",) #: An application's job is marked lines in admin's crontab, never a cron.d file. OWN_CRON_D_DIR: ClassVar[str | None] = None #: No package manager owns a crontab line on QTS. OWNERS_SH: ClassVar[str] = "cat >/dev/null" TIME_ZONE_SH: ClassVar[str] = _TIME_ZONE_SH #: The crontab QTS keeps across a boot, and whose it is: uid 0 is ``admin`` on QTS. QTS_CRONTAB: ClassVar[str] = "/etc/config/crontab" ROOT_USER: ClassVar[str] = "admin" CROND_RESTART: ClassVar[tuple[str, ...]] = ("/etc/init.d/crond.sh", "restart") #: Where the new text is staged, as a word ``sh`` expands; BusyBox's ``mktemp`` #: wants a template. STAGE_DIR: ClassVar[str] = "${TMPDIR:-/tmp}" # -- reading --------------------------------------------------------------------------------- def _qts_report(self) -> str: """The report ``parse_reading`` takes: admin's crontab, the spool, the time zone. A missing ``/etc/config/crontab`` ends it before its end marker, so the reading raises. Every file ends with a newline of its own, so a last line without one does not swallow the next header. """ crontab = shlex.quote(self.QTS_CRONTAB) spool = " ".join(f"{shlex.quote(d)}/*" for d in self.CRON_SPOOL_DIRS) skip = shlex.quote(self.ROOT_USER) return ( "printf '%s%s\\n' SJ_ BEGIN; " f"printf '[user %s]\\n' {crontab}; sed 's/^/|/' {crontab} || exit 1; echo; " f'for f in {spool}; do [ -f "$f" ] || continue; ' f'case "${{f##*/}}" in {skip}|cron.update) continue ;; esac; ' "printf '[user %s]\\n' \"$f\"; sed 's/^/|/' \"$f\" || exit 1; echo; done; " f"echo '[tz]'; {{ {self.TIME_ZONE_SH}; }}; echo '[owners]'; " "printf '%s%s\\n' SJ_ END" ) def _sj_read(self) -> Reading: result = self.run_command(self._qts_report(), privileged=True, timeout=120) reading = parse_reading(result.stdout) for job in reading.jobs: if job["source"] != self.QTS_CRONTAB: continue job["run_as"] = self.ROOT_USER job["digest"] = job_digest(job) if job["managed_by"] != "application" and is_platform_command(str(job["command"])): job["managed_by"] = "platform" job["actions"] = ["run"] return reading # -- admin's crontab ------------------------------------------------------------------------- def _sj_spool_user(self, path: str) -> str | None: if path == self.QTS_CRONTAB: return self.ROOT_USER return super()._sj_spool_user(path) def _sj_crontab(self, user: str) -> str: if user != self.ROOT_USER: return super()._sj_crontab(user) return self._sj_checked(["cat", "--", self.QTS_CRONTAB]).stdout def _sj_stage(self, content: str) -> str: template = f'"{self.STAGE_DIR}/sj.XXXXXX"' stage = f't=$(mktemp {template}) && chmod 600 "$t" && cat > "$t" && printf %s "$t"' result = self.run_command(stage, timeout=30, stdin=content.encode()) path = result.stdout.strip().splitlines()[-1:] or [""] if result.exit_code != 0 or not path[0].startswith("/"): raise RuntimeError(f"cannot stage a file: {result.stderr.strip()}") return path[0] def _sj_write_crontab(self, user: str, text: str) -> None: """admin's into ``/etc/config/crontab`` first, then into crond; others as they are.""" if user != self.ROOT_USER: super()._sj_write_crontab(user, text) return staged = self._sj_stage(text) try: self._sj_checked(["cp", "--", staged, self.QTS_CRONTAB]) finally: self.run_command(shlex.join(["rm", "-f", "--", staged]), timeout=30) self._sj_checked(["crontab", self.QTS_CRONTAB]) self._sj_checked(self.CROND_RESTART) # -- running --------------------------------------------------------------------------------- def _sj_as(self, user: str, script: str) -> list[str]: if user == self.ROOT_USER: return ["sh", "-c", script] return super()._sj_as(user, script) def _sj_run(self, job: dict[str, object], reading: Reading) -> ScheduledJobResultDict: """The line's command as crond would run it, bounded by :data:`BOUNDED_RUN`.""" line = self._sj_line(job, self._sj_text(str(job["source"]))) argv = self._sj_as(line.run_as, run_script(line.command, line.env)) bounded = ["sh", "-c", BOUNDED_RUN, "sh", str(RUN_TIMEOUT), *argv] return _result(self._sj_root(bounded, timeout=RUN_TIMEOUT + 30), "ran") # -- an application's own jobs --------------------------------------------------------------- def put_scheduled_job( self, spec: ScheduledJobSpecDict, *, digest: str | None = None ) -> ScheduledJobResultDict: """An application's job as marked lines in admin's crontab, the only one QTS keeps. ``root`` is taken for admin, uid 0 on QTS. """ if spec.get("run_as") not in (self.ROOT_USER, "root"): raise ScheduledJobRefused( f"QTS keeps only {self.ROOT_USER}'s crontab across a boot; " f"a job cannot run as {spec.get('run_as')!r}" ) return super().put_scheduled_job({**spec, "run_as": self.ROOT_USER}, digest=digest)