driver / lint (pull_request) Successful in 18s
driver / standard (pull_request) Successful in 22s
driver / types (pull_request) Failing after 1m19s
driver / test (3.13) (pull_request) Failing after 58s
driver / test (3.12) (pull_request) Failing after 1m4s
driver / lowest (pull_request) Failing after 23s
driver / build (pull_request) Successful in 31s
driver / security (pull_request) Failing after 1m12s
CI / driver (pull_request) Failing after 2m32s
driver / publish (pull_request) Skipped
An apply of the cron module would put someone's half-finished web-UI edit live along with ours. Decided 2026-11-03 (NetOrk/netork#1933). Refs #18
708 lines
25 KiB
Python
708 lines
25 KiB
Python
"""Scheduled jobs on OpenMediaVault: the web UI's through RPC, the rest as on Linux (#18).
|
|
|
|
OMV writes its cron files itself, from its own database: the web UI's "Scheduled
|
|
Jobs" (and the power-management schedule) go to ``/etc/cron.d/openmediavault-*``
|
|
on every apply of the ``cron`` module, rsync jobs, the mail-queue flush and the
|
|
apticron run likewise. An edit there would be taken back without a word. So those
|
|
files are ``platform`` and never written through the Linux path; the lines of the
|
|
web UI's file are replaced by the jobs ``Cron.getList`` returns, and those are
|
|
switched, run, made and removed through ``Cron.*`` -- then ``Config.applyChanges``
|
|
for ``cron`` alone, so changes someone left pending in the web UI stay pending.
|
|
|
|
The NAS below is synthetic: the report napalm-linux's reader prints, and the RPC
|
|
answers ``omv-rpc`` gives, in OMV 8's shapes (``Cron.getList`` keeps each time
|
|
field a comma-separated string, ``Cron.set`` takes lists).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import shlex
|
|
|
|
import pytest
|
|
from napalm_device_types import (
|
|
CommandResult,
|
|
ScheduledJobChanged,
|
|
ScheduledJobRefused,
|
|
)
|
|
|
|
from napalm_openmediavault import _scheduled_jobs as sj
|
|
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
|
|
|
NEW = "fa4b1c66-ef79-11e5-87a0-0002b3a176b4"
|
|
SYNC = "2c1d3e4f-0a1b-4c2d-8e3f-405162738495"
|
|
WEEKLY = "3d2e4f50-1b2c-4d3e-9f40-5162738495a6"
|
|
OWN = "4e3f5061-2c3d-4e4f-a051-62738495a6b7"
|
|
POWER = "5f406172-3d4e-4f50-b162-738495a6b7c8"
|
|
|
|
REPORT = """SJ_BEGIN
|
|
[system /etc/cron.d/openmediavault-userdefined]
|
|
|# This file is auto-generated by openmediavault (https://www.openmediavault.org)
|
|
|SHELL=/bin/sh
|
|
|15 2 * * 1,3 root /var/lib/openmediavault/cron.d/userdefined-2c1d3e4f-0a1b-4c2d-8e3f-405162738495 >/dev/null 2>&1
|
|
[system /etc/cron.d/openmediavault-powermngmt]
|
|
|0 23 * * * root systemctl poweroff >/dev/null 2>&1
|
|
[system /etc/cron.d/openmediavault-rsync]
|
|
|0 3 * * * root /var/lib/openmediavault/cron.d/rsync-6a7b8c9d >/dev/null 2>&1
|
|
[system /etc/cron.d/certbot]
|
|
|0 */12 * * * root certbot -q renew
|
|
[run-parts hourly 1 1234 /etc/cron.hourly/openmediavault-flushmailq]
|
|
[run-parts daily 1 5678 /etc/cron.daily/openmediavault-check_locked_users]
|
|
[tz]
|
|
/usr/share/zoneinfo/Europe/Berlin
|
|
[owners]
|
|
certbot: /etc/cron.d/certbot
|
|
openmediavault: /etc/cron.daily/openmediavault-check_locked_users
|
|
SJ_END
|
|
"""
|
|
|
|
|
|
def _job(uuid: str, **fields: object) -> dict[str, object]:
|
|
job: dict[str, object] = {
|
|
"uuid": uuid,
|
|
"enable": True,
|
|
"execution": "exactly",
|
|
"sendemail": False,
|
|
"comment": "",
|
|
"type": "userdefined",
|
|
"minute": "0",
|
|
"everynminute": False,
|
|
"hour": "0",
|
|
"everynhour": False,
|
|
"month": "*",
|
|
"dayofmonth": "*",
|
|
"everyndayofmonth": False,
|
|
"dayofweek": "*",
|
|
"username": "root",
|
|
"command": "true",
|
|
}
|
|
job.update(fields)
|
|
return job
|
|
|
|
|
|
def _jobs() -> list[dict[str, object]]:
|
|
return [
|
|
_job(
|
|
SYNC,
|
|
minute="15",
|
|
everynminute=True,
|
|
hour="2",
|
|
dayofweek="1,3",
|
|
comment="Nightly sync",
|
|
command="rsync -a /srv/a /srv/b",
|
|
),
|
|
_job(WEEKLY, enable=False, execution="weekly", username="backup", command="backup.sh"),
|
|
_job(
|
|
OWN,
|
|
execution="daily",
|
|
sendemail=True,
|
|
comment="napalm-scheduled-job: cleanup Remove old snapshots",
|
|
command="cleanup --old\necho done",
|
|
),
|
|
_job(POWER, type="shutdown", hour="23", command="systemctl poweroff"),
|
|
]
|
|
|
|
|
|
class Nas:
|
|
"""An OMV NAS as the driver sees it: ``run_command`` and ``omv-rpc`` through sudo."""
|
|
|
|
def __init__(self) -> None:
|
|
self.jobs = _jobs()
|
|
self.dirty = ["apt"]
|
|
self.users = {"root": "root", "backup": "backup"}
|
|
self.commands: list[str] = []
|
|
self.calls: list[tuple[str, object]] = []
|
|
self.listed = None # what Cron.getList says, if not the jobs
|
|
self.output = [("hello\n", True), ("world\n", False)]
|
|
self.fail = ""
|
|
|
|
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
|
self.commands.append(command)
|
|
if command.startswith("printf '%s%s\\n' SJ_"):
|
|
return CommandResult(REPORT, "", 0)
|
|
if command.startswith("t=$(mktemp)"):
|
|
return CommandResult("/tmp/tmp.Staged", "", 0)
|
|
argv = shlex.split(command)
|
|
if argv[0] == "stat":
|
|
return CommandResult("644 root root\n", "", 0)
|
|
if argv[:3] == ["id", "-gn", "--"]:
|
|
group = self.users.get(argv[3])
|
|
return CommandResult(group or "", "" if group else "no such user", 0 if group else 1)
|
|
return CommandResult("", "", 0)
|
|
|
|
def sudo_status(self, command: str, read_timeout: float = 100):
|
|
if command.startswith("cat ") and "dirtymodules" in command:
|
|
return json.dumps(self.dirty), 0
|
|
argv = shlex.split(command)
|
|
assert argv[:3] == ["omv-rpc", "-u", "admin"], command
|
|
method = f"{argv[3]}.{argv[4]}"
|
|
params = json.loads(argv[5]) if len(argv) > 5 else None
|
|
self.calls.append((method, params))
|
|
if method == self.fail:
|
|
return "ERROR: the job failed: exit 3", 1
|
|
return json.dumps(self._answer(method, params)), 0
|
|
|
|
def _answer(self, method: str, params): # noqa: C901 - one branch per RPC method
|
|
if method == "Cron.getList":
|
|
assert params["type"] == ["userdefined", "reboot", "shutdown", "standby"]
|
|
data = self.jobs if self.listed is None else self.listed
|
|
return {"total": len(self.jobs), "data": data}
|
|
if method == "Cron.set":
|
|
stored = {k: ",".join(v) if isinstance(v, list) else v for k, v in params.items()}
|
|
if stored["uuid"] == NEW:
|
|
stored["uuid"] = "6b7c8d9e-4e5f-4061-8273-8495a6b7c8d9"
|
|
self.jobs.append(stored)
|
|
else:
|
|
self.jobs = [stored if j["uuid"] == stored["uuid"] else j for j in self.jobs]
|
|
self.dirty.append("cron")
|
|
return stored
|
|
if method == "Cron.delete":
|
|
self.jobs = [j for j in self.jobs if j["uuid"] != params["uuid"]]
|
|
self.dirty.append("cron")
|
|
return {}
|
|
if method == "Cron.execute":
|
|
return "/tmp/bgstatusQx1"
|
|
if method == "Exec.getOutput":
|
|
chunk, running = self.output.pop(0)
|
|
return {
|
|
"filename": params["filename"],
|
|
"pos": params["pos"] + len(chunk),
|
|
"output": chunk,
|
|
"running": running,
|
|
}
|
|
if method == "Exec.stop":
|
|
return None
|
|
if method == "Config.applyChanges":
|
|
self.dirty = [m for m in self.dirty if m not in params["modules"]]
|
|
return None
|
|
raise AssertionError(method)
|
|
|
|
def called(self, method: str) -> list[object]:
|
|
return [params for m, params in self.calls if m == method]
|
|
|
|
|
|
@pytest.fixture
|
|
def nas() -> Nas:
|
|
return Nas()
|
|
|
|
|
|
@pytest.fixture
|
|
def driver(nas: Nas) -> OpenMediaVaultDriver:
|
|
d = OpenMediaVaultDriver("nas", "admin", "p")
|
|
d.run_command = nas.run_command # type: ignore[method-assign]
|
|
d._sudo_status = nas.sudo_status # type: ignore[method-assign]
|
|
return d
|
|
|
|
|
|
def _by_key(driver: OpenMediaVaultDriver) -> dict[str, dict[str, object]]:
|
|
return {str(j["key"]): dict(j) for j in driver.get_scheduled_jobs()["jobs"]}
|
|
|
|
|
|
# -- what OMV offers -------------------------------------------------------------------------
|
|
|
|
|
|
def test_omv_offers_every_verb_of_the_contract():
|
|
for verb in (
|
|
"get_scheduled_jobs",
|
|
"manage_scheduled_job",
|
|
"put_scheduled_job",
|
|
"delete_scheduled_job",
|
|
):
|
|
assert callable(getattr(OpenMediaVaultDriver, verb)), verb
|
|
|
|
|
|
def test_every_file_omv_generates_is_platform():
|
|
for path in (
|
|
"/etc/cron.d/openmediavault-userdefined",
|
|
"/etc/cron.d/openmediavault-powermngmt",
|
|
"/etc/cron.d/openmediavault-rsync",
|
|
"/etc/cron.d/openmediavault-mkrrdgraph",
|
|
"/etc/cron.hourly/openmediavault-flushmailq",
|
|
"/etc/cron.daily/openmediavault-apticron",
|
|
"/etc/cron.weekly/openmediavault-apticron",
|
|
"/etc/cron.daily/openmediavault-samba-recycle",
|
|
):
|
|
assert sj.generated(path), path
|
|
assert not sj.generated("/etc/cron.d/certbot")
|
|
assert not sj.generated("/etc/cron.daily/openmediavault-check_locked_users")
|
|
|
|
|
|
# -- reading ---------------------------------------------------------------------------------
|
|
|
|
|
|
def test_the_web_ui_jobs_come_from_rpc(driver):
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
|
|
assert job["kind"] == "cron"
|
|
assert job["source"] == "omv:cron"
|
|
assert job["schedule"] == "*/15 2 * * 1,3"
|
|
assert job["schedule_kind"] == "cron"
|
|
assert (job["run_as"], job["command"], job["enabled"]) == (
|
|
"root",
|
|
"rsync -a /srv/a /srv/b",
|
|
True,
|
|
)
|
|
assert job["managed_by"] == "admin"
|
|
assert job["actions"] == ["enable", "disable", "run"]
|
|
assert job["description"] == "Nightly sync"
|
|
|
|
|
|
def test_the_generated_lines_of_the_web_ui_jobs_are_not_reported_twice(driver):
|
|
sources = {str(j["source"]) for j in driver.get_scheduled_jobs()["jobs"]}
|
|
|
|
assert "/etc/cron.d/openmediavault-userdefined" not in sources
|
|
assert "/etc/cron.d/openmediavault-powermngmt" not in sources
|
|
|
|
|
|
def test_a_shortcut_is_the_cron_alias_and_a_disabled_job_is_reported(driver):
|
|
job = _by_key(driver)[f"omv:{WEEKLY}"]
|
|
|
|
assert (job["schedule"], job["enabled"], job["run_as"]) == ("@weekly", False, "backup")
|
|
|
|
|
|
def test_an_applications_job_is_known_by_its_comment(driver):
|
|
job = _by_key(driver)[f"omv:{OWN}"]
|
|
|
|
assert job["managed_by"] == "application"
|
|
assert (job["name"], job["description"]) == ("cleanup", "Remove old snapshots")
|
|
assert job["actions"] == ["enable", "disable", "run", "edit", "delete"]
|
|
assert job["command"] == "cleanup --old\necho done"
|
|
|
|
|
|
def test_a_power_management_job_is_switched_but_not_run(driver):
|
|
job = _by_key(driver)[f"omv:{POWER}"]
|
|
|
|
assert job["source"] == "omv:powermgmt"
|
|
assert job["schedule"] == "0 23 * * *"
|
|
assert job["actions"] == ["enable", "disable"]
|
|
|
|
|
|
def test_the_rest_of_the_host_is_read_as_on_linux(driver):
|
|
reading = driver.get_scheduled_jobs()
|
|
certbot = next(j for j in reading["jobs"] if j["source"] == "/etc/cron.d/certbot")
|
|
package = _by_key(driver)["run-parts:/etc/cron.daily/openmediavault-check_locked_users"]
|
|
|
|
assert reading["time_zone"] == "Europe/Berlin"
|
|
assert certbot["managed_by"] == "package"
|
|
assert certbot["actions"] == ["enable", "disable", "run"]
|
|
assert package["managed_by"] == "package"
|
|
|
|
|
|
def test_a_generated_job_is_platform_and_only_runs(driver):
|
|
jobs = _by_key(driver)
|
|
rsync = next(j for j in jobs.values() if j["source"] == "/etc/cron.d/openmediavault-rsync")
|
|
flush = jobs["run-parts:/etc/cron.hourly/openmediavault-flushmailq"]
|
|
|
|
for job in (rsync, flush):
|
|
assert job["managed_by"] == "platform"
|
|
assert job["actions"] == ["run"]
|
|
|
|
|
|
def test_a_list_cut_short_raises(driver, nas):
|
|
nas.listed = nas.jobs[:2]
|
|
|
|
with pytest.raises(ValueError):
|
|
driver.get_scheduled_jobs()
|
|
|
|
|
|
def test_a_failed_list_raises(driver, nas):
|
|
nas.fail = "Cron.getList"
|
|
|
|
with pytest.raises(RuntimeError):
|
|
driver.get_scheduled_jobs()
|
|
|
|
|
|
def test_the_digest_sees_a_change_of_the_email_setting(driver, nas):
|
|
before = _by_key(driver)[f"omv:{SYNC}"]["digest"]
|
|
nas.jobs[0]["sendemail"] = True
|
|
|
|
assert _by_key(driver)[f"omv:{SYNC}"]["digest"] != before
|
|
|
|
|
|
# -- never a generated file ------------------------------------------------------------------
|
|
|
|
|
|
_WRITES = {"install", "crontab", "chmod", "rm", "tee", "mv", "cp", "sed", "systemctl"}
|
|
#: What reads a file or runs a job, and so may name a generated file.
|
|
_READS = {"cat", "timeout", "id"}
|
|
|
|
|
|
def _wrote(nas: Nas) -> list[str]:
|
|
"""Every command but the report that writes, or that names a generated file to do so."""
|
|
commands = [c for c in nas.commands if not c.startswith("printf '%s%s\\n' SJ_")]
|
|
return [
|
|
c
|
|
for c in commands
|
|
if shlex.split(c)[0] in _WRITES
|
|
or ("openmediavault-" in c and shlex.split(c)[0] not in _READS)
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("action", ["enable", "disable"])
|
|
def test_a_generated_job_is_never_switched_by_the_linux_path(driver, nas, action):
|
|
for job in _by_key(driver).values():
|
|
if job["managed_by"] != "platform":
|
|
continue
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.manage_scheduled_job(str(job["key"]), action, digest=str(job["digest"]))
|
|
|
|
assert _wrote(nas) == []
|
|
|
|
|
|
def test_the_linux_writers_refuse_a_generated_file(driver, nas):
|
|
flush = _by_key(driver)["run-parts:/etc/cron.hourly/openmediavault-flushmailq"]
|
|
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver._sj_write("/etc/cron.d/openmediavault-userdefined", "* * * * * root true\n")
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver._sj_switch(flush, False)
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver._sj_delete_cron({"source": "/etc/cron.d/openmediavault-rsync", "name": "x"})
|
|
assert _wrote(nas) == []
|
|
|
|
|
|
def test_the_linux_writers_still_write_any_other_file(driver, nas):
|
|
driver._sj_write("/etc/cron.d/certbot", "0 */12 * * * root certbot -q renew\n")
|
|
driver._sj_delete_cron({"source": "/etc/cron.d/tidy", "name": "tidy", "run_as": "root"})
|
|
|
|
assert any(c.startswith("install") and c.endswith("/etc/cron.d/certbot") for c in nas.commands)
|
|
assert shlex.join(["rm", "-f", "--", "/etc/cron.d/tidy"]) in nas.commands
|
|
|
|
|
|
def test_a_generated_cron_line_still_runs(driver, nas):
|
|
rsync = next(
|
|
j for j in _by_key(driver).values() if j["source"] == "/etc/cron.d/openmediavault-rsync"
|
|
)
|
|
nas.run_command = _with_file(nas, "/etc/cron.d/openmediavault-rsync") # type: ignore[method-assign]
|
|
driver.run_command = nas.run_command # type: ignore[method-assign]
|
|
|
|
result = driver.manage_scheduled_job(str(rsync["key"]), "run", digest=str(rsync["digest"]))
|
|
|
|
assert result["success"] is True
|
|
assert any("rsync-6a7b8c9d" in c for c in nas.commands)
|
|
assert _wrote(nas) == []
|
|
|
|
|
|
def _with_file(nas: Nas, path: str):
|
|
text = "0 3 * * * root /var/lib/openmediavault/cron.d/rsync-6a7b8c9d >/dev/null 2>&1\n"
|
|
original = nas.run_command
|
|
|
|
def run_command(command, **kwargs):
|
|
if command == shlex.join(["cat", "--", path]):
|
|
nas.commands.append(command)
|
|
return CommandResult(text, "", 0)
|
|
return original(command, **kwargs)
|
|
|
|
return run_command
|
|
|
|
|
|
def test_any_other_job_keeps_the_linux_behaviour(driver, nas):
|
|
job = _by_key(driver)["run-parts:/etc/cron.daily/openmediavault-check_locked_users"]
|
|
|
|
driver.manage_scheduled_job(str(job["key"]), "disable", digest=str(job["digest"]))
|
|
|
|
assert (
|
|
shlex.join(["chmod", "-x", "--", "/etc/cron.daily/openmediavault-check_locked_users"])
|
|
in nas.commands
|
|
)
|
|
assert nas.called("Cron.set") == []
|
|
|
|
|
|
# -- switching and running a web UI job ------------------------------------------------------
|
|
|
|
|
|
def test_disable_sets_the_job_unchanged_but_enable(driver, nas):
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
|
|
result = driver.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
|
|
(sent,) = nas.called("Cron.set")
|
|
assert sent == {
|
|
**_jobs()[0],
|
|
"enable": False,
|
|
"minute": ["15"],
|
|
"hour": ["2"],
|
|
"month": ["*"],
|
|
"dayofmonth": ["*"],
|
|
"dayofweek": ["1", "3"],
|
|
}
|
|
assert result["success"] is True
|
|
assert nas.called("Config.applyChanges") == [{"modules": ["cron"], "force": False}]
|
|
assert nas.dirty == ["apt"]
|
|
assert _by_key(driver)[f"omv:{SYNC}"]["enabled"] is False
|
|
|
|
|
|
def test_enable_switches_a_disabled_job_on(driver, nas):
|
|
job = _by_key(driver)[f"omv:{WEEKLY}"]
|
|
|
|
driver.manage_scheduled_job(job["key"], "enable", digest=job["digest"])
|
|
|
|
assert nas.called("Cron.set")[0]["enable"] is True
|
|
|
|
|
|
def test_a_job_changed_since_it_was_read_is_not_written(driver, nas):
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
nas.jobs[0]["command"] = "rsync -a /srv/a /srv/c"
|
|
|
|
with pytest.raises(ScheduledJobChanged):
|
|
driver.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
assert nas.called("Cron.set") == []
|
|
assert nas.called("Config.applyChanges") == []
|
|
|
|
|
|
def test_an_unknown_job_is_a_lookup_error(driver):
|
|
with pytest.raises(LookupError):
|
|
driver.manage_scheduled_job("omv:00000000-0000-4000-8000-000000000000", "run", digest="x")
|
|
|
|
|
|
def test_an_unknown_action_is_refused(driver):
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.manage_scheduled_job(job["key"], "edit", digest=job["digest"])
|
|
|
|
|
|
def test_a_power_management_job_is_not_run(driver, nas):
|
|
job = _by_key(driver)[f"omv:{POWER}"]
|
|
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
assert nas.called("Cron.execute") == []
|
|
|
|
|
|
def test_run_follows_the_output_to_the_end(driver, nas, monkeypatch):
|
|
monkeypatch.setattr(sj, "_sleep", lambda _s: None)
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
|
|
result = driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
|
|
assert nas.called("Cron.execute") == [{"uuid": SYNC}]
|
|
assert nas.called("Exec.getOutput") == [
|
|
{"filename": "/tmp/bgstatusQx1", "pos": 0},
|
|
{"filename": "/tmp/bgstatusQx1", "pos": 6},
|
|
]
|
|
assert result == {"success": True, "output": "hello\nworld"}
|
|
|
|
|
|
def test_a_run_that_fails_says_so(driver, nas, monkeypatch):
|
|
monkeypatch.setattr(sj, "_sleep", lambda _s: None)
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
nas.output = [("hello\n", True)]
|
|
|
|
def status(command: str, read_timeout: float = 100):
|
|
"""The job ends with exit 3: OMV raises from the next ``Exec.getOutput``."""
|
|
if "getOutput" in command and '"pos": 6' in command:
|
|
return "ERROR: the job failed: exit 3", 1
|
|
return nas.sudo_status(command, read_timeout)
|
|
|
|
driver._sudo_status = status # type: ignore[method-assign]
|
|
result = driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
|
|
assert result["success"] is False
|
|
assert "hello" in result["output"]
|
|
assert "exit 3" in result["output"]
|
|
|
|
|
|
def test_a_run_past_the_timeout_is_stopped(driver, nas, monkeypatch):
|
|
clock = iter(range(0, 10_000, 200))
|
|
monkeypatch.setattr(sj, "_sleep", lambda _s: None)
|
|
monkeypatch.setattr(sj, "_monotonic", lambda: next(clock))
|
|
nas.output = [("tick\n", True)] * 10
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
|
|
result = driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
|
|
assert nas.called("Exec.stop") == [{"filename": "/tmp/bgstatusQx1"}]
|
|
assert result["success"] is False
|
|
assert "stopped after 300 s" in result["output"]
|
|
|
|
|
|
# -- an application's own job ----------------------------------------------------------------
|
|
|
|
|
|
def _spec(**fields):
|
|
spec = {
|
|
"name": "rotate",
|
|
"schedule": "*/10 1-3 * * 0",
|
|
"run_as": "backup",
|
|
"command": "rotate-logs\necho rotated",
|
|
"enabled": True,
|
|
"description": "Rotate the logs",
|
|
}
|
|
spec.update(fields)
|
|
return spec
|
|
|
|
|
|
def test_put_creates_an_omv_job(driver, nas):
|
|
result = driver.put_scheduled_job(_spec())
|
|
|
|
(sent,) = nas.called("Cron.set")
|
|
assert sent == {
|
|
"uuid": NEW,
|
|
"enable": True,
|
|
"execution": "exactly",
|
|
"sendemail": False,
|
|
"comment": "napalm-scheduled-job: rotate Rotate the logs",
|
|
"type": "userdefined",
|
|
"minute": ["10"],
|
|
"everynminute": True,
|
|
"hour": ["1", "2", "3"],
|
|
"everynhour": False,
|
|
"month": ["*"],
|
|
"dayofmonth": ["*"],
|
|
"everyndayofmonth": False,
|
|
"dayofweek": ["7"],
|
|
"username": "backup",
|
|
"command": "rotate-logs\necho rotated",
|
|
}
|
|
assert nas.called("Config.applyChanges") == [{"modules": ["cron"], "force": False}]
|
|
assert result == {"success": True, "output": "omv:6b7c8d9e-4e5f-4061-8273-8495a6b7c8d9 created"}
|
|
job = _by_key(driver)["omv:6b7c8d9e-4e5f-4061-8273-8495a6b7c8d9"]
|
|
assert (job["managed_by"], job["name"], job["schedule"]) == (
|
|
"application",
|
|
"rotate",
|
|
"*/10 1,2,3 * * 7",
|
|
)
|
|
|
|
|
|
def test_put_changes_the_applications_job_and_keeps_its_email_setting(driver, nas):
|
|
job = _by_key(driver)[f"omv:{OWN}"]
|
|
|
|
result = driver.put_scheduled_job(
|
|
_spec(name="cleanup", schedule="@daily", run_as="root"), digest=job["digest"]
|
|
)
|
|
|
|
(sent,) = nas.called("Cron.set")
|
|
assert (sent["uuid"], sent["execution"], sent["sendemail"]) == (OWN, "daily", True)
|
|
assert result["output"] == f"omv:{OWN} changed"
|
|
|
|
|
|
def test_put_of_a_name_already_there_without_digest_is_a_change_unseen(driver, nas):
|
|
with pytest.raises(ScheduledJobChanged):
|
|
driver.put_scheduled_job(_spec(name="cleanup"))
|
|
assert nas.called("Cron.set") == []
|
|
|
|
|
|
def test_put_with_a_digest_for_a_job_not_there_is_a_lookup_error(driver):
|
|
with pytest.raises(LookupError):
|
|
driver.put_scheduled_job(_spec(), digest="0123456789abcdef")
|
|
|
|
|
|
def test_put_over_a_changed_job_is_refused(driver, nas):
|
|
job = _by_key(driver)[f"omv:{OWN}"]
|
|
nas.jobs[2]["command"] = "something else"
|
|
|
|
with pytest.raises(ScheduledJobChanged):
|
|
driver.put_scheduled_job(_spec(name="cleanup"), digest=job["digest"])
|
|
assert nas.called("Cron.set") == []
|
|
|
|
|
|
def test_put_for_a_user_the_nas_does_not_have_is_refused(driver, nas):
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.put_scheduled_job(_spec(run_as="nobody"))
|
|
assert nas.called("Cron.set") == []
|
|
|
|
|
|
def test_put_of_an_invalid_spec_is_refused_before_anything_runs(driver, nas):
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.put_scheduled_job(_spec(schedule="61 * * * *"))
|
|
assert nas.calls == []
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("schedule", "execution"),
|
|
[
|
|
("@reboot", "reboot"),
|
|
("@hourly", "hourly"),
|
|
("@daily", "daily"),
|
|
("@midnight", "daily"),
|
|
("@weekly", "weekly"),
|
|
("@monthly", "monthly"),
|
|
("@yearly", "yearly"),
|
|
("@annually", "yearly"),
|
|
],
|
|
)
|
|
def test_a_cron_alias_is_omvs_shortcut(schedule, execution):
|
|
assert sj.omv_schedule(schedule)["execution"] == execution
|
|
|
|
|
|
def test_a_step_on_month_and_weekday_is_written_as_its_values():
|
|
fields = sj.omv_schedule("0 0 * */4 1-5/2")
|
|
|
|
assert fields["month"] == ["1", "5", "9"]
|
|
assert fields["dayofweek"] == ["1", "3", "5"]
|
|
|
|
|
|
def test_a_day_field_keeps_its_star_meaning():
|
|
"""``1-31`` is not ``*``: with a weekday set, cron runs on either."""
|
|
assert sj.omv_schedule("0 0 1-31 * 1")["dayofmonth"] == [str(d) for d in range(1, 32)]
|
|
|
|
|
|
def test_a_schedule_cron_would_not_take_is_refused():
|
|
with pytest.raises(ScheduledJobRefused):
|
|
sj.omv_schedule("61 * * * *")
|
|
|
|
|
|
def test_a_weekday_step_beside_a_day_of_month_is_refused():
|
|
"""OMV has no ``*/n`` for weekdays; its values would turn cron's AND into an OR."""
|
|
with pytest.raises(ScheduledJobRefused):
|
|
sj.omv_schedule("0 0 1 * */2")
|
|
|
|
|
|
def test_a_cron_schedule_reads_back_from_omvs_fields():
|
|
for schedule in ("*/10 1,2,3 * * 7", "0 0 */2 1,6 *", "@reboot", "@yearly"):
|
|
fields = {
|
|
k: ",".join(v) if isinstance(v, list) else v
|
|
for k, v in sj.omv_schedule(schedule).items()
|
|
}
|
|
assert sj.cron_schedule(fields) == schedule
|
|
|
|
|
|
# -- deleting --------------------------------------------------------------------------------
|
|
|
|
|
|
def test_delete_removes_the_applications_job(driver, nas):
|
|
job = _by_key(driver)[f"omv:{OWN}"]
|
|
|
|
result = driver.delete_scheduled_job(job["key"], digest=job["digest"])
|
|
|
|
assert nas.called("Cron.delete") == [{"uuid": OWN}]
|
|
assert nas.called("Config.applyChanges") == [{"modules": ["cron"], "force": False}]
|
|
assert result == {"success": True, "output": f"omv:{OWN} deleted"}
|
|
|
|
|
|
def test_delete_of_an_admins_job_is_refused(driver, nas):
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.delete_scheduled_job(job["key"], digest=job["digest"])
|
|
assert nas.called("Cron.delete") == []
|
|
|
|
|
|
def test_delete_of_a_changed_job_is_refused(driver, nas):
|
|
job = _by_key(driver)[f"omv:{OWN}"]
|
|
nas.jobs[2]["enable"] = False
|
|
|
|
with pytest.raises(ScheduledJobChanged):
|
|
driver.delete_scheduled_job(job["key"], digest=job["digest"])
|
|
assert nas.called("Cron.delete") == []
|
|
|
|
|
|
def test_delete_of_any_other_job_is_the_linux_one(driver, nas):
|
|
certbot = next(
|
|
j for j in driver.get_scheduled_jobs()["jobs"] if j["source"] == "/etc/cron.d/certbot"
|
|
)
|
|
|
|
with pytest.raises(ScheduledJobRefused):
|
|
driver.delete_scheduled_job(certbot["key"], digest=certbot["digest"])
|
|
assert _wrote(nas) == []
|
|
|
|
|
|
def test_a_cron_module_with_changes_pending_refuses_every_write(driver, nas):
|
|
"""An apply would put someone's half-finished web-UI edit live along with ours."""
|
|
nas.dirty = ["apt", "cron"]
|
|
job = _by_key(driver)[f"omv:{SYNC}"]
|
|
with pytest.raises(ScheduledJobRefused, match="unapplied changes"):
|
|
driver.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
assert nas.called("Cron.set") == [] and nas.called("Config.applyChanges") == []
|