diff --git a/infra/chr/test_templates.py b/infra/chr/test_templates.py index a9f9efb..167936f 100644 --- a/infra/chr/test_templates.py +++ b/infra/chr/test_templates.py @@ -20,15 +20,15 @@ SAMPLES = { TemplateId.QUEUE_LIMIT: ( {"target": "10.0.0.42", "upload_mbps": 5, "download_mbps": 10}, - ["+/queue simple add", "name=netcortex-limit-10.0.0.42", "max-limit=5M/10M"], + ["+/queue simple add", "name=nc-test-limit-10.0.0.42", "max-limit=5M/10M"], ), TemplateId.FAILOVER_ROUTE: ( {"primary_gateway": "10.0.2.2", "backup_gateway": "192.0.2.1"}, - ["check-gateway=ping", "gateway=192.0.2.1", "netcortex:failover_route"], + ["check-gateway=ping", "gateway=192.0.2.1", "nc-test:failover_route"], ), TemplateId.PRIORITY_QUEUE: ( {"uplink": "ether1", "uplink_mbps": 90}, - ["new-packet-mark=netcortex-priority", "name=netcortex-uplink", "packet-mark=no-mark"], + ["new-packet-mark=nc-test-priority", "name=nc-test-uplink", "packet-mark=no-mark"], ), TemplateId.DNS_SERVERS: ( {"servers": ["1.1.1.1", "8.8.8.8"]}, diff --git a/packages/agent/scripts/reliability.py b/packages/agent/scripts/reliability.py new file mode 100644 index 0000000..557f152 --- /dev/null +++ b/packages/agent/scripts/reliability.py @@ -0,0 +1,99 @@ +"""How often does Gemma produce a valid report with the right template, on e2e-like inputs? + + uv run python packages/agent/scripts/reliability.py [--heavy 5 --down 3 --dns 3] + +Builds each incident the way the live run sees it, without the database: the stand-in +injector's rows for sim-tower (30 min normal, then the incident for ONSET), the stand-in +detector, and the agent with the worker's settings (thinking off, temperature 0.2). +Needs the model server (OLLAMA_BASE_URL). +""" + +import argparse +import asyncio +import random +from datetime import UTC, datetime, timedelta + +import pandas as pd +from netcortex_agent import stub_detector, stub_injector +from netcortex_agent.agent import run_investigation +from netcortex_core import ( + IFACE_COLUMNS, + PROBE_COLUMNS, + SUBSCRIBER_COLUMNS, + Cause, + MetricsWindow, +) + +ONSET = timedelta(seconds=90) # incidents opened 60-150 s after injection in the e2e runs +SITE = stub_injector.SIM_SITE + + +def frames(parts, as_of: datetime) -> MetricsWindow: + data = [ + pd.DataFrame([r.model_dump() for p in parts for r in p[i]], columns=list(columns)) + for i, columns in enumerate((PROBE_COLUMNS, IFACE_COLUMNS, SUBSCRIBER_COLUMNS)) + ] + return MetricsWindow( + as_of=as_of, probe_metrics=data[0], iface_metrics=data[1], subscriber_metrics=data[2] + ) + + +def incident(cause: Cause, seed: int): + rng = random.Random(seed) + now = datetime.now(UTC).replace(second=0, microsecond=0) + start = now - ONSET + window = frames( + [ + stub_injector._rows(now - timedelta(minutes=30), start, None, rng), + stub_injector._rows(start, now + timedelta(seconds=1), cause, rng), + ], + now, + ) + return window, stub_detector.detect(SITE.id, window, frames([], now - timedelta(minutes=30))) + + +def right_params(cause: Cause, params: dict) -> bool: + template, expected, _ = stub_injector.EXPECTED[cause] + if cause is Cause.DNS_SLOW: + return "192.0.2.53" not in params.get("servers", ["192.0.2.53"]) + return all(params.get(key) == value for key, value in expected.items()) + + +async def main(counts: dict[Cause, int]) -> None: + rows = [] + for cause, n in counts.items(): + for run in range(n): + window, detection = incident(cause, seed=run) + report, stats = await run_investigation(SITE.id, detection, window, site=SITE) + template = stub_injector.EXPECTED[cause][0] + ok = not stats.fell_back and report.template_id == template + ok_params = ok and right_params(cause, report.template_params) + rows.append((cause, ok, ok_params, stats)) + print( + f"{cause.value:12} run{run + 1} {stats.seconds:5.1f}s " + f"detector={detection.cause_guess.value:12} " + f"template={report.template_id.value:15} right={'Y' if ok else 'n'} " + f"params={'Y' if ok_params else 'n'} retries={stats.output_retries} " + f"fallback={stats.fell_back} {report.template_params}", + flush=True, + ) + for reason in stats.retry_reasons: + print(f" retry: {reason}") + n = len(rows) + print( + f"\n{sum(r[1] for r in rows)}/{n} valid with the right template, " + f"{sum(r[2] for r in rows)}/{n} also with the right params; " + f"{sum(r[3].fell_back for r in rows)}/{n} failed validation twice (fallback), " + f"{sum(r[3].output_retries > 0 for r in rows)}/{n} needed a retry" + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--heavy", type=int, default=5) + parser.add_argument("--down", type=int, default=3) + parser.add_argument("--dns", type=int, default=3) + args = parser.parse_args() + asyncio.run( + main({Cause.HEAVY_USER: args.heavy, Cause.UPLINK_DOWN: args.down, Cause.DNS_SLOW: args.dns}) + ) diff --git a/packages/fixes/src/netcortex_fixes/__init__.py b/packages/fixes/src/netcortex_fixes/__init__.py index 85852c8..821bdc2 100644 --- a/packages/fixes/src/netcortex_fixes/__init__.py +++ b/packages/fixes/src/netcortex_fixes/__init__.py @@ -1,6 +1,14 @@ """RouterOS fix templates: the only source of router commands.""" -from netcortex_fixes.checker import DryRun, apply, check_fix, dry_run, rollback +from netcortex_fixes.checker import ( + ApplyFailed, + DryRun, + apply, + check_fix, + dry_run, + failure_reason, + rollback, +) from netcortex_fixes.errors import ParamError from netcortex_fixes.router import RouterClient, RouterError from netcortex_fixes.templates import ( @@ -10,17 +18,20 @@ get_template, load_templates, render, + tag_for, templates_for, validate, ) __all__ = [ + "ApplyFailed", "DryRun", "RouterClient", "RouterError", "apply", "check_fix", "dry_run", + "failure_reason", "rollback", "NONE_TEMPLATE", "ParamError", @@ -29,6 +40,7 @@ "get_template", "load_templates", "render", + "tag_for", "templates_for", "validate", ] diff --git a/packages/fixes/src/netcortex_fixes/checker.py b/packages/fixes/src/netcortex_fixes/checker.py index c56a0e2..2b14de6 100644 --- a/packages/fixes/src/netcortex_fixes/checker.py +++ b/packages/fixes/src/netcortex_fixes/checker.py @@ -3,6 +3,10 @@ dry_run: export -> apply -> export and diff -> roll back -> export and compare with the original. A fix passes only if it applied cleanly, changed something, and rolled back to exactly the original config. + +Every object a fix creates is named after its incident (tag nc-1a2b3c4d), and rollbacks +target only those names. If an apply fails partway, only what it created is undone; config +that existed before is never removed or changed. """ import difflib @@ -14,7 +18,7 @@ from netcortex_core import FixPlan, Settings, TemplateId, db, get_settings from netcortex_fixes.router import RouterClient, RouterError -from netcortex_fixes.templates import get_template, render, validate +from netcortex_fixes.templates import TEST_TAG, get_template, render, tag_for, validate @dataclass @@ -24,7 +28,12 @@ class DryRun: commands: str rollback: str diff: list[str] # config lines the fix added (+) or removed (-) - log: str + log: str # ends with "Result: passed" or "Result: FAILED: " + reason: str = "" # why it failed; empty if it passed + + +class ApplyFailed(RouterError): + """A fix could not be applied. The message says what was (or wasn't) undone.""" def router_params(template_id: TemplateId, client: RouterClient) -> dict[str, Any]: @@ -47,23 +56,51 @@ def _diff(before: list[str], after: list[str]) -> list[str]: ] -def dry_run(template_id: TemplateId | str, params: dict[str, Any], client: RouterClient) -> DryRun: +def _apply(client: RouterClient, commands: str, rollback: str, tag: str) -> str: + """Run a fix's commands. On failure, undo only what they created, then raise ApplyFailed.""" + before = client.export() + if tag in commands and any(tag in line for line in before): + raise ApplyFailed(f"objects named {tag}-* already exist on the router; nothing changed") + try: + return client.run(commands) + except RouterError as exc: + reason = str(exc) + if not _diff(before, client.export()): + raise ApplyFailed(f"{reason}; nothing was applied, so nothing was rolled back") + try: # partly applied: the rollback targets only this fix's own (tagged) objects + client.run(rollback) + except RouterError as exc: + raise ApplyFailed(f"{reason}; undoing the partial change also failed: {exc}") from exc + leftover = _diff(before, client.export()) + if leftover: + raise ApplyFailed(f"{reason}; partial change NOT fully undone: {'; '.join(leftover)}") + raise ApplyFailed(f"{reason}; the partial change was rolled back") + + +def dry_run( + template_id: TemplateId | str, + params: dict[str, Any], + client: RouterClient, + tag: str = TEST_TAG, +) -> DryRun: template_id = TemplateId(template_id) if template_id is TemplateId.NONE: return DryRun(True, {}, "", "", [], "Template none: no router change to test.") params = validate(template_id, params | router_params(template_id, client)) - commands, rollback = render(template_id, params) + commands, rollback = render(template_id, params, tag) log = [f"Dry run of {template_id.value} on CHR at {datetime.now(UTC):%Y-%m-%d %H:%M:%S} UTC"] + def result(diff: list[str], reason: str) -> DryRun: + log.append(f"Result: FAILED: {reason}" if reason else "Result: passed") + return DryRun(not reason, params, commands, rollback, diff, "\n".join(log), reason) + before = client.export() try: - log.append(client.run(commands)) - applied = True - except RouterError as exc: + log.append(_apply(client, commands, rollback, tag)) + except ApplyFailed as exc: log.append(f"APPLY FAILED: {exc}") - applied = False - after = client.export() - diff = _diff(before, after) + return result([], f"apply failed: {exc}") + diff = _diff(before, client.export()) log.append("Config change:\n" + ("\n".join(diff) or "(none)")) try: @@ -77,13 +114,12 @@ def dry_run(template_id: TemplateId | str, params: dict[str, Any], client: Route log.append("NOT RESTORED, differences from the original:\n" + "\n".join(leftover)) checks = { - "applied cleanly": applied, "changed the config": bool(diff), "rolled back cleanly": rolled_back, - "config restored exactly": not leftover, + "restored the config exactly": not leftover, } log.append("; ".join(f"{name}: {'yes' if ok else 'NO'}" for name, ok in checks.items())) - return DryRun(all(checks.values()), params, commands, rollback, diff, "\n".join(log)) + return result(diff, ", ".join(f"not {name}" for name, ok in checks.items() if not ok)) def check_fix( @@ -95,8 +131,9 @@ def check_fix( ) -> FixPlan: """Dry-run a proposed fix on CHR and store the result in fix_plans.""" client = client or RouterClient.chr(settings) + tag = tag_for(incident_id) try: - result = dry_run(template_id, params, client) + result = dry_run(template_id, params, client, tag) plan = FixPlan( incident_id=incident_id, template_id=TemplateId(template_id), @@ -107,7 +144,7 @@ def check_fix( dry_run_log=result.log, ) except RouterError as exc: # CHR down: the plan is stored as not tested - commands, rollback = render(template_id, params) + commands, rollback = render(template_id, params, tag) plan = FixPlan( incident_id=incident_id, template_id=TemplateId(template_id), @@ -115,13 +152,19 @@ def check_fix( commands=commands, rollback=rollback, dry_run_ok=False, - dry_run_log=f"Dry run could not run: {exc}", + dry_run_log=f"Dry run could not run: {exc}\nResult: FAILED: CHR unreachable", ) with db.get_pool(settings).connection() as conn: db.insert_fix_plan(conn, plan) return plan +def failure_reason(plan: FixPlan) -> str: + """The reason line a failed dry run ends with, for status notes and events.""" + last = plan.dry_run_log.strip().splitlines()[-1] if plan.dry_run_log.strip() else "" + return last.removeprefix("Result: FAILED: ") if last.startswith("Result: FAILED") else "" + + def _target(settings: Settings | None) -> Settings: settings = settings or get_settings() if settings.apply_target != "chr": @@ -132,18 +175,21 @@ def _target(settings: Settings | None) -> Settings: def apply( plan: FixPlan, client: RouterClient | None = None, settings: Settings | None = None ) -> str: - """Apply an approved, dry-run-tested fix to the CHR test router.""" + """Apply an approved, dry-run-tested fix to the CHR test router. + + Raises ApplyFailed if it can't; only what this fix created is undone. + """ if plan.decision != "approved": raise RouterError("Refusing to apply a fix that has not been approved") if not plan.dry_run_ok: raise RouterError("Refusing to apply a fix that did not pass its dry run") client = client or RouterClient.chr(_target(settings)) - return client.run(plan.commands) + return _apply(client, plan.commands, plan.rollback, tag_for(plan.incident_id)) def rollback( plan: FixPlan, client: RouterClient | None = None, settings: Settings | None = None ) -> str: - """Undo an applied fix on the CHR test router.""" + """Undo an applied fix on the CHR test router (it removes only this incident's objects).""" client = client or RouterClient.chr(_target(settings)) return client.run(plan.rollback) diff --git a/packages/fixes/src/netcortex_fixes/templates.py b/packages/fixes/src/netcortex_fixes/templates.py index 0a66f14..a98bc09 100644 --- a/packages/fixes/src/netcortex_fixes/templates.py +++ b/packages/fixes/src/netcortex_fixes/templates.py @@ -10,6 +10,7 @@ from functools import cache from pathlib import Path from typing import Any, Literal +from uuid import UUID import yaml from jinja2 import StrictUndefined @@ -179,10 +180,26 @@ def validate( return clean -def render(template_id: TemplateId | str, params: dict[str, Any]) -> tuple[str, str]: - """(apply commands, rollback commands) for validated params.""" +TEST_TAG = "nc-test" # for checks outside an incident (unit tests, the CHR harness) + + +def tag_for(incident_id: UUID) -> str: + """The name prefix of every router object one incident's fix creates: nc-1a2b3c4d.""" + return f"nc-{str(incident_id)[:8]}" + + +def render( + template_id: TemplateId | str, params: dict[str, Any], tag: str = TEST_TAG +) -> tuple[str, str]: + """(apply commands, rollback commands) for validated params. + + Objects the fix creates are named after `tag`, and the rollback removes only those, so + fixes for different incidents never collide or remove each other's (or anyone's) config. + """ + if not re.fullmatch(r"nc-[0-9a-z]+", tag): + raise ParamError(f"bad tag {tag!r}") template = get_template(template_id) clean = validate(template.id, params) - apply = _jinja.from_string(template.apply).render(**clean).strip() - rollback = _jinja.from_string(template.rollback).render(**clean).strip() + apply = _jinja.from_string(template.apply).render(**clean, tag=tag).strip() + rollback = _jinja.from_string(template.rollback).render(**clean, tag=tag).strip() return apply, rollback diff --git a/packages/fixes/tests/test_fixes_checker.py b/packages/fixes/tests/test_fixes_checker.py index 359cd65..02e023e 100644 --- a/packages/fixes/tests/test_fixes_checker.py +++ b/packages/fixes/tests/test_fixes_checker.py @@ -1,16 +1,29 @@ +import re from uuid import uuid4 import httpx import pytest from netcortex_core import FixPlan, Settings, TemplateId -from netcortex_fixes import RouterClient, RouterError, apply, checker, dry_run +from netcortex_fixes import ( + ApplyFailed, + RouterClient, + RouterError, + apply, + checker, + dry_run, + failure_reason, + render, + tag_for, +) BASELINE = ["/ip dns set servers=192.0.2.53", "/queue simple add name=sub-10.0.0.42"] QUEUE = {"target": "10.0.0.42", "upload_mbps": 5, "download_mbps": 10} +PRIORITY = {"uplink": "ether1", "uplink_mbps": 160} class FakeRouter: - """Keeps config lines; `add` commands append, `remove [find name=...]` deletes.""" + """Keeps config lines like RouterOS: `add` rejects a taken name, `remove [find x="y"]` + deletes only lines containing y.""" def __init__(self, *, ignore_rollback=False, ignore_apply=False, fail_on=None): self.config = list(BASELINE) @@ -24,12 +37,16 @@ def __init__(self, *, ignore_rollback=False, ignore_apply=False, fail_on=None): def run(self, script): for line in script.splitlines(): self.ran.append(line) + name = re.search(r' name="?([^" ]+)', line) if self.fail_on and self.fail_on in line: raise RouterError(f"{line!r} failed: bad command name") if " add " in line and not self.ignore_apply: + if name and any(f"name={name[1]}" in c.replace('"', "") for c in self.config): + raise RouterError(f"{line!r} failed: already have such name") self.config.append(line) elif " remove " in line and not self.ignore_rollback: - self.config = [c for c in self.config if "netcortex" not in c] + target = re.search(r'\[find \w+="([^"]+)"\]', line)[1] + self.config = [c for c in self.config if target not in c] elif line.startswith("/ip dns set"): # replaced in place, like a real export self.config = [line if c.startswith("/ip dns set") else c for c in self.config] return "ok" @@ -43,13 +60,13 @@ def get(self, path): def test_dry_run_passes_when_the_fix_applies_and_rolls_back_exactly(): router = FakeRouter() - result = dry_run("queue_limit", QUEUE, router) - assert result.ok + result = dry_run("queue_limit", QUEUE, router, tag="nc-1a2b3c4d") + assert result.ok and result.reason == "" assert result.diff == [ - '+/queue simple add name="netcortex-limit-10.0.0.42" target=10.0.0.42 ' - 'max-limit=5M/10M comment="netcortex:queue_limit"' + '+/queue simple add name="nc-1a2b3c4d-limit-10.0.0.42" target=10.0.0.42 ' + 'max-limit=5M/10M comment="nc-1a2b3c4d:queue_limit"' ] - assert "config restored exactly: yes" in result.log + assert result.log.endswith("Result: passed") and router.config == BASELINE def test_dry_run_reads_router_params_for_rollback(): @@ -62,19 +79,55 @@ def test_dry_run_reads_router_params_for_rollback(): def test_dry_run_fails_when_rollback_leaves_changes(): result = dry_run("queue_limit", QUEUE, FakeRouter(ignore_rollback=True)) assert not result.ok - assert "NOT RESTORED" in result.log and "config restored exactly: NO" in result.log + assert "NOT RESTORED" in result.log + assert result.reason == "not restored the config exactly" def test_dry_run_fails_when_the_fix_changes_nothing(): result = dry_run("queue_limit", QUEUE, FakeRouter(ignore_apply=True)) - assert not result.ok and "changed the config: NO" in result.log + assert not result.ok and result.reason == "not changed the config" -def test_dry_run_fails_and_still_rolls_back_when_a_command_is_rejected(): +def test_a_rejected_first_command_changes_nothing_and_rolls_nothing_back(): router = FakeRouter(fail_on="/queue simple add") result = dry_run("queue_limit", QUEUE, router) - assert not result.ok and "APPLY FAILED" in result.log - assert any(" remove " in line for line in router.ran) # rollback still attempted + assert not result.ok and "nothing was applied" in result.reason + assert not any(" remove " in line for line in router.ran) + assert result.log.endswith(f"Result: FAILED: {result.reason}") + + +def test_an_existing_object_with_the_same_name_is_never_touched(): + router = FakeRouter() + theirs = '/queue simple add name="nc-1a2b3c4d-limit-10.0.0.42" target=10.0.0.42' + router.config.append(theirs) + result = dry_run("queue_limit", QUEUE, router, tag="nc-1a2b3c4d") + assert not result.ok and "already exist" in result.reason + assert router.config == [*BASELINE, theirs] + assert not any(" remove " in line for line in router.ran) + + +def test_a_partly_applied_fix_undoes_only_its_own_objects(): + router = FakeRouter(fail_on="/queue tree add") # the two mangle rules go in first + router.config.append('/ip firewall mangle add comment="netcortex:priority_queue"') + before = list(router.config) + result = dry_run("priority_queue", PRIORITY, router, tag="nc-1a2b3c4d") + assert not result.ok and "the partial change was rolled back" in result.reason + assert router.config == before # including the older, untagged netcortex rule + + +def test_fixes_for_two_incidents_do_not_collide(): + router = FakeRouter() + first, second = uuid4(), uuid4() + applied = plan(incident_id=first, commands=render("queue_limit", QUEUE, tag_for(first))[0]) + apply(applied, router, Settings(_env_file=None)) + result = dry_run("queue_limit", QUEUE, router, tag=tag_for(second)) + assert result.ok and applied.commands in router.config # the first fix stays in place + + +def test_a_failed_apply_says_why(): + router = FakeRouter(fail_on="/queue simple add") + with pytest.raises(ApplyFailed, match="bad command name; nothing was applied"): + apply(plan(), router, Settings(_env_file=None)) def test_template_none_needs_no_router(): @@ -85,7 +138,7 @@ def test_template_none_needs_no_router(): def plan(**changes) -> FixPlan: values = dict( incident_id=uuid4(), template_id=TemplateId.QUEUE_LIMIT, params=QUEUE, - commands="/queue simple add name=x", rollback="/queue simple remove [find name=x]", + commands='/queue simple add name="x"', rollback='/queue simple remove [find name="x"]', dry_run_ok=True, decision="approved", ) # fmt: skip return FixPlan(**(values | changes)) @@ -122,7 +175,13 @@ def connection(self): result = checker.check_fix(incident_id, "queue_limit", QUEUE, FakeRouter()) assert stored == [result] assert result.incident_id == incident_id and result.dry_run_ok - assert "netcortex-limit-10.0.0.42" in result.commands and result.rollback + assert f"{tag_for(incident_id)}-limit-10.0.0.42" in result.commands and result.rollback + assert failure_reason(result) == "" + + +def test_failure_reason_comes_from_the_dry_run_log(): + failed = plan(dry_run_ok=False, dry_run_log="...\nResult: FAILED: not changed the config") + assert failure_reason(failed) == "not changed the config" def client_with(handler) -> RouterClient: diff --git a/packages/fixes/tests/test_fixes_chr_live.py b/packages/fixes/tests/test_fixes_chr_live.py index c588cae..cc5d758 100644 --- a/packages/fixes/tests/test_fixes_chr_live.py +++ b/packages/fixes/tests/test_fixes_chr_live.py @@ -39,7 +39,7 @@ def test_approved_fix_applies_and_rolls_back_on_chr(chr_router): ) try: apply(plan, chr_router) - assert any("netcortex-limit-10.0.0.42" in line for line in chr_router.export()) + assert any("nc-test-limit-10.0.0.42" in line for line in chr_router.export()) finally: rollback(plan, chr_router) assert chr_router.export() == before diff --git a/packages/fixes/tests/test_fixes_templates.py b/packages/fixes/tests/test_fixes_templates.py index afca581..21627c5 100644 --- a/packages/fixes/tests/test_fixes_templates.py +++ b/packages/fixes/tests/test_fixes_templates.py @@ -1,6 +1,8 @@ +from uuid import UUID + import pytest from netcortex_core import Cause, TemplateId -from netcortex_fixes import ParamError, load_templates, render, templates_for, validate +from netcortex_fixes import ParamError, load_templates, render, tag_for, templates_for, validate VALID = { "queue_limit": {"target": "10.0.0.42", "upload_mbps": 2, "download_mbps": 10}, @@ -44,7 +46,17 @@ def test_valid_params_render_apply_and_rollback(template_id): def test_rendered_commands_contain_only_validated_values(): apply, rollback = render("queue_limit", {**VALID["queue_limit"], "target": "10.0.0.40/29"}) assert "target=10.0.0.40/29 max-limit=2M/10M" in apply - assert 'name="netcortex-limit-10.0.0.40_29"' in rollback + assert 'name="nc-test-limit-10.0.0.40_29"' in rollback + + +def test_object_names_carry_the_incident_tag(): + incident_id = UUID("1a2b3c4d-0000-4000-8000-000000000000") + assert tag_for(incident_id) == "nc-1a2b3c4d" + for template_id in VALID: + apply, rollback = render(template_id, VALID[template_id], tag_for(incident_id)) + assert "netcortex" not in apply + rollback + with pytest.raises(ParamError, match="bad tag"): + render("queue_limit", VALID["queue_limit"], tag='x"; /system reset') def test_defaults_are_filled_in(): diff --git a/services/worker/src/netcortex_worker/activities.py b/services/worker/src/netcortex_worker/activities.py index 119b78e..d557550 100644 --- a/services/worker/src/netcortex_worker/activities.py +++ b/services/worker/src/netcortex_worker/activities.py @@ -197,6 +197,7 @@ def _check_fix(incident_id: UUID, site_id: str, template_id: TemplateId, params: site_id, fix_plan_id=str(plan.id), dry_run_ok=plan.dry_run_ok, + reason=fixes.failure_reason(plan), ) return plan diff --git a/services/worker/src/netcortex_worker/workflows.py b/services/worker/src/netcortex_worker/workflows.py index f8375b3..69fbb3a 100644 --- a/services/worker/src/netcortex_worker/workflows.py +++ b/services/worker/src/netcortex_worker/workflows.py @@ -16,6 +16,7 @@ from temporalio.workflow import ParentClosePolicy with workflow.unsafe.imports_passed_through(): + import netcortex_fixes as fixes from netcortex_agent import facts from netcortex_agent.agent import Deps, fallback_report, with_news from netcortex_core import DetectionResult, FixPlan, IncidentReport, IncidentStatus, TemplateId @@ -169,7 +170,10 @@ async def run(self, inp: IncidentInput) -> str: except ActivityError as exc: workflow.logger.warning("dry run could not run: %s", exc) if plan is None or not plan.dry_run_ok: - await self._status(inp, IncidentStatus.REJECTED, "fix did not pass its CHR dry run") + reason = fixes.failure_reason(plan) if plan else "it could not run" + await self._status( + inp, IncidentStatus.REJECTED, f"fix did not pass its CHR dry run: {reason}" + ) return self.status.value # 3. Wait for the owner. @@ -205,8 +209,8 @@ async def run(self, inp: IncidentInput) -> str: start_to_close_timeout=timedelta(seconds=120), retry_policy=RetryPolicy(maximum_attempts=1), ) - except ActivityError as exc: - await self._rollback(inp, approved, f"apply failed: {exc.cause or exc}") + except ActivityError as exc: # apply() already undid whatever part of it went in + await self._status(inp, IncidentStatus.ROLLED_BACK, f"apply failed: {exc.cause or exc}") return self.status.value await self._status( inp, IncidentStatus.VERIFYING, f"watching for {inp.timing.verify_wait_s:.0f} s" diff --git a/templates/routeros/failover_route.yaml b/templates/routeros/failover_route.yaml index 88f8612..61acb82 100644 --- a/templates/routeros/failover_route.yaml +++ b/templates/routeros/failover_route.yaml @@ -20,9 +20,9 @@ params: # route had no check-gateway before. apply: | /ip route set [find dst-address="0.0.0.0/0" gateway="{{ primary_gateway }}"] check-gateway=ping - /ip route add dst-address=0.0.0.0/0 gateway={{ backup_gateway }} distance={{ backup_distance }} check-gateway=ping comment="netcortex:failover_route" + /ip route add dst-address=0.0.0.0/0 gateway={{ backup_gateway }} distance={{ backup_distance }} check-gateway=ping comment="{{ tag }}:failover_route" rollback: | - /ip route remove [find comment="netcortex:failover_route"] + /ip route remove [find comment="{{ tag }}:failover_route"] /ip route unset [find dst-address="0.0.0.0/0" gateway="{{ primary_gateway }}"] check-gateway verify: metric: loss_pct diff --git a/templates/routeros/priority_queue.yaml b/templates/routeros/priority_queue.yaml index ccd5d1b..883cce6 100644 --- a/templates/routeros/priority_queue.yaml +++ b/templates/routeros/priority_queue.yaml @@ -20,15 +20,15 @@ params: # Shapes upload on the uplink interface. Packets are marked in prerouting, so marks apply # to traffic from the LAN towards the uplink. apply: | - /ip firewall mangle add chain=prerouting protocol=udp dst-port=53 action=mark-packet new-packet-mark=netcortex-priority passthrough=no comment="netcortex:priority_queue" - /ip firewall mangle add chain=prerouting protocol=udp dst-port={{ game_ports }} action=mark-packet new-packet-mark=netcortex-priority passthrough=no comment="netcortex:priority_queue" - /queue tree add name=netcortex-uplink parent={{ uplink }} max-limit={{ uplink_mbps }}M comment="netcortex:priority_queue" - /queue tree add name=netcortex-priority parent=netcortex-uplink packet-mark=netcortex-priority priority=1 comment="netcortex:priority_queue" - /queue tree add name=netcortex-bulk parent=netcortex-uplink packet-mark=no-mark priority=8 comment="netcortex:priority_queue" + /ip firewall mangle add chain=prerouting protocol=udp dst-port=53 action=mark-packet new-packet-mark={{ tag }}-priority passthrough=no comment="{{ tag }}:priority_queue" + /ip firewall mangle add chain=prerouting protocol=udp dst-port={{ game_ports }} action=mark-packet new-packet-mark={{ tag }}-priority passthrough=no comment="{{ tag }}:priority_queue" + /queue tree add name={{ tag }}-uplink parent={{ uplink }} max-limit={{ uplink_mbps }}M comment="{{ tag }}:priority_queue" + /queue tree add name={{ tag }}-priority parent={{ tag }}-uplink packet-mark={{ tag }}-priority priority=1 comment="{{ tag }}:priority_queue" + /queue tree add name={{ tag }}-bulk parent={{ tag }}-uplink packet-mark=no-mark priority=8 comment="{{ tag }}:priority_queue" rollback: | - /queue tree remove [find parent="netcortex-uplink"] - /queue tree remove [find name="netcortex-uplink"] - /ip firewall mangle remove [find comment="netcortex:priority_queue"] + /queue tree remove [find parent="{{ tag }}-uplink"] + /queue tree remove [find name="{{ tag }}-uplink"] + /ip firewall mangle remove [find comment="{{ tag }}:priority_queue"] verify: metric: rtt_ms goal: decrease diff --git a/templates/routeros/queue_limit.yaml b/templates/routeros/queue_limit.yaml index 40a0cbe..2d71c65 100644 --- a/templates/routeros/queue_limit.yaml +++ b/templates/routeros/queue_limit.yaml @@ -19,9 +19,9 @@ params: # A new simple queue is added at the end of the list. On routers that already have one # queue per subscriber, it must be moved above that subscriber's queue to take effect. apply: | - /queue simple add name="netcortex-limit-{{ target | replace('/', '_') }}" target={{ target }} max-limit={{ upload_mbps }}M/{{ download_mbps }}M comment="netcortex:queue_limit" + /queue simple add name="{{ tag }}-limit-{{ target | replace('/', '_') }}" target={{ target }} max-limit={{ upload_mbps }}M/{{ download_mbps }}M comment="{{ tag }}:queue_limit" rollback: | - /queue simple remove [find name="netcortex-limit-{{ target | replace('/', '_') }}"] + /queue simple remove [find name="{{ tag }}-limit-{{ target | replace('/', '_') }}"] # The cap must be at most 50% of the subscriber's current rate in its busier direction. checks: [cap_below_current_rate] verify: