holddown 0.18.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.
- holddown/__init__.py +0 -0
- holddown/adapters/__init__.py +115 -0
- holddown/adapters/ios.py +212 -0
- holddown/adapters/iosxe.py +265 -0
- holddown/adapters/iosxr.py +101 -0
- holddown/adapters/junos.py +196 -0
- holddown/adapters/junos_netconf.py +153 -0
- holddown/adapters/srlinux.py +164 -0
- holddown/cli.py +361 -0
- holddown/inventory/__init__.py +110 -0
- holddown/inventory/nautobot.py +72 -0
- holddown/inventory/netbox.py +56 -0
- holddown/notify.py +133 -0
- holddown/policy.py +473 -0
- holddown/proxy.py +530 -0
- holddown/servers/__init__.py +8 -0
- holddown/servers/ios.py +233 -0
- holddown/servers/srlinux.py +155 -0
- holddown/signing.py +72 -0
- holddown/state.py +339 -0
- holddown-0.18.0.dist-info/METADATA +591 -0
- holddown-0.18.0.dist-info/RECORD +25 -0
- holddown-0.18.0.dist-info/WHEEL +4 -0
- holddown-0.18.0.dist-info/entry_points.txt +4 -0
- holddown-0.18.0.dist-info/licenses/LICENSE +21 -0
holddown/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Adapters: everything Holddown has to know about one upstream MCP server.
|
|
2
|
+
|
|
3
|
+
The rules in holddown.policy are the same for every vendor. An adapter supplies what differs:
|
|
4
|
+
the names of the upstream's arguments, how its replies read, how a device diff is classified,
|
|
5
|
+
and the defaults `holddown init` writes. The policy picks one with `upstream.adapter`.
|
|
6
|
+
"""
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from importlib import import_module
|
|
11
|
+
|
|
12
|
+
NAMES = ("junos", "srlinux", "ios", "iosxe", "iosxr", "junos_netconf")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Adapter:
|
|
17
|
+
name: str
|
|
18
|
+
# Argument names of the upstream's tools.
|
|
19
|
+
router: str
|
|
20
|
+
routers: str | None # a list of routers, where a tool takes one
|
|
21
|
+
command: str
|
|
22
|
+
config: str
|
|
23
|
+
format: str | None # config format argument, if the upstream has one
|
|
24
|
+
dry_run: str
|
|
25
|
+
timer: str # rollback timer of a confirmed commit
|
|
26
|
+
timer_seconds: int # seconds in one unit of `timer`
|
|
27
|
+
timer_example: int
|
|
28
|
+
# How the text of a successful reply starts, and how a failed one does.
|
|
29
|
+
dry_run_ok: str
|
|
30
|
+
commit_ok: str
|
|
31
|
+
confirm_ok: str
|
|
32
|
+
failure_prefixes: tuple
|
|
33
|
+
# The device diff inside a dry-run reply, and the findings in that diff. findings() takes
|
|
34
|
+
# the diff and, optionally, the names of the router's management interfaces as an
|
|
35
|
+
# inventory gives them; without them the adapter falls back on its own idea of which
|
|
36
|
+
# interface that is.
|
|
37
|
+
diff_of: Callable[[str], str]
|
|
38
|
+
findings: Callable[..., tuple]
|
|
39
|
+
# Commands: text that is never allowed, and what to tell the agent on a refusal.
|
|
40
|
+
command_banned: tuple
|
|
41
|
+
command_refusal: str
|
|
42
|
+
example_check: str
|
|
43
|
+
# Why this config text cannot be judged by its diff alone ("" when it can).
|
|
44
|
+
config_problem: Callable[[str], str]
|
|
45
|
+
# Defaults for `holddown init`.
|
|
46
|
+
tools: dict
|
|
47
|
+
allow_prefixes: tuple
|
|
48
|
+
upstream: tuple
|
|
49
|
+
upstream_hint: str
|
|
50
|
+
# The argument that takes a commit comment, where the upstream has one. Holddown adds
|
|
51
|
+
# its own tag there, so the router's commit log points back to the audit log.
|
|
52
|
+
comment: str | None = None
|
|
53
|
+
# The words that may follow a | in a command, written in full. None: the upstream's
|
|
54
|
+
# commands have no pipe that this adapter lets through (see command_banned). A dict
|
|
55
|
+
# gives, for each of those words, the options (words starting with a dash) it may take.
|
|
56
|
+
pipes: tuple | dict | None = None
|
|
57
|
+
# The change list inside the reply to a commit, or None when the reply has none. The
|
|
58
|
+
# proxy compares it with the diff of the dry run.
|
|
59
|
+
committed_diff: Callable[[str], str | None] = lambda text: (
|
|
60
|
+
text.split("Changes:", 1)[1].strip() if "Changes:" in text else None)
|
|
61
|
+
# True where the dry run's diff is worked out by the upstream and not by the router, so
|
|
62
|
+
# the two lists can differ line by line for one and the same change. They are then
|
|
63
|
+
# compared by their findings.
|
|
64
|
+
predicted_diff: bool = False
|
|
65
|
+
# Seconds after a timer ran out before the router is asked whether it rolled back.
|
|
66
|
+
rollback_grace: int = 30
|
|
67
|
+
# How a dry-run reply starts when the upstream found nothing to change, where that is
|
|
68
|
+
# not a reply of the dry_run_ok kind with an empty diff.
|
|
69
|
+
no_change: tuple = ()
|
|
70
|
+
# The BGP sessions of a router, read by the proxy before a commit and before a confirm.
|
|
71
|
+
# bgp_command is the show command, bgp_states turns its output into {neighbour: True
|
|
72
|
+
# when Established} (None when it cannot be read), and bgp_expect turns a diff into
|
|
73
|
+
# what the change does to each neighbour it touches (see expectations()) and whether
|
|
74
|
+
# it takes down sessions it does not name. No command: no such check.
|
|
75
|
+
bgp_command: str = ""
|
|
76
|
+
bgp_states: Callable[[str], dict | None] | None = None
|
|
77
|
+
bgp_expect: Callable[[str], tuple] | None = None
|
|
78
|
+
# Keywords that make a show command write, clear or disturb something. Refused in full
|
|
79
|
+
# and cut short.
|
|
80
|
+
command_keywords: tuple = ()
|
|
81
|
+
# For a command tool that takes a list of routers: its reply as {router: that router's
|
|
82
|
+
# output, or None where the reply does not say}. Without it the reply is one answer
|
|
83
|
+
# for every router named.
|
|
84
|
+
batch_results: Callable[[str], dict] | None = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
ADDRESS = re.compile(r"^(?:\d{1,3}(?:\.\d{1,3}){3}|[0-9A-Fa-f]*:[0-9A-Fa-f:.]*)$")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def expectations(touches):
|
|
91
|
+
"""What a change means for each BGP neighbour it touches: "down", "up" or "any".
|
|
92
|
+
|
|
93
|
+
`touches` holds (neighbour, sign, kind) for every changed line under a neighbour: the
|
|
94
|
+
sign is + or -, and the kind is "self" (the neighbour as a whole, or what makes it one),
|
|
95
|
+
"shutdown", "any" (a line that says nothing about the session) or "other". A neighbour
|
|
96
|
+
that is removed or shut down is meant to go down. Any other change to it, taking a
|
|
97
|
+
shutdown away included, is meant to leave it Established.
|
|
98
|
+
"""
|
|
99
|
+
seen = {}
|
|
100
|
+
for peer, sign, kind in touches:
|
|
101
|
+
seen.setdefault(peer, set()).add((sign, kind))
|
|
102
|
+
expect = {}
|
|
103
|
+
for peer, lines in seen.items():
|
|
104
|
+
gone = ("-", "self") in lines and ("+", "self") not in lines
|
|
105
|
+
if gone or ("+", "shutdown") in lines:
|
|
106
|
+
expect[peer] = "down"
|
|
107
|
+
else:
|
|
108
|
+
expect[peer] = "up" if any(kind != "any" for _, kind in lines) else "any"
|
|
109
|
+
return expect
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def get(name):
|
|
113
|
+
if name not in NAMES:
|
|
114
|
+
raise SystemExit(f"holddown: unknown adapter '{name}' (known: {', '.join(NAMES)})")
|
|
115
|
+
return import_module(f"{__name__}.{name}").ADAPTER
|
holddown/adapters/ios.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Cisco IOS and IOS XE over SSH, through the MCP server that comes with Holddown
|
|
2
|
+
(holddown/servers/ios.py)."""
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from . import ADDRESS, Adapter, expectations
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def kw(word, least):
|
|
9
|
+
"""A keyword as IOS accepts it: any abbreviation of at least `least` letters."""
|
|
10
|
+
rest = word[least:]
|
|
11
|
+
return word[:least] + "".join(f"(?:{c}" for c in rest) + ")?" * len(rest)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# The upstream's dry run prints one change per line, with the lines it sits under:
|
|
15
|
+
# + interface Ethernet0/1 / description to ios2
|
|
16
|
+
# - router bgp 65001 / neighbor 10.0.1.2 shutdown
|
|
17
|
+
# Patterns are matched against that text without the sign and without a leading `no` or
|
|
18
|
+
# `default` on any part. First match wins.
|
|
19
|
+
# The management interface, where no inventory names it: the lab's.
|
|
20
|
+
DEFAULT_MGMT = ("Ethernet0/0",)
|
|
21
|
+
# Words that turn a show command into something else, on IOS, IOS XE or IOS XR.
|
|
22
|
+
# 'show tech-support' writes an archive to the disk on IOS XR and runs for minutes anywhere;
|
|
23
|
+
# 'to-file' and 'extract-pcap' write what 'show logging process' found to a file; a
|
|
24
|
+
# trailing 'clear' resets the counters just shown ('show platform hardware qfp active
|
|
25
|
+
# statistics drop clear'); 'show memory debug leaks' runs the leak detector.
|
|
26
|
+
KEYWORDS = ("tech-support", "to-file", "extract-pcap", "clear", "leaks")
|
|
27
|
+
# Lockout is everything that decides who can reach and log in to the router: lines, users,
|
|
28
|
+
# AAA, keys, the management servers, every access list and where one is applied (the change
|
|
29
|
+
# list does not say which interface carries the management traffic), control-plane policing
|
|
30
|
+
# and its class and policy maps, VRFs (the management interface may sit in one), and what
|
|
31
|
+
# runs commands later or changes what a command means (event manager, kron, alias).
|
|
32
|
+
LOCKOUT = re.compile(
|
|
33
|
+
rf"^(?:{kw('line', 2)}|{kw('username', 2)}|{kw('aaa', 2)}|{kw('enable', 3)}"
|
|
34
|
+
rf"|{kw('login', 3)}|{kw('privilege', 2)}|{kw('tacacs', 2)}\S*|{kw('radius', 2)}\S*"
|
|
35
|
+
rf"|{kw('crypto', 2)}|{kw('archive', 2)}|{kw('access-list', 2)}"
|
|
36
|
+
rf"|{kw('control-plane', 4)}|{kw('event', 2)}|{kw('kron', 2)}"
|
|
37
|
+
rf"|{kw('alias', 2)}|{kw('parser', 3)}|{kw('vrf', 2)}|{kw('class-map', 2)}"
|
|
38
|
+
rf"|{kw('policy-map', 3)}|{kw('netconf-yang', 4)}\S*|{kw('restconf', 4)}"
|
|
39
|
+
rf"|{kw('scripting', 3)}|{kw('guestshell', 2)}|{kw('iox', 3)}"
|
|
40
|
+
rf"|ip (?:{kw('ssh', 2)}|{kw('scp', 2)}|{kw('access-list', 2)}|{kw('access-group', 8)}"
|
|
41
|
+
rf"|{kw('http', 2)}|{kw('vrf', 2)}|{kw('tacacs', 2)}|{kw('radius', 2)}|{kw('telnet', 3)}"
|
|
42
|
+
rf"|{kw('tftp', 3)}|{kw('ftp', 2)})"
|
|
43
|
+
rf"|ipv6 (?:{kw('access-list', 2)}|{kw('traffic-filter', 2)})"
|
|
44
|
+
rf"|{kw('access-class', 8)})(?: |$)", re.I)
|
|
45
|
+
FINDING_PATTERNS = [
|
|
46
|
+
("lockout", LOCKOUT),
|
|
47
|
+
# A description and nothing under it: a deeper line would run in interface mode.
|
|
48
|
+
("description", re.compile(r"^interface \S+ / description (?:(?! / ).)*$", re.I)),
|
|
49
|
+
("bgp", re.compile(r"^router bgp\b", re.I)),
|
|
50
|
+
("routing", re.compile(
|
|
51
|
+
r"^(?:ip route|ip prefix-list|ip as-path|ip community-list|route-map"
|
|
52
|
+
r"|router (?:ospf|ospfv3|eigrp|isis|rip))\b", re.I)),
|
|
53
|
+
]
|
|
54
|
+
NEGATION = re.compile(rf"^(?:no|{kw('default', 3)}) ", re.I)
|
|
55
|
+
|
|
56
|
+
# Lines that are not configuration. `do` runs an exec command from configuration mode, and
|
|
57
|
+
# after `end` or `exit` the following lines run somewhere other than where they are written;
|
|
58
|
+
# either way the router would do something the diff does not show. A banner spans lines.
|
|
59
|
+
NOT_CONFIG = re.compile(
|
|
60
|
+
rf"^(?:do(?:-\S*)?|en|end|{kw('exit', 2)}|{kw('configure', 4)}|{kw('banner', 2)})(?: |$)",
|
|
61
|
+
re.I)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def diff_of(dry_run_text):
|
|
65
|
+
"""The change list inside a successful dry-run reply."""
|
|
66
|
+
return dry_run_text.split("Changes:", 1)[1].strip() if "Changes:" in dry_run_text else ""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _mgmt(names):
|
|
70
|
+
"""Matches an `interface ...` line that names one of these interfaces, however IOS lets
|
|
71
|
+
it be written: abbreviated (`int e0/0`), with a space, as a sub-interface, in a range."""
|
|
72
|
+
spellings = []
|
|
73
|
+
for name in names:
|
|
74
|
+
kind, number = re.match(r"([A-Za-z-]*) ?(.*)", name).groups()
|
|
75
|
+
spellings.append(rf"{re.escape(kind[:1])}[a-z-]* ?{re.escape(number)}")
|
|
76
|
+
return re.compile(rf"^{kw('interface', 3)} (?:.*[ ,-])?(?:{'|'.join(spellings)})(?![\d/])",
|
|
77
|
+
re.I)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _classify(statement):
|
|
81
|
+
for name, pattern in FINDING_PATTERNS:
|
|
82
|
+
if pattern.search(statement):
|
|
83
|
+
return name
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def findings(diff, mgmt=None):
|
|
88
|
+
"""Classify every line of the upstream's change list. `mgmt` names the router's
|
|
89
|
+
management interfaces; without it, the lab's.
|
|
90
|
+
|
|
91
|
+
IOS runs a line in global mode when the mode it is written under does not know it, so
|
|
92
|
+
an indented line is judged twice: under its parents and as if it stood on its own.
|
|
93
|
+
"""
|
|
94
|
+
management = _mgmt(mgmt or DEFAULT_MGMT)
|
|
95
|
+
found = set()
|
|
96
|
+
for line in diff.splitlines():
|
|
97
|
+
sign, _, rest = line.strip().partition(" ")
|
|
98
|
+
if not line.strip():
|
|
99
|
+
continue
|
|
100
|
+
if sign not in ("+", "-") or not rest:
|
|
101
|
+
found.add("other") # a line this parser does not know is never ignored
|
|
102
|
+
continue
|
|
103
|
+
parts = [NEGATION.sub("", " ".join(part.split())) for part in rest.split(" / ")]
|
|
104
|
+
if any(management.search(part) for part in parts):
|
|
105
|
+
found.add("lockout")
|
|
106
|
+
else:
|
|
107
|
+
found.add(_classify(" / ".join(parts)) or "other")
|
|
108
|
+
for start in range(1, len(parts)):
|
|
109
|
+
alone = _classify(" / ".join(parts[start:]))
|
|
110
|
+
if alone:
|
|
111
|
+
found.add(alone)
|
|
112
|
+
return tuple(sorted(found))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
NEIGHBOR = re.compile(rf"^{kw('neighbor', 2)} (\S+)(?: (.*))?$", re.I)
|
|
116
|
+
SHUTDOWN = re.compile(rf"^{kw('shutdown', 2)}(?: |$)", re.I)
|
|
117
|
+
REMOTE_AS = re.compile(rf"^{kw('remote-as', 2)}(?: |$)", re.I)
|
|
118
|
+
ACTIVATE = re.compile(rf"^{kw('activate', 2)}(?: |$)", re.I)
|
|
119
|
+
BGP = re.compile(rf"^{kw('router', 3)} {kw('bgp', 2)}(?: |$)", re.I)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def bgp_expect(diff):
|
|
123
|
+
"""`remote-as` is what makes a neighbour one; a peer group's lines, or `router bgp`
|
|
124
|
+
removed as a whole, take down sessions the change list does not name."""
|
|
125
|
+
touches, wide = [], False
|
|
126
|
+
for line in diff.splitlines():
|
|
127
|
+
sign, _, rest = line.strip().partition(" ")
|
|
128
|
+
parts = [" ".join(part.split()) for part in rest.split(" / ")]
|
|
129
|
+
if sign not in ("+", "-") or not BGP.match(NEGATION.sub("", parts[0])):
|
|
130
|
+
continue
|
|
131
|
+
if NEGATION.match(parts[-1]): # "+ no neighbor ..." is that line removed
|
|
132
|
+
sign, parts[-1] = "-", NEGATION.sub("", parts[-1])
|
|
133
|
+
neighbor = NEIGHBOR.match(parts[-1])
|
|
134
|
+
if not neighbor:
|
|
135
|
+
wide = wide or (len(parts) == 1 and sign == "-")
|
|
136
|
+
continue
|
|
137
|
+
peer, what = neighbor.group(1), neighbor.group(2) or ""
|
|
138
|
+
if not ADDRESS.match(peer):
|
|
139
|
+
wide = True
|
|
140
|
+
elif len(parts) > 2 or ACTIVATE.match(what):
|
|
141
|
+
touches.append((peer, sign, "any")) # one address family of the session
|
|
142
|
+
else:
|
|
143
|
+
kind = ("shutdown" if SHUTDOWN.match(what) else
|
|
144
|
+
"self" if REMOTE_AS.match(what) or not what else "other")
|
|
145
|
+
touches.append((peer, sign, kind))
|
|
146
|
+
return expectations(touches), wide
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def bgp_states(text):
|
|
150
|
+
"""{neighbour: Established} from `show ip bgp summary`, or `show bgp summary` on
|
|
151
|
+
IOS XR: the last column holds a prefix count once the session is up, else a state."""
|
|
152
|
+
states = {}
|
|
153
|
+
for line in text.splitlines():
|
|
154
|
+
fields = line.split()
|
|
155
|
+
if len(fields) > 8 and ADDRESS.match(fields[0]):
|
|
156
|
+
states[fields[0]] = bool(re.fullmatch(r"\d+[!*]?", fields[-1]))
|
|
157
|
+
return states
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def config_problem(text):
|
|
161
|
+
for line in text.splitlines():
|
|
162
|
+
words = line.strip()
|
|
163
|
+
if any(ord(char) < 32 and char != "\t" for char in line) or NOT_CONFIG.match(words):
|
|
164
|
+
return ("The config must hold configuration lines only, laid out as in 'show "
|
|
165
|
+
"running-config' (sub-mode lines indented under their parent). 'do', "
|
|
166
|
+
"'end', 'exit', 'configure' and 'banner' are not accepted. This line is "
|
|
167
|
+
f"not: {words[:80]!r}")
|
|
168
|
+
return ""
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
ADAPTER = Adapter(
|
|
172
|
+
name="ios",
|
|
173
|
+
router="router_name",
|
|
174
|
+
routers=None,
|
|
175
|
+
command="command",
|
|
176
|
+
config="config_text",
|
|
177
|
+
format=None,
|
|
178
|
+
dry_run="dry_run",
|
|
179
|
+
timer="confirm_timeout_mins",
|
|
180
|
+
timer_seconds=60,
|
|
181
|
+
timer_example=2,
|
|
182
|
+
dry_run_ok="Dry run: changes worked out",
|
|
183
|
+
commit_ok="Configuration committed on",
|
|
184
|
+
confirm_ok="Commit confirmed on",
|
|
185
|
+
failure_prefixes=("Error",),
|
|
186
|
+
diff_of=diff_of,
|
|
187
|
+
predicted_diff=True,
|
|
188
|
+
bgp_command="show ip bgp summary",
|
|
189
|
+
bgp_states=bgp_states,
|
|
190
|
+
bgp_expect=bgp_expect,
|
|
191
|
+
findings=findings,
|
|
192
|
+
command_banned=("|",),
|
|
193
|
+
command_keywords=KEYWORDS,
|
|
194
|
+
command_refusal=("Only 'show' commands may be run, without a pipe ('| redirect', "
|
|
195
|
+
"'| tee' and '| append' write files). Commands that change state "
|
|
196
|
+
"(clear, configure, reload, copy, ...) are not allowed, and neither "
|
|
197
|
+
"is a show command with one of the words tech-support, to-file, "
|
|
198
|
+
"extract-pcap, clear or leaks, in full or cut short: those write a "
|
|
199
|
+
"file, reset counters or disturb the router."),
|
|
200
|
+
example_check="show ip bgp summary",
|
|
201
|
+
config_problem=config_problem,
|
|
202
|
+
tools={
|
|
203
|
+
"hidden": [],
|
|
204
|
+
"read": ["get_router_list", "get_config"],
|
|
205
|
+
"command": ["execute_command"],
|
|
206
|
+
"commit": "load_and_commit_config",
|
|
207
|
+
"confirm": "confirm_commit",
|
|
208
|
+
},
|
|
209
|
+
allow_prefixes=("show",),
|
|
210
|
+
upstream=("holddown-ios-mcp", "-f", "~/.config/holddown/devices.json"),
|
|
211
|
+
upstream_hint="",
|
|
212
|
+
)
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""Cisco IOS XE over NETCONF, through multivendor-netconf-mcp
|
|
2
|
+
(https://github.com/Jitter00/multivendor-netconf-mcp)."""
|
|
3
|
+
import re
|
|
4
|
+
import xml.etree.ElementTree as ET
|
|
5
|
+
|
|
6
|
+
from . import ADDRESS, Adapter, expectations
|
|
7
|
+
from .ios import KEYWORDS, bgp_states
|
|
8
|
+
|
|
9
|
+
NATIVE = "{http://cisco.com/ns/yang/Cisco-IOS-XE-native}native"
|
|
10
|
+
# The upstream of the NETCONF adapters, at the release they were tried with. Holddown reads
|
|
11
|
+
# its replies, so a later release is taken on here, with the tests, and not by itself.
|
|
12
|
+
NETCONF_MCP = "multivendor-netconf-mcp==0.3.1"
|
|
13
|
+
|
|
14
|
+
# The upstream's dry run compares the candidate with the running configuration and prints
|
|
15
|
+
# one line per leaf that differs, as its path in the native model with list keys in brackets:
|
|
16
|
+
# + interface GigabitEthernet[2] description = to xe2
|
|
17
|
+
# + router bgp[65001] neighbor[10.0.2.2] shutdown
|
|
18
|
+
# A line is parsed into its steps, (element name, list key or None), and the rules below are
|
|
19
|
+
# matched against the element names only: a key or a value, which the change's author
|
|
20
|
+
# chooses, can never read as part of the path.
|
|
21
|
+
STEP = re.compile(r"([^\s\[\]=][^\s\[\]]*)(?:\[((?:[^\]\\]|\\.)*)\])?")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_line(line):
|
|
25
|
+
"""(sign, steps, value) of one line of a change list, or None when it is not one.
|
|
26
|
+
In a key the upstream writes `]` as `\\]` and `\\` as `\\\\`; the value runs to the end
|
|
27
|
+
of the line."""
|
|
28
|
+
sign, _, rest = line.strip().partition(" ")
|
|
29
|
+
if sign not in ("+", "-") or not rest:
|
|
30
|
+
return None
|
|
31
|
+
steps, at = [], 0
|
|
32
|
+
while True:
|
|
33
|
+
step = STEP.match(rest, at)
|
|
34
|
+
if not step:
|
|
35
|
+
return None
|
|
36
|
+
key = step.group(2)
|
|
37
|
+
steps.append((step.group(1),
|
|
38
|
+
None if key is None else re.sub(r"\\([\]\\])", r"\1", key)))
|
|
39
|
+
at = step.end()
|
|
40
|
+
if at == len(rest):
|
|
41
|
+
return sign, tuple(steps), None
|
|
42
|
+
if rest.startswith(" = ", at):
|
|
43
|
+
return sign, tuple(steps), rest[at + 3:]
|
|
44
|
+
if rest[at] != " ":
|
|
45
|
+
return None
|
|
46
|
+
at += 1
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# A rule is a path of element names from the top of the model. One place in it is a name,
|
|
50
|
+
# a set of names, or ANY; a rule matches every path that starts with it, or with END as its
|
|
51
|
+
# last place only the path of that length.
|
|
52
|
+
ANY, END = object(), object()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def matches(names, rule):
|
|
56
|
+
if rule[-1] is END:
|
|
57
|
+
rule = rule[:-1]
|
|
58
|
+
if len(names) != len(rule):
|
|
59
|
+
return False
|
|
60
|
+
return len(names) >= len(rule) and all(
|
|
61
|
+
want is ANY or (name in want if isinstance(want, frozenset) else name == want)
|
|
62
|
+
for name, want in zip(names, rule, strict=False))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _any_of(text):
|
|
66
|
+
return frozenset(text.split())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# First match wins.
|
|
70
|
+
FINDING_RULES = [
|
|
71
|
+
# As for the ios adapter: who can reach and log in to the router, every access list and
|
|
72
|
+
# where one is applied, control-plane policing with its class and policy maps, VRFs,
|
|
73
|
+
# and what runs commands later or changes what a command means.
|
|
74
|
+
("lockout", (
|
|
75
|
+
(_any_of("line username aaa enable login privilege tacacs tacacs-server radius "
|
|
76
|
+
"radius-server crypto control-plane event kron access-list archive alias "
|
|
77
|
+
"parser vrf policy class-map policy-map netconf-yang restconf scripting "
|
|
78
|
+
"guestshell iox"),),
|
|
79
|
+
("ip", _any_of("ssh scp access-list http vrf tacacs radius telnet tftp ftp")),
|
|
80
|
+
("ipv6", "access-list"),
|
|
81
|
+
("interface", ANY, "ip", "access-group"),
|
|
82
|
+
("interface", ANY, "ipv6", "traffic-filter"),
|
|
83
|
+
("interface", ANY, "vrf"),
|
|
84
|
+
("interface", ANY, "ip", "vrf"),
|
|
85
|
+
)),
|
|
86
|
+
("description", (("interface", ANY, "description", END),)),
|
|
87
|
+
("bgp", (("router", "bgp"),)),
|
|
88
|
+
("routing", (
|
|
89
|
+
("ip", _any_of("route prefix-list prefix-lists as-path community-list")),
|
|
90
|
+
("route-map",),
|
|
91
|
+
("router", _any_of("ospf ospfv3 eigrp isis rip")),
|
|
92
|
+
)),
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def diff_of(dry_run_text):
|
|
97
|
+
"""The change list inside a successful dry-run reply."""
|
|
98
|
+
return dry_run_text.split("Changes:", 1)[1].strip() if "Changes:" in dry_run_text else ""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# The management interface, where no inventory names it: the lab's.
|
|
102
|
+
DEFAULT_MGMT = ("GigabitEthernet1",)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _mgmt(names):
|
|
106
|
+
"""Tells whether a path is on one of these interfaces or a subinterface of one:
|
|
107
|
+
GigabitEthernet1 is `interface GigabitEthernet[1]` in the native model."""
|
|
108
|
+
wanted = {re.match(r"([A-Za-z-]*) ?(.*)", name).groups() for name in names}
|
|
109
|
+
|
|
110
|
+
def management(steps):
|
|
111
|
+
if len(steps) < 2 or steps[0][0] != "interface" or steps[1][1] is None:
|
|
112
|
+
return False
|
|
113
|
+
kind, number = steps[1]
|
|
114
|
+
return (kind, re.sub(r"\.\d+$", "", number)) in wanted
|
|
115
|
+
return management
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def classify(diff, rules, management):
|
|
119
|
+
"""Findings for a change list of `+ path` and `- path` lines: lockout for anything on a
|
|
120
|
+
management interface, else by the first rule that matches the path."""
|
|
121
|
+
found = set()
|
|
122
|
+
for line in diff.splitlines():
|
|
123
|
+
if not line.strip():
|
|
124
|
+
continue
|
|
125
|
+
parsed = parse_line(line)
|
|
126
|
+
if parsed is None:
|
|
127
|
+
found.add("other") # a line this parser does not know is never ignored
|
|
128
|
+
continue
|
|
129
|
+
steps = parsed[1]
|
|
130
|
+
names = tuple(name for name, _ in steps)
|
|
131
|
+
if management(steps):
|
|
132
|
+
found.add("lockout")
|
|
133
|
+
continue
|
|
134
|
+
found.add(next((finding for finding, paths in rules
|
|
135
|
+
if any(matches(names, rule) for rule in paths)), "other"))
|
|
136
|
+
return tuple(sorted(found))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def findings(diff, mgmt=None):
|
|
140
|
+
"""Classify every line of the upstream's change list. `mgmt` names the router's
|
|
141
|
+
management interfaces; without it, the lab's."""
|
|
142
|
+
return classify(diff, FINDING_RULES, _mgmt(mgmt or DEFAULT_MGMT))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def neighbor_touches(diff, find):
|
|
146
|
+
"""(neighbour, sign, kind) for the lines of a change list under a BGP neighbour.
|
|
147
|
+
`find` takes a line's steps and returns what stands between `router bgp` and the
|
|
148
|
+
neighbour (a VRF, an address family), its address, and the steps below it; None for a
|
|
149
|
+
line that is not under a neighbour."""
|
|
150
|
+
touches = []
|
|
151
|
+
for line in diff.splitlines():
|
|
152
|
+
parsed = parse_line(line)
|
|
153
|
+
found = find(parsed[1]) if parsed else None
|
|
154
|
+
if not found:
|
|
155
|
+
continue
|
|
156
|
+
between, peer, below = found
|
|
157
|
+
what = below[0][0] if below else ""
|
|
158
|
+
if between or not ADDRESS.match(peer):
|
|
159
|
+
kind = "any" # one address family or VRF, or a peer group
|
|
160
|
+
else:
|
|
161
|
+
kind = ("shutdown" if what.startswith("shutdown") else
|
|
162
|
+
"self" if what.startswith("remote-as") else "other")
|
|
163
|
+
touches.append((peer, parsed[0], kind))
|
|
164
|
+
return touches
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _neighbor(steps):
|
|
168
|
+
names = [name for name, _ in steps]
|
|
169
|
+
if names[:2] != ["router", "bgp"] or steps[1][1] is None:
|
|
170
|
+
return None
|
|
171
|
+
for at in range(2, len(steps)):
|
|
172
|
+
if steps[at][0] == "neighbor" and steps[at][1] is not None:
|
|
173
|
+
return steps[2:at], steps[at][1], steps[at + 1:]
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def bgp_expect(diff):
|
|
178
|
+
touches = neighbor_touches(diff, _neighbor)
|
|
179
|
+
# A peer group's lines take down sessions the change list does not name.
|
|
180
|
+
wide = any(not ADDRESS.match(peer) for peer, _, _ in touches)
|
|
181
|
+
return expectations(t for t in touches if ADDRESS.match(t[0])), wide
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def xml_problem(text, accepted, wanted):
|
|
185
|
+
"""Why this text is not a change the dry run would show in full, or "". `accepted` says
|
|
186
|
+
whether a top-level element's tag is in the model the dry run compares."""
|
|
187
|
+
if re.search(r"<!\s*(DOCTYPE|ENTITY)", text, re.I):
|
|
188
|
+
return "The config may not carry a DOCTYPE or entity declarations."
|
|
189
|
+
try:
|
|
190
|
+
root = ET.fromstring(text.strip())
|
|
191
|
+
except ET.ParseError as error:
|
|
192
|
+
return f"The config must be well-formed XML: {error}"
|
|
193
|
+
tops = list(root) if root.tag.rpartition("}")[2] == "config" else [root]
|
|
194
|
+
for top in tops:
|
|
195
|
+
if not accepted(top.tag):
|
|
196
|
+
return (f"Every top-level element of the config must be {wanted}; this one is "
|
|
197
|
+
f"{top.tag!r}.")
|
|
198
|
+
return "" if tops else "The config is empty."
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def config_problem(text):
|
|
202
|
+
"""The dry run compares the native model only, so a change has to be written in it:
|
|
203
|
+
one made through another model (ietf-interfaces, openconfig, NACM) would not be seen."""
|
|
204
|
+
return xml_problem(text, lambda tag: tag == NATIVE,
|
|
205
|
+
'<native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">')
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
SECTION = re.compile(r"^=== (.+) ===\n", re.M)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def batch_results(text):
|
|
212
|
+
"""What execute_command_batch returned, per router: each router's output follows a
|
|
213
|
+
line `=== name ===`. A router's output can hold such a line itself (an interface
|
|
214
|
+
description may say anything), so a name that heads two sections has no answer."""
|
|
215
|
+
parts = SECTION.split(text)[1:]
|
|
216
|
+
found = {}
|
|
217
|
+
for name, output in zip(parts[::2], parts[1::2], strict=True):
|
|
218
|
+
found[name] = None if name in found else output
|
|
219
|
+
return found
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
ADAPTER = Adapter(
|
|
223
|
+
name="iosxe",
|
|
224
|
+
router="router_name",
|
|
225
|
+
routers="router_names",
|
|
226
|
+
command="command",
|
|
227
|
+
config="config_text",
|
|
228
|
+
format=None,
|
|
229
|
+
dry_run="dry_run",
|
|
230
|
+
timer="confirm_timeout_secs",
|
|
231
|
+
timer_seconds=1,
|
|
232
|
+
timer_example=120,
|
|
233
|
+
dry_run_ok="Dry run: validated by",
|
|
234
|
+
commit_ok="Configuration committed on",
|
|
235
|
+
confirm_ok="Commit confirmed on",
|
|
236
|
+
failure_prefixes=("Error",),
|
|
237
|
+
diff_of=diff_of,
|
|
238
|
+
findings=findings,
|
|
239
|
+
bgp_command="show ip bgp summary",
|
|
240
|
+
bgp_states=bgp_states,
|
|
241
|
+
bgp_expect=bgp_expect,
|
|
242
|
+
command_banned=("|",),
|
|
243
|
+
command_keywords=KEYWORDS,
|
|
244
|
+
batch_results=batch_results,
|
|
245
|
+
command_refusal=("Only 'show' commands may be run, without a pipe ('| redirect', "
|
|
246
|
+
"'| tee' and '| append' write files): to filter the output use the tool's "
|
|
247
|
+
"include, exclude, head, tail and count arguments. Commands that change state "
|
|
248
|
+
"(clear, configure, reload, copy, ...) are not allowed, and neither "
|
|
249
|
+
"is a show command with one of the words tech-support, to-file, "
|
|
250
|
+
"extract-pcap, clear or leaks, in full or cut short: those write a "
|
|
251
|
+
"file, reset counters or disturb the router."),
|
|
252
|
+
example_check="show ip bgp summary",
|
|
253
|
+
config_problem=config_problem,
|
|
254
|
+
tools={
|
|
255
|
+
"hidden": [],
|
|
256
|
+
"read": ["get_router_list", "get_config", "get_facts", "get_state"],
|
|
257
|
+
"command": ["execute_command", "execute_command_batch"],
|
|
258
|
+
"commit": "load_and_commit_config",
|
|
259
|
+
"confirm": "confirm_commit",
|
|
260
|
+
},
|
|
261
|
+
allow_prefixes=("show",),
|
|
262
|
+
upstream=("uvx", "--from", NETCONF_MCP, "multivendor-netconf-mcp", "-f",
|
|
263
|
+
"~/.config/holddown/devices.json"),
|
|
264
|
+
upstream_hint="",
|
|
265
|
+
)
|