"""Scheduled jobs on OPNsense: the cron jobs of its configuration (napalm-device-types). OPNsense keeps its cron jobs in config.xml (System > Settings > Cron) and writes them into the crontab itself; each job runs one **configd action** with optional parameters, never a shell line. The REST API reads and writes them: ``/api/cron/settings/get`` answers with every job at once, the action as the option its ``command`` list has selected; ``get_job`` without a uuid is a blank job whose ``command`` options are the actions configd offers; ``add_job``, ``set_job``, ``del_job`` and ``toggle_job`` write, ``/api/cron/service/reconfigure`` regenerates the crontab. OPNsense routes ``search_jobs`` and ``searchJobs`` to the same action; the snake-case spelling is the documented one. **Who owns a job.** A job another component registered (its ``origin`` is not ``cron``: the intrusion detection's rule update, say) is ``platform``. A job whose description starts with ``napalm-scheduled-job: `` was written through :meth:`OPNsenseScheduledJobsMixin.put_scheduled_job` (``application``); every other one an admin made (``admin``). Every job can be enabled and disabled; only an application's job can be edited or deleted. **Not here.** The API cannot run a configd action now, so no job takes ``run``. What OPNsense puts in the crontab beyond config.xml -- ``periodic``, the plugins' own system jobs -- is not reachable over the API and is not read. The time zone is not read either (None). **Parameters, one per line.** Up to 26.1 OPNsense split the parameters the way a shell does; 26.7 takes one argument per line. Arguments without blanks, quotes or backslashes, one per line, mean the same to both, so those are all a job written here takes. """ from __future__ import annotations import re from collections.abc import Iterable from typing import TYPE_CHECKING, Any from napalm_device_types.cron import ALIASES, is_reboot from napalm_device_types.scheduled_jobs import ( ACTIONS, DELETE, EDIT, ScheduledJobChanged, ScheduledJobDict, ScheduledJobRefused, ScheduledJobResultDict, ScheduledJobsMixin, ScheduledJobSpecDict, ScheduledJobsReadingDict, check_job_name, check_spec, job_digest, ) _SETTINGS = "/api/cron/settings" _RECONFIGURE = "/api/cron/service/reconfigure" _KEY = "opnsense:" #: The origin of a job made in the cron settings themselves. _OWN_ORIGIN = "cron" #: How a job written by put_scheduled_job begins its description. MARKER = "napalm-scheduled-job: " _FIELDS = ("minutes", "hours", "days", "months", "weekdays") _SWITCH = ["enable", "disable"] _OWN = [*_SWITCH, EDIT, DELETE] #: OPNsense's month and weekday fields take numbers (months also upper case names). _MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec") _WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat") _NAME = re.compile(r"[A-Za-z]+") #: A parameter every OPNsense release hands configd as one argument. _PLAIN_ARGUMENT = re.compile(r"[^\s'\"\\]+") def _selected(field: Any) -> str: """The option a list field has selected (none: ""); a plain value as it is.""" if not isinstance(field, dict): return str(field or "") chosen = (k for k, o in field.items() if isinstance(o, dict) and o.get("selected") in (1, "1")) return next(chosen, "") def _command(node: dict[str, Any]) -> str: """The configd action and its parameters, as one line.""" parameters = str(node.get("parameters") or "").splitlines() return " ".join([_selected(node.get("command")), *(p.strip() for p in parameters if p.strip())]) def _schedule(uuid: str, node: dict[str, Any]) -> str: fields = [node.get(field) for field in _FIELDS] if not all(isinstance(f, str) and f.strip() for f in fields): raise ValueError(f"cron job {uuid} came back without its schedule") return " ".join(str(f).strip() for f in fields) def _ownership(origin: str, description: str) -> tuple[str, str | None, str]: """(managed_by, the application's job name or None, the description to show).""" if origin != _OWN_ORIGIN: return "platform", None, description if not description.startswith(MARKER): return "admin", None, description name, _, rest = description[len(MARKER) :].partition(" ") try: check_job_name(name) except ScheduledJobRefused: return "admin", None, description return "application", name, rest.strip() def scheduled_job(uuid: str, node: dict[str, Any]) -> ScheduledJobDict: """One job of the cron settings, as napalm-device-types reads it.""" origin = str(node.get("origin") or _OWN_ORIGIN) managed_by, name, description = _ownership(origin, str(node.get("description") or "")) job: dict[str, Any] = { "key": f"{_KEY}{uuid}", "kind": "cron", "source": "config.xml", # The crontab line calls configctl; configd runs the action as root. "run_as": "root", "schedule": _schedule(uuid, node), "schedule_kind": "cron", "command": _command(node), "enabled": str(node.get("enabled")) == "1", "managed_by": managed_by, "actions": list(_OWN if name else _SWITCH), } if name: job["name"] = name if description: job["description"] = description job["digest"] = job_digest(job) return job # type: ignore[return-value] def scheduled_jobs(answer: Any) -> list[ScheduledJobDict]: """Every job in an answer of ``/api/cron/settings/get``. :raises ValueError: when the answer has no list of jobs -- never "no jobs". """ try: jobs = answer["job"]["jobs"]["job"] except (KeyError, TypeError) as exc: raise ValueError("the cron settings came back without their jobs") from exc if jobs == []: # an empty ArrayField comes back as a JSON list return [] if not isinstance(jobs, dict): raise ValueError(f"the cron settings came back with jobs as {type(jobs).__name__}") return [scheduled_job(uuid, node) for uuid, node in jobs.items()] def _numbers(field: str, names: tuple[str, ...], low: int) -> str: return _NAME.sub(lambda m: str(names.index(m.group().lower()) + low), field) def cron_fields(schedule: str) -> dict[str, str]: """The five fields OPNsense stores of *schedule*, which :func:`check_spec` passed.""" if is_reboot(schedule): raise ScheduledJobRefused("OPNsense's cron jobs have no @reboot") text = schedule.strip() fields = ALIASES.get(text.lower(), text).split() fields[3] = _numbers(fields[3], _MONTHS, 1) fields[4] = _numbers(fields[4], _WEEKDAYS, 0) return dict(zip(_FIELDS, fields, strict=True)) def configd_action(command: str, actions: Iterable[str]) -> tuple[str, list[str]]: """(the configd action *command* names, its parameters). The action is the longest one configd offers that *command* starts with; the words after it are its parameters. """ if "\n" in command.strip(): raise ScheduledJobRefused("an OPNsense job runs one configd action, on one line") words = command.split() known = set(actions) for end in range(len(words), 0, -1): action = " ".join(words[:end]) if action in known: parameters = words[end:] for parameter in parameters: if not _PLAIN_ARGUMENT.fullmatch(parameter): raise ScheduledJobRefused(f"not a parameter OPNsense passes on: {parameter!r}") return action, parameters raise ScheduledJobRefused( f"configd offers no action {command!r}; get_scheduled_job_commands() lists them" ) def _saved(result: dict[str, Any], what: str) -> None: if result.get("result") == "saved": return if result.get("validations"): raise ScheduledJobRefused(f"OPNsense refused {what}: {result['validations']}") raise RuntimeError(f"OPNsense did not save {what}: {result}") class OPNsenseScheduledJobsMixin(ScheduledJobsMixin): """The cron jobs of config.xml; needs the driver's ``_get`` and ``_post``.""" if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers def _get(self, path: str) -> dict[str, Any]: ... def _post(self, path: str, data: dict[str, Any] | None = None) -> dict[str, Any]: ... def get_scheduled_job_commands(self) -> list[dict[str, str]]: """The configd actions a job can run: ``[{"command", "description"}]``, by command. :raises ValueError: when the list came back empty -- configd did not answer. """ answer = self._get(f"{_SETTINGS}/get_job") job = answer.get("job") if isinstance(answer, dict) else None options = job.get("command") if isinstance(job, dict) else None if not isinstance(options, dict) or not options: raise ValueError("the cron settings came back without configd's actions") return [ {"command": key, "description": str(option.get("value") or key)} for key, option in sorted(options.items()) if key and isinstance(option, dict) ] def get_scheduled_jobs(self) -> ScheduledJobsReadingDict: """Every cron job of config.xml, in one request; the time zone is not read. :raises ValueError: when the answer came back without its jobs. """ return {"jobs": scheduled_jobs(self._get(f"{_SETTINGS}/get")), "time_zone": None} def _sj_job(self, key: str, digest: str) -> ScheduledJobDict: job = next((j for j in self.get_scheduled_jobs()["jobs"] if j["key"] == key), None) if job is None: raise LookupError(f"no scheduled job {key}") if job["digest"] != digest: raise ScheduledJobChanged(f"{key} changed on the host since it was read") return job def _sj_own(self, name: str, digest: str | None) -> ScheduledJobDict | None: jobs = self.get_scheduled_jobs()["jobs"] current = next((j for j in jobs if j.get("name") == name), None) if digest is None: if current is not None: raise ScheduledJobChanged(f"a job {name} is there already") return None if current is None: raise LookupError(f"no scheduled job named {name}") if current["digest"] != digest: raise ScheduledJobChanged(f"{current['key']} changed on the host since it was read") return current def _sj_reload(self) -> None: result = self._post(_RECONFIGURE) if result.get("status") != "ok": raise RuntimeError(f"cron did not reload: {result}") def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict: """Enable or disable the job *key*; no job runs now (the API cannot).""" if action not in ACTIONS: raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}") job = self._sj_job(key, digest) if action not in job["actions"]: raise ScheduledJobRefused( f"{key} cannot {action}: OPNsense's API does not run a configd action now" ) flag = "1" if action == "enable" else "0" uuid = key.removeprefix(_KEY) result = self._post(f"{_SETTINGS}/toggle_job/{uuid}/{flag}") if result.get("result") not in ("Enabled", "Disabled"): raise RuntimeError(f"OPNsense did not {action} {key}: {result}") self._sj_reload() return {"success": True, "output": f"{key} {action}d"} def put_scheduled_job( self, spec: ScheduledJobSpecDict, *, digest: str | None = None ) -> ScheduledJobResultDict: """Create or change the application's job ``spec["name"]``. ``command`` is a configd action (:meth:`get_scheduled_job_commands`), with its parameters after it. """ check_spec(spec) if spec["run_as"] != "root": raise ScheduledJobRefused("an OPNsense job runs its configd action as root") fields = cron_fields(spec["schedule"]) commands = (c["command"] for c in self.get_scheduled_job_commands()) action, parameters = configd_action(spec["command"], commands) current = self._sj_own(spec["name"], digest) job = { "enabled": "1" if spec["enabled"] else "0", **fields, "command": action, "parameters": "\n".join(parameters), "description": f"{MARKER}{spec['name']} {spec.get('description') or ''}".rstrip(), } if current is None: result = self._post(f"{_SETTINGS}/add_job", {"job": job}) uuid = str(result.get("uuid") or "") else: uuid = current["key"].removeprefix(_KEY) result = self._post(f"{_SETTINGS}/set_job/{uuid}", {"job": job}) _saved(result, f"the job {spec['name']}") self._sj_reload() return {"success": True, "output": f"{_KEY}{uuid} {'changed' if current else 'created'}"} def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict: """Delete the application's job *key*; any other job is only switched.""" job = self._sj_job(key, digest) if job["managed_by"] != "application": raise ScheduledJobRefused( f"{key} was not written by an application; it is only switched" ) result = self._post(f"{_SETTINGS}/del_job/{key.removeprefix(_KEY)}") if result.get("result") != "deleted": raise RuntimeError(f"OPNsense did not delete {key}: {result}") self._sj_reload() return {"success": True, "output": f"{key} deleted"}