-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsros.py
3571 lines (3346 loc) · 156 KB
/
sros.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
# -*- coding: utf-8 -*-
# © 2020 Nokia
# Licensed under the Apache License 2.0 License
# SPDX-License-Identifier: Apache-2.0
# Copyright 2016 Dravetech AB. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""
Napalm driver for SROS.
"""
# import standard library
import json
import time
import re
import datetime
import traceback
import xmltodict
from dictdiffer import diff
import paramiko
# import NAPALM libraries
from lxml import etree
from napalm.base import NetworkDriver
from napalm.base.exceptions import (
ConnectionException,
SessionLockedException,
MergeConfigException,
ReplaceConfigException,
CommitError,
CommandErrorException,
)
from napalm.base.helpers import convert, ip, as_number
import napalm.base.constants as C
# import third party libraries
from ncclient import manager
from ncclient.xml_ import to_ele, to_xml
# import local modules
from napalm_sros.utils.parse_output_to_dict import parse_with_textfsm
from napalm_sros.nc_filters import GET_ARP_TABLE,GET_BGP_CONFIG,GET_ENVIRONMENT, \
GET_FACTS,GET_INTERFACES,GET_INTERFACES_COUNTERS,GET_INTERFACES_IP, \
GET_IPV6_NEIGHBORS_TABLE,GET_LLDP_NEIGHBORS,GET_LLDP_NEIGHBORS_DETAIL, \
GET_NETWORK_INSTANCES,GET_NTP_PEERS,GET_NTP_SERVERS,GET_OPTICS, \
GET_PROBES_CONFIG,GET_ROUTE_TO,GET_SNMP_INFORMATION,GET_USERS
from .api import get_bgp_neighbors, get_bgp_neighbors_detail
import logging
log = logging.getLogger(__file__)
class NokiaSROSDriver(NetworkDriver):
"""Napalm driver for Skeleton."""
def __init__(self, hostname, username, password, timeout=60, optional_args=None):
"""Constructor."""
self.manager = None
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.conn = None
self.conn_ssh = None
self.ssh_channel = None
self.fmt = None
self.locked = False
self.terminal_stdout_re = [
re.compile(
r"[\r\n]*\!?\*?(\((ex|gl|pr|ro)\))?\[.*\][\r\n]+[ABCD]\:\S+\@\S+\#\s$"
),
re.compile(r"[\r\n]*\*?[ABCD]:[\w\-\.\,\>]+[#\$]\s"),
]
self.terminal_stderr_re = [
re.compile("Error: .*[\r\n]+"),
re.compile("(MINOR|MAJOR|CRITICAL): .*[\r\n]+"),
]
self.ipv4_address_re = re.compile(
r"(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}"
+ "(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))"
)
self.ipv6_address_re = re.compile(
r"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"
)
self.cmd_line_pattern_re = re.compile(r"\*?(.*?)(>.*)*#.*?")
if optional_args is None:
optional_args = {}
self.sros_get_format = optional_args.get("sros_get_format", "xml")
self.sros_compare_format = optional_args.get("sros_compare_format", "json")
self.port = optional_args.get("port", 830)
self.conn_ssh = optional_args.get("ssh_conn", None)
self.ssh_channel = optional_args.get("ssh_channel", None)
# locking variables
self.lock_disable = optional_args.get("lock_disable", False)
self.session_config_lock = optional_args.get("config_lock", False)
# namespace map
self.nsmap = {
"state_ns": "urn:nokia.com:sros:ns:yang:sr:state",
"configure_ns": "urn:nokia.com:sros:ns:yang:sr:conf",
}
self.optional_args = None
def open(self):
"""Implement the NAPALM method open (mandatory)"""
# Create a NETCONF connection to the host
try:
if self.manager:
self.conn = self.manager.connect()
else:
self.conn = manager.connect(
host=self.hostname,
port=self.port,
username=self.username,
password=self.password,
hostkey_verify=False,
timeout=self.timeout,
)
revision = re.compile( ".*&revision=(.*).*" )
self.state_revisions = [ revision.match(i).groups()[0] for i in self.conn.server_capabilities if "nokia-state" in i ]
log.info( self.state_revisions )
self.R19 = '2016-07-06' in self.state_revisions # Older SR OS release e.g. '2022-10-19' or '2016-07-06'
except ConnectionException as ce:
print("Error in opening netconf connection : {}".format(ce))
log.error(
"Error in opening netconf connection : %s" % traceback.format_exc()
)
except Exception as e:
print("Error in opening netconf connection : {}".format(e))
log.error(
"Error in opening netconf connection : %s" % traceback.format_exc()
)
def close(self):
"""Implement the NAPALM method close (mandatory)"""
# Close the NETCONF connection with the host
# netconf connection
if self.conn is not None:
self.conn.close_session()
# ssh connection
if self.conn_ssh is not None:
self.conn_ssh.close()
def _create_ssh(self):
try:
self.conn_ssh = paramiko.SSHClient()
self.conn_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.conn_ssh.connect(
hostname=self.hostname,
port=22,
username=self.username,
password=self.password,
timeout = self.timeout
)
self.ssh_channel = self.conn_ssh.invoke_shell()
except Exception as e:
print("Error in opening a ssh connection: {}".format(e))
log.error("Error in opening a ssh connection: %s" % traceback.format_exc())
def _perform_cli_commands(self, commands, is_get, no_more=False):
if no_more:
# Disable paged responses, note that the '/' changes the filenames
# for mocked data responses under test/unit/mocked_data
# - they now require a leading '_'
commands = ["/environment more false"] + commands
try:
is_alive = False
if self.conn_ssh is not None:
is_alive = self.conn_ssh.get_transport().is_active()
if not is_alive:
self._create_ssh()
buff = ""
if is_get:
for command in commands:
if "\n" not in command:
command = command + "\n"
self.ssh_channel.send(command)
while True:
time.sleep(0.150)
resp = self.ssh_channel.recv(9999)
buff += resp.decode("ascii")
if re.search(self.terminal_stdout_re[0], buff):
break
else:
# chunk commands into lists of length 500
# send all the 500 commands together
# receive the output from the router
# the last while loop is to ensure that we have received all the output
# from the router for the remaining commands
command_list = []
if len(commands) > 500:
n = 500
command_list = [
commands[i * n : (i + 1) * n]
for i in range((len(commands) + n - 1) // n)
]
else:
n = len(commands)
command_list = [
commands[i * n : (i + 1) * n]
for i in range((len(commands) + n - 1) // n)
]
if len(command_list) == 0:
pass
for command_set in command_list:
for command in command_set:
if "\n" not in command:
command = command + "\n"
if self.ssh_channel.send_ready():
self.ssh_channel.send(command)
time.sleep(0.1)
while self.ssh_channel.recv_ready():
time.sleep(0.1)
resp = self.ssh_channel.recv(999)
buff += resp.decode("ascii")
time.sleep(1.0)
while self.ssh_channel.recv_ready():
time.sleep(0.1)
resp = self.ssh_channel.recv(999)
buff += resp.decode("ascii")
return buff
except Exception as e:
print("Error in method perform cli commands : {}".format(e))
log.error("Error in _perform_cli_commands : %s" % traceback.format_exc())
return None
def _lock_config(self):
if not self.locked:
try:
self.conn.lock()
self.locked = True
except SessionLockedException as se:
print("Error in locking the session: {}".format(se))
log.error("Error in locking the session: %s" % traceback.format_exc())
except Exception as e:
print("Error in locking the session caused exception: {}".format(e))
log.error(
"Error in locking the session caused exception: %s" %
traceback.format_exc(),
)
def _unlock_config(self):
if self.locked:
try:
self.conn.unlock()
self.locked = False
except Exception as e:
print("Error in unlocking the session: {}".format(e))
log.error("Error in unlocking the session: %s" % traceback.format_exc())
def _find_txt(self, xml_tree, path, default="", namespaces=None):
"""
Extracts the text value from an XML tree, using XPath.
In case of error, will return a default value.
:param xml_tree: the XML Tree object. Assumed is <type 'lxml.etree._Element'>.
:param path: XPath to be applied, in order to extract the desired data.
:param default: Value to be returned in case of error.
:param namespaces: prefix-namespace mappings to process XPath
:return: a str value.
"""
value = ""
try:
xpath_applied = xml_tree.xpath(
path, namespaces=namespaces
) # will consider the first match only
xpath_length = len(xpath_applied) # get a count of items in XML tree
if xpath_length and xpath_applied[0] is not None:
xpath_result = xpath_applied[0]
if isinstance(xpath_result, type(xml_tree)):
if xpath_result.text is not None:
value = xpath_result.text.strip()
else:
value = xpath_result
else:
if xpath_applied == "":
log.error(
"Unable to find the specified-text-element/XML path: %s in \
the XML tree provided. Total Items in XML tree: %d "
% (path, xpath_length)
)
except Exception as e: # in case of any exception, returns default
print("Error while finding text in xml: {}".format(e))
log.error("Error while finding text in xml: %s" % traceback.format_exc())
value = default
return str(value)
def is_alive(self):
"""
Returns a flag with the connection state. Depends on the nature of API used by each driver.
The state does not reflect only on the connection status (when SSH), it must also take into
consideration other parameters,
e.g.: NETCONF session might not be usable, although the underlying
SSH session is still open etc.
"""
try:
is_alive_dict = {}
if self.conn is not None and self.conn_ssh is not None:
is_alive_dict.update({"is_alive": True})
else:
is_alive_dict.update({"is_alive": False})
return is_alive_dict
except Exception as e: # in case of any exception, returns default
print("Error occurred in is_alive method: {}".format(e))
log.error("Error occurred in is_alive: %s" % traceback.format_exc())
def discard_config(self):
"""
Discards the configuration loaded into the candidate.
"""
if self.fmt == "xml":
self.conn.discard_changes()
else:
self._perform_cli_commands(["discard"], True)
if not self.lock_disable and not self.session_config_lock:
self._unlock_config()
def commit_config(self, message="", revert_in=None):
"""
Commits the changes requested by the method load_replace_candidate or load_merge_candidate.
"""
if self.fmt == "text":
buff = self._perform_cli_commands(["commit"], True)
# If error while performing commit, return the error
error = ""
for item in buff.split("\n"):
if any(match.search(item) for match in self.terminal_stderr_re):
row = item.strip()
row_list = row.split(": ")
error += row_list[2]
if error:
log.error(f"Error during commit: {error}")
raise CommitError(error)
elif self.fmt == "xml":
self.conn.commit()
if not self.lock_disable and not self.session_config_lock:
self._unlock_config()
def rollback(self):
"""
If changes were made, revert changes to the original state.
"""
cmd = ["/quit-config", "/configure exclusive", "rollback 1", "commit", "exit"]
buff = self._perform_cli_commands(cmd, True)
error = ""
if buff is not None:
for item in buff.split("\n"):
if "MINOR: CLI #2069" in item:
continue
elif any(match.search(item) for match in self.terminal_stderr_re):
row = item.strip()
row_list = row.split(": ")
error += row_list[2]
if error:
log.error(f"Error during rollback: {error}")
raise CommandErrorException(error)
def compare_config(self):
"""
:return: A string showing the difference between the running configuration and the candidate
configuration. The running_config is loaded automatically just before doing the comparison
so there is no need for you to do it.
"""
buff = ""
if self.fmt == "text":
buff = self._perform_cli_commands( ["compare"], True, no_more=True )
# buff = self._perform_cli_commands(["/environment more false", "compare"])
else:
# if format is xml we convert them into dict and perform a diff on configs to return the difference
# running_dict = xmltodict.parse(running_config, process_namespaces=True)
running_dict = xmltodict.parse(
self.get_config(retrieve="running")["running"],
process_namespaces=self.sros_compare_format != "json",
)
# candidate_dict = xmltodict.parse(candidate_config, process_namespaces=True)
candidate_dict = xmltodict.parse(
self.get_config(retrieve="candidate")["candidate"],
process_namespaces=self.sros_compare_format != "json",
)
new_buff = ""
result = diff(running_dict, candidate_dict)
if self.sros_compare_format == "json":
new_buff += "\n".join(
[json.dumps(e, sort_keys=True, indent=4) for e in result]
)
else:
new_buff += " ".join([str(elem) for elem in result])
return new_buff
if buff is not None:
new_buff = ""
first_compare = False
for item in buff.split("\n"):
if any(match.search(item) for match in self.terminal_stderr_re):
row = item.strip()
new_buff += row
break
if not first_compare and "compare" in item:
first_compare = True
continue
elif re.search(r'\(ex\)\[\/?\]', item):
continue
elif "/environment more false" in item:
continue
elif self.cmd_line_pattern_re.search(item):
continue
elif self.terminal_stdout_re[0].search(item):
continue
else:
row = item.rstrip()
if row == "":
continue
if "configure" in row:
row = row.lstrip()
new_buff += row
new_buff += "\n"
return new_buff.rstrip("\n")
else:
return ""
def _determinne_config_format(self, config) -> str:
if config.strip().startswith("<"):
return "xml"
return "text"
def load_merge_candidate(self, filename=None, config=None):
"""
Populates the candidate configuration. You can populate it from a file or from a string.
If you send both a filename and a string containing the configuration, the file takes precedence.
If you use this method the existing configuration will be merged with the candidate configuration
once you commit the changes. This method will not change the configuration by itself.
:param filename: Path to the file containing the desired configuration. By default is None.
:param config: String containing the desired configuration.
Raises: MergeConfigException – If there is an error on the configuration sent.
"""
if filename is None:
configuration = config
else:
with open(filename) as f:
configuration = f.read()
self.fmt = self._determinne_config_format(configuration)
if self.fmt == "xml":
if not self.lock_disable and not self.session_config_lock:
self._lock_config()
configuration = etree.XML(configuration)
configuration_tree = etree.ElementTree(configuration)
root = configuration_tree.getroot()
if root.tag != "{urn:ietf:params:xml:ns:netconf:base:1.0}config":
newroot = etree.Element(
"{urn:ietf:params:xml:ns:netconf:base:1.0}config"
)
newroot.insert(0, root)
self.conn.edit_config(
config=newroot, target="candidate", default_operation="merge"
)
else:
self.conn.edit_config(
config=configuration,
target="candidate",
default_operation="merge",
)
self.conn.validate(source="candidate")
else:
configuration = configuration.split("\n")
configuration.insert(0, "edit-config exclusive")
buff = self._perform_cli_commands(configuration, False)
# error checking
if buff is not None:
for item in buff.split("\n"):
if any(match.search(item) for match in self.terminal_stderr_re):
log.error(f"Merge issue : {item}")
raise MergeConfigException("Merge issue: %s", item)
else:
raise MergeConfigException("Timeout during load_merge_candidate")
def load_replace_candidate(self, filename=None, config=None):
"""
Populates the candidate configuration. You can populate it from a file or from a string.
If you send both a filename and a string containing the configuration, the file takes
precedence.
If you use this method the existing configuration will be merged with the candidate
configuration once you commit the changes. This method will not change the configuration
by itself.
:param filename: Path to the file containing the desired configuration. By default is None.
:param config: String containing the desired configuration.
Raises: ReplaceConfigException – If there is an error on the configuration sent.
"""
if filename is None:
configuration = config
else:
with open(filename) as f:
configuration = f.read()
self.fmt = self._determinne_config_format(configuration)
if self.fmt == "xml":
if not self.lock_disable and not self.session_config_lock:
self._lock_config()
configuration = etree.XML(configuration)
configuration_tree = etree.ElementTree(configuration)
root = configuration_tree.getroot()
if root.tag != "{urn:ietf:params:xml:ns:netconf:base:1.0}config":
newroot = etree.Element(
"{urn:ietf:params:xml:ns:netconf:base:1.0}config"
)
newroot.insert(0, root)
self.conn.edit_config(
config=newroot, target="candidate", default_operation="replace",
)
else:
self.conn.edit_config(
config=configuration,
target="candidate",
default_operation="replace",
)
self.conn.validate(source="candidate")
else:
configuration = configuration.split("\n")
configuration.insert(0, "edit-config exclusive")
configuration.insert(1, "delete configure")
buff = self._perform_cli_commands(configuration, False)
# error checking
if buff is not None:
for item in buff.split("\n"):
if any(match.search(item) for match in self.terminal_stderr_re):
log.error( f"Replace issue: {item}" )
raise ReplaceConfigException("Replace issue: %s", item)
else:
raise ReplaceConfigException("Timeout during load_replace_candidate")
def get_facts(self):
"""
Returns a dictionary containing the following information:
uptime - Uptime of the device in seconds.
vendor - Manufacturer of the device.
model - Device model.
hostname - Hostname of the device
fqdn - Fqdn of the device
os_version - String with the OS version running on the device.
serial_number - Serial number of the device
interface_list - List of the interfaces of the device
"""
try:
interface_list = []
result = to_ele(self.conn.get(filter=GET_FACTS["_"]).data_xml)
hostname = self._find_txt(
result,
"state_ns:state/state_ns:system/state_ns:oper-name",
default="",
namespaces=self.nsmap,
)
fqdn = hostname
uptime = self._find_txt(
result,
"state_ns:state/state_ns:system/state_ns:up-time",
default="",
namespaces=self.nsmap,
)
# In uptime, last three digits are milliseconds
if uptime:
uptime = uptime[:-3]+ "." + uptime[-3:]
uptime = convert(float, uptime, default=0.0)
else:
uptime = -1.0
interfaces = result.xpath(
"state_ns:state/state_ns:router/state_ns:interface/state_ns:interface-name",
namespaces=self.nsmap,
)
for i in interfaces:
interface_list.append(i.text)
return {
"vendor": "Nokia",
"model": self._find_txt(
result,
"state_ns:state/state_ns:system/state_ns:platform",
default="",
namespaces=self.nsmap,
),
"serial_number": self._find_txt(
result,
"state_ns:state/state_ns:chassis/state_ns:hardware-data/state_ns:serial-number",
default="",
namespaces=self.nsmap,
),
"os_version": self._find_txt(
result,
"state_ns:state/state_ns:system/state_ns:version/state_ns:version-number",
default="",
namespaces=self.nsmap,
),
"hostname": hostname,
"fqdn": fqdn,
"uptime": uptime,
"interface_list": interface_list,
}
except Exception as e:
print("Error in method get facts : {}".format(e))
log.error("Error in method get facts : %s" % traceback.format_exc())
def get_interfaces(self):
# All physical ports and interfaces
# retrieval of management interface speed and mac is not implemented
"""
Returns a dictionary of dictionaries.
The keys for the first dictionary will be the interfaces in the devices.
The inner dictionary will containing the following data for each interface:
is_up (True/False)
is_enabled (True/False)
description (string)
last_flapped (float in seconds)
speed (float in Mbit)
MTU (in Bytes)
mac_address (string)
"""
try:
interfaces = {}
result = to_ele(
self.conn.get(
filter=GET_INTERFACES(R19=self.R19), with_defaults="report-all"
).data_xml
)
# get physical interfaces (ports) information
for port in result.xpath("state_ns:state/state_ns:port", namespaces=self.nsmap):
port_id = self._find_txt(
port, "state_ns:port-id", namespaces=self.nsmap
) # port name
if port_id == "":
continue
pd = {} # port dict
pd["mac_address"] = self._find_txt(
port, "state_ns:hardware-mac-address", namespaces=self.nsmap
)
pd["is_up"] = (
True
if self._find_txt(port, "state_ns:oper-state", namespaces=self.nsmap)
== "up"
else False
)
pd["speed"] = convert(
float,
self._find_txt(
port, "state_ns:ethernet/state_ns:oper-speed", namespaces=self.nsmap
),
)
pd["last_flapped"] = -1.0 # flap information is not available in YANG yet
pd["is_enabled"] = (
True
if self._find_txt(
result,
'configure_ns:configure/configure_ns:port[configure_ns:port-id="{}"]/configure_ns:admin-state'.format(
port_id
),
namespaces=self.nsmap,
)
== "enable"
else False
)
pd["mtu"] = convert(
int,
self._find_txt(
result,
'configure_ns:configure/configure_ns:port[configure_ns:port-id="{}"]/configure_ns:ethernet/configure_ns:mtu'.format(
port_id
),
namespaces=self.nsmap,
),
)
pd["description"] = self._find_txt(
result,
'configure_ns:configure/configure_ns:port[configure_ns:port-id="{}"]/configure_ns:description'.format(
port_id
),
namespaces=self.nsmap,
)
interfaces[port_id] = pd
# get logical interfaces (interfaces) information
for if_state in result.xpath(
"state_ns:state/state_ns:router/state_ns:interface", namespaces=self.nsmap
):
if_name = self._find_txt(
if_state, "state_ns:interface-name", namespaces=self.nsmap
)
if if_name == "":
continue
ifd = {} # interface dict
if_mac = ""
if_port = ""
# configuration portion of the interface
if_cfg_block = result.find(
f'configure_ns:configure/configure_ns:router/configure_ns:interface[configure_ns:interface-name="{if_name}"]',
self.nsmap,
)
if if_cfg_block is not None and len(if_cfg_block) > 0:
# description
ifd["description"] = self._find_txt(
if_cfg_block, "configure_ns:description", namespaces=self.nsmap
)
# MAC address
cfg_mac = self._find_txt(
if_cfg_block, "configure_ns:mac", namespaces=self.nsmap
)
# configured mac address
if cfg_mac != "":
if_mac = cfg_mac
# port info
_p = self._find_txt(
if_cfg_block, "configure_ns:port", namespaces=self.nsmap
)
if_port = (
_p.split(":")[0] if (_p != "" and ":" in _p) else ""
) # port name without .1q tag
# configured admin-state
ifd["is_enabled"] = (
True
if self._find_txt(
if_cfg_block, "configure_ns:admin-state", namespaces=self.nsmap
)
== "enable"
else False
)
# state portion of the port associated with interface
if_port_state_block = []
if if_port != "":
if_port_state_block = result.find(
f'state_ns:state/state_ns:port[state_ns:port-id="{if_port}"]',
self.nsmap,
)
if if_mac == "":
if if_name != "system":
# take port's MAC for non system interfaces
if if_port_state_block is not None and len(if_port_state_block) > 0:
if_mac = self._find_txt(
if_port_state_block,
"state_ns:hardware-mac-address",
namespaces=self.nsmap,
)
else:
# system interface gets chassis MAC
if_mac = self._find_txt(
result,
"state_ns:state/state_ns:chassis/state_ns:hardware-data/state_ns:base-mac-address",
namespaces=self.nsmap,
)
ifd["mac_address"] = if_mac
# speed is a port inherited value
if_speed = -1.0 # default value for system/loopback interface
if if_port:
if if_port_state_block is not None and len(if_port_state_block) > 0:
if_speed = convert(
float,
self._find_txt(
if_port_state_block,
"state_ns:ethernet/state_ns:oper-speed",
namespaces=self.nsmap,
),
)
ifd["speed"] = if_speed
ifd["is_up"] = self._find_txt(
if_state, "state_ns:if-oper-status" if self.R19 else "state_ns:oper-state",
namespaces=self.nsmap
) == "up"
flap_time = self._find_txt(
if_state, "state_ns:last-oper-change", namespaces=self.nsmap
)
ifd["last_flapped"] = (
datetime.datetime.strptime(
flap_time, "%Y-%m-%dT%H:%M:%S.%fZ"
).timestamp()
if flap_time != ""
else -1.0
)
ifd["mtu"] = convert(
int,
self._find_txt(if_state, "state_ns:oper-ip-mtu", namespaces=self.nsmap),
)
interfaces[if_name] = ifd
return interfaces
except Exception as e:
print("Error in method get interfaces : {}".format(e))
log.error("Error in method get interfaces : %s" % traceback.format_exc())
def get_interfaces_counters(self):
# (Statistics of all ports and router/interface is taken)
"""
Returns a dictionary of dictionaries where the first key is an interface name
and the inner dictionary contains the following keys:
tx_errors (int)
rx_errors (int)
tx_discards (int)
rx_discards (int)
tx_octets (int)
rx_octets (int)
tx_unicast_packets (int)
rx_unicast_packets (int)
tx_multicast_packets (int)
rx_multicast_packets (int)
tx_broadcast_packets (int)
rx_broadcast_packets (int)
"""
try:
interface_counters = {}
result = to_ele(
self.conn.get(
filter=GET_INTERFACES_COUNTERS["_"], with_defaults="report-all"
).data_xml
)
# Looping through port-list to get statistics of individual port
for port in result.xpath("state_ns:state/state_ns:port", namespaces=self.nsmap):
port_id = self._find_txt(port, "state_ns:port-id", namespaces=self.nsmap)
if port_id == "":
continue
interface_counters[port_id] = {
"tx_errors": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:out-errors",
namespaces=self.nsmap,
),
default=-1,
),
"rx_errors": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:in-errors",
namespaces=self.nsmap,
),
default=-1,
),
"tx_discards": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:out-discards",
namespaces=self.nsmap,
),
default=-1,
),
"rx_discards": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:in-discards",
namespaces=self.nsmap,
),
default=-1,
),
"tx_octets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:out-octets",
namespaces=self.nsmap,
),
default=-1,
),
"rx_octets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:in-octets",
namespaces=self.nsmap,
),
default=-1,
),
"tx_unicast_packets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:out-unicast-packets",
namespaces=self.nsmap,
),
default=-1,
),
"rx_unicast_packets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:in-unicast-packets",
namespaces=self.nsmap,
),
default=-1,
),
"tx_multicast_packets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:out-multicast-packets",
namespaces=self.nsmap,
),
default=-1,
),
"rx_multicast_packets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:in-multicast-packets",
namespaces=self.nsmap,
),
default=-1,
),
"tx_broadcast_packets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:out-broadcast-packets",
namespaces=self.nsmap,
),
default=-1,
),
"rx_broadcast_packets": convert(
int,
self._find_txt(
port,
"state_ns:statistics/state_ns:in-broadcast-packets",
namespaces=self.nsmap,
),
default=-1,
),
}
# Looping through interfaces-list to get statistics of interfaces port
for iface in result.xpath(
"state_ns:state/state_ns:router/state_ns:interface", namespaces=self.nsmap
):
if_name = self._find_txt(
iface, "state_ns:interface-name", namespaces=self.nsmap
)
if if_name == "":
continue
interface_counters[if_name] = {
"tx_errors": -1,
"rx_errors": -1,
"tx_discards": convert(
int,
self._find_txt(
iface,
"state_ns:statistics/state_ns:ip/state_ns:out-discard-packets",
namespaces=self.nsmap,
),
default=-1,
),
"rx_discards": -1,
"tx_octets": convert(
int,
self._find_txt(
iface,
"state_ns:statistics/state_ns:ip/state_ns:out-octets",
namespaces=self.nsmap,
),
default=-1,
),
"rx_octets": convert(
int,
self._find_txt(
iface,
"state_ns:statistics/state_ns:ip/state_ns:in-octets",
namespaces=self.nsmap,
),
default=-1,