ciscopktrewind 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """ciscopktrewind: snapshots and verified rollback for Cisco IOS configs."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,94 @@
1
+ """Restore a device to a snapshot, safely, and prove it.
2
+
3
+ The order is the safety story:
4
+ 1. read the device; refuse if it isn't the snapshot's device (model + serial);
5
+ 2. store the current state first, so the restore itself can be undone;
6
+ 3. plan; an imported snapshot (pasted, loaded from a file) needs explicit confirmation;
7
+ 4. re-read right before typing and refuse if the device changed since the plan;
8
+ 5. type the plan (never `end`), then read back and verify.
9
+ Nothing here reports success without step 5 saying so.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Literal
16
+
17
+ from .model import RestorePlan, Snapshot
18
+ from .normalize import state_digest
19
+ from .plan import plan, to_commands
20
+ from .store import SnapshotStore, device_key, new_snapshot
21
+ from .transports import CommandResult, DeviceState, Transport, TransportError
22
+ from .verify import VerificationResult, verify
23
+
24
+ Outcome = Literal["verified", "planned", "nothing-to-do", "refused", "failed"]
25
+
26
+
27
+ class RestoreRefused(Exception):
28
+ """A safety rule stopped the restore before anything was typed."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class RestoreResult:
33
+ outcome: Outcome
34
+ plan: RestorePlan | None
35
+ applied: tuple[CommandResult, ...]
36
+ verification: VerificationResult | None
37
+ safety_snapshot_id: str | None
38
+ detail: str = ""
39
+
40
+ @property
41
+ def rejected(self) -> tuple[CommandResult, ...]:
42
+ return tuple(r for r in self.applied if r.status != 0)
43
+
44
+
45
+ def restore(
46
+ transport: Transport,
47
+ target: Snapshot,
48
+ store: SnapshotStore,
49
+ *,
50
+ dry_run: bool = False,
51
+ confirm_imported: bool = False,
52
+ source: str = "ciscopktrewind",
53
+ ) -> RestoreResult:
54
+ state = transport.read_state()
55
+ if device_key(state.identity) != device_key(target.identity):
56
+ raise RestoreRefused(
57
+ f"snapshot is for {target.identity.model} {target.identity.serial}, "
58
+ f"device is {state.identity.model} {state.identity.serial}"
59
+ )
60
+
61
+ before = _snapshot_of(state, f"{source}: before restore")
62
+
63
+ # VLANs are planned only when both sides have a table. A snapshot without one
64
+ # (a pasted config) means "unknown", never "delete every VLAN".
65
+ use_vlans = state.vlans is not None and bool(target.vlans)
66
+ p = plan(state.config_text, target.config_text,
67
+ state.vlans if use_vlans else None, target.vlans if use_vlans else None)
68
+ if not p.steps:
69
+ v = verify(state.config_text, state.vlans, target)
70
+ return RestoreResult("nothing-to-do" if v.verified else "failed", p, (), v, None, v.detail)
71
+ if dry_run: # a preview, allowed for any snapshot; types and saves nothing
72
+ return RestoreResult("planned", p, (), None, None, f"{len(p.steps)} step(s) planned")
73
+ if target.origin == "imported" and not confirm_imported:
74
+ raise RestoreRefused("this snapshot was imported, not read from the device; "
75
+ "review the plan and confirm to restore it")
76
+
77
+ now = transport.read_state()
78
+ if state_digest(now.config_text, now.vlans or ()) != state_digest(state.config_text, state.vlans or ()):
79
+ raise RestoreRefused("the device changed since the plan was made; run the restore again")
80
+ store.save(before) # so the restore itself can be undone
81
+ applied = tuple(transport.apply(to_commands(p)))
82
+ try:
83
+ after = transport.read_state()
84
+ rejected = sum(1 for r in applied if r.status != 0)
85
+ v = verify(after.config_text, after.vlans, target, rejected=rejected)
86
+ store.save(_snapshot_of(after, f"{source}: after restore"))
87
+ except TransportError as exc:
88
+ v = verify(None, None, target)
89
+ return RestoreResult("failed", p, applied, v, before.id, f"could not read the device back: {exc}")
90
+ return RestoreResult("verified" if v.verified else "failed", p, applied, v, before.id, v.detail)
91
+
92
+
93
+ def _snapshot_of(state: DeviceState, source: str) -> Snapshot:
94
+ return new_snapshot(state.config_text, state.vlans or (), state.identity, source=source)