feat(scheduled-jobs): scheduled jobs through PosixScheduledJobsMixin (#67)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 13s
driver / test (3.12) (pull_request) Failing after 51s
driver / types (pull_request) Failing after 59s
driver / test (3.13) (pull_request) Failing after 47s
driver / lowest (pull_request) Failing after 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Failing after 1m14s
CI / driver (pull_request) Failing after 2m29s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 13s
driver / test (3.12) (pull_request) Failing after 51s
driver / types (pull_request) Failing after 59s
driver / test (3.13) (pull_request) Failing after 47s
driver / lowest (pull_request) Failing after 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Failing after 1m14s
CI / driver (pull_request) Failing after 2m29s
driver / publish (pull_request) Skipped
get_scheduled_jobs reads /etc/crontab, /etc/cron.d, the user crontabs, run-parts, anacron and every systemd timer 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. get_cron_jobs goes: it read without root, missed most of what a host schedules, and nothing called it. Requires napalm-device-types 4.26.0. Closes #67
This commit is contained in:
1 parent
cb0e308a78
commit
ca32b89686
7 files changed
+77
-110
No files matched your search
@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Scheduled jobs (NetOrk/netork#1933, #67), through napalm-device-types' `PosixScheduledJobsMixin`:
|
||||
`get_scheduled_jobs()` reads `/etc/crontab`, `/etc/cron.d`, the user crontabs (Debian,
|
||||
RHEL, Alpine), the run-parts directories, `/etc/anacrontab` and every systemd timer in one
|
||||
round trip as root; `manage_scheduled_job()` enables, disables or runs one now;
|
||||
`put_scheduled_job()` and `delete_scheduled_job()` write and remove an application's own.
|
||||
OpenMediaVault and QNAP QTS inherit it and decide per verb in their own packages.
|
||||
- netOrk's own account with a fixed uid (NetOrk/netork#1817): `_account_create_with_uid`
|
||||
makes it with `useradd -m -u <uid>`. Below `UID_MIN` useradd warns and goes on, as a
|
||||
system's account.
|
||||
@@ -122,6 +128,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
calls its default route `default` as well. An IPv6 host route is now a `/128`
|
||||
instead of a `/32`.
|
||||
|
||||
### Removed
|
||||
- `get_cron_jobs()`: it read without root, missed other users' crontabs, `/etc/crontab`,
|
||||
run-parts, anacron and every systemd timer, and nothing called it. `get_scheduled_jobs()`
|
||||
replaces it.
|
||||
|
||||
## [0.15.1] - 2026-10-23
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -62,7 +62,7 @@ with Driver(
|
||||
services = dev.get_services()
|
||||
users = dev.get_os_users()
|
||||
procs = dev.get_processes()
|
||||
jobs = dev.get_cron_jobs()
|
||||
jobs = dev.get_scheduled_jobs()["jobs"]
|
||||
|
||||
# Upgrade specific packages
|
||||
result = dev.apply_updates(["openssh-server", "curl"])
|
||||
@@ -108,7 +108,9 @@ with Driver(
|
||||
| `manage_service(name, action)` | ✅ | systemd: start, stop, restart, enable, disable |
|
||||
| `get_os_users()` | ✅ | `/etc/passwd` + `/etc/group` |
|
||||
| `get_processes()` | ✅ | `ps axo` |
|
||||
| `get_cron_jobs()` | ✅ | user crontabs + `/etc/cron.d/` |
|
||||
| `get_scheduled_jobs()` | ✅ | `/etc/crontab`, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers (napalm-device-types' `PosixScheduledJobsMixin`) |
|
||||
| `manage_scheduled_job(key, action, digest=)` | ✅ | enable, disable, run now |
|
||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | ✅ | an application's own job: a systemd timer, else `/etc/cron.d`, else the user's crontab |
|
||||
|
||||
## Package manager auto-detection
|
||||
|
||||
|
||||
+2
-72
@@ -42,6 +42,7 @@ from napalm_device_types import (
|
||||
LldpNeighborDict,
|
||||
OpenSshServerMixin,
|
||||
OSDriver,
|
||||
PosixScheduledJobsMixin,
|
||||
ServiceClustersMixin,
|
||||
ServicePackagesMixin,
|
||||
SnmpAgentMixin,
|
||||
@@ -60,7 +61,6 @@ from napalm_device_types import (
|
||||
)
|
||||
from napalm_device_types.models import (
|
||||
ApplyUpdatesResultDict,
|
||||
CronJobDict,
|
||||
FixResultDict,
|
||||
FixStepOutcomeDict,
|
||||
PackageDict,
|
||||
@@ -310,6 +310,7 @@ class LinuxDriver(
|
||||
SystemIdentityMixin,
|
||||
OpenSshServerMixin,
|
||||
SystemdServicesMixin,
|
||||
PosixScheduledJobsMixin,
|
||||
HostStatusMixin,
|
||||
ContainerEngineMixin,
|
||||
HostnameMixin,
|
||||
@@ -1754,77 +1755,6 @@ class LinuxDriver(
|
||||
)
|
||||
return processes
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# OSDriver – cron jobs
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_cron_jobs(self) -> list[CronJobDict]:
|
||||
"""Return cron entries from user crontabs and /etc/cron.d."""
|
||||
jobs: list[CronJobDict] = []
|
||||
|
||||
# /etc/cron.d/* — system-wide cron fragments (include user field)
|
||||
cron_d_files = self._send("ls /etc/cron.d/ 2>/dev/null").splitlines()
|
||||
for fname in cron_d_files:
|
||||
fname = fname.strip()
|
||||
if not fname:
|
||||
continue
|
||||
content = self._send(f"cat /etc/cron.d/{fname} 2>/dev/null")
|
||||
for line in content.splitlines():
|
||||
job = self._parse_cron_line(line, source_user="root", has_user_field=True)
|
||||
if job:
|
||||
jobs.append(job)
|
||||
|
||||
# Per-user crontabs from /var/spool/cron/crontabs (Debian) or /var/spool/cron (RHEL)
|
||||
for spool_dir in ("/var/spool/cron/crontabs", "/var/spool/cron"):
|
||||
ls_out = self._send(f"ls {spool_dir} 2>/dev/null")
|
||||
for uname in ls_out.splitlines():
|
||||
uname = uname.strip()
|
||||
if not uname:
|
||||
continue
|
||||
content = self._send(f"cat {spool_dir}/{uname} 2>/dev/null")
|
||||
for line in content.splitlines():
|
||||
job = self._parse_cron_line(line, source_user=uname, has_user_field=False)
|
||||
if job:
|
||||
jobs.append(job)
|
||||
|
||||
return jobs
|
||||
|
||||
@staticmethod
|
||||
def _parse_cron_line(line: str, source_user: str, has_user_field: bool) -> CronJobDict | None:
|
||||
"""Parse a single crontab line; returns ``None`` for comments/blanks."""
|
||||
stripped = line.strip()
|
||||
# Remove trailing comment
|
||||
comment = ""
|
||||
if "#" in stripped:
|
||||
idx = stripped.index("#")
|
||||
comment = stripped[idx + 1 :].strip()
|
||||
stripped = stripped[:idx].strip()
|
||||
|
||||
if not stripped or stripped.startswith("@") or stripped.startswith("MAILTO"):
|
||||
return None
|
||||
|
||||
parts = stripped.split(None, 6 if has_user_field else 5)
|
||||
expected = 6 if has_user_field else 5
|
||||
if len(parts) < expected:
|
||||
return None
|
||||
|
||||
schedule = " ".join(parts[:5])
|
||||
if has_user_field:
|
||||
user = parts[5]
|
||||
command = parts[6] if len(parts) > 6 else ""
|
||||
else:
|
||||
user = source_user
|
||||
command = parts[5] if len(parts) > 5 else ""
|
||||
|
||||
job: CronJobDict = {
|
||||
"user": user,
|
||||
"schedule": schedule,
|
||||
"command": command,
|
||||
}
|
||||
if comment:
|
||||
job["description"] = comment
|
||||
return job
|
||||
|
||||
# ── Device actions ────────────────────────────────────────────────────────
|
||||
|
||||
def get_snmp_config(self) -> SNMPConfigDict | None:
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ classifiers = [
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=4.24.0",
|
||||
"napalm-device-types>=4.26.0",
|
||||
"netmiko>=4.0.0",
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
]
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"coverage_floor": 57.0,
|
||||
"function_complexity": {
|
||||
"napalm_linux/linux.py::LinuxDriver._collect_platform_info": 24,
|
||||
"napalm_linux/linux.py::LinuxDriver._parse_cron_line": 12,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_networks": 13,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_route_to": 13,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_snmp_config": 13,
|
||||
@@ -21,7 +20,7 @@
|
||||
"napalm_linux.linux"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_linux/linux.py": 2118
|
||||
"napalm_linux/linux.py": 2048
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -114,39 +114,6 @@ def _mock_send(driver_fixture, output: str):
|
||||
driver_fixture._device.send_command.return_value = output
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _parse_cron_line
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestParseCronLine:
|
||||
def test_regular_user_cron(self):
|
||||
line = "0 4 * * * /usr/local/bin/backup.sh # nightly backup"
|
||||
job = LinuxDriver._parse_cron_line(line, source_user="root", has_user_field=False)
|
||||
assert job is not None
|
||||
assert job["user"] == "root"
|
||||
assert job["schedule"] == "0 4 * * *"
|
||||
assert job["command"] == "/usr/local/bin/backup.sh"
|
||||
assert job.get("description") == "nightly backup"
|
||||
|
||||
def test_cron_d_with_user_field(self):
|
||||
line = "*/5 * * * * www-data /usr/bin/php /var/www/cron.php"
|
||||
job = LinuxDriver._parse_cron_line(line, source_user="root", has_user_field=True)
|
||||
assert job is not None
|
||||
assert job["user"] == "www-data"
|
||||
assert job["schedule"] == "*/5 * * * *"
|
||||
assert "/usr/bin/php" in job["command"]
|
||||
|
||||
def test_comment_line_returns_none(self):
|
||||
assert LinuxDriver._parse_cron_line("# this is a comment", "root", False) is None
|
||||
|
||||
def test_blank_line_returns_none(self):
|
||||
assert LinuxDriver._parse_cron_line(" ", "root", False) is None
|
||||
|
||||
def test_mailto_returns_none(self):
|
||||
assert LinuxDriver._parse_cron_line("MAILTO=root", "root", False) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_interfaces (parsing)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Scheduled jobs on a Linux host: napalm-device-types' POSIX implementation (#67).
|
||||
|
||||
The report, its parse and every write are ``PosixScheduledJobsMixin``'s; the
|
||||
driver carries the command across ``run_command``, as root, in one round trip.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from napalm_device_types import CommandResult, PosixScheduledJobsMixin
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
REPORT = """SJ_BEGIN
|
||||
[system /etc/cron.d/certbot]
|
||||
|0 */12 * * * root certbot -q renew
|
||||
[tz]
|
||||
/usr/share/zoneinfo/Europe/Berlin
|
||||
[owners]
|
||||
certbot: /etc/cron.d/certbot
|
||||
SJ_END
|
||||
"""
|
||||
|
||||
|
||||
def _driver() -> LinuxDriver:
|
||||
driver = LinuxDriver("host", "user", "pw")
|
||||
driver.run_command = MagicMock(return_value=CommandResult(REPORT, "", 0)) # type: ignore[method-assign]
|
||||
return driver
|
||||
|
||||
|
||||
def test_a_linux_host_offers_every_verb():
|
||||
assert issubclass(LinuxDriver, PosixScheduledJobsMixin)
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
):
|
||||
assert callable(getattr(LinuxDriver, verb))
|
||||
|
||||
|
||||
def test_the_jobs_are_read_as_root_in_one_round_trip():
|
||||
driver = _driver()
|
||||
reading = driver.get_scheduled_jobs()
|
||||
assert reading["time_zone"] == "Europe/Berlin"
|
||||
(job,) = reading["jobs"]
|
||||
assert (job["run_as"], job["managed_by"], job["command"]) == (
|
||||
"root",
|
||||
"package",
|
||||
"certbot -q renew",
|
||||
)
|
||||
driver.run_command.assert_called_once()
|
||||
assert driver.run_command.call_args.kwargs["privileged"] is True
|
||||
|
||||
|
||||
def test_the_old_cron_reader_is_gone():
|
||||
assert not hasattr(LinuxDriver, "get_cron_jobs")
|
||||
Reference in new issue
Block a user