Compare commits

..
2 Commits
Author SHA1 Message Date
patrickandClaude Sonnet 5.5 83d5e58ea5 Document Livepatch alerts
CI / tests (Python 3.10) (pull_request) Successful in 27s
CI / tests (Python 3.11) (pull_request) Successful in 26s
CI / tests (Python 3.12) (pull_request) Successful in 26s
CI / tests (Python 3.13) (pull_request) Successful in 27s
CI / lint (pull_request) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:18:40 -04:00
patrickandClaude Sonnet 5.5 650806bfce Alert when Livepatch is broken or has stopped reporting
The alert check now also notifies, once per problem, when a host's Livepatch has
been unhealthy for livepatch_alert_after_hours (default 6), or when a host that
used to report Livepatch no longer does (a dead daemon leaves the agent with
nothing to send). A livepatch_alerts table records which hosts have reported
Livepatch, when the current problem began and whether it was notified, so hosts
without Livepatch never alert and restarts do not repeat messages. Stale hosts
are skipped.

livepatch_problem() is now the single test for unhealthy, shared with the cover
rule for pending reboots, and names the check state when that is the problem.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:18:39 -04:00
10 changed files with 364 additions and 7 deletions

No files matched your search

+12
View File
@@ -58,6 +58,18 @@ fresh report. Run `sudo kernelwatch check-alerts` to check immediately, or inspe
Upgrading starts the clock at the first check, so expect the first Upgrading starts the clock at the first check, so expect the first
notifications a day after you re-run `install.sh`. notifications a day after you re-run `install.sh`.
- **Livepatch alerts.** On Ubuntu hosts using
[Livepatch](how-it-works.md), a host whose live patching has been broken for
`livepatch_alert_after_hours` (default 6) gets one high-priority notification:
an unhealthy state (not `applied` or `nothing-to-apply`), a failed check, or an
unsupported kernel. It also fires when a host that *used to* report Livepatch
stops, which is what a dead Livepatch daemon looks like, since the agent then has
nothing to send. Hosts that have never reported Livepatch never alert. As with the
other alerts it's once per problem; getting healthy again re-arms it, and a brief
blip that clears within the period sends nothing. Stale hosts are skipped. A host
where you turn Livepatch off on purpose sends one message and then stays quiet.
`livepatch_alert_after_hours = 0` turns these off.
Use the topic's direct publish URL, with token authentication if needed; it must Use the topic's direct publish URL, with token authentication if needed; it must
accept the POST without a browser login or redirect. The topic and token stay accept the POST without a browser login or redirect. The topic and token stay
in the server config (root-owned, readable by the `kernelwatch` service group). in the server config (root-owned, readable by the `kernelwatch` service group).
+2 -1
View File
@@ -49,7 +49,8 @@ How the agent works it out:
date, so cover ends 14 days before it and the host goes to `reboot` as usual. date, so cover ends 14 days before it and the host goes to `reboot` as usual.
Any other reboot reason (libc, systemd) still counts. If Livepatch is failing, Any other reboot reason (libc, systemd) still counts. If Livepatch is failing,
unsupported or in a state we don't know, the host gets no cover and the reason unsupported or in a state we don't know, the host gets no cover and the reason
is noted. Hosts without Livepatch are unaffected. `canonical-livepatch` needs is noted, and after `livepatch_alert_after_hours` you get an
[ntfy alert](alerts.md). Hosts without Livepatch are unaffected. `canonical-livepatch` needs
root and a snap cgroup, so like needrestart it runs in its own unit, root and a snap cgroup, so like needrestart it runs in its own unit,
`kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch` `kernelwatch-livepatch.service`, which writes `/run/kernelwatch/livepatch`
before each report. It's skipped when the snap isn't installed. before each report. It's skipped when the snap isn't installed.
+54 -1
View File
@@ -13,7 +13,7 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener
from . import db from . import db
from .config import Config from .config import Config
from .status import LEVELS, evaluate from .status import LEVELS, evaluate, livepatch_problem
class DeliveryError(Exception): class DeliveryError(Exception):
@@ -99,6 +99,8 @@ def check(cfg: Config) -> int:
failures = _check_hosts(cfg, conn) failures = _check_hosts(cfg, conn)
if cfg.status_alert_after_hours > 0: if cfg.status_alert_after_hours > 0:
failures += _check_status(cfg, conn) failures += _check_status(cfg, conn)
if cfg.livepatch_alert_after_hours > 0:
failures += _check_livepatch(cfg, conn)
return failures return failures
finally: finally:
conn.close() conn.close()
@@ -183,6 +185,57 @@ def _check_status(cfg: Config, conn: sqlite3.Connection) -> int:
return failures return failures
def _check_livepatch(cfg: Config, conn: sqlite3.Connection) -> int:
"""Notify once per episode when Livepatch has been broken for the grace period.
Two cases: Livepatch reports an unhealthy state, or a host that used to report
Livepatch no longer does (its daemon died, or `canonical-livepatch status` fails,
so the agent has nothing to send). A host is only "used to" once it has reported
Livepatch, so hosts without it never alert. Getting healthy again forgets the
problem, so a later one alerts again. Stale hosts are skipped: their data can't
be trusted and the stale alert covers them."""
saved = db.livepatch_alerts(conn)
grace = cfg.livepatch_alert_after_hours * 3600
failures = 0
for h in db.latest_reports(conn):
name, report, now = h["host"], h["report"], time.time()
if evaluate(h["received_at"], report, now, cfg).level == "stale":
continue
state = report.get("livepatch_state")
if state is None and name not in saved:
continue
problem = (livepatch_problem(report) if state is not None
else "livepatch status is no longer being reported")
since, notified = saved.get(name, (None, False))
if problem is None:
current = (None, False)
else:
since = int(now) if since is None else since
current = (since, notified)
if not notified and now - since >= grace:
title = f"kernelwatch: {name} Livepatch problem"
if state is None:
detail = ("It reported Livepatch before and no longer does, so the Livepatch "
"daemon may have stopped or been disabled.")
else:
detail = (f"State: {state}, check: {report.get('livepatch_check_state') or '?'}, "
f"supported: {report.get('livepatch_supported') or '?'}.")
message = (f"{name}: {problem} since {_utc(since)}.\n{detail}\n"
"The running kernel may be missing live patches. On the host, check "
"`canonical-livepatch status` and `systemctl status kernelwatch-livepatch`.")
try:
publish(cfg, title, message, stale=True, tag="shield")
except DeliveryError as exc:
print(f"kernelwatch: notification failed for {name}: {exc}", file=sys.stderr)
failures += 1
else:
current = (since, True)
print(f"kernelwatch: livepatch notification sent for {name}")
if saved.get(name) != current:
db.save_livepatch_alert(conn, name, *current)
return failures
def notify_backup_failure(cfg: Config) -> int: def notify_backup_failure(cfg: Config) -> int:
"""Tell the ntfy topic the nightly backup failed. Returns 1 if that couldn't be sent. """Tell the ntfy topic the nightly backup failed. Returns 1 if that couldn't be sent.
+5
View File
@@ -57,6 +57,9 @@ class Config:
backup_heartbeat_url: str = "" backup_heartbeat_url: str = ""
# Notify when a host has needed a reboot or updates for this long; 0 disables. # Notify when a host has needed a reboot or updates for this long; 0 disables.
status_alert_after_hours: float = 24.0 status_alert_after_hours: float = 24.0
# Notify when Livepatch has been unhealthy, or a host that used to report it has
# stopped, for this long; 0 disables.
livepatch_alert_after_hours: float = 6.0
def load(path: str | None = None) -> Config: def load(path: str | None = None) -> Config:
@@ -108,6 +111,8 @@ def load(path: str | None = None) -> Config:
valid = False valid = False
if not valid: if not valid:
raise SystemExit(f"{path}: {key} must be an HTTP(S) URL without spaces or a fragment") raise SystemExit(f"{path}: {key} must be an HTTP(S) URL without spaces or a fragment")
if not math.isfinite(cfg.livepatch_alert_after_hours) or cfg.livepatch_alert_after_hours < 0:
raise SystemExit(f"{path}: livepatch_alert_after_hours must be zero or positive and finite")
if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token): if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token):
raise SystemExit(f"{path}: ntfy settings must not contain control characters") raise SystemExit(f"{path}: ntfy settings must not contain control characters")
if cfg.ntfy_url: if cfg.ntfy_url:
+26
View File
@@ -42,6 +42,11 @@ CREATE TABLE IF NOT EXISTS status_alerts (
since INTEGER NOT NULL, since INTEGER NOT NULL,
notified_level TEXT notified_level TEXT
); );
CREATE TABLE IF NOT EXISTS livepatch_alerts (
host TEXT PRIMARY KEY REFERENCES hosts(name) ON DELETE CASCADE,
since INTEGER,
notified INTEGER NOT NULL DEFAULT 0
);
""" """
@@ -271,6 +276,27 @@ def clear_status_alert(conn: sqlite3.Connection, host: str) -> None:
conn.execute("DELETE FROM status_alerts WHERE host = ?", (host,)) conn.execute("DELETE FROM status_alerts WHERE host = ?", (host,))
# --- livepatch notifications -------------------------------------------------
def livepatch_alerts(conn: sqlite3.Connection) -> dict[str, tuple[int | None, bool]]:
"""host -> (when its current Livepatch problem began or None, whether it was
notified). A host appears once it has reported Livepatch at all, which is how
"stopped reporting it" is told apart from "never had it"."""
return {r["host"]: (r["since"], bool(r["notified"]))
for r in conn.execute("SELECT * FROM livepatch_alerts")}
def save_livepatch_alert(conn: sqlite3.Connection, host: str, since: int | None,
notified: bool) -> None:
# The host may have been removed while a notification was in flight.
conn.execute(
"INSERT INTO livepatch_alerts (host, since, notified) "
"SELECT name, ?, ? FROM hosts WHERE name = ? "
"ON CONFLICT(host) DO UPDATE SET since = excluded.since, notified = excluded.notified",
(since, int(notified), host),
)
# --- users & sessions ------------------------------------------------------- # --- users & sessions -------------------------------------------------------
def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None: def set_user(conn: sqlite3.Connection, name: str, pw_hash: str) -> None:
+21 -5
View File
@@ -105,6 +105,24 @@ def kernel_reboot_pending(report: dict[str, Any]) -> str | None:
return None return None
def livepatch_problem(report: dict[str, Any]) -> str | None:
"""Why Livepatch isn't working on this host, or None if it is (or isn't in use).
"Working" means a state we recognise as healthy, a completed check and a
supported kernel. The same test decides cover for a pending reboot and whether
to send a Livepatch alert."""
state = report.get("livepatch_state")
if state is None:
return None
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
or report.get("livepatch_supported") != "supported"):
parts = [state, report.get("livepatch_supported") or "?"]
if report.get("livepatch_check_state") != "checked":
parts.append(f"check: {report.get('livepatch_check_state') or '?'}")
return f"livepatch not healthy ({', '.join(parts)})"
return None
def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]: def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | None]:
"""(is the running kernel kept patched by Livepatch, a note about it). """(is the running kernel kept patched by Livepatch, a note about it).
@@ -112,16 +130,14 @@ def livepatch_cover(report: dict[str, Any], now: float) -> tuple[bool, str | Non
support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts support ends, so cover lapses LIVEPATCH_MARGIN_DAYS before that date. Hosts
without Livepatch data, or with Livepatch in any state we don't recognise as without Livepatch data, or with Livepatch in any state we don't recognise as
healthy, get no cover and are judged as before.""" healthy, get no cover and are judged as before."""
state = report.get("livepatch_state") if report.get("livepatch_state") is None:
if state is None:
return False, None return False, None
if problem := livepatch_problem(report):
return False, problem
try: try:
deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "") deadline = date.fromisoformat(report.get("livepatch_upgrade_required") or "")
except ValueError: except ValueError:
deadline = None deadline = None
if (state not in LIVEPATCH_HEALTHY_STATES or report.get("livepatch_check_state") != "checked"
or report.get("livepatch_supported") != "supported"):
return False, f"livepatch not healthy ({state}, {report.get('livepatch_supported') or '?'})"
if deadline is None: if deadline is None:
return False, "livepatch end of support date unknown" return False, "livepatch end of support date unknown"
left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days left = (deadline - datetime.fromtimestamp(now, timezone.utc).date()).days
+4
View File
@@ -51,6 +51,10 @@ ntfy_timeout_seconds = 10.0
# 0 disables. Needs ntfy_url. # 0 disables. Needs ntfy_url.
status_alert_after_hours = 24.0 status_alert_after_hours = 24.0
# Also notify (once per problem) when Ubuntu Livepatch has been unhealthy, or a host
# that used to report it has stopped, for this long. 0 disables. Needs ntfy_url.
livepatch_alert_after_hours = 6.0
# Dead-man's switch: an external monitor (e.g. healthchecks.io) that alerts when the # Dead-man's switch: an external monitor (e.g. healthchecks.io) that alerts when the
# pings STOP, which is how you learn kernelwatch itself isn't running. Treat these # pings STOP, which is how you learn kernelwatch itself isn't running. Treat these
# URLs like passwords. Empty disables. # URLs like passwords. Empty disables.
+210
View File
@@ -391,6 +391,216 @@ class BackupFailureAlertTest(unittest.TestCase):
self.assertEqual(self.publish.call_count, 1) self.assertEqual(self.publish.call_count, 1)
class LivepatchAlertsTest(unittest.TestCase):
"""Notify when Livepatch is unhealthy, or stops being reported, for too long."""
HEALTHY = {"livepatch_state": "applied", "livepatch_check_state": "checked",
"livepatch_supported": "supported", "livepatch_upgrade_required": "2099-01-01",
"livepatch_fix_count": 2}
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.cfg = temp_config(self.tmp.name, ntfy_url="https://ntfy.example.test/fleet",
status_alert_after_hours=0, livepatch_alert_after_hours=6.0)
db.init(self.cfg.db_path)
self.conn = db.connect(self.cfg.db_path)
self.addCleanup(self.conn.close)
self.now = NOW
clock = mock.patch("kernelwatch.alerts.time.time", side_effect=lambda: self.now)
clock.start()
self.addCleanup(clock.stop)
publisher = mock.patch("kernelwatch.alerts.publish")
self.publish = publisher.start()
self.addCleanup(publisher.stop)
stack = contextlib.ExitStack()
self.addCleanup(stack.close)
stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
self.errors = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
db.add_host(self.conn, "web01", auth.token_hash(auth.new_token()))
def report(self, host="web01", livepatch=True, **fields):
payload = {"kernel_running": "6.8.0-136-generic", "apt_lists_age_seconds": 60}
if livepatch:
payload.update(self.HEALTHY)
payload.update(fields)
self.conn.execute("INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
(host, self.now, json.dumps(payload)))
def hours(self, n):
self.now += int(n * 3600)
def run_check(self):
self.assertEqual(alerts.check(self.cfg), 0)
def titles(self):
return [c.args[1] for c in self.publish.call_args_list]
def test_unhealthy_state_alerts_once_after_the_grace_period(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(5)
self.report(livepatch_state="apply-failed")
self.run_check()
self.publish.assert_not_called()
self.hours(1.1)
self.report(livepatch_state="apply-failed")
self.run_check()
self.assertEqual(self.titles(), ["kernelwatch: web01 Livepatch problem"])
(_, _, message), kwargs = self.publish.call_args
self.assertIn("livepatch not healthy (apply-failed, supported)", message)
self.assertIn("State: apply-failed, check: checked, supported: supported.", message)
self.assertIn("canonical-livepatch status", message)
self.assertTrue(kwargs["stale"]) # high priority
for _ in range(5): # never repeated while the same episode lasts
self.hours(1)
self.report(livepatch_state="apply-failed")
self.run_check()
self.assertEqual(self.publish.call_count, 1)
def test_each_kind_of_unhealthy_counts(self):
for fields in ({"livepatch_state": "applying"}, {"livepatch_check_state": "check-failed"},
{"livepatch_supported": "unsupported"}, {"livepatch_state": "kernel-upgrade-required"}):
with self.subTest(fields=fields):
self.publish.reset_mock()
db.remove_host(self.conn, "web01")
db.add_host(self.conn, "web01", auth.token_hash(auth.new_token()))
self.report(**fields)
self.run_check()
self.hours(7)
self.report(**fields)
self.run_check()
self.assertEqual(self.publish.call_count, 1)
def test_healthy_states_never_alert(self):
for state in ("applied", "nothing-to-apply"):
self.report(livepatch_state=state)
self.run_check()
self.hours(48)
self.report(livepatch_state=state)
self.run_check()
self.publish.assert_not_called()
def test_a_brief_problem_that_clears_never_alerts_and_resets_the_clock(self):
self.report(livepatch_check_state="check-failed")
self.run_check()
self.hours(5)
self.report()
self.run_check()
self.assertEqual(db.livepatch_alerts(self.conn)["web01"], (None, False))
self.hours(5) # a new problem starts a fresh grace period, not the old one
self.report(livepatch_check_state="check-failed")
self.run_check()
self.hours(5)
self.report(livepatch_check_state="check-failed")
self.run_check()
self.publish.assert_not_called()
def test_a_later_problem_alerts_again(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(7)
self.report(livepatch_state="apply-failed")
self.run_check()
self.report()
self.run_check()
self.hours(1)
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(7)
self.report(livepatch_state="apply-failed")
self.run_check()
self.assertEqual(self.publish.call_count, 2)
def test_a_host_that_stops_reporting_livepatch_alerts(self):
self.report() # healthy: now known to use Livepatch
self.run_check()
self.assertIn("web01", db.livepatch_alerts(self.conn))
self.hours(1)
self.report(livepatch=False) # the daemon died; the agent has nothing to send
self.run_check()
self.hours(5)
self.report(livepatch=False)
self.run_check()
self.publish.assert_not_called()
self.hours(1.1)
self.report(livepatch=False)
self.run_check()
self.assertEqual(self.publish.call_count, 1)
message = self.publish.call_args.args[2]
self.assertIn("no longer being reported", message)
self.assertIn("It reported Livepatch before and no longer does", message)
def test_a_blip_of_missing_data_between_good_reports_is_forgiven(self):
self.report()
self.run_check()
self.hours(1)
self.report(livepatch=False) # e.g. snapd was restarting for one report
self.run_check()
self.hours(1)
self.report()
self.run_check()
self.hours(8)
self.report()
self.run_check()
self.publish.assert_not_called()
def test_hosts_that_never_had_livepatch_never_alert(self):
for _ in range(4):
self.report(livepatch=False)
self.run_check()
self.hours(24)
self.publish.assert_not_called()
self.assertEqual(db.livepatch_alerts(self.conn), {})
def test_stale_hosts_are_skipped(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(20) # no reports since: stale, so only the stale alert speaks
self.run_check()
self.assertEqual(self.titles(), ["kernelwatch: web01 is stale"])
def test_failed_delivery_is_retried_until_it_succeeds(self):
self.report(livepatch_state="apply-failed")
self.run_check()
self.hours(7)
self.report(livepatch_state="apply-failed")
self.publish.side_effect = alerts.DeliveryError("ntfy returned HTTP 503")
self.assertEqual(alerts.check(self.cfg), 1)
self.assertEqual(db.livepatch_alerts(self.conn)["web01"][1], False)
self.assertIn("notification failed for web01", self.errors.getvalue())
self.publish.side_effect = None
self.run_check()
self.assertEqual(db.livepatch_alerts(self.conn)["web01"][1], True)
self.run_check()
self.assertEqual(self.publish.call_count, 2) # the failed try and the one that landed
def test_zero_disables_it(self):
cfg = dataclasses.replace(self.cfg, livepatch_alert_after_hours=0)
self.report(livepatch_state="apply-failed")
self.assertEqual(alerts.check(cfg), 0)
self.hours(100)
self.report(livepatch_state="apply-failed")
self.assertEqual(alerts.check(cfg), 0)
self.publish.assert_not_called()
self.assertEqual(db.livepatch_alerts(self.conn), {})
def test_removing_a_host_forgets_it(self):
self.report()
self.run_check()
db.remove_host(self.conn, "web01")
self.assertEqual(db.livepatch_alerts(self.conn), {})
def test_state_is_only_written_when_it_changes(self):
self.report()
self.run_check()
with mock.patch("kernelwatch.alerts.db.save_livepatch_alert") as save:
self.hours(1)
self.report()
self.run_check()
save.assert_not_called()
class NtfyHTTPTest(unittest.TestCase): class NtfyHTTPTest(unittest.TestCase):
def setUp(self): def setUp(self):
class Sink(BaseHTTPRequestHandler): class Sink(BaseHTTPRequestHandler):
+9
View File
@@ -75,6 +75,15 @@ class ConfigTest(unittest.TestCase):
with self.subTest(bad=bad), self.assertRaises(SystemExit): with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"report_min_interval_seconds = {bad}\n")) config.load(self.write(tmp, f"report_min_interval_seconds = {bad}\n"))
def test_livepatch_alert_hours_validated(self):
with tempdir() as tmp:
self.assertEqual(config.Config().livepatch_alert_after_hours, 6.0)
self.assertEqual(config.load(self.write(tmp, "livepatch_alert_after_hours = 0\n"))
.livepatch_alert_after_hours, 0)
for bad in ("-1", "inf", "nan", '"6"'):
with self.subTest(bad=bad), self.assertRaises(SystemExit):
config.load(self.write(tmp, f"livepatch_alert_after_hours = {bad}\n"))
def test_status_alert_hours_validated(self): def test_status_alert_hours_validated(self):
with tempdir() as tmp: with tempdir() as tmp:
self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n")) self.assertEqual(config.load(self.write(tmp, "status_alert_after_hours = 0\n"))
+21
View File
@@ -37,6 +37,27 @@ def livepatched(days_left=300, **kw):
return report(**fields) return report(**fields)
class LivepatchProblemTest(unittest.TestCase):
def test_none_when_healthy_or_not_in_use(self):
from kernelwatch.status import livepatch_problem
self.assertIsNone(livepatch_problem(report()))
self.assertIsNone(livepatch_problem(livepatched()))
self.assertIsNone(livepatch_problem(livepatched(livepatch_state="nothing-to-apply")))
def test_describes_each_unhealthy_case(self):
from kernelwatch.status import livepatch_problem
self.assertEqual(livepatch_problem(livepatched(livepatch_state="apply-failed")),
"livepatch not healthy (apply-failed, supported)")
self.assertEqual(livepatch_problem(livepatched(livepatch_check_state="check-failed")),
"livepatch not healthy (applied, supported, check: check-failed)")
self.assertEqual(livepatch_problem(livepatched(livepatch_check_state=None)),
"livepatch not healthy (applied, supported, check: ?)")
self.assertEqual(livepatch_problem(livepatched(livepatch_supported="unsupported")),
"livepatch not healthy (applied, unsupported)")
self.assertEqual(livepatch_problem(livepatched(livepatch_supported=None)),
"livepatch not healthy (applied, ?)")
class LivepatchTest(unittest.TestCase): class LivepatchTest(unittest.TestCase):
def evaluate(self, rep): def evaluate(self, rep):
return evaluate(NOW - 60, rep, NOW, CFG) return evaluate(NOW - 60, rep, NOW, CFG)