"""An application's scheduled job as Task Scheduler XML (#8). Pure: no I/O. :meth:`~napalm_windows.scheduled_tasks.WindowsScheduledJobsMixin.put_scheduled_job` registers the task this module writes, in the root folder ``\\``, named by the job. **The cron expression becomes triggers, exactly or not at all.** A day schedule is one of Task Scheduler's: every day (``ScheduleByDay``), weekdays (``ScheduleByWeek``), or days of the month in some months (``ScheduleByMonth``). The times of day become one trigger at the first time with a repetition when they are three or more evenly spaced (``*/5``, ``*/15 8-17``, ``0 */6``), else one trigger per time, else one repeating trigger per hour when the minutes are evenly spaced (``*/7``) -- at most 48 triggers, Task Scheduler's limit. ``@reboot`` is a boot trigger. What Task Scheduler cannot say is refused, naming why: cron's *either* rule (both day fields set), a weekday together with days of the month or with months, and times that need more than 48 triggers. A trigger's start is a local time without an offset, so it follows the host's clock as cron does; a repetition counts elapsed time, so on the day summer time starts or ends its later runs shift by the hour. **The command runs in ``cmd.exe``**: ``cmd.exe /d /s /c ""`` -- ``/d`` skips AutoRun, ``/s`` keeps the command as it is between the outer quotes. One line, as a command line is; the reading gives it back as it was written. **The principal** is ``SYSTEM`` (the local system account) or a local user, who runs it whether logged on or not without a stored password (``S4U``): such a run has no network credentials, so a share needs the computer's access. **The description** is ``napalm-scheduled-job: `` and a second line ``schedule: ``: the job's name, and its schedule as the application gave it. """ from __future__ import annotations import html from itertools import pairwise from napalm_device_types import ScheduledJobRefused, ScheduledJobSpecDict from napalm_device_types.cron import CronSchedule, is_reboot, parse_cron #: The first line of an application's task description, before its name. JOB_MARKER = "napalm-scheduled-job: " #: The line of an application's task description that holds its cron expression. SCHEDULE_LINE = "schedule: " CMD = "%SystemRoot%\\System32\\cmd.exe" _CMD_PREFIX = '/d /s /c "' #: Task Scheduler's limit of triggers on one task. MAX_TRIGGERS = 48 _START_DATE = "2020-01-01" _SYSTEM_SID = "S-1-5-18" _NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task" _WEEKDAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") _MONTHS = ( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ) _ALL_DAYS = frozenset(range(1, 32)) _ALL_MONTHS = frozenset(range(1, 13)) _ALL_WEEKDAYS = frozenset(range(7)) #: (minute of the day it starts, repetition interval, repetition duration) in minutes. _Clock = tuple[int, int | None, int | None] # -- the command --------------------------------------------------------------------------------- def _escape(text: str) -> str: """*text* as XML character data.""" return html.escape(text, quote=False) def _check_text(what: str, text: str) -> None: if "\n" in text or "\r" in text: raise ScheduledJobRefused(f"a task's {what} is one line") if any(ord(c) < 32 and c != "\t" for c in text): raise ScheduledJobRefused(f"a task's {what} cannot hold a control character") def command_action(command: str) -> tuple[str, str]: """The ``Exec`` action's command and arguments that run *command* in ``cmd.exe``.""" command = command.strip() _check_text("command", command) return CMD, f'{_CMD_PREFIX}{command}"' def own_command(execute: str | None, arguments: str | None) -> str | None: """The command :func:`command_action` wrapped; None for any other action.""" args = arguments or "" if (execute or "").lower() != CMD.lower(): return None if not (args.startswith(_CMD_PREFIX) and args.endswith('"') and len(args) > len(_CMD_PREFIX)): return None return args[len(_CMD_PREFIX) : -1] def description(spec: ScheduledJobSpecDict) -> str: """The task's description: the job's name and description, then its cron expression.""" first = f"{JOB_MARKER}{spec['name']} {spec.get('description') or ''}".rstrip() return f"{first}\n{SCHEDULE_LINE}{spec['schedule'].strip()}" # -- the schedule -------------------------------------------------------------------------------- def _evenly_spaced(values: list[int]) -> int | None: """The step between *values*, two or more; None when they are not evenly spaced.""" if len(values) < 2: return None step = values[1] - values[0] return step if all(b - a == step for a, b in pairwise(values)) else None def _clocks(s: CronSchedule) -> list[_Clock]: times = sorted(h * 60 + m for h in s.hours for m in s.minutes) step = _evenly_spaced(times) if step is not None and len(times) > 2: return [(times[0], step, times[-1] - times[0] + 1)] if len(times) <= MAX_TRIGGERS: return [(t, None, None) for t in times] minutes = sorted(s.minutes) step = _evenly_spaced(minutes) if step is not None and len(s.hours) <= MAX_TRIGGERS: span = minutes[-1] - minutes[0] + 1 return [(h * 60 + minutes[0], step, span) for h in sorted(s.hours)] raise ScheduledJobRefused( f"these times of day need more than {MAX_TRIGGERS} triggers, Task Scheduler's limit" ) def _names(names: tuple[str, ...], values: frozenset[int], first: int) -> str: return "".join(f"<{names[v - first]} />" for v in sorted(values)) def _day_schedule(s: CronSchedule) -> str: if s.either_day: raise ScheduledJobRefused( "Task Scheduler cannot fire on either a day of the month or a weekday, " "as cron does when both are set" ) every_date = s.days == _ALL_DAYS and s.months == _ALL_MONTHS if s.weekdays == _ALL_WEEKDAYS and every_date: return "1" if every_date: days = _names(_WEEKDAYS, s.weekdays, 0) return ( f"{days}" "1" ) if s.weekdays == _ALL_WEEKDAYS: days = "".join(f"{d}" for d in sorted(s.days)) months = _names(_MONTHS, s.months, 1) return ( f"{days}" f"{months}" ) raise ScheduledJobRefused( "Task Scheduler cannot combine a weekday with days of the month or with months" ) def _duration(minutes: int) -> str: hours, rest = divmod(minutes, 60) return "PT" + (f"{hours}H" if hours else "") + (f"{rest}M" if rest or not hours else "") def _calendar_trigger(clock: _Clock, day_schedule: str) -> str: start, interval, duration = clock repetition = "" if interval is not None and duration is not None: repetition = ( f"{_duration(interval)}" f"{_duration(duration)}" "false" ) hour, minute = divmod(start, 60) return ( f"{repetition}" f"{_START_DATE}T{hour:02d}:{minute:02d}:00" f"true{day_schedule}" ) def triggers(schedule: str) -> list[str]: """The triggers that fire exactly when the cron expression *schedule* does. :raises ScheduledJobRefused: for a shape Task Scheduler cannot express, or an expression cron would not take. """ if is_reboot(schedule): return ["true"] try: s = parse_cron(schedule) except ValueError as exc: raise ScheduledJobRefused(str(exc)) from exc day_schedule = _day_schedule(s) return [_calendar_trigger(clock, day_schedule) for clock in _clocks(s)] # -- the task ------------------------------------------------------------------------------------ def _principal(run_as: str) -> str: if run_as.upper() == "SYSTEM": return f"{_SYSTEM_SID}HighestAvailable" return ( f"{_escape(run_as)}S4U" "LeastPrivilege" ) def task_xml(spec: ScheduledJobSpecDict) -> str: """The whole task for *spec*, as ``Register-ScheduledTask -Xml`` takes it. :raises ScheduledJobRefused: for a schedule, command or description a task cannot hold. """ execute, arguments = command_action(spec["command"]) _check_text("description", spec.get("description") or "") trigger_xml = "".join(triggers(spec["schedule"])) enabled = "true" if spec["enabled"] else "false" return ( f'' f"{_escape(description(spec))}" "" f"{trigger_xml}" f'{_principal(spec["run_as"])}' "IgnoreNew" "false" "false" "false" "true" f"{enabled}" f'{_escape(execute)}' f"{_escape(arguments)}" "" )