forked from CiscoDevNet/pathman-sr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathman_sr.py
1736 lines (1488 loc) · 65.4 KB
/
pathman_sr.py
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 python2.7
"""
* Copyright (c) 2016 by Cisco Systems, Inc.
* All rights reserved.
Pathman SR
Niklas Montin, 20140705, [email protected]
-- Get the link-state topology and build a graph
20141022, Niklas - Fixed Helium support - removed the repeated key portion 'l3-unicast-igp-topology'
Could add a test to see what key to use.
20141111, Niklas - Fixed one more Helium key-change path[path][0] and 'network-topology-pcep:' being repeated
20141201, Niklas - ver3.5 - compacted the filestructure: rerst_server_v5, topo_data and pathman35
20141202, Niklas - ver 4.0 - PCEP stateful 07 work, using xml
20141203, Niklas - Adding rotating log
20141204, Niklas - ver 4.1 Enhanced url error checking, nprint retired for python logging
20141208, Niklas - ver 4.2 config_ini.py now holds relevant environmend variables (ODL ip-address and port)
20141213, Niklas - ver 4.3 configfile instead of configdict
added 2sec delay after create of stateful 07 LSP
20150303, Niklas - ver 4.4, merged 4.2 and 4.3 changes - sleep and error checking
20150303, Niklas - ver 4.5, refresh topology when getTopo is send
20150312, Wei - ver 4.6, add prefix in node and traffic in link
20150312, Niklas - ver 4.7, added support for 66 nodes in topo with GPS coordinates (topo_data.py)
20150401, Wei - ver 4.7.1, fix bug for missing nodes
20150407, Niklas - ver 4.7.2, minor bugfix for missing command status from 02LSP
20150522, Niklas - ver 4.8, OSPF support, broadcast network support, namelookup for ospf
20150531, Niklas - ver 4.9, pseudo node fixes
20150830, Niklas - ver 4.9b - Lithium changes - auth and xml payload for create and delete
20150930, Niklas - ver 5.0 - Minor cleanup for publishing
20160316, Niklas - ver 5.1 - Adding Netconf module for config scan
20160328, Niklas - ver 5.2 - Added SegmentRouting support
20160411, Niklas - ver 5.2b - Verified both OSPF and ISIS support w xrvr-6.0.0
20160510, Niklas - ver 5.3 - Added pcep and sr data to list and topo commands
20160528, Alexei Zverev - ver 5.3.1 - Added sr_enabled & pcep_enabled boolean flags to REST response
20160529, Niklas - ver 5.3.2 - loopback is no present even if pcep is not enabled.
20160601, Niklas - ver 5.4 - Created two topologies, one bgp-ls based topo for display, one sr-based for paths
20160608, Niklas - ver 5.5 - Added fixes from Pathman project: metrics, asymmetric links
20160614, Niklas - ver 5.6 - added update function for SR paths
included a pathman fix for missing termination-points
20160811, Niklas - ver 5.7 - Changed Netconf url's to avoid mount point issues. tested w xrv 6.0.0, 6.0.1
- Added sid_list to LSP to not list false SR LSPs
20160831, Niklas - ver 5.7b - added pseudo node fix from Pathman project
20160905, Niklas - ver 5.8 - Added ODL version detection and new netconf urls for Boron.
20160906, Giles - ver 5.9 - Fixed TE metric get for ISIS,
20160906, Niklas - ver 5.9b - Added topologies for TE and IGP metrics
20160912, Niklas - ver 5.9c - Fixed Boron version check from false positives
"""
__author__ = 'niklas'
import os, re, time, sys
import requests
import json
import logging
import logging.config
from logging.handlers import RotatingFileHandler
from logging import Formatter
from collections import namedtuple
from copy import deepcopy
from topo_data import topologyData
#==============================================================
version = '5.9c'
# Defaults overridden by pathman_ini.py
odl_ip = '127.0.0.1'
odl_port = '8181'
log_file = 'pathman.log'
log_size = 2000000
log_count = 3
log_level = 'INFO'
#log_level = 'DEBUG'
from pathman_ini import *
#==============================================================
Node = namedtuple('Node', ['name', 'id', 'loopback', 'portlist','pcc','pcep_type','prefix', 'sid'])
LSP = namedtuple('LSP',['name', 'pcc', 'hoplist', 'iphoplist', 'sid_list'])
get_version = 'http://%s:%s/restconf/modules' %(odl_ip, odl_port)
get_topo = 'http://%s:%s/restconf/operational/network-topology:network-topology/topology/example-linkstate-topology' %(odl_ip, odl_port)
get_pcep = 'http://%s:%s/restconf/operational/network-topology:network-topology/topology/pcep-topology' %(odl_ip, odl_port)
create_lsp = 'http://%s:%s/restconf/operations/network-topology-pcep:add-lsp' %(odl_ip, odl_port)
update_lsp = 'http://%s:%s/restconf/operations/network-topology-pcep:update-lsp' %(odl_ip, odl_port)
delete_lsp = 'http://%s:%s/restconf/operations/network-topology-pcep:remove-lsp' %(odl_ip, odl_port)
get_nodes = 'http://%s:%s/restconf/config/opendaylight-inventory:nodes' %(odl_ip, odl_port)
get_node_topo = 'http://%s:%s/restconf/operational/network-topology:network-topology/topology/topology-netconf' %(odl_ip, odl_port)
get_node_config = 'http://%s:%s/restconf/config/network-topology:network-topology/topology/topology-netconf/node/{node}/yang-ext:mount/' %(odl_ip, odl_port)
get_node_isis_config = 'http://%s:%s/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/{node}/yang-ext:mount/Cisco-IOS-XR-clns-isis-cfg:isis' %(odl_ip, odl_port)
get_node_ospf_config = 'http://%s:%s/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/{node}/yang-ext:mount/Cisco-IOS-XR-ipv4-ospf-cfg:ospf' %(odl_ip, odl_port)
get_node_bgp_config = 'http://%s:%s/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/{node}/yang-ext:mount/Cisco-IOS-XR-ipv4-bgp-cfg:bgp' %(odl_ip, odl_port)
curl_cmd = 'curl -X POST -H Content-Type:application/json -d '
topo_toplevel_parts = [u'node', u'topology-id', u'link', u'topology-types', u'server-provided']
pcep_toplevel_parts = ['topology']
pcep_topology_parts = ['topology-id', 'topology-types', 'node']
string = "bgpls://IsisLevel2:1/type=node&as=65504&domain=505290270&router=0000.0000.0029"
odl_version_list = [
{'boron':{'name': "openconfig-interfaces", 'revision': "2016-04-12"}},
{'beryllium':{'name':"odl-rsvp-parser-spi-cfg", 'revision':"2015-08-26"}},
{'lithium':{'name':"aaa-authn-model", 'revision':"2014-10-29"}},
{'helium':{'name':"opendaylight-topology", 'revision':"2013-10-30"}},
]
lsp07_xml = '''<input xmlns="urn:opendaylight:params:xml:ns:yang:topology:pcep">
<node>{pcc}</node>
<name>{name}</name>
<arguments>
<lsp xmlns="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<delegate>true</delegate>
<administrative>true</administrative>
</lsp>
<endpoints-obj>
<ipv4>
<source-ipv4-address>{src}</source-ipv4-address>
<destination-ipv4-address>{dst}</destination-ipv4-address>
</ipv4>
</endpoints-obj>
<ero>{ero}</ero>
</arguments>
<network-topology-ref xmlns:topo="urn:TBD:params:xml:ns:yang:network-topology">/topo:network-topology/topo:topology[topo:topology-id="pcep-topology"]</network-topology-ref>
</input>'''
lsp_sr_xml = '''<input xmlns="urn:opendaylight:params:xml:ns:yang:topology:pcep">
<node>{pcc}</node>
<name>{name}</name>
<arguments>
<lsp xmlns="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<delegate>true</delegate>
<administrative>true</administrative>
</lsp>
<endpoints-obj>
<ipv4>
<source-ipv4-address>{src}</source-ipv4-address>
<destination-ipv4-address>{dst}</destination-ipv4-address>
</ipv4>
<processing-rule>true</processing-rule>
</endpoints-obj>
<path-setup-type xmlns="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<pst>1</pst>
</path-setup-type>
<ero>{ero}</ero>
</arguments>
<network-topology-ref xmlns:topo="urn:TBD:params:xml:ns:yang:network-topology">/topo:network-topology/topo:topology[topo:topology-id="pcep-topology"]</network-topology-ref>
</input>'''
lsp_sr_update_xml = '''<input xmlns="urn:opendaylight:params:xml:ns:yang:topology:pcep">
<node>{pcc}</node>
<name>{name}</name>
<arguments>
<lsp xmlns="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<delegate>true</delegate>
<administrative>true</administrative>
</lsp>
<path-setup-type xmlns="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<pst>1</pst>
</path-setup-type>
<ero>{ero}</ero>
</arguments>
<network-topology-ref xmlns:topo="urn:TBD:params:xml:ns:yang:network-topology">/topo:network-topology/topo:topology[topo:topology-id="pcep-topology"]</network-topology-ref>
</input>'''
lspDelete_xml = '''<input xmlns="urn:opendaylight:params:xml:ns:yang:topology:pcep">
<node>{pcc}</node>
<name>{name}</name>
<network-topology-ref xmlns:topo="urn:TBD:params:xml:ns:yang:network-topology">/topo:network-topology/topo:topology[topo:topology-id="pcep-topology"]</network-topology-ref>
</input>'''
lsp07_xml_helium = '''<input>
<node>{pcc}</node>
<name>{name}</name>
<arguments>
<lsp xmlns:stateful="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<delegate>true</delegate>
<administrative>true</administrative>
</lsp>
<endpoints-obj>
<ipv4>
<source-ipv4-address>{src}</source-ipv4-address>
<destination-ipv4-address>{dst}</destination-ipv4-address>
</ipv4>
</endpoints-obj>
<ero>{ero}</ero>
</arguments>
<network-topology-ref xmlns:topo="urn:TBD:params:xml:ns:yang:network-topology">/topo:network-topology/topo:topology[topo:topology-id="pcep-topology"]</network-topology-ref>
</input>'''
lsp07update_xml = '''<input>
<node>{pcc}</node>
<name>{name}</name>
<arguments>
<lsp xmlns:stateful="urn:opendaylight:params:xml:ns:yang:pcep:ietf:stateful">
<delegate>true</delegate>
<administrative>true</administrative>
</lsp>
<ero>{ero}</ero>
</arguments>
<network-topology-ref xmlns:topo="urn:TBD:params:xml:ns:yang:network-topology">/topo:network-topology/topo:topology[topo:topology-id="pcep-topology"]</network-topology-ref>
</input>'''
ero_xml = '''<subobject>
<loose>false</loose>
<ip-prefix><ip-prefix>{hop}/32</ip-prefix></ip-prefix>
</subobject>
'''
ero_sr_xml = '''<subobject>
<loose>false</loose>
<sid-type xmlns="urn:opendaylight:params:xml:ns:yang:pcep:segment:routing">ipv4-node-id</sid-type>
<m-flag xmlns="urn:opendaylight:params:xml:ns:yang:pcep:segment:routing">true</m-flag>
<sid xmlns="urn:opendaylight:params:xml:ns:yang:pcep:segment:routing">{sid}</sid>
<ip-address xmlns="urn:opendaylight:params:xml:ns:yang:pcep:segment:routing">{hop}</ip-address>
</subobject>'''
class Puck():
""" Name Node was taken,
holds path information to neighbors,
every node spawns of Pucks as their neighbors,
not a one-to-one with nodes.
"""
def __init__(self, id = '', end = '',pathlist = [], metriclist = [], topo = [], past = []):
self.id = id
self.end = end
self.pathlist = pathlist
self.metriclist = metriclist
self.topo = topo
self.pastlist = past
debug_modules = ['node_structure']
class debugFilter(logging.Filter):
''' limits debug output to selected modules '''
def filter(self, record):
if record.levelname != 'DEBUG':
return True
else:
return record.funcName in debug_modules
class MyFormatter(logging.Formatter):
''' Gives us a dot instead of a comma in the log printout '''
converter = time.gmtime
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s.%03d" % (t, record.msecs)
return s
LOGGING = {
'version': 1,
'filters': {
'module_filter': {
'()': debugFilter
}
},
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
'to_screen': {
'format': '[%(levelname)s] %(funcName)s: %(message)s'
},
'to_file':{
'()':MyFormatter,
'format' : '%(process)d %(asctime)12s UTC %(name)s:%(funcName)-12s %(levelname)s: %(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'filters': ['module_filter'],
'formatter':'to_screen'
},
'logtofile':{
'class': 'logging.handlers.RotatingFileHandler',
'filters': ['module_filter'],
'formatter':'to_file',
'filename': log_file,
'maxBytes': log_size,
'backupCount': 3,
'encoding': 'utf8'
}
},
'root': {
'level': log_level,
#'handlers': ['console','logtofile']
'handlers': ['logtofile']
},
}
def netconf_list_old():
'''get nodes from netconf'''
result = get_url(get_nodes)
conf_list = []
if True:
try:
for node in result['nodes']['node']:
conf_list.append(node['id'])
except:
logging.error("format error in netconf node-list: %s" % str(result))
pass
return conf_list
def version_check():
"""modified from odl_gateway"""
url = get_version
result = get_url(url)
if True:
name_list = [mod['name'] for mod in result['modules']['module']]
rev_list = [mod['revision'] for mod in result['modules']['module']]
for odl_ver in odl_version_list:
version = odl_ver.keys()[0]
if odl_ver[version]['name'] in name_list:
if odl_ver[version]['revision'] == rev_list[name_list.index(odl_ver[version]['name'])]:
logging.info("Found ODL Release: %s" % version)
return version
return ""
def netconf_list(dummy=None):
'''modified from from odl_gateway'''
odl_version = version_check()
if odl_version in ['beryllium', 'boron']:
url = get_node_topo
else:
url = get_nodes
result = get_url(url)
conf_list = []
if True:
if isinstance(result, dict):
if 'nodes' in result.keys():
try:
for node in result['nodes']['node']:
conf_list.append(node['id'])
except:
logging.error("format error in netconf node-list: %s" % str(result))
pass
elif 'topology' in result.keys():
try:
for node in result['topology'][0]['node']:
conf_list.append(node['node-id'])
except:
logging.error("format error in netconf node-list: %s" % str(result))
pass
return conf_list
def get_netconf():
'''get configs for nodes added to controller'''
def get_config(url_list, match):
for url in url_list:
result = get_url(url.format(**temp))
if result != {}:
reply = keyd_dict_walker(result, match)
if reply != -1:
return reply
return -1
netconf_nodes = netconf_list()
node_configs = {}
rid_dict = {}
for node in netconf_nodes:
if node != "controller-config":
temp = {'node':node}
try:
sid = get_config([get_node_isis_config, get_node_ospf_config], 'prefix-sid')
rid = get_config([get_node_bgp_config], 'router-id')
logging.info('rid: %s, sid: %s' %(rid, sid))
if sid != -1:
node_configs.update({node:sid})
logging.info("got netconf data for: %s" % node)
else:
logging.info("No sid for: %s" % node)
if rid != -1:
rid_dict.update({rid:sid})
logging.info("router-id: %s" % rid)
else:
logging.error("No rid for: %s" % node)
except:
logging.error("failure to get netconf data for: %s" % node)
return node_configs, rid_dict
def keyd_dict_walker(mdict, key):
""" walk the dict and find value of key """
#print " being called "
if key in mdict.keys():
return mdict[key]
else:
for keys in mdict.keys():
if type(mdict[keys]) == dict:
temp = keyd_dict_walker(mdict[keys],key)
if temp != -1:
return temp
break
elif type(mdict[keys]) == list:
for item in mdict[keys]:
if type(item) == dict:
temp = keyd_dict_walker(item,key)
if temp != -1:
return temp
break
return -1
def node_sr_update(node_list):
def update(node, temp_sid):
if 'value' in temp_sid.keys():
node_list[node_list.index(node)] = node._replace(sid = temp_sid['value'])
logging.info("SR sid updated for: %s" % node.name)
elif 'sid-value' in temp_sid.keys():
node_list[node_list.index(node)] = node._replace(sid = temp_sid['sid-value'])
logging.info("SR sid updated for: %s" % node.name)
else:
logging.error("No sid value for: %s - %s" % (node.name,temp_sid))
node_configs, rid_dict = get_netconf()
for node in node_list:
temp_sid = node_configs.get(node.name,{})
rid_sid = rid_dict.get(node.loopback,{})
if len(temp_sid) >0:
update(node, temp_sid)
elif len(rid_sid) >0:
update(node, rid_sid)
else:
logging.error("No sid for: %s" % node.name)
return node_list
def get_loop_list(path_list):
""" get loopbacks for nodes in pathlist"""
logging.info("Path: %s" % path_list)
loop_list = []
#path_list.pop(0)
for name in path_list:
try:
temp_loop = node_list[[node.name for node in node_list].index(name)].loopback
if temp_loop not in loop_list:
loop_list.append(temp_loop)
except ValueError:
logging.error("Name not in loop_list: %s" % name)
try:
loop_list.pop(0)
except IndexError:
logging.error("Empty Loop-list for :%s" % path_list)
logging.info("Loop list: %s" % loop_list)
return loop_list
def get_sid_list(path_list):
""" get sids for nodes in pathlist"""
logging.info("Path: %s" % path_list)
sid_list = []
#path_list.pop(0)
for name in path_list:
try:
temp_sid = node_list[[node.name for node in node_list].index(name)].sid
if temp_sid not in sid_list:
sid_list.append(temp_sid)
except ValueError:
logging.error("Name not in sid_list: %s" % name)
try:
sid_list.pop(0)
except IndexError:
logging.error("Empty Sid-list for :%s" % path_list)
logging.info("SID list: %s" % sid_list)
return sid_list
##########
def name_check(address):
'''check if a name is mapped to address'''
import socket
try:
name = socket.gethostbyaddr(address)[0]
return True, name
except:
return False, ""
def ipv4_in_network(ip, network):
'''check if the ip is in the network'''
def mask_check(num):
''' check bits in mask and how many octets we need to match'''
oct = num /8
bits = num % 8
return oct, bits
mask = network.split('/')[-1]
net = network.split('/')[0]
ip_oct = ip.split('.')
net_oct = net.split('.')
oct, bits = mask_check(int(mask))
for i in range(oct):
if ip_oct[i] != net_oct[i]:
return False
# Are you still here?
if oct == 4 or bits == 0:
return True
ip_bin = bin(int(ip_oct[oct]))
net_bin = bin(int(net_oct[oct]))
if ip_bin[2:bits+2] == net_bin[2:bits+2]:
return True
else:
return False
def get_url(url):
'''request url'''
headers = {'Content-type': 'application/json'}
try:
response = requests.get(url, headers = headers, auth = (odl_user,odl_password), verify=False)
logging.info("Url get Status: %s" % response.status_code)
if response.status_code in [200]:
return response.json()
else:
logging.info(str(response.text))
return {}
except requests.exceptions.ConnectionError, e:
logging.error('Connection Error: %s' % e.message)
return {}
def locations_of_substring(string,target, offset=0):
'''recursive counter of all occurances'''
temp = []
start = string.find(target)
if start != -1:
temp = [start+offset]
temp += locations_of_substring(string[start+len(target):],target, offset +start+len(target))
return temp
def html_style(string):
""" find arguments and build list of dicts """
first = locations_of_substring(string,'/')
start = locations_of_substring(string,'&')
end = locations_of_substring(string,'=')
start.insert(0,first[-1])
return chop_chop(start,end,string)
def chop_chop(start, end, string):
""" Build value pair dict from restconf response """
mydict = {}
while len(start)>0:
arg = string[start[0]+1:end[0]]
if len(start) > 1:
inext = start[1]
else:
inext = len(string)
value = string[end[0]+1:inext]
mydict.update({arg:value})
start.pop(0)
end.pop(0)
return mydict
def find_link2(local, remote, address):
""" Determine what node is connected to which """
for link_dict in link_list:
if link_dict['local-router'] == local and link_dict['remote-router'] == remote:
try:
return link_dict[address]
except:
return -1
return(-1)
def node_structure(my_topology, debug = 2):
""" learn (print out) the topology structure """
node_list = []
pcc_list = get_pcep_type(debug)
logging.debug("pcc_list: %s" % pcc_list)
try:
node_dictlist = my_topology['topology'][0]['node']
if len(pcc_list) > 0:
loops = [pnode['loopback'] for pnode in pcc_list]
else:
loops = []
logging.debug("Loopbacks of nodes: %s" % loops)
except:
logging.info("We have no nodes in our BGP-LS topology")
return []
for nodes in my_topology['topology'][0]['node']:
#try:
node_dict = html_style(nodes['node-id'])
#logging.debug("node_dict: %s" % node_dict)
prefix_array = []
if 'prefix' in nodes['l3-unicast-igp-topology:igp-node-attributes'].keys():
for prefix in nodes['l3-unicast-igp-topology:igp-node-attributes']['prefix']:
prefix_array.append(prefix['prefix'])
#logging.debug("prefix: %s, metric: %s " % (prefix['prefix'],prefix['metric']))
node_ports = []
if 'termination-point' in nodes.keys():
for link in nodes['termination-point']:
#logging.debug("port: %s " % link['tp-id'])
if 'tp-id' in link.keys():
port_dict = html_style(link['tp-id'])
if 'ipv4' in port_dict.keys():
node_ports.append(port_dict['ipv4'])
else:
logging.error("Node {0} is missing 'termination-point' ".format(node_dict['router']))
index = -1
router_id = ""
name = ""
pcc = ""
pcep_type = ""
sid = ""
for keys in nodes['l3-unicast-igp-topology:igp-node-attributes'].keys():
if keys == 'router-id':
router_id = nodes['l3-unicast-igp-topology:igp-node-attributes']['router-id'][0]
if router_id in loops:
index = loops.index(router_id)
pcc = pcc_list[index]['pcc']
pcep_type = pcc_list[index]['pcep_type']
elif keys == 'name':
name = nodes['l3-unicast-igp-topology:igp-node-attributes']['name']
if name == "":
name = node_dict['router']
if 'router-id' in nodes['l3-unicast-igp-topology:igp-node-attributes'].keys():
success, hname = name_check(nodes['l3-unicast-igp-topology:igp-node-attributes']['router-id'][0])
if success:
name = hname
node = Node(name,node_dict['router'],router_id,node_ports,pcc, pcep_type, prefix_array, sid)
logging.info("New node: %s" % str(node))
node_list.append(node)
logging.info(node_list)
return node_list
def pseudo_net_build(node_list):
pseudo_net = []
for node in node_list:
if node.name == node.id:
for owner in node_list:
if owner.id == node.id[:len(owner.id)] and owner.name != node.name:
pseudo_network = '0.0.0.0/32'
for network in owner.prefix:
#logging.info("calling ipv4_in_network for: %s - owner:%s" %(node.name,owner.name))
if node.portlist != [] and ipv4_in_network(node.portlist[0], network):
pseudo_network = network
node_list[node_list.index(node)] = node._replace(name= owner.name+node.id[len(owner.id):],pcep_type="pseudonode",prefix=pseudo_network)
pseudo_net += node.portlist
logging.info("Owner of Pseduo: %s is: %s" % (node.name, owner.name))
break
logging.info(pseudo_net)
return pseudo_net
def node_links(my_topology, node_list, bgp=False, metric='igp'):
""" Dumps link info """
def metric_test(attributes):
""" Pick a metric to return """
if 'metric' in attributes.keys():
return attributes['metric']
elif 'ospf-topology:ospf-link-attributes' in attributes.keys() and 'ted' in attributes['ospf-topology:ospf-link-attributes']:
return attributes['ospf-topology:ospf-link-attributes']['ted'].get('te-default-metric', 10)
elif 'isis-topology:isis-link-attributes' in attributes.keys() and 'ted' in attributes['isis-topology:isis-link-attributes']:
return attributes['isis-topology:isis-link-attributes']['ted'].get('te-default-metric', 10)
else:
return 10
net = {}
link_list = []
sr_enabled = [node.id for node in node_list if node.sid != '']
try:
for link in my_topology['topology'][0]['link']:
link_dict = html_style(link['link-id'])
link_list.append(link_dict)
if bgp or set([link_dict['local-router'], link_dict['remote-router']]).issubset(set(sr_enabled)):
if link_dict['local-router'] in net.keys():
net[link_dict['local-router']].update({link_dict['remote-router']: metric_test(link['l3-unicast-igp-topology:igp-link-attributes'])})
else:
net.update({link_dict['local-router']: {link_dict['remote-router']: metric_test(link['l3-unicast-igp-topology:igp-link-attributes'])}})
except:
logging.info("We have no links in our BGP-LS topology")
return net, link_list
def copyTopo(node_dict, ref_nodelist):
""" copy coordinates from ref topo """
for node in ref_nodelist:
if node_dict['name'] == node['name']:
for key in ['latitude','longitude','type','icon','y','x']:
node_dict[key] = node[key]
def pseudo_net_check(address):
'''add pseduo node hop in hoplist'''
addr = address.split('/')[0]
for node in pseudo_list:
#for prefix in node.prefix:
if ipv4_in_network(addr, node.prefix):
logging.info("Found: %s" % node.name)
return True, node.name
return False, ''
def list_pcep_lsp(node_list, debug):
""" reads pcep db from netowrk and provies a list of lsp's """
my_pcep = get_url(get_pcep)
loops = [pnode.loopback for pnode in node_list]
lsplist = []
try:
for node in my_pcep['topology'][0]['node']:
pcc = node['network-topology-pcep:path-computation-client']['ip-address']
if 'reported-lsp' in node['network-topology-pcep:path-computation-client'].keys():
for path in node['network-topology-pcep:path-computation-client']['reported-lsp']:
name = path['name']
ip_hoplist = []
sid_list = []
if 'odl-pcep-ietf-stateful07:lsp' in path['path'][0].keys():
if 'operational' in path['path'][0]['odl-pcep-ietf-stateful07:lsp'].keys():
oper = path['path'][0]['odl-pcep-ietf-stateful07:lsp']['operational']
# if path['path'][0]['odl-pcep-ietf-stateful07:lsp']['operational'] == 'up':
if oper == 'up' or oper == 'active':
if 'rro' in path['path'][0].keys():
route_obj = path['path'][0]['rro']['subobject']
else:
route_obj = path['path'][0]['ero']['subobject']
# for nexthop in path['path'][0]['ero']['subobject']:
for nexthop in route_obj:
if 'ip-prefix' in nexthop.keys():
ip_hoplist.append(nexthop['ip-prefix']['ip-prefix'])
if 'odl-pcep-segment-routing:sid-type' in nexthop.keys():
if nexthop['odl-pcep-segment-routing:sid-type'] == 'ipv4-node-id':
ip_hoplist.append(nexthop['odl-pcep-segment-routing:ip-address'])
sid_list.append(nexthop['odl-pcep-segment-routing:sid'])
elif nexthop['odl-pcep-segment-routing:sid-type'] == 'ipv4-adjacency':
ip_hoplist.append(nexthop['odl-pcep-segment-routing:remote-ip-address'])
sid_list.append(nexthop['odl-pcep-segment-routing:sid'])
hoplist = []
originate = name_from_pcc(pcc, node_list, debug)
if originate != '':
hoplist.append(originate)
for interface in ip_hoplist:
temp = find_node(node_list, interface,debug)
if temp == None:
try:
index = loops.index(interface)
temp = node_list[index].name
except ValueError:
logging.error("Interface not found: %s" % interface)
logging.info("interface: %s, temp: %s" %(interface, temp))
#if temp in pseudo_net:
success, pname = pseudo_net_check(interface)
if success:
hoplist.append(pname)
hoplist.append(temp)
my_lsp = LSP(name, pcc, hoplist, ip_hoplist, sid_list)
lsplist.append(my_lsp)
except:
logging.info("We have no nodes in our PCEP Topology")
return lsplist
def find_node(node_list, interface, debug):
""" find which node and interface belongs to """
for node in node_list:
if "pseudonode" not in node:
for port in node.portlist:
if port == interface.split('/')[0]:
return node.name
def find_link(my_topology, local, remote, debug = 2):
""" Determine what node is connected to which """
for link in my_topology['topology'][0]['link']:
link_dict = html_style(link['link-id'])
if link_dict['local-router'] == local and link_dict['remote-router'] == remote:
try:
return link_dict['ipv4-neigh']
except:
return -1
return(-1)
def map_name2node(node_list, name):
""" find node id from name """
for node in node_list:
if name == node.name:
return node.id
return '0000.0000.0000'
def map_node2name(node_list, node_id):
""" find name from node-id """
for node in node_list:
if node_id == node.id:
return node.name
return "none"
def reduce_topo(topo, begone):
""" Remove node from topo """
new_topo = deepcopy(topo)
for nodes in new_topo:
if begone in new_topo[nodes]:
del new_topo[nodes][begone]
del new_topo[begone]
return new_topo
def nikstra(this_node):
""" find all paths between start and end) """
if this_node.id == this_node.end:
return
else:
nbor_list = []
new_topo = reduce_topo(this_node.topo, this_node.id)
for neighbor in this_node.topo[this_node.id]:
if neighbor == this_node.end:
this_node.pathlist.append([this_node.id,this_node.end])
this_node.metriclist.append(this_node.topo[this_node.id][this_node.end])
else:
# full init required here - due to python feature :)
nbor = Puck()
nbor.id = neighbor
nbor.end = this_node.end
nbor.pathlist = []
nbor.metriclist = []
nbor.pastlist = []
nbor.pastlist.append(this_node.id)
nbor.topo = deepcopy(new_topo)
nbor_list.append(nbor)
nikstra(nbor)
for path in nbor.pathlist:
path.insert(0,this_node.id)
for i in range(len(nbor.metriclist)):
nbor.metriclist[i] = nbor.metriclist[i] + this_node.topo[this_node.id][nbor.id]
for nbor in nbor_list:
for path in nbor.pathlist:
if path != []:
this_node.pathlist.append(path)
for i in range(len(nbor.metriclist)):
this_node.metriclist.append(nbor.metriclist[i])
return
def translate_pathnames(pathlist, debug):
""" Insert nodenames in pathlist """
npathlist = []
for path in pathlist:
npath = []
for nodeid in path:
npath.append(map_node2name(node_list, nodeid))
npathlist.append(npath)
return npathlist
def translate_pathids(path, debug):
""" Insert nodeids in pathlist """
npath = []
for nodename in path:
npath.append(map_name2node(node_list, nodename))
return npath
def hop_not_source(linklist, hop):
""" make sure hop is not a source """
for links in linklist:
if links['source'] == hop:
return False
return True
def translate_topo(node_list, net, debug):
""" returns net topology in names """
name_net = {}
for nodeid in net.keys():
name_hops = {}
for hopid in net[nodeid]:
name_hops.update({map_node2name(node_list, hopid):net[nodeid][hopid]})
name_net.update({map_node2name(node_list, nodeid):name_hops})
return name_net
def get_pcep_type(debug):
'''update our node_list have pcep info'''
my_pcep = get_url(get_pcep)
pcc_list = []
try:
for node in my_pcep['topology'][0]['node']:
loopback = node['network-topology-pcep:path-computation-client']['ip-address']
pcc = node['node-id']
if 'odl-pcep-ietf-stateful07:stateful' in node['network-topology-pcep:path-computation-client']['stateful-tlv'].keys():
pcep_type = '07'
else:
pcep_type = '02'
pcc_list.append({'pcc':pcc, 'loopback':loopback,'pcep_type':pcep_type} )
except:
logging.info("We have no nodes in our PCEP Topology")
return pcc_list
def lsp_create_json(src, dst, name_of_lsp , pcc, debug):
""" build a json structure to create LSPs """
lsp_dict = {}
lsp_dict.update({"input":{}})
lsp_dict["input"].update({"node":pcc,
"name": name_of_lsp,
"network-topology-ref":'/network-topology:network-topology/network-topology:topology[network-topology:topology-id=\"pcep-topology\"]',
"arguments":{}
})
lsp_dict["input"]["arguments"] = {"endpoints-obj":{"ipv4":{"source-ipv4-address":src, "destination-ipv4-address": dst}}}
return lsp_dict
def lsp_create_xml_07(src, dst, name_of_lsp , pcc, hoplist, debug):
""" build a xml structure to create LSPs """
hop_xml_list = []
for hop in hoplist:
step = {"hop":hop}
new_xml = ero_xml.format(**step)
hop_xml_list.append(new_xml)
ero = "".join(hop_xml_list)
new_lsp = {"pcc":pcc,"name":name_of_lsp,"src":src,"dst":dst,"ero":ero}
new_lsp_xml07 = lsp07_xml.format(**new_lsp)
return new_lsp_xml07
def lsp_create_xml_sr(src, dst, name_of_lsp , pcc, hoplist, sid_list, debug):
""" build a xml structure to create LSPs """
hop_xml_list = []
for hop, sid in zip(hoplist, sid_list):
step = {"hop":hop, "sid":sid}
new_xml = ero_sr_xml.format(**step)
hop_xml_list.append(new_xml)
ero = "".join(hop_xml_list)
new_lsp = {"pcc":pcc,"name":name_of_lsp,"src":src,"dst":dst,"ero":ero}
new_lsp_xml_sr = lsp_sr_xml.format(**new_lsp)
return new_lsp_xml_sr
def lsp_update_xml_sr(src, dst, name_of_lsp , pcc, hoplist, sid_list, debug):
""" build a xml structure to update LSPs """
hop_xml_list = []
for hop, sid in zip(hoplist, sid_list):
step = {"hop":hop, "sid":sid}
new_xml = ero_sr_xml.format(**step)
hop_xml_list.append(new_xml)
ero = "".join(hop_xml_list)
new_lsp = {"pcc":pcc,"name":name_of_lsp,"src":src,"dst":dst,"ero":ero}
new_lsp_xml_sr = lsp_sr_update_xml.format(**new_lsp)
return new_lsp_xml_sr
def lsp_update_xml_07(src, dst, name_of_lsp , pcc, hoplist, debug):
""" build a xml structure to update a LSPs """
hop_xml_list = []
for hop in hoplist:
step = {"hop":hop}
new_xml = ero_xml.format(**step)
hop_xml_list.append(new_xml)