driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 13s
driver / test (3.12) (pull_request) Failing after 15s
driver / test (3.13) (pull_request) Failing after 13s
driver / types (pull_request) Failing after 25s
driver / lowest (pull_request) Failing after 19s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Failing after 36s
CI / driver (pull_request) Failing after 1m10s
driver / publish (pull_request) Skipped
get_scheduled_jobs reads /etc/crontab and the user crontabs in /var/cron/tabs, on FreeBSD also both cron.d directories and every periodic script, in one round trip as root; manage_scheduled_job enables, disables or runs one now; put_ and delete_scheduled_job write and remove an application's own job (/etc/cron.d on FreeBSD, marked lines in the user's crontab on OpenBSD). A periodic script is what FreeBSD runs daily, weekly, monthly and for the security run; it does its work only when its periodic.conf knob says YES, so that knob is its enabled state, written with sysrc to /etc/periodic.conf. A later periodic.conf that still overrides it is reported instead of claimed as done. A script whose knob is not known only runs; one whose knob is off does nothing when run and offers no run. BSD su takes no shell (FreeBSD's -s is a MAC label) and -m starts root's own shell, csh on many FreeBSD hosts, so another user's job goes to /bin/sh on stdin. OpenBSD cron's -n/-q/-s flags are left off when a line runs now. What the base system ships is platform: FreeBSD's /etc/crontab and /etc/periodic, OpenBSD's newsyslog and /etc/daily|weekly|monthly lines, which stay one job each. get_cron_jobs goes: it read without root and missed cron.d, every other user and periodic. Requires napalm-device-types 4.26.0. Closes #27
595 lines
25 KiB
Python
595 lines
25 KiB
Python
"""Scheduled jobs on FreeBSD and OpenBSD: cron with the BSD paths, FreeBSD's periodic (#27).
|
|
|
|
The report is napalm-device-types' ``PosixScheduledJobsMixin``'s, with the
|
|
periodic scan behind it in the same round trip. Both are run by a real ``sh``
|
|
over a directory tree that stands in for the host, with ``crontab``, ``install``,
|
|
``stat``, ``su``, ``pkg`` and ``sysrc`` replaced by scripts that keep a log -- so
|
|
the shell itself is what is tested, not a hand-written copy of its output.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from napalm_device_types import CommandResult, PosixScheduledJobsMixin
|
|
from napalm_device_types.scheduled_jobs import ScheduledJobChanged, ScheduledJobRefused
|
|
|
|
from napalm_bsd import FreeBSDDriver, OpenBSDDriver, parse
|
|
from napalm_bsd import periodic as periodic_module
|
|
from napalm_bsd.base import BsdDriver
|
|
from napalm_bsd.periodic import PERIODIC_DIRS
|
|
|
|
CRONTAB = """#!/bin/sh
|
|
echo "crontab $*" >> "$LOG"
|
|
[ "$1" = -u ] || exit 2
|
|
if [ "$3" = -l ]; then
|
|
[ -f "$SPOOL/$2" ] || { echo "crontab: no crontab for $2" >&2; exit 1; }
|
|
cat "$SPOOL/$2"
|
|
else
|
|
cp "$3" "$SPOOL/$2"
|
|
fi
|
|
"""
|
|
|
|
# BSD install has no -D here; owner and group are root's to set.
|
|
INSTALL = """#!/bin/sh
|
|
echo "install $*" >> "$LOG"
|
|
args=""
|
|
while [ $# -gt 0 ]; do case "$1" in -o|-g) shift 2 ;; -D) exit 64 ;; *) args="$args '$1'"; shift ;; esac; done
|
|
eval "/usr/bin/install $args"
|
|
"""
|
|
|
|
# BSD stat: -f <format>; GNU stat answers for it.
|
|
STAT = """#!/bin/sh
|
|
echo "stat $*" >> "$LOG"
|
|
[ "$1" = -f ] && [ "$2" = "%Lp %Su %Sg" ] && [ "$3" = -- ] || exit 64
|
|
exec /usr/bin/stat -c '%a %U %G' -- "$4"
|
|
"""
|
|
|
|
# BSD su: -m keeps the environment and starts the caller's shell with what follows the login.
|
|
SU = """#!/bin/sh
|
|
echo "su $* HOME=$HOME USER=$USER LOGNAME=$LOGNAME" >> "$LOG"
|
|
[ "$1" = -m ] && [ "$3" = -c ] || exit 64
|
|
exec $4
|
|
"""
|
|
|
|
PKG = """#!/bin/sh
|
|
case "$1" in
|
|
-N) exit 0 ;;
|
|
which) [ "$2" = -q ] && [ "$3" = -- ] || exit 64
|
|
case " $OWNED " in *" $4 "*) echo "pkg-2.1.2" ;; *) exit 1 ;; esac ;;
|
|
esac
|
|
"""
|
|
|
|
# sysrc -f <file> <knob>=<value>: replace the knob's line, or add one.
|
|
SYSRC = """#!/bin/sh
|
|
echo "sysrc $*" >> "$LOG"
|
|
[ "$1" = -f ] || exit 64
|
|
f=$2; k=${3%%=*}; v=${3#*=}
|
|
touch "$f"
|
|
old=$(sed -n "s/^$k=\\"*\\([^\\"]*\\)\\"*/\\1/p" "$f")
|
|
grep -v "^$k=" "$f" > "$f.new"; echo "$k=\\"$v\\"" >> "$f.new"; mv "$f.new" "$f"
|
|
echo "$k: ${old:-} -> $v"
|
|
"""
|
|
|
|
DEFAULTS = """\
|
|
periodic_conf_files="ROOT/etc/periodic.conf ROOT/etc/periodic.conf.local"
|
|
source_periodic_confs() {
|
|
for i in $periodic_conf_files; do [ -r "$i" ] && . "$i"; done
|
|
}
|
|
daily_clean_disks_enable="NO"
|
|
daily_status_disks_enable="YES"
|
|
security_status_chksetuid_enable="YES"
|
|
"""
|
|
|
|
SCRIPT = """#!/bin/sh
|
|
if [ -r ROOT/etc/defaults/periodic.conf ]; then
|
|
. ROOT/etc/defaults/periodic.conf
|
|
source_periodic_confs
|
|
fi
|
|
case "$KNOB" in
|
|
[Yy][Ee][Ss]) echo "WHAT ran (PERIODIC=$PERIODIC)" ;;
|
|
esac
|
|
"""
|
|
|
|
|
|
def _recorded(system: str, name: str) -> str:
|
|
return (Path(__file__).parent / "fixtures" / system / name).read_text()
|
|
|
|
|
|
def _tool(root: Path, name: str, body: str) -> None:
|
|
path = root / "bin" / name
|
|
path.write_text(body)
|
|
path.chmod(0o755)
|
|
|
|
|
|
def _script(root: Path, name: str, knob: str, *, what: str = "", mode: int = 0o755) -> None:
|
|
path = root / name
|
|
body = SCRIPT.replace("ROOT", str(root)).replace("KNOB", knob)
|
|
path.write_text(body.replace("WHAT", what or path.name))
|
|
path.chmod(mode)
|
|
|
|
|
|
class _Host:
|
|
"""What both test hosts share: every command run by sh, in a directory."""
|
|
|
|
root: Path
|
|
commands: list[str]
|
|
|
|
def _setup(self, root: Path) -> None:
|
|
self.root = root
|
|
self.commands = []
|
|
group = subprocess.run(["id", "-gn"], capture_output=True, text=True).stdout.strip()
|
|
self.ROOT_GROUP = group # type: ignore[misc]
|
|
self.CRON_SYSTEM_FILES = (str(root / "etc/crontab"),) # type: ignore[misc]
|
|
self.CRON_SPOOL_DIRS = (str(root / "var/cron/tabs"),) # type: ignore[misc]
|
|
|
|
def run_command(self, command, *, privileged=False, timeout=60, stdin=None): # type: ignore[no-untyped-def]
|
|
self.commands.append(command)
|
|
env = {
|
|
**os.environ,
|
|
"PATH": f"{self.root / 'bin'}:{os.environ['PATH']}",
|
|
"LOG": str(self.root / "log"),
|
|
"SPOOL": str(self.root / "var/cron/tabs"),
|
|
"OWNED": str(self.root / "usr/local/etc/periodic/daily/411.pkg-backup"),
|
|
"HOME": "/root",
|
|
}
|
|
done = subprocess.run(
|
|
["sh", "-c", command], input=stdin, capture_output=True, env=env, timeout=30
|
|
)
|
|
return CommandResult(done.stdout.decode(), done.stderr.decode(), done.returncode)
|
|
|
|
def log(self) -> str:
|
|
log = self.root / "log"
|
|
return log.read_text() if log.exists() else ""
|
|
|
|
|
|
class FreeBSDHost(_Host, FreeBSDDriver):
|
|
def __init__(self, root: Path) -> None:
|
|
FreeBSDDriver.__init__(self, "host", "admin", "")
|
|
self._setup(root)
|
|
etc = root / "etc"
|
|
self.CRON_D_DIRS = (str(etc / "cron.d"), str(root / "usr/local/etc/cron.d")) # type: ignore[misc]
|
|
self.OWN_CRON_D_DIR = str(etc / "cron.d") # type: ignore[misc]
|
|
self.PERIODIC_DIRS = tuple( # type: ignore[misc]
|
|
(period, f"{root}{directory}") for period, directory in PERIODIC_DIRS
|
|
)
|
|
self.PERIODIC_DEFAULTS = str(etc / "defaults/periodic.conf") # type: ignore[misc]
|
|
self.PERIODIC_CONF = str(etc / "periodic.conf") # type: ignore[misc]
|
|
self.PLATFORM_SOURCES = (str(etc / "crontab"), f"{etc}/periodic/*") # type: ignore[misc]
|
|
|
|
|
|
class OpenBSDHost(_Host, OpenBSDDriver):
|
|
def __init__(self, root: Path) -> None:
|
|
OpenBSDDriver.__init__(self, "host", "admin", "")
|
|
self._setup(root)
|
|
|
|
|
|
@pytest.fixture
|
|
def root(tmp_path: Path) -> Path:
|
|
for d in (
|
|
"etc/cron.d",
|
|
"etc/defaults",
|
|
"usr/local/etc/cron.d",
|
|
"var/cron/tabs",
|
|
"bin",
|
|
*(f"etc/periodic/{p}" for p in ("daily", "weekly", "monthly", "security")),
|
|
"usr/local/etc/periodic/daily",
|
|
):
|
|
(tmp_path / d).mkdir(parents=True)
|
|
(tmp_path / "etc/crontab").write_text(_recorded("freebsd-host", "cat_etc_crontab.txt"))
|
|
(tmp_path / "usr/local/etc/cron.d/certbot").write_text("0 */12 * * * root certbot -q renew\n")
|
|
(tmp_path / "var/cron/tabs/www").write_text(
|
|
f'*/5 * * * * echo "$HOME $USER" > {tmp_path}/ran\n'
|
|
)
|
|
(tmp_path / "etc/defaults/periodic.conf").write_text(DEFAULTS.replace("ROOT", str(tmp_path)))
|
|
(tmp_path / "etc/periodic.conf").write_text('daily_clean_disks_enable="YES"\n')
|
|
for name, knob in (
|
|
("daily/100.clean-disks", "daily_clean_disks_enable"),
|
|
("daily/400.status-disks", "daily_status_disks_enable"),
|
|
("daily/480.leapfile-ntpd", "daily_ntpd_leapfile_enable"),
|
|
("daily/999.local", "daily_local"),
|
|
("security/100.chksetuid", "security_status_chksetuid_enable"),
|
|
):
|
|
_script(tmp_path, f"etc/periodic/{name}", knob)
|
|
_script(tmp_path, "etc/periodic/security/security.functions", "nothing", mode=0o444)
|
|
_script(
|
|
tmp_path,
|
|
"usr/local/etc/periodic/daily/411.pkg-backup",
|
|
"{daily_backup_pkgdb_enable:-YES}",
|
|
)
|
|
for name, body in (
|
|
("crontab", CRONTAB),
|
|
("install", INSTALL),
|
|
("stat", STAT),
|
|
("su", SU),
|
|
("pkg", PKG),
|
|
("sysrc", SYSRC),
|
|
):
|
|
_tool(tmp_path, name, body)
|
|
return tmp_path
|
|
|
|
|
|
def _jobs(host: PosixScheduledJobsMixin) -> dict[str, dict]:
|
|
return {j["key"]: j for j in host.get_scheduled_jobs()["jobs"]}
|
|
|
|
|
|
def _periodic(root: Path, path: str) -> str:
|
|
return f"periodic:{root}{path}"
|
|
|
|
|
|
class TestTheBsdPaths:
|
|
@pytest.mark.parametrize("cls", [FreeBSDDriver, OpenBSDDriver])
|
|
def test_cron_and_nothing_of_linux(self, cls):
|
|
assert issubclass(cls, PosixScheduledJobsMixin)
|
|
assert cls.CRON_SYSTEM_FILES == ("/etc/crontab",)
|
|
assert cls.CRON_SPOOL_DIRS == ("/var/cron/tabs",)
|
|
assert cls.RUN_PARTS_DIRS == ()
|
|
assert cls.ANACRONTAB == ""
|
|
assert cls.ROOT_GROUP == "wheel"
|
|
assert cls.STAT_ARGV == ("stat", "-f", "%Lp %Su %Sg", "--")
|
|
assert cls.INSTALL == ("install",)
|
|
# No BSD runs systemd, even where a directory of that name turns up.
|
|
assert cls("h", "u", "")._sj_paths().systemd_marker == ""
|
|
|
|
def test_freebsd_reads_both_cron_d_and_writes_to_the_base_one(self):
|
|
assert FreeBSDDriver.CRON_D_DIRS == ("/etc/cron.d", "/usr/local/etc/cron.d")
|
|
assert FreeBSDDriver.OWN_CRON_D_DIR == "/etc/cron.d"
|
|
assert FreeBSDDriver.PLATFORM_SOURCES == ("/etc/crontab", "/etc/periodic/*")
|
|
|
|
def test_openbsd_has_no_cron_d(self):
|
|
assert OpenBSDDriver.CRON_D_DIRS == ()
|
|
assert OpenBSDDriver.OWN_CRON_D_DIR is None
|
|
|
|
def test_the_old_getter_is_gone(self):
|
|
assert "get_cron_jobs" not in vars(BsdDriver)
|
|
assert not hasattr(parse, "crontab")
|
|
|
|
|
|
class TestFreeBSDReading:
|
|
def test_one_round_trip_as_root(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
host.get_scheduled_jobs()
|
|
assert len(host.commands) == 1
|
|
|
|
def test_cron_from_every_bsd_place(self, root: Path):
|
|
jobs = _jobs(FreeBSDHost(root))
|
|
cron = {(j["source"], j["run_as"]) for j in jobs.values() if j["kind"] == "cron"}
|
|
assert cron == {
|
|
(str(root / "etc/crontab"), "operator"),
|
|
(str(root / "etc/crontab"), "root"),
|
|
(str(root / "usr/local/etc/cron.d/certbot"), "root"),
|
|
(str(root / "var/cron/tabs/www"), "www"),
|
|
}
|
|
|
|
def test_the_base_crontab_is_the_platforms(self, root: Path):
|
|
jobs = _jobs(FreeBSDHost(root)).values()
|
|
by_source = {j["source"]: j["managed_by"] for j in jobs if j["kind"] == "cron"}
|
|
assert by_source[str(root / "etc/crontab")] == "platform"
|
|
assert by_source[str(root / "usr/local/etc/cron.d/certbot")] == "admin"
|
|
|
|
def test_every_executable_periodic_script_is_a_job(self, root: Path):
|
|
jobs = _jobs(FreeBSDHost(root))
|
|
periodic = sorted(k for k, j in jobs.items() if j["kind"] == "periodic")
|
|
assert periodic == sorted(
|
|
_periodic(root, p)
|
|
for p in (
|
|
"/etc/periodic/daily/100.clean-disks",
|
|
"/etc/periodic/daily/400.status-disks",
|
|
"/etc/periodic/daily/480.leapfile-ntpd",
|
|
"/etc/periodic/daily/999.local",
|
|
"/etc/periodic/security/100.chksetuid",
|
|
"/usr/local/etc/periodic/daily/411.pkg-backup",
|
|
)
|
|
)
|
|
|
|
def test_a_periodic_job(self, root: Path):
|
|
job = _jobs(FreeBSDHost(root))[_periodic(root, "/etc/periodic/daily/100.clean-disks")]
|
|
path = f"{root}/etc/periodic/daily/100.clean-disks"
|
|
assert {
|
|
k: job[k] for k in ("source", "run_as", "schedule", "schedule_kind", "command")
|
|
} == {
|
|
"source": path,
|
|
"run_as": "root",
|
|
"schedule": "daily",
|
|
"schedule_kind": "period",
|
|
"command": path,
|
|
}
|
|
assert job["managed_by"] == "platform"
|
|
assert job["actions"] == ["enable", "disable", "run"]
|
|
|
|
def test_enabled_is_its_knob_after_the_overrides(self, root: Path):
|
|
jobs = _jobs(FreeBSDHost(root))
|
|
# NO in the defaults, YES in /etc/periodic.conf.
|
|
assert jobs[_periodic(root, "/etc/periodic/daily/100.clean-disks")]["enabled"]
|
|
assert jobs[_periodic(root, "/etc/periodic/daily/400.status-disks")]["enabled"]
|
|
# security_status_<name>_enable, as the security scripts name it.
|
|
assert (
|
|
jobs[_periodic(root, "/etc/periodic/security/100.chksetuid")]["schedule"] == "security"
|
|
)
|
|
assert jobs[_periodic(root, "/etc/periodic/security/100.chksetuid")]["enabled"]
|
|
|
|
def test_a_knob_that_is_off_cannot_run(self, root: Path):
|
|
(root / "etc/periodic.conf").write_text("daily_status_disks_enable=NO\n")
|
|
job = _jobs(FreeBSDHost(root))[_periodic(root, "/etc/periodic/daily/400.status-disks")]
|
|
assert not job["enabled"]
|
|
# The script itself would do nothing.
|
|
assert job["actions"] == ["enable", "disable"]
|
|
|
|
def test_the_knob_the_script_names_when_it_is_not_its_name(self, root: Path):
|
|
job = _jobs(FreeBSDHost(root))[_periodic(root, "/etc/periodic/daily/480.leapfile-ntpd")]
|
|
assert job["actions"] == ["enable", "disable"] # daily_ntpd_leapfile_enable is unset
|
|
|
|
def test_a_script_without_a_knob_only_runs(self, root: Path):
|
|
job = _jobs(FreeBSDHost(root))[_periodic(root, "/etc/periodic/daily/999.local")]
|
|
assert job["actions"] == ["run"]
|
|
assert job["enabled"]
|
|
|
|
def test_a_scripts_own_default(self, root: Path):
|
|
job = _jobs(FreeBSDHost(root))[
|
|
_periodic(root, "/usr/local/etc/periodic/daily/411.pkg-backup")
|
|
]
|
|
assert job["enabled"] # ${daily_backup_pkgdb_enable:-YES}, set nowhere
|
|
assert job["managed_by"] == "package"
|
|
|
|
def test_a_changed_script_or_knob_changes_the_digest(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
key = _periodic(root, "/etc/periodic/daily/100.clean-disks")
|
|
before = _jobs(host)[key]["digest"]
|
|
(root / "etc/periodic.conf").write_text("daily_clean_disks_enable=NO\n")
|
|
off = _jobs(host)[key]["digest"]
|
|
assert off != before
|
|
_script(root, "etc/periodic/daily/100.clean-disks", "daily_clean_disks_enable", what="x")
|
|
assert _jobs(host)[key]["digest"] != off
|
|
|
|
def test_the_time_zone(self, root: Path):
|
|
(root / "zoneinfo").write_text("Europe/Berlin\n")
|
|
host = FreeBSDHost(root)
|
|
host.TIME_ZONE_SH = FreeBSDDriver.TIME_ZONE_SH.replace( # type: ignore[misc]
|
|
"/var/db/zoneinfo", str(root / "zoneinfo")
|
|
)
|
|
assert host.get_scheduled_jobs()["time_zone"] == "Europe/Berlin"
|
|
|
|
def test_without_pkg_nothing_is_a_packages(self, root: Path):
|
|
_tool(root, "pkg", "#!/bin/sh\necho 'pkg is not installed' >&2\nexit 1\n")
|
|
jobs = _jobs(FreeBSDHost(root))
|
|
assert "package" not in {j["managed_by"] for j in jobs.values()}
|
|
|
|
def test_a_periodic_conf_that_stops_the_shell_raises(self, root: Path):
|
|
(root / "etc/periodic.conf").write_text("exit 1\n")
|
|
with pytest.raises(ValueError, match="periodic.conf could not be read"):
|
|
FreeBSDHost(root).get_scheduled_jobs()
|
|
|
|
def test_a_periodic_report_cut_short_raises(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
full = host.run_command
|
|
|
|
def cut(command, **kw): # type: ignore[no-untyped-def]
|
|
done = full(command, **kw)
|
|
return done._replace(stdout=done.stdout.split("PERIODIC_END")[0])
|
|
|
|
host.run_command = cut # type: ignore[method-assign]
|
|
with pytest.raises(ValueError, match="cut short"):
|
|
host.get_scheduled_jobs()
|
|
|
|
|
|
class TestFreeBSDPeriodicActions:
|
|
def _job(self, host: FreeBSDHost, path: str) -> dict:
|
|
return _jobs(host)[_periodic(host.root, path)]
|
|
|
|
def test_disable_and_enable_write_periodic_conf(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
result = host.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
assert result["success"], result
|
|
assert f"sysrc -f {root}/etc/periodic.conf daily_clean_disks_enable=NO" in host.log()
|
|
off = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
assert not off["enabled"]
|
|
host.manage_scheduled_job(job["key"], "enable", digest=off["digest"])
|
|
assert self._job(host, "/etc/periodic/daily/100.clean-disks")["enabled"]
|
|
|
|
def test_a_later_periodic_conf_that_wins_is_said(self, root: Path):
|
|
(root / "etc/periodic.conf.local").write_text("daily_clean_disks_enable=YES\n")
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
result = host.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
assert not result["success"]
|
|
assert "daily_clean_disks_enable" in result["output"] and "YES" in result["output"]
|
|
|
|
def test_a_failed_sysrc_says_so(self, root: Path):
|
|
_tool(root, "sysrc", "#!/bin/sh\necho 'sysrc: read-only file system' >&2\nexit 1\n")
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
result = host.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
assert result == {"success": False, "output": "sysrc: read-only file system"}
|
|
|
|
def test_a_script_that_fails_says_so(self, root: Path):
|
|
(root / "etc/periodic/daily/999.local").write_text("#!/bin/sh\nexit 3\n")
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/999.local")
|
|
result = host.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
assert result == {"success": False, "output": "exit 3"}
|
|
|
|
def test_a_cron_job_on_freebsd_is_still_crons(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = next(j for j in _jobs(host).values() if j["command"] == "newsyslog")
|
|
result = host.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
assert result["success"]
|
|
assert (
|
|
"#napalm-disabled: 0\t*\t*\t*\t*\troot\tnewsyslog" in (root / "etc/crontab").read_text()
|
|
)
|
|
|
|
def test_run_runs_the_script_as_periodic_does(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
result = host.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
assert result == {"success": True, "output": "100.clean-disks ran (PERIODIC=daily)"}
|
|
assert host.commands[-1].startswith("timeout 300 env PERIODIC=daily ")
|
|
|
|
def test_security_runs_as_the_daily_run_spawns_it(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/security/100.chksetuid")
|
|
result = host.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
assert result["output"] == "100.chksetuid ran (PERIODIC=security daily)"
|
|
|
|
def test_a_script_without_a_knob_is_not_switched(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/999.local")
|
|
with pytest.raises(ScheduledJobRefused):
|
|
host.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
|
|
|
def test_a_change_it_did_not_see_and_an_unknown_action(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
with pytest.raises(ScheduledJobChanged):
|
|
host.manage_scheduled_job(job["key"], "disable", digest="0" * 16)
|
|
with pytest.raises(ScheduledJobRefused):
|
|
host.manage_scheduled_job(job["key"], "explode", digest=job["digest"])
|
|
with pytest.raises(LookupError):
|
|
host.manage_scheduled_job("periodic:/nowhere", "run", digest="x")
|
|
|
|
def test_a_periodic_script_is_never_deleted(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._job(host, "/etc/periodic/daily/100.clean-disks")
|
|
with pytest.raises(ScheduledJobRefused):
|
|
host.delete_scheduled_job(job["key"], digest=job["digest"])
|
|
|
|
|
|
class TestFreeBSDCron:
|
|
def _cron(self, host: _Host, path: str) -> dict:
|
|
return next(
|
|
j
|
|
for j in _jobs(host).values()
|
|
if j["source"] == path and j["kind"] == "cron" # type: ignore[arg-type]
|
|
)
|
|
|
|
def test_a_cron_d_line_switched_through_bsd_stat_and_install(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
path = root / "usr/local/etc/cron.d/certbot"
|
|
job = self._cron(host, str(path))
|
|
mode = os.stat(path).st_mode & 0o777
|
|
assert host.manage_scheduled_job(job["key"], "disable", digest=job["digest"])["success"]
|
|
assert path.read_text() == "#napalm-disabled: 0 */12 * * * root certbot -q renew\n"
|
|
assert f"stat -f %Lp %Su %Sg -- {path}" in host.log()
|
|
assert f"install -m {mode:o} -o " in host.log()
|
|
assert os.stat(path).st_mode & 0o777 == mode
|
|
|
|
def test_another_users_line_runs_through_su_as_cron_would(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
job = self._cron(host, str(root / "var/cron/tabs/www"))
|
|
result = host.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
assert result["success"], result
|
|
# HOME is the user's, from the password file; USER and LOGNAME are the user.
|
|
home = subprocess.run(
|
|
["awk", "-F:", '$1 == "www" { print $6 }', "/etc/passwd"],
|
|
capture_output=True,
|
|
text=True,
|
|
).stdout.strip()
|
|
assert (root / "ran").read_text() == f"{home or '/'} www\n"
|
|
assert "su -m www -c /bin/sh" in host.log()
|
|
assert host.commands[-1].startswith("timeout 300 sh -c ")
|
|
|
|
def test_an_applications_job_is_a_file_in_etc_cron_d(self, root: Path):
|
|
host = FreeBSDHost(root)
|
|
spec = {
|
|
"name": "tidy",
|
|
"schedule": "*/30 1-2 * * *",
|
|
"run_as": "root",
|
|
"command": "find /tmp -mtime +7 -delete",
|
|
"enabled": True,
|
|
"description": "tidy tmp",
|
|
}
|
|
host.put_scheduled_job(spec) # type: ignore[arg-type]
|
|
assert (root / "etc/cron.d/tidy").read_text() == (
|
|
"# napalm-scheduled-job: tidy tidy tmp\n*/30 1-2 * * * root find /tmp -mtime +7 -delete\n"
|
|
)
|
|
job = _jobs(host)["job:tidy"]
|
|
assert job["managed_by"] == "application"
|
|
host.delete_scheduled_job("job:tidy", digest=job["digest"])
|
|
assert not (root / "etc/cron.d/tidy").exists()
|
|
|
|
|
|
class TestOpenBSD:
|
|
@pytest.fixture
|
|
def host(self, root: Path) -> OpenBSDHost:
|
|
# root's crontab as OpenBSD 7.9 ships it, and a line with cron's flags.
|
|
tab = _recorded("openbsd-vm", "crontab_l.txt")
|
|
flagged = f"~\t*\t*\t*\t*\t-ns echo flagged > {root / 'ran'}\n"
|
|
(root / "var/cron/tabs/root").write_text(tab + flagged)
|
|
return OpenBSDHost(root)
|
|
|
|
def test_the_maintenance_scripts_are_roots_crontab_lines_once(self, host: OpenBSDHost):
|
|
jobs = list(_jobs(host).values())
|
|
assert {j["kind"] for j in jobs} == {"cron"}
|
|
daily = [j for j in jobs if "/etc/daily" in j["command"]]
|
|
assert len(daily) == 1
|
|
assert (daily[0]["schedule"], daily[0]["run_as"]) == ("30 1 * * *", "root")
|
|
|
|
def test_the_base_systems_lines_are_the_platforms(self, host: OpenBSDHost):
|
|
managed = {j["command"]: j["managed_by"] for j in _jobs(host).values()}
|
|
for command in ("/usr/bin/newsyslog", "/bin/sh /etc/daily", "/bin/sh /etc/monthly"):
|
|
assert managed[command] == "platform"
|
|
assert managed[f"-ns echo flagged > {host.root}/ran"] == "admin"
|
|
assert managed[f'echo "$HOME $USER" > {host.root}/ran'] == "admin"
|
|
|
|
def test_a_line_with_cron_flags_runs_without_them(self, host: OpenBSDHost):
|
|
job = next(j for j in _jobs(host).values() if "flagged" in j["command"])
|
|
assert job["schedule"] == "~ * * * *"
|
|
result = host.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
|
assert result["success"], result
|
|
assert (host.root / "ran").read_text() == "flagged\n"
|
|
|
|
def test_no_periodic_and_the_time_zone_from_localtime(self, host: OpenBSDHost):
|
|
assert OpenBSDDriver.TIME_ZONE_SH == "readlink /etc/localtime 2>/dev/null"
|
|
host.get_scheduled_jobs()
|
|
assert "PERIODIC_" not in host.commands[0]
|
|
|
|
def test_an_applications_job_is_marked_lines_in_the_users_crontab(self, host: OpenBSDHost):
|
|
spec = {
|
|
"name": "tidy",
|
|
"schedule": "0 4 * * *",
|
|
"run_as": "nobody",
|
|
"command": "true",
|
|
"enabled": False,
|
|
}
|
|
host.put_scheduled_job(spec) # type: ignore[arg-type]
|
|
assert (host.root / "var/cron/tabs/nobody").read_text() == (
|
|
"# napalm-scheduled-job: tidy\n#napalm-disabled: 0 4 * * * true\n"
|
|
)
|
|
assert "crontab -u nobody /" in host.log()
|
|
|
|
|
|
class TestSu:
|
|
def test_root_runs_its_script_directly(self):
|
|
assert FreeBSDDriver("h", "u", "")._sj_as("root", "true") == ["sh", "-c", "true"]
|
|
|
|
def test_su_has_no_shell_option_so_the_script_goes_to_sh_on_stdin(self):
|
|
argv = FreeBSDDriver("h", "u", "")._sj_as("www", "echo hi")
|
|
assert argv[:2] == ["sh", "-c"]
|
|
assert argv[3:] == ["sh", "www", "echo hi"]
|
|
assert "su -m " in argv[2] and "-s" not in argv[2].split()
|
|
|
|
|
|
class TestPeriodicParse:
|
|
def test_the_knob_of_a_script(self):
|
|
knob = periodic_module.knob_of
|
|
assert knob(
|
|
"daily", "/etc/periodic/daily/100.clean-disks", ["daily_clean_disks_enable"]
|
|
) == (
|
|
"daily_clean_disks_enable",
|
|
False,
|
|
)
|
|
assert knob("security", "/x/100.chksetuid", ["security_status_chksetuid_enable"]) == (
|
|
"security_status_chksetuid_enable",
|
|
False,
|
|
)
|
|
assert knob("daily", "/x/411.pkg-backup", ["daily_backup_pkgdb_enable:-YES"]) == (
|
|
"daily_backup_pkgdb_enable",
|
|
True,
|
|
)
|
|
# Two knobs, neither the script's name: which one switches it is not known.
|
|
assert knob("daily", "/x/500.y", ["daily_a_enable", "daily_b_enable"]) == (None, False)
|
|
assert knob("daily", "/x/999.local", []) == (None, False)
|