-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathfrr-reload.py
More file actions
executable file
·2741 lines (2389 loc) · 103 KB
/
Copy pathfrr-reload.py
File metadata and controls
executable file
·2741 lines (2389 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
# Frr Reloader
# Copyright (C) 2014 Cumulus Networks, Inc.
#
"""
This program
- reads a frr configuration text file
- reads frr's current running configuration via "vtysh -c 'show running'"
- compares the two configs and determines what commands to execute to
synchronize frr's running configuration with the configuration in the
text file
"""
from __future__ import print_function, unicode_literals
import argparse
import datetime
import logging
import os, os.path
import random
import re
import string
import subprocess
import sys
from collections import OrderedDict
from ipaddress import IPv6Address, ip_network
from pprint import pformat
# Python 3
def iteritems(d):
return iter(d.items())
log = logging.getLogger(__name__)
class VtyshException(Exception):
pass
class Vtysh(object):
def __init__(self, bindir=None, confdir=None, sockdir=None, pathspace=None):
self.bindir = bindir
self.confdir = confdir
self.pathspace = pathspace
self.common_args = [os.path.join(bindir or "", "vtysh")]
if confdir:
self.common_args.extend(["--config_dir", confdir])
if sockdir:
self.common_args.extend(["--vty_socket", sockdir])
if pathspace:
self.common_args.extend(["-N", pathspace])
def _call(self, args, stdin=None, stdout=None, stderr=None):
kwargs = {}
if stdin is not None:
kwargs["stdin"] = stdin
if stdout is not None:
kwargs["stdout"] = stdout
if stderr is not None:
kwargs["stderr"] = stderr
return subprocess.Popen(self.common_args + args, **kwargs)
def _call_cmd(self, command, stdin=None, stdout=None, stderr=None):
if isinstance(command, list):
args = [item for sub in command for item in ["-c", sub]]
else:
args = ["-c", command]
return self._call(args, stdin, stdout, stderr)
def __call__(self, command, stdouts=None):
"""
Call a CLI command (e.g. "show running-config")
Output text is automatically redirected, decoded and returned.
Multiple commands may be passed as list.
"""
proc = self._call_cmd(command, stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.wait() != 0:
if stdouts is not None:
stdouts.append(stdout.decode("UTF-8"))
raise VtyshException(
'vtysh returned status %d for command "%s"' % (proc.returncode, command)
)
return stdout.decode("UTF-8")
def is_config_available(self):
"""
Return False if no frr daemon is running or some other vtysh session is
in 'configuration terminal' mode which will prevent us from making any
configuration changes.
"""
output = self("configure")
if "configuration is locked" in output.lower():
log.error(f"vtysh 'configure' returned\n{output}\n")
return False
return True
def exec_file(self, filename):
child = self._call(["-f", filename])
if child.wait() != 0:
raise VtyshException(
f"vtysh (exec file) exited with status {child.returncode}"
)
def mark_file(self, filename, stdin=None):
child = self._call(
["-m", "-f", filename],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
stdout, stderr = child.communicate()
except subprocess.TimeoutExpired:
child.kill()
stdout, stderr = child.communicate()
raise VtyshException("vtysh call timed out!")
if child.wait() != 0:
raise VtyshException(
"vtysh (mark file) exited with status %d:\n%s"
% (child.returncode, stderr)
)
return stdout.decode("UTF-8")
def mark_show_run(self, daemon=None):
cmd = "show running-config"
if daemon:
cmd += " %s" % daemon
cmd += " no-header"
show_run = self._call_cmd(cmd, stdout=subprocess.PIPE)
mark = self._call(
["-m", "-f", "-"], stdin=show_run.stdout, stdout=subprocess.PIPE
)
show_run.wait()
stdout, stderr = mark.communicate()
mark.wait()
if show_run.returncode != 0:
raise VtyshException(
"vtysh (show running-config) exited with status %d:"
% (show_run.returncode)
)
if mark.returncode != 0:
raise VtyshException(
"vtysh (mark running-config) exited with status %d" % (mark.returncode)
)
return stdout.decode("UTF-8")
class Context(object):
"""
A Context object represents a section of frr configuration such as:
!
interface swp3
description swp3 -> r8's swp1
ipv6 nd suppress-ra
link-detect
!
or a single line context object such as this:
ip forwarding
"""
def __init__(self, keys, lines):
self.keys = keys
self.lines = lines
# Keep a dictionary of the lines, this is to make it easy to tell if a
# line exists in this Context
self.dlines = OrderedDict()
for ligne in lines:
self.dlines[ligne] = True
def __str__(self):
return str(self.keys) + " : " + str(self.lines)
def add_lines(self, lines):
"""
Add lines to specified context
"""
self.lines.extend(lines)
for ligne in lines:
self.dlines[ligne] = True
def get_normalized_es_id(line):
"""
The es-id or es-sys-mac need to be converted to lower case
"""
sub_strs = ["evpn mh es-id", "evpn mh es-sys-mac"]
for sub_str in sub_strs:
obj = re.match(sub_str + r" (?P<esi>\S*)", line)
if obj:
line = "%s %s" % (sub_str, obj.group("esi").lower())
break
return line
def get_normalized_mac_ip_line(line):
if line.startswith("evpn mh es"):
return get_normalized_es_id(line)
if not "ipv6 add" in line:
return get_normalized_ipv6_line(line)
return line
def get_normalized_interface_vrf(line):
"""
If 'interface <int_name> vrf <vrf_name>' is present in file,
we need to remove the explicit "vrf <vrf_name>"
so that the context information is created
correctly and configurations are matched appropriately.
"""
intf_vrf = re.search(r"interface (\S+) vrf (\S+)", line)
if intf_vrf:
old_line = "vrf %s" % intf_vrf.group(2)
new_line = line.replace(old_line, "").strip()
return new_line
return line
def get_normalized_ebgp_multihop_line(line):
obj = re.search(r"(.*)ebgp-multihop\s+255", line)
if obj:
line = obj.group(1) + "ebgp-multihop"
return line
def get_normalized_aggregate_address_line(line):
"""
The keywords of an "aggregate-address" command can be entered in any
order, but FRR always renders them in a fixed order:
aggregate-address <prefix> [as-set] [summary-only] [route-map NAME]
[origin <egp|igp|incomplete>] [matching-MED-only] [suppress-map NAME]
Reorder a user-supplied line into that canonical order so that a line
written with the keywords in a different order is not seen as a change.
Otherwise frr-reload deletes and re-adds the aggregate on every reload,
briefly withdrawing the aggregate route.
"""
match = re.match(
r"^aggregate-address\s+(\S+(?:\s+\d+\.\d+\.\d+\.\d+)?)\s*(.*)$", line
)
if not match:
return line
prefix = match.group(1)
rest = match.group(2).split()
as_set = False
summary_only = False
match_med = False
route_map = None
origin = None
suppress_map = None
i = 0
while i < len(rest):
tok = rest[i]
if tok == "as-set":
as_set = True
elif tok == "summary-only":
summary_only = True
elif tok == "matching-MED-only":
match_med = True
elif tok == "route-map" and i + 1 < len(rest):
i += 1
route_map = rest[i]
elif tok == "origin" and i + 1 < len(rest):
i += 1
origin = rest[i]
elif tok == "suppress-map" and i + 1 < len(rest):
i += 1
suppress_map = rest[i]
else:
# Unrecognized token; leave the line untouched.
return line
i += 1
normalized = "aggregate-address " + prefix
if as_set:
normalized += " as-set"
if summary_only:
normalized += " summary-only"
if route_map:
normalized += " route-map " + route_map
if origin:
normalized += " origin " + origin
if match_med:
normalized += " matching-MED-only"
if suppress_map:
normalized += " suppress-map " + suppress_map
return normalized
def get_normalized_static_route_line(line):
"""
The optional keywords of "ip route" / "ipv6 route" commands can be entered
in any order, but FRR always renders them in a fixed order:
ip route <prefix> <nexthop> [tag T] [D] [metric M] [label L]
[segments S [encap-behavior E]] [nexthop-vrf V] [table TBL]
[weight W] [onlink] [color C]
[bfd [multi-hop] [source SRC] [profile P]]
(For ipv6, there's also [from <src-prefix>] after the destination prefix.)
Reorder a user-supplied line into that canonical order so that a line
written with the keywords in a different order is not seen as a change.
Otherwise frr-reload deletes and re-adds the route on every reload,
briefly creating a routing hole.
"""
match = re.match(r"^(ip|ipv6) route\s+(\S+)\s+(.*)$", line)
if not match:
return line
afi = match.group(1)
prefix = match.group(2)
rest = match.group(3).split()
src_prefix = None
nexthop = []
tag = None
distance = None
metric = None
label = None
segments = None
encap_behavior = None
nexthop_vrf = None
table = None
weight = None
onlink = False
color = None
bfd = False
bfd_multi_hop = False
bfd_source = None
bfd_profile = None
vrf = None
i = 0
if afi == "ipv6" and i < len(rest) and rest[i] == "from":
i += 1
if i < len(rest):
src_prefix = rest[i]
i += 1
while i < len(rest):
tok = rest[i]
if tok in ("blackhole", "reject", "Null0"):
nexthop.append(tok)
elif tok == "tag" and i + 1 < len(rest):
i += 1
tag = rest[i]
elif tok == "metric" and i + 1 < len(rest):
i += 1
metric = rest[i]
elif tok == "label" and i + 1 < len(rest):
i += 1
label = rest[i]
elif tok == "segments" and i + 1 < len(rest):
i += 1
segments = rest[i]
elif segments and tok == "encap-behavior" and i + 1 < len(rest):
i += 1
encap_behavior = rest[i]
elif tok == "nexthop-vrf" and i + 1 < len(rest):
i += 1
nexthop_vrf = rest[i]
elif tok == "table" and i + 1 < len(rest):
i += 1
table = rest[i]
elif tok == "weight" and i + 1 < len(rest):
i += 1
weight = rest[i]
elif tok == "onlink":
onlink = True
elif tok == "color" and i + 1 < len(rest):
i += 1
color = rest[i]
elif tok == "bfd":
bfd = True
elif bfd and tok == "multi-hop":
bfd_multi_hop = True
elif bfd and tok == "source" and i + 1 < len(rest):
i += 1
bfd_source = rest[i]
elif bfd and tok == "profile" and i + 1 < len(rest):
i += 1
bfd_profile = rest[i]
elif tok == "vrf" and i + 1 < len(rest):
i += 1
vrf = rest[i]
elif re.match(r"^\d+$", tok) and int(tok) <= 255:
distance = tok
elif not nexthop:
nexthop.append(tok)
elif len(nexthop) == 1 and not any(
kw in rest[: i + 1]
for kw in [
"from",
"tag",
"metric",
"label",
"segments",
"nexthop-vrf",
"table",
"weight",
"onlink",
"color",
"bfd",
]
):
nexthop.append(tok)
else:
return line
i += 1
if not nexthop:
return line
normalized = afi + " route " + prefix
if src_prefix:
normalized += " from " + src_prefix
normalized += " " + " ".join(nexthop)
if tag:
normalized += " tag " + tag
if distance:
normalized += " " + distance
if metric:
normalized += " metric " + metric
if label:
normalized += " label " + label
if segments:
normalized += " segments " + segments
if encap_behavior:
normalized += " encap-behavior " + encap_behavior
if nexthop_vrf:
normalized += " nexthop-vrf " + nexthop_vrf
if table:
normalized += " table " + table
if weight:
normalized += " weight " + weight
if onlink:
normalized += " onlink"
if color:
normalized += " color " + color
if bfd:
if bfd_multi_hop:
normalized += " bfd multi-hop"
else:
normalized += " bfd"
if bfd_source:
normalized += " source " + bfd_source
if bfd_profile:
normalized += " profile " + bfd_profile
if vrf:
normalized += " vrf " + vrf
return normalized
# This dictionary contains a tree of all commands that we know start a
# new multi-line context. All other commands are treated either as
# commands inside a multi-line context or as single-line contexts. This
# dictionary should be updated whenever a new node is added to FRR.
ctx_keywords = {
"router bgp ": {
"address-family ": {
"vni ": {},
},
"vnc defaults": {},
"vnc nve-group ": {},
"vnc l2-group ": {},
"vrf-policy ": {},
"bmp targets ": {},
"segment-routing srv6": {},
},
"router rip": {},
"router ripng": {},
"router isis ": {
"segment-routing srv6": {
"node-msd": {},
},
},
"router openfabric ": {},
"router ospf": {},
"router ospf6": {},
"router eigrp ": {},
"router babel": {},
"router pim": {},
"router pim6": {},
"mpls ldp": {"address-family ": {"interface ": {}}},
"l2vpn ": {"member pseudowire ": {}},
"key chain ": {"key ": {}},
"vrf ": {"rpki": {}},
"interface ": {"link-params": {}},
"pseudowire ": {},
"segment-routing": {
"traffic-eng": {
"segment-list ": {},
"policy ": {"candidate-path ": {}},
"pcep": {"pcc": {}, "pce ": {}, "pce-config ": {}},
},
"srv6": {
"locators": {"locator ": {}},
"static-sids": {},
"encapsulation": {},
"formats": {"format": {}},
},
},
"nexthop-group ": {},
"route-map ": {},
"pbr-map ": {},
"rpki": {},
"bfd": {"peer ": {}, "profile ": {}},
"line vty": {},
}
class Config(object):
"""
A frr configuration is stored in a Config object. A Config object
contains a dictionary of Context objects where the Context keys
('router ospf' for example) are our dictionary key.
"""
def __init__(self, vtysh):
self.lines = []
self.contexts = OrderedDict()
self.vtysh = vtysh
def load_from_file(self, filename):
"""
Read configuration from specified file and slurp it into internal memory
The internal representation has been marked appropriately by passing it
through vtysh with the -m parameter
"""
log.info(f"Loading Config object from file {filename}")
file_output = self.vtysh.mark_file(filename)
vrf_context = None
pim_vrfs = []
for line in file_output.split("\n"):
line = line.strip()
# Compress duplicate whitespaces
line = " ".join(line.split())
# Detect when we are within a vrf context for converting legacy PIM commands
if vrf_context:
re_vrf = re.match("^(exit-vrf|exit|end)$", line)
if re_vrf:
vrf_context = None
else:
re_vrf = re.match("^vrf ([a-z]+)$", line)
if re_vrf:
vrf_context = re_vrf.group(1)
# Detect legacy pim commands that need to move under the router pim context
re_pim = re.match(
"^ip(v6)? pim ((ecmp|join|keep|mlag|packets|register|rp|send|spt|ssm).*)$",
line,
)
if re_pim and re_pim.group(2):
router_pim = "router pim"
if re_pim.group(1):
router_pim += "6"
if vrf_context:
router_pim += " vrf " + vrf_context
if vrf_context:
pim_vrfs.append(router_pim)
pim_vrfs.append(re_pim.group(2))
pim_vrfs.append("exit")
line = "# PIM VRF LINE MOVED TO ROUTER PIM"
else:
self.lines.append(router_pim)
self.lines.append(re_pim.group(2))
line = "exit"
re_pim = re.match("^ip(v6)? ((ssmpingd|msdp).*)$", line)
if re_pim and re_pim.group(2):
router_pim = "router pim"
if re_pim.group(1):
router_pim += "6"
if vrf_context:
router_pim += " vrf " + vrf_context
if vrf_context:
pim_vrfs.append(router_pim)
pim_vrfs.append(re_pim.group(2))
pim_vrfs.append("exit")
line = "# PIM VRF LINE MOVED TO ROUTER PIM"
else:
self.lines.append(router_pim)
self.lines.append(re_pim.group(2))
line = "exit"
# Remove 'vrf <vrf_name>' from 'interface <x> vrf <vrf_name>'
if line.startswith("interface ") and "vrf" in line:
line = get_normalized_interface_vrf(line)
if ":" in line:
line = get_normalized_mac_ip_line(line)
if "ebgp-multihop" in line:
line = get_normalized_ebgp_multihop_line(line)
if line.startswith("aggregate-address "):
line = get_normalized_aggregate_address_line(line)
if line.startswith("ip route ") or line.startswith("ipv6 route "):
line = get_normalized_static_route_line(line)
# vrf static routes can be added in two ways. The old way is:
#
# "ip route x.x.x.x/x y.y.y.y vrf <vrfname>"
#
# but it's rendered in the configuration as the new way::
#
# vrf <vrf-name>
# ip route x.x.x.x/x y.y.y.y
# exit-vrf
#
# this difference causes frr-reload to not consider them a
# match and delete vrf static routes incorrectly.
# fix the old way to match new "show running" output so a
# proper match is found.
if (
line.startswith("ip route ") or line.startswith("ipv6 route ")
) and " vrf " in line:
newline = line.split(" ")
vrf_index = newline.index("vrf")
vrf_ctx = newline[vrf_index] + " " + newline[vrf_index + 1]
del newline[vrf_index : vrf_index + 2]
newline = " ".join(newline)
self.lines.append(vrf_ctx)
self.lines.append(newline)
self.lines.append("exit-vrf")
line = "end"
self.lines.append(line)
if len(pim_vrfs) > 0:
self.lines.append(pim_vrfs)
self.load_contexts()
def load_from_show_running(self, daemon):
"""
Read running configuration and slurp it into internal memory
The internal representation has been marked appropriately by passing it
through vtysh with the -m parameter
"""
log.info("Loading Config object from vtysh show running")
config_text = self.vtysh.mark_show_run(daemon)
for line in config_text.split("\n"):
line = line.strip()
if (
line == "Building configuration..."
or line == "Current configuration:"
or not line
):
continue
self.lines.append(line)
self.load_contexts()
def get_lines(self):
"""
Return the lines read in from the configuration
"""
return "\n".join(self.lines)
def get_contexts(self):
"""
Return the parsed context as strings for display, log etc.
"""
for _, ctx in sorted(iteritems(self.contexts)):
print(str(ctx))
def save_contexts(self, key, lines):
"""
Save the provided key and lines as a context
"""
if not key:
return
# IP addresses specified in "network" statements, "ip prefix-lists"
# etc. can differ in the host part of the specification the user
# provides and what the running config displays. For example, user can
# specify 11.1.1.1/24, and the running config displays this as
# 11.1.1.0/24. Ensure we don't do a needless operation for such lines.
# IS-IS & OSPFv3 have no "network" support.
re_key_rt = re.match(r"(ip|ipv6)\s+route\s+([A-Fa-f:.0-9/]+)(.*)$", key[0])
if re_key_rt:
addr = re_key_rt.group(2)
if "/" in addr:
try:
newaddr = ip_network(addr, strict=False)
key[0] = "%s route %s/%s%s" % (
re_key_rt.group(1),
str(newaddr.network_address),
newaddr.prefixlen,
re_key_rt.group(3),
)
except ValueError:
pass
re_key_rt = re.match(
r"(ip|ipv6)\s+prefix-list(.*)(permit|deny)\s+([A-Fa-f:.0-9/]+)(.*)$", key[0]
)
if re_key_rt:
addr = re_key_rt.group(4)
if "/" in addr:
try:
network_addr = ip_network(addr, strict=False)
newaddr = "%s/%s" % (
str(network_addr.network_address),
network_addr.prefixlen,
)
except ValueError:
newaddr = addr
else:
newaddr = addr
legestr = re_key_rt.group(5)
re_lege = re.search(r"(.*)le\s+(\d+)\s+ge\s+(\d+)(.*)", legestr)
if re_lege:
legestr = "%sge %s le %s%s" % (
re_lege.group(1),
re_lege.group(3),
re_lege.group(2),
re_lege.group(4),
)
key[0] = "%s prefix-list%s%s %s%s" % (
re_key_rt.group(1),
re_key_rt.group(2),
re_key_rt.group(3),
newaddr,
legestr,
)
if lines and key[0].startswith("router bgp"):
newlines = []
for line in lines:
re_net = re.match(r"network\s+([A-Fa-f:.0-9/]+)(.*)$", line)
if re_net:
addr = re_net.group(1)
if "/" not in addr and key[0].startswith("router bgp"):
# This is most likely an error because with no
# prefixlen, BGP treats the prefixlen as 8
addr = addr + "/8"
try:
network_addr = ip_network(addr, strict=False)
line = "network %s/%s %s" % (
str(network_addr.network_address),
network_addr.prefixlen,
re_net.group(2),
)
newlines.append(line)
except ValueError:
# Really this should be an error. What's a network
# without an IP Address following it ?
newlines.append(line)
else:
newlines.append(line)
lines = newlines
# More fixups in user specification and what running config shows.
# "null0" in routes must be replaced by Null0.
if (
key[0].startswith("ip route")
or key[0].startswith("ipv6 route")
and "null0" in key[0]
):
key[0] = re.sub(r"\s+null0(\s*$)", " Null0", key[0])
if lines and key[0].startswith("vrf "):
newlines = []
for line in lines:
if line.startswith("ip route ") or line.startswith("ipv6 route "):
if "null0" in line:
line = re.sub(r"\s+null0(\s*$)", " Null0", line)
newlines.append(line)
else:
newlines.append(line)
lines = newlines
if lines:
if tuple(key) not in self.contexts:
ctx = Context(tuple(key), lines)
self.contexts[tuple(key)] = ctx
else:
ctx = self.contexts[tuple(key)]
ctx.add_lines(lines)
else:
if tuple(key) not in self.contexts:
ctx = Context(tuple(key), [])
self.contexts[tuple(key)] = ctx
def load_contexts(self):
"""
Parse the configuration and create contexts for each appropriate block
The end of a context is flagged via the 'end' keyword:
!
interface swp52
ipv6 nd suppress-ra
link-detect
!
end
router bgp 10
bgp router-id 10.0.0.1
bgp log-neighbor-changes
no bgp default ipv4-unicast
neighbor EBGP peer-group
neighbor EBGP advertisement-interval 1
neighbor EBGP timers connect 10
neighbor 2001:40:1:4::6 remote-as 40
neighbor 2001:40:1:8::a remote-as 40
!
end
address-family ipv6
neighbor IBGPv6 activate
neighbor 2001:10::2 peer-group IBGPv6
neighbor 2001:10::3 peer-group IBGPv6
exit-address-family
!
end
router ospf
ospf router-id 10.0.0.1
log-adjacency-changes detail
timers throttle spf 0 50 5000
!
end
The code assumes that its working on the output from the "vtysh -m"
command. That provides the appropriate markers to signify end of
a context. This routine uses that to build the contexts for the
config.
There are single line contexts such as "log file /media/node/zebra.log"
and multi-line contexts such as "router ospf" and subcontexts
within a context such as "address-family" within "router bgp"
In each of these cases, the first line of the context becomes the
key of the context. So "router bgp 10" is the key for the non-address
family part of bgp, "router bgp 10, address-family ipv6 unicast" is
the key for the subcontext and so on.
"""
# stack of context keys
ctx_keys = []
# stack of context keywords
cur_ctx_keywords = [ctx_keywords]
# list of stored commands
cur_ctx_lines = []
for line in self.lines:
if not line:
continue
if line.startswith("!") or line.startswith("#"):
continue
if line.startswith("exit"):
# ignore on top level
if len(ctx_keys) == 0:
continue
# save current context
self.save_contexts(ctx_keys, cur_ctx_lines)
# exit current context
log.debug(f"LINE {line:<50}: exit context {' '.join(ctx_keys):<50}")
ctx_keys.pop()
cur_ctx_keywords.pop()
cur_ctx_lines = []
continue
if line.startswith("end"):
# exit all contexts
while len(ctx_keys) > 0:
# save current context
self.save_contexts(ctx_keys, cur_ctx_lines)
# exit current context
log.debug(f"LINE {line:<50}: exit context {' '.join(ctx_keys):<50}")
ctx_keys.pop()
cur_ctx_keywords.pop()
cur_ctx_lines = []
continue
new_ctx = False
# check if the line is a context-entering keyword
for k, v in cur_ctx_keywords[-1].items():
if line.startswith(k):
# candidate-path is a special case. It may be a node and
# may be a single-line command. The distinguisher is the
# word "dynamic" or "explicit" at the middle of the line.
# It was perhaps not the best choice by the pathd authors
# but we have what we have.
if k == "candidate-path " and "explicit" in line:
# this is a single-line command
break
# save current context
self.save_contexts(ctx_keys, cur_ctx_lines)
# enter new context
new_ctx = True
ctx_keys.append(line)
cur_ctx_keywords.append(v)
cur_ctx_lines = []
log.debug(
f"LINE {line:<50}: enter context {' '.join(ctx_keys):<50}"
)
break
if new_ctx:
continue
if len(ctx_keys) == 0:
log.debug(f"LINE {line:<50}: single-line context")
self.save_contexts([line], [])
else:
log.debug(
f"LINE {line:<50}: add to current context {' '.join(ctx_keys):<50}"
)
cur_ctx_lines.append(line)
# Save the context of the last one
if len(ctx_keys) > 0:
self.save_contexts(ctx_keys, cur_ctx_lines)
def lines_to_config(ctx_keys, line, delete):
"""
Return the command as it would appear in frr.conf
"""
cmd = []
# If there's no `line` and `ctx_keys` length is 1, then it may be a single-line command.
# In this case, we should treat it as a single command in an empty context.
if len(ctx_keys) == 1 and not line:
single = True
for k, v in ctx_keywords.items():
if ctx_keys[0].startswith(k):
single = False
break
if single:
line = ctx_keys[0]
ctx_keys = []
if line:
for i, ctx_key in enumerate(ctx_keys):
cmd.append(" " * i + ctx_key)
line = line.lstrip()
indent = len(ctx_keys) * " "