[Python-modules-commits] [napalm-iosxr] 01/03: Import napalm-iosxr_0.3.2.orig.tar.gz

Vincent Bernat bernat at moszumanska.debian.org
Thu Nov 3 19:56:18 UTC 2016


This is an automated email from the git hooks/post-receive script.

bernat pushed a commit to branch master
in repository napalm-iosxr.

commit 0ea7741656790de22154e37e5800ceae46059a36
Author: Vincent Bernat <bernat at debian.org>
Date:   Thu Nov 3 20:53:27 2016 +0100

    Import napalm-iosxr_0.3.2.orig.tar.gz
---
 PKG-INFO                           |    6 +-
 napalm_iosxr.egg-info/PKG-INFO     |    6 +-
 napalm_iosxr.egg-info/SOURCES.txt  |    1 +
 napalm_iosxr.egg-info/requires.txt |    2 +-
 napalm_iosxr/__init__.py           |   15 +-
 napalm_iosxr/iosxr.py              | 1776 ++++++++++++++++++------------------
 requirements.txt                   |    2 +-
 setup.cfg                          |    7 +
 setup.py                           |    6 +-
 test/unit/TestIOSXRDriver.py       |   19 +-
 10 files changed, 926 insertions(+), 914 deletions(-)

diff --git a/PKG-INFO b/PKG-INFO
index ce48e66..d7f302a 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,10 +1,10 @@
 Metadata-Version: 1.1
 Name: napalm-iosxr
-Version: 0.2.2
+Version: 0.3.2
 Summary: Network Automation and Programmability Abstraction Layer with Multivendor support
 Home-page: https://github.com/napalm-automation/napalm-iosxr
-Author: David Barroso
-Author-email: dbarrosop at dravetech.com
+Author: David Barroso, Mircea Ulinic
+Author-email: dbarrosop at dravetech.com, mircea at cloudflare.com
 License: UNKNOWN
 Description: UNKNOWN
 Platform: UNKNOWN
diff --git a/napalm_iosxr.egg-info/PKG-INFO b/napalm_iosxr.egg-info/PKG-INFO
index ce48e66..d7f302a 100644
--- a/napalm_iosxr.egg-info/PKG-INFO
+++ b/napalm_iosxr.egg-info/PKG-INFO
@@ -1,10 +1,10 @@
 Metadata-Version: 1.1
 Name: napalm-iosxr
-Version: 0.2.2
+Version: 0.3.2
 Summary: Network Automation and Programmability Abstraction Layer with Multivendor support
 Home-page: https://github.com/napalm-automation/napalm-iosxr
-Author: David Barroso
-Author-email: dbarrosop at dravetech.com
+Author: David Barroso, Mircea Ulinic
+Author-email: dbarrosop at dravetech.com, mircea at cloudflare.com
 License: UNKNOWN
 Description: UNKNOWN
 Platform: UNKNOWN
diff --git a/napalm_iosxr.egg-info/SOURCES.txt b/napalm_iosxr.egg-info/SOURCES.txt
index f10aac1..dfccece 100644
--- a/napalm_iosxr.egg-info/SOURCES.txt
+++ b/napalm_iosxr.egg-info/SOURCES.txt
@@ -1,5 +1,6 @@
 MANIFEST.in
 requirements.txt
+setup.cfg
 setup.py
 napalm_iosxr/__init__.py
 napalm_iosxr/iosxr.py
diff --git a/napalm_iosxr.egg-info/requires.txt b/napalm_iosxr.egg-info/requires.txt
index 2a3c075..8361757 100644
--- a/napalm_iosxr.egg-info/requires.txt
+++ b/napalm_iosxr.egg-info/requires.txt
@@ -1,3 +1,3 @@
-napalm-base
+napalm-base>=0.18.0
 pyIOSXR>=0.20
 netaddr
diff --git a/napalm_iosxr/__init__.py b/napalm_iosxr/__init__.py
index f01b18e..73ba30a 100644
--- a/napalm_iosxr/__init__.py
+++ b/napalm_iosxr/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 # Copyright 2016 Dravetech AB. All rights reserved.
 #
 # The contents of this file are licensed under the Apache License, Version 2.0
@@ -13,4 +14,16 @@
 # the License.
 
 """napalm_iosxr package."""
-from iosxr import IOSXRDriver
+
+# Import stdlib
+import pkg_resources
+
+# Import local modules
+from napalm_iosxr.iosxr import IOSXRDriver  # noqa
+
+__all__ = ('IOSXRDriver',)
+
+try:
+    __version__ = pkg_resources.get_distribution('napalm-iosxr').version
+except pkg_resources.DistributionNotFound:
+    __version__ = "Not installed"
diff --git a/napalm_iosxr/iosxr.py b/napalm_iosxr/iosxr.py
index 66fe695..87812d3 100644
--- a/napalm_iosxr/iosxr.py
+++ b/napalm_iosxr/iosxr.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 # Copyright 2015 Spotify AB. All rights reserved.
 #
 # The contents of this file are licensed under the Apache License, Version 2.0
@@ -12,16 +13,17 @@
 # License for the specific language governing permissions and limitations under
 # the License.
 
-# python std lib
+from __future__ import unicode_literals
+
+# import stdlib
 import re
 import copy
 from collections import defaultdict
 
-# third party libs
+# import third party lib
 from lxml import etree as ETREE
-import xml.etree.ElementTree as ET
 
-from netaddr import IPAddress
+from netaddr import IPAddress  # needed for traceroute, to check IP version
 from netaddr.core import AddrFormatError
 
 from pyIOSXR import IOSXR
@@ -29,15 +31,20 @@ from pyIOSXR.exceptions import ConnectError
 from pyIOSXR.exceptions import TimeoutError
 from pyIOSXR.exceptions import InvalidInputError
 
-# napalm_base
-from napalm_base.helpers import convert, find_txt, mac, ip
+# import NAPALM base
+import napalm_base.helpers
 from napalm_base.base import NetworkDriver
-from napalm_base.utils import string_parsers
-from napalm_base.exceptions import ConnectionException, MergeConfigException, ReplaceConfigException,\
-                                   CommandErrorException, CommandTimeoutException
+from napalm_base.utils import py23_compat
+from napalm_base.exceptions import ConnectionException
+from napalm_base.exceptions import MergeConfigException
+from napalm_base.exceptions import ReplaceConfigException
+from napalm_base.exceptions import CommandTimeoutException
 
 
 class IOSXRDriver(NetworkDriver):
+
+    """IOS-XR driver class: inherits NetworkDriver from napalm_base."""
+
     def __init__(self, hostname, username, password, timeout=60, optional_args=None):
         self.hostname = hostname
         self.username = username
@@ -49,7 +56,12 @@ class IOSXRDriver(NetworkDriver):
             optional_args = {}
         self.port = optional_args.get('port', 22)
         self.lock_on_connect = optional_args.get('config_lock', True)
-        self.device = IOSXR(hostname, username, password, timeout=timeout, port=self.port, lock=self.lock_on_connect)
+        self.device = IOSXR(hostname,
+                            username,
+                            password,
+                            timeout=timeout,
+                            port=self.port,
+                            lock=self.lock_on_connect)
 
     def open(self):
         try:
@@ -112,25 +124,6 @@ class IOSXRDriver(NetworkDriver):
     def rollback(self):
         self.device.rollback()
 
-
-    # perhaps both should be moved in napalm_base.helpers at some point
-    @staticmethod
-    def _find_txt(xml_tree, path, default = ''):
-        try:
-            return xml_tree.find(path).text.strip()
-        except Exception:
-            return default
-
-
-    @staticmethod
-    def _convert(to, who, default = u''):
-        if who is None:
-            return default
-        try:
-            return to(who)
-        except:
-            return default
-
     def get_facts(self):
 
         facts = {
@@ -144,14 +137,8 @@ class IOSXRDriver(NetworkDriver):
             'interface_list': []
         }
 
-        facts_rpc_request = (
-            '<Get>'
-                '<Operational>'
-                    '<SystemTime/>'
-                    '<PlatformInventory/>'
-                '</Operational>'
-            '</Get>'
-        )
+        facts_rpc_request = '<Get><Operational><SystemTime/><PlatformInventory/>\
+        </Operational></Get>'
 
         facts_rpc_reply = ETREE.fromstring(self.device.make_rpc_call(facts_rpc_request))
         system_time_xpath = './/SystemTime/Uptime'
@@ -159,11 +146,16 @@ class IOSXRDriver(NetworkDriver):
         system_time_tree = facts_rpc_reply.xpath(system_time_xpath)[0]
         platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)[0]
 
-        hostname = convert(unicode, find_txt(system_time_tree, 'Hostname'))
-        uptime = convert(int, find_txt(system_time_tree, 'Uptime'), -1)
-        serial = convert(unicode, find_txt(platform_attr_tree, 'SerialNumber'))
-        os_version = convert(unicode, find_txt(platform_attr_tree, 'SoftwareRevision'))
-        model = convert(unicode, find_txt(platform_attr_tree, 'ModelName'))
+        hostname = napalm_base.helpers.convert(
+            unicode, napalm_base.helpers.find_txt(system_time_tree, 'Hostname'))
+        uptime = napalm_base.helpers.convert(
+            int, napalm_base.helpers.find_txt(system_time_tree, 'Uptime'), -1)
+        serial = napalm_base.helpers.convert(
+            unicode, napalm_base.helpers.find_txt(platform_attr_tree, 'SerialNumber'))
+        os_version = napalm_base.helpers.convert(
+            unicode, napalm_base.helpers.find_txt(platform_attr_tree, 'SoftwareRevision'))
+        model = napalm_base.helpers.convert(
+            unicode, napalm_base.helpers.find_txt(platform_attr_tree, 'ModelName'))
         interface_list = self.get_interfaces().keys()
 
         facts.update({
@@ -196,19 +188,23 @@ class IOSXRDriver(NetworkDriver):
         interfaces_rpc_reply = ETREE.fromstring(self.device.make_rpc_call(interfaces_rpc_request))
 
         for interface_tree in interfaces_rpc_reply.xpath('.//Interfaces/InterfaceTable/Interface'):
-            interface_name = find_txt(interface_tree, 'Naming/InterfaceName')
+            interface_name = napalm_base.helpers.find_txt(interface_tree, 'Naming/InterfaceName')
             if not interface_name:
                 continue
-            is_up = (find_txt(interface_tree, 'LineState') == 'IM_STATE_UP')
-            is_enabled = (find_txt(interface_tree, 'LineState') == 'IM_STATE_UP')
-            mac_address = mac(find_txt(interface_tree, 'MACAddress/Address'))
-            speed = int(convert(int, find_txt(interface_tree, 'Bandwidth'), 0) * 1e-3)
-            description = find_txt(interface_tree, 'Description')
+            is_up = (napalm_base.helpers.find_txt(interface_tree, 'LineState') == 'IM_STATE_UP')
+            enabled = (napalm_base.helpers.find_txt(interface_tree, 'State') == 'IM_STATE_UP')
+            raw_mac = napalm_base.helpers.find_txt(interface_tree, 'MACAddress/Address')
+            mac_address = napalm_base.helpers.convert(
+                napalm_base.helpers.mac, raw_mac, raw_mac)
+            speed = napalm_base.helpers.convert(
+                int, napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface_tree, 'Bandwidth'), 0) * 1e-3)
+            description = napalm_base.helpers.find_txt(interface_tree, 'Description')
             interfaces[interface_name] = copy.deepcopy(INTERFACE_DEFAULTS)
             interfaces[interface_name].update({
                 'is_up': is_up,
                 'speed': speed,
-                'is_enabled': is_enabled,
+                'is_enabled': enabled,
                 'mac_address': mac_address,
                 'description': description
             })
@@ -216,46 +212,55 @@ class IOSXRDriver(NetworkDriver):
         return interfaces
 
     def get_interfaces_counters(self):
-        rpc_command = "<Get><Operational><Interfaces><InterfaceTable></InterfaceTable></Interfaces></Operational></Get>"
-        result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
-
-        interface_counters = dict()
-
-        for interface in result_tree.iter('Interface'):
-
-            interface_name = interface.find('InterfaceHandle').text
+        rpc_command = '<Get><Operational><Interfaces><InterfaceTable></InterfaceTable>\
+        </Interfaces></Operational></Get>'
+        result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-            interface_stats = dict()
+        interface_counters = {}
 
-            if interface.find('InterfaceStatistics') is None:
+        for interface in result_tree.xpath('.//Interface'):
+            interface_name = napalm_base.helpers.find_txt(interface, 'InterfaceHandle')
+            interface_stats = {}
+            if not interface.xpath('InterfaceStatistics'):
                 continue
             else:
-                interface_stats = dict()
-                interface_stats['tx_multicast_packets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/MulticastPacketsSent').text)
-                interface_stats['tx_discards'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/OutputDrops').text)
-                interface_stats['tx_octets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/BytesSent').text)
-                interface_stats['tx_errors'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/OutputErrors').text)
-                interface_stats['rx_octets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/BytesReceived').text)
-                interface_stats['tx_unicast_packets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/PacketsSent').text)
-                interface_stats['rx_errors'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/InputErrors').text)
-                interface_stats['tx_broadcast_packets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/BroadcastPacketsSent').text)
-                interface_stats['rx_multicast_packets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/MulticastPacketsReceived').text)
-                interface_stats['rx_broadcast_packets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/BroadcastPacketsReceived').text)
-                interface_stats['rx_discards'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/InputDrops').text)
-                interface_stats['rx_unicast_packets'] = int(interface.find(
-                    'InterfaceStatistics/FullInterfaceStats/PacketsReceived').text)
-
+                interface_stats = {}
+                interface_stats['tx_multicast_packets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/MulticastPacketsSent'))
+                interface_stats['tx_discards'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/OutputDrops'))
+                interface_stats['tx_octets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/BytesSent'))
+                interface_stats['tx_errors'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/OutputErrors'))
+                interface_stats['rx_octets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/BytesReceived'))
+                interface_stats['tx_unicast_packets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/PacketsSent'))
+                interface_stats['rx_errors'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/InputErrors'))
+                interface_stats['tx_broadcast_packets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/BroadcastPacketsSent'))
+                interface_stats['rx_multicast_packets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/MulticastPacketsReceived'))
+                interface_stats['rx_broadcast_packets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/BroadcastPacketsReceived'))
+                interface_stats['rx_discards'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/InputDrops'))
+                interface_stats['rx_unicast_packets'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(interface,
+                        'InterfaceStatistics/FullInterfaceStats/PacketsReceived'))
             interface_counters[interface_name] = interface_stats
 
         return interface_counters
@@ -266,165 +271,132 @@ class IOSXRDriver(NetworkDriver):
             Helper to provide XML-query for the VRF-type we're interested in.
             """
             if vrf_name == "global":
-                rpc_command = """<Get>
-                        <Operational>
-                            <BGP>
-                                <InstanceTable>
-                                    <Instance>
-                                        <Naming>
-                                            <InstanceName>
-                                                default
-                                            </InstanceName>
-                                        </Naming>
-                                        <InstanceActive>
-                                            <DefaultVRF>
-                                                <GlobalProcessInfo>
-                                                </GlobalProcessInfo>
-                                                <NeighborTable>
-                                                </NeighborTable>
-                                            </DefaultVRF>
-                                        </InstanceActive>
-                                    </Instance>
-                                </InstanceTable>
-                            </BGP>
-                        </Operational>
-                    </Get>"""
+                rpc_command = '<Get><Operational><BGP><InstanceTable><Instance><Naming>\
+                <InstanceName>default</InstanceName></Naming><InstanceActive><DefaultVRF>\
+                <GlobalProcessInfo></GlobalProcessInfo><NeighborTable></NeighborTable></DefaultVRF>\
+                </InstanceActive></Instance></InstanceTable></BGP></Operational></Get>'
 
             else:
-                rpc_command = """<Get>
-                        <Operational>
-                            <BGP>
-                                <InstanceTable>
-                                    <Instance>
-                                        <Naming>
-                                            <InstanceName>
-                                                default
-                                            </InstanceName>
-                                        </Naming>
-                                        <InstanceActive>
-                                            <VRFTable>
-                                                <VRF>
-                                                    <Naming>
-                                                        %s
-                                                    </Naming>
-                                                    <GlobalProcessInfo>
-                                                    </GlobalProcessInfo>
-                                                    <NeighborTable>
-                                                    </NeighborTable>
-                                                </VRF>
-                                            </VRFTable>
-                                         </InstanceActive>
-                                    </Instance>
-                                </InstanceTable>
-                            </BGP>
-                        </Operational>
-                    </Get>""" % vrf_name
+                rpc_command = '<Get><Operational><BGP><InstanceTable><Instance><Naming>\
+                <InstanceName>default</InstanceName></Naming><InstanceActive><VRFTable><VRF>\
+                <Naming>{vrf_name}</Naming><GlobalProcessInfo></GlobalProcessInfo><NeighborTable>\
+                </NeighborTable></VRF></VRFTable></InstanceActive></Instance></InstanceTable>\
+                </BGP></Operational></Get>'.format(vrf_name=vrf_name)
             return rpc_command
 
         """
         Initial run to figure out what VRF's are available
-        Decided to get this one from Configured-section because bulk-getting all instance-data to do the same could get ridiculously heavy
+        Decided to get this one from Configured-section
+        because bulk-getting all instance-data to do the same could get ridiculously heavy
         Assuming we're always interested in the DefaultVRF
         """
 
         active_vrfs = ["global"]
 
-        rpc_command = """<Get>
-                            <Operational>
-                                <BGP>
-                                    <ConfigInstanceTable>
-                                        <ConfigInstance>
-                                            <Naming>
-                                                <InstanceName>
-                                                    default
-                                                </InstanceName>
-                                            </Naming>
-                                            <ConfigInstanceVRFTable>
-                                            </ConfigInstanceVRFTable>
-                                        </ConfigInstance>
-                                    </ConfigInstanceTable>
-                                </BGP>
-                            </Operational>
-                        </Get>"""
-
-        result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
-
-        for node in result_tree.iter('ConfigVRF'):
-            active_vrfs.append(str(node.find('Naming/VRFName').text))
-
-        result = dict()
+        rpc_command = '<Get><Operational><BGP><ConfigInstanceTable><ConfigInstance><Naming>\
+        <InstanceName>default</InstanceName></Naming><ConfigInstanceVRFTable>\
+        </ConfigInstanceVRFTable></ConfigInstance></ConfigInstanceTable></BGP></Operational></Get>'
+
+        result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
+
+        for node in result_tree.xpath('.//ConfigVRF'):
+            active_vrfs.append(napalm_base.helpers.find_txt(node, 'Naming/VRFName'))
+
+        result = {}
 
         for vrf in active_vrfs:
             rpc_command = generate_vrf_query(vrf)
-            result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
+            result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-            this_vrf = dict()
-            this_vrf['peers'] = dict()
+            this_vrf = {}
+            this_vrf['peers'] = {}
 
             if vrf == "global":
-                this_vrf['router_id'] = unicode(result_tree.find(
-                    'Get/Operational/BGP/InstanceTable/Instance/InstanceActive/DefaultVRF/GlobalProcessInfo/VRF/RouterID').text)
+                this_vrf['router_id'] = napalm_base.helpers.convert(
+                    unicode, napalm_base.helpers.find_txt(result_tree,
+                        'Get/Operational/BGP/InstanceTable/Instance/InstanceActive/DefaultVRF\
+                        /GlobalProcessInfo/VRF/RouterID'))
             else:
-                this_vrf['router_id'] = unicode(result_tree.find(
-                    'Get/Operational/BGP/InstanceTable/Instance/InstanceActive/VRFTable/VRF/GlobalProcessInfo/VRF/RouterID').text)
-
-            neighbors = dict()
-
-            for neighbor in result_tree.iter('Neighbor'):
-                this_neighbor = dict()
-                this_neighbor['local_as'] = int(neighbor.find('LocalAS').text)
-                this_neighbor['remote_as'] = int(neighbor.find('RemoteAS').text)
-                this_neighbor['remote_id'] = unicode(neighbor.find('RouterID').text)
-
-                if neighbor.find('ConnectionAdminStatus').text is "1":
+                this_vrf['router_id'] = napalm_base.helpers.convert(
+                    unicode, napalm_base.helpers.find_txt(result_tree,
+                        'Get/Operational/BGP/InstanceTable/Instance/InstanceActive/VRFTable/VRF\
+                        /GlobalProcessInfo/VRF/RouterID'))
+
+            neighbors = {}
+
+            for neighbor in result_tree.xpath('.//Neighbor'):
+                this_neighbor = {}
+                this_neighbor['local_as'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(neighbor, 'LocalAS'))
+                this_neighbor['remote_as'] = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(neighbor, 'RemoteAS'))
+                this_neighbor['remote_id'] = napalm_base.helpers.convert(
+                    unicode, napalm_base.helpers.find_txt(neighbor, 'RouterID'))
+
+                if napalm_base.helpers.find_txt(neighbor, 'ConnectionAdminStatus') is "1":
                     this_neighbor['is_enabled'] = True
                 try:
-                    this_neighbor['description'] = unicode(neighbor.find('Description').text)
+                    this_neighbor['description'] = napalm_base.helpers.convert(
+                        unicode, napalm_base.helpers.find_txt(neighbor, 'Description'))
                 except AttributeError:
                     this_neighbor['description'] = u''
 
-                this_neighbor['is_enabled'] = str(neighbor.find('ConnectionAdminStatus').text) is "1"
+                this_neighbor['is_enabled'] = (
+                    napalm_base.helpers.find_txt(neighbor, 'ConnectionAdminStatus') == "1")
 
-                if str(neighbor.find('ConnectionAdminStatus').text) is "1":
+                if str(napalm_base.helpers.find_txt(neighbor, 'ConnectionAdminStatus')) is "1":
                     this_neighbor['is_enabled'] = True
                 else:
                     this_neighbor['is_enabled'] = False
 
-                if str(neighbor.find('ConnectionState').text) == "BGP_ST_ESTAB":
+                if str(napalm_base.helpers.find_txt(neighbor, 'ConnectionState')) == "BGP_ST_ESTAB":
                     this_neighbor['is_up'] = True
-                    this_neighbor['uptime'] = int(neighbor.find('ConnectionEstablishedTime').text)
+                    this_neighbor['uptime'] = napalm_base.helpers.convert(
+                        int, napalm_base.helpers.find_txt(neighbor, 'ConnectionEstablishedTime'))
                 else:
                     this_neighbor['is_up'] = False
                     this_neighbor['uptime'] = -1
 
-                this_neighbor['address_family'] = dict()
+                this_neighbor['address_family'] = {}
 
-                if neighbor.find('ConnectionRemoteAddress/AFI').text == "IPv4":
+                if napalm_base.helpers.find_txt(neighbor,
+                'ConnectionRemoteAddress/AFI') == "IPv4":
                     this_afi = "ipv4"
-                elif neighbor.find('ConnectionRemoteAddress/AFI').text == "IPv6":
+                elif napalm_base.helpers.find_txt(neighbor,
+                'ConnectionRemoteAddress/AFI') == "IPv6":
                     this_afi = "ipv6"
                 else:
-                    this_afi = neighbor.find('ConnectionRemoteAddress/AFI').text
+                    this_afi = napalm_base.helpers.find_txt(neighbor, 'ConnectionRemoteAddress/AFI')
 
-                this_neighbor['address_family'][this_afi] = dict()
+                this_neighbor['address_family'][this_afi] = {}
 
                 try:
-                    this_neighbor['address_family'][this_afi][
-                        "received_prefixes"] = int(neighbor.find('AFData/Entry/PrefixesAccepted').text) + int(
-                            neighbor.find('AFData/Entry/PrefixesDenied').text)
-                    this_neighbor['address_family'][this_afi][
-                        "accepted_prefixes"] = int(neighbor.find('AFData/Entry/PrefixesAccepted').text)
-                    this_neighbor['address_family'][this_afi][
-                        "sent_prefixes"] = int(neighbor.find('AFData/Entry/PrefixesAdvertised').text)
+                    this_neighbor['address_family'][this_afi]["received_prefixes"] = \
+                        napalm_base.helpers.convert(int,
+                            napalm_base.helpers.find_txt(
+                                neighbor, 'AFData/Entry/PrefixesAccepted'), 0) + \
+                        napalm_base.helpers.convert(int,
+                            napalm_base.helpers.find_txt(
+                                neighbor, 'AFData/Entry/PrefixesDenied'), 0)
+                    this_neighbor['address_family'][this_afi]["accepted_prefixes"] = \
+                        napalm_base.helpers.convert(int,
+                            napalm_base.helpers.find_txt(
+                                neighbor, 'AFData/Entry/PrefixesAccepted'), 0)
+                    this_neighbor['address_family'][this_afi]["sent_prefixes"] = \
+                        napalm_base.helpers.convert(int,
+                            napalm_base.helpers.find_txt(
+                                neighbor, 'AFData/Entry/PrefixesAdvertised'), 0)
                 except AttributeError:
                     this_neighbor['address_family'][this_afi]["received_prefixes"] = -1
                     this_neighbor['address_family'][this_afi]["accepted_prefixes"] = -1
                     this_neighbor['address_family'][this_afi]["sent_prefixes"] = -1
 
-                try:
-                    neighbor_ip = unicode(neighbor.find('Naming/NeighborAddress/IPV4Address').text)
-                except AttributeError:
-                    neighbor_ip = unicode(neighbor.find('Naming/NeighborAddress/IPV6Address').text)
+                neighbor_ip = napalm_base.helpers.ip(
+                    napalm_base.helpers.find_txt(
+                        neighbor, 'Naming/NeighborAddress/IPV4Address') or
+                    napalm_base.helpers.find_txt(
+                        neighbor, 'Naming/NeighborAddress/IPV6Address')
+                )
 
                 neighbors[neighbor_ip] = this_neighbor
 
@@ -434,63 +406,34 @@ class IOSXRDriver(NetworkDriver):
         return result
 
     def get_environment(self):
-        def get_module_xml_query(module,selection):
-            return """<Get>
-                        <AdminOperational>
-                            <EnvironmentalMonitoring>
-                                <RackTable>
-                                    <Rack>
-                                        <Naming>
-                                            <rack>0</rack>
-                                        </Naming>
-                                        <SlotTable>
-                                            <Slot>
-                                                <Naming>
-                                                    <slot>%s</slot>
-                                                </Naming>
-                                                %s
-                                            </Slot>
-                                        </SlotTable>
-                                    </Rack>
-                                </RackTable>
-                            </EnvironmentalMonitoring>
-                        </AdminOperational>
-                    </Get>""" % (module,selection)
-
-        environment_status = dict()
-        environment_status['fans'] = dict()
-        environment_status['temperature'] = dict()
-        environment_status['power'] = dict()
-        environment_status['cpu'] = dict()
-        environment_status['memory'] = int()
+        def get_module_xml_query(module, selection):
+            return '<Get><AdminOperational><EnvironmentalMonitoring><RackTable><Rack><Naming>\
+            <rack>0</rack></Naming><SlotTable><Slot><Naming><slot>{slot}</slot></Naming>{name}\
+            </Slot></SlotTable></Rack></RackTable></EnvironmentalMonitoring></AdminOperational>\
+            </Get>'.format(slot=module, name=selection)
+
+        environment_status = {}
+        environment_status['fans'] = {}
+        environment_status['temperature'] = {}
+        environment_status['power'] = {}
+        environment_status['cpu'] = {}
+        environment_status['memory'] = 0.0
 
         # finding slots with equipment we're interested in
-        rpc_command = """<Get>
-            <AdminOperational>
-                <PlatformInventory>
-                    <RackTable>
-                        <Rack>
-                            <Naming>
-                                <Name>0</Name>
-                            </Naming>
-                            <SlotTable>
-                            </SlotTable>
-                        </Rack>
-                    </RackTable>
-                </PlatformInventory>
-            </AdminOperational>
-        </Get>"""
-
-        result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
+        rpc_command = '<Get><AdminOperational><PlatformInventory><RackTable><Rack><Naming>\
+        <Name>0</Name></Naming><SlotTable></SlotTable></Rack></RackTable></PlatformInventory>\
+        </AdminOperational></Get>'
 
-        active_modules = defaultdict(list)
+        result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-        for slot in result_tree.iter("Slot"):
-            for card in slot.iter("CardTable"):
-                #find enabled slots, figoure out type and save for later
-                if card.find('Card/Attributes/FRUInfo/ModuleAdministrativeState').text == "ADMIN_UP":
+        active_modules = defaultdict(list)
 
-                    slot_name = slot.find('Naming/Name').text
+        for slot in result_tree.xpath(".//Slot"):
+            for card in slot.xpath(".//CardTable"):
+                # find enabled slots, figoure out type and save for later
+                if napalm_base.helpers.find_txt(card,
+                'Card/Attributes/FRUInfo/ModuleAdministrativeState') == "ADMIN_UP":
+                    slot_name = napalm_base.helpers.find_txt(slot, 'Naming/Name')
                     module_type = re.sub("\d+", "", slot_name)
                     if len(module_type) > 0:
                         active_modules[module_type].append(slot_name)
@@ -505,21 +448,24 @@ class IOSXRDriver(NetworkDriver):
             if psu in ["PM6", "PM7"]:    # Cisco bug, chassis difference V01<->V02
                 continue
 
-            rpc_command = get_module_xml_query(psu,'')
-            result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
+            rpc_command = get_module_xml_query(psu, '')
+            result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-            psu_status = dict()
+            psu_status = {}
             psu_status['status'] = False
-            psu_status['capacity'] = float()
-            psu_status['output'] = float()
-
-            for sensor in result_tree.iter('SensorName'):
-                if sensor.find('Naming/Name').text == "host__VOLT":
-                    this_psu_voltage = float(sensor.find('ValueBrief').text)
-                elif sensor.find('Naming/Name').text == "host__CURR":
-                    this_psu_current = float(sensor.find('ValueBrief').text)
-                elif sensor.find('Naming/Name').text == "host__PM":
-                    this_psu_capacity = float(sensor.find('ValueBrief').text)
+            psu_status['capacity'] = 0.0
+            psu_status['output'] = 0.0
+
+            for sensor in result_tree.xpath('.//SensorName'):
+                if napalm_base.helpers.find_txt(sensor, 'Naming/Name') == "host__VOLT":
+                    this_psu_voltage = napalm_base.helpers.convert(
+                        float, napalm_base.helpers.find_txt(sensor, 'ValueBrief'))
+                elif napalm_base.helpers.find_txt(sensor, 'Naming/Name') == "host__CURR":
+                    this_psu_current = napalm_base.helpers.convert(
+                        float, napalm_base.helpers.find_txt(sensor, 'ValueBrief'))
+                elif napalm_base.helpers.find_txt(sensor, 'Naming/Name') == "host__PM":
+                    this_psu_capacity = napalm_base.helpers.convert(
+                        float, napalm_base.helpers.find_txt(sensor, 'ValueBrief'))
 
             if this_psu_capacity > 0:
                 psu_status['capacity'] = this_psu_capacity
@@ -534,19 +480,22 @@ class IOSXRDriver(NetworkDriver):
         # Memory
         #
 
-        rpc_command = "<Get><AdminOperational><MemorySummary></MemorySummary></AdminOperational></Get>"
-        result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
+        rpc_command = '<Get><AdminOperational><MemorySummary>\
+        </MemorySummary></AdminOperational></Get>'
+        result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-        for node in result_tree.iter('Node'):
-            print
-            if node.find('Naming/NodeName/Slot').text == active_modules['RSP'][0]:    # first enabled RSP
-                available_ram = int(node.find('Summary/SystemRAMMemory').text)
-                free_ram = int(node.find('Summary/FreeApplicationMemory').text)
+        for node in result_tree.xpath('.//Node'):
+            if napalm_base.helpers.find_txt(node,
+            'Naming/NodeName/Slot') == active_modules['RSP'][0]:
+                available_ram = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(node, 'Summary/SystemRAMMemory'))
+                free_ram = napalm_base.helpers.convert(
+                    int, napalm_base.helpers.find_txt(node, 'Summary/FreeApplicationMemory'))
                 break    # we're only looking at one of the RSP's
 
         if available_ram and free_ram:
             used_ram = available_ram - free_ram
-            memory = dict()
+            memory = {}
             memory['available_ram'] = available_ram
             memory['used_ram'] = used_ram
             environment_status['memory'] = memory
@@ -556,31 +505,37 @@ class IOSXRDriver(NetworkDriver):
         #
 
         for fan in active_modules['FT']:
-            rpc_command = get_module_xml_query(fan,'')
-            result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
-            for module in result_tree.iter('Module'):
-                for sensortype in module.iter('SensorType'):
-                    for sensorname in sensortype.iter('SensorNameTable'):
-                        if sensorname.find('SensorName/Naming/Name').text == "host__FanSpeed_0":
-                            environment_status['fans'][fan] = {'status': int(sensorname.find(
-                                'SensorName/ValueDetailed/Status').text) is 1}
+            rpc_command = get_module_xml_query(fan, '')
+            result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
+            for module in result_tree.xpath('.//Module'):
+                for sensortype in module.xpath('.//SensorType'):
+                    for sensorname in sensortype.xpath('.//SensorNameTable'):
+                        if napalm_base.helpers.find_txt(sensorname,
+                        'SensorName/Naming/Name') == "host__FanSpeed_0":
+                            environment_status['fans'][fan] = {
+                                'status': napalm_base.helpers.convert(
+                                    int, napalm_base.helpers.find_txt(sensorname,
+                                        'SensorName/ValueDetailed/Status')
+                                    ) == 1
+                            }
 
         #
         # CPU
         #
-        cpu = dict()
+        cpu = {}
 
-        rpc_command = "<Get><Operational><SystemMonitoring></SystemMonitoring></Operational></Get>"
-        result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
+        rpc_command = '<Get><Operational><SystemMonitoring></SystemMonitoring></Operational></Get>'
+        result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-        for module in result_tree.iter('CPUUtilization'):
-            this_cpu = dict()
-            this_cpu["%usage"] = float(module.find('TotalCPUFiveMinute').text)
+        for module in result_tree.xpath('.//CPUUtilization'):
+            this_cpu = {}
+            this_cpu["%usage"] = napalm_base.helpers.convert(
+                float, napalm_base.helpers.find_txt(module, 'TotalCPUFiveMinute'))
 
-            rack = module.find('Naming/NodeName/Rack').text
-            slot = module.find('Naming/NodeName/Slot').text
-            instance = module.find('Naming/NodeName/Instance').text
-            position =  "%s/%s/%s" % (rack,slot,instance)
+            rack = napalm_base.helpers.find_txt(module, 'Naming/NodeName/Rack')
+            slot = napalm_base.helpers.find_txt(module, 'Naming/NodeName/Slot')
+            instance = napalm_base.helpers.find_txt(module, 'Naming/NodeName/Instance')
+            position = "%s/%s/%s" % (rack, slot, instance)
 
             cpu[position] = this_cpu
 
@@ -590,29 +545,28 @@ class IOSXRDriver(NetworkDriver):
         # Temperature
         #
 
-        temperature = dict()
-
         slot_list = set()
         for category, slot in active_modules.iteritems():
             slot_list |= set(slot)
 
         for slot in slot_list:
-            rpc_command = get_module_xml_query(slot,'')
-            result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
-
-            for sensor in result_tree.findall(".//SensorName"):
-                if not sensor.find('Naming/Name').text == "host__Inlet0":
+            rpc_command = get_module_xml_query(slot, '')
+            result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
+            for sensor in result_tree.xpath(".//SensorName"):
+                if not napalm_base.helpers.find_txt(sensor, 'Naming/Name') == "host__Inlet0":
                     continue
-                this_reading = dict()
-                this_reading['temperature'] = float(sensor.find('ValueBrief').text)
-
-                threshold_value = [float(x.text) for x in sensor.findall("ThresholdTable/Threshold/ValueBrief")]
-
-                this_reading['is_alert'] = threshold_value[2] <= this_reading['temperature'] <= threshold_value[3]
-                this_reading['is_critical'] = threshold_value[4] <= this_reading['temperature'] <= threshold_value[5]
-
+                this_reading = {}
+                this_reading['temperature'] = napalm_base.helpers.convert(
+                    float, napalm_base.helpers.find_txt(sensor, 'ValueBrief'))
+                threshold_value = [
+                    napalm_base.helpers.convert(float, x.text)
+                    for x in sensor.xpath("ThresholdTable/Threshold/ValueBrief")
+                ]
+                this_reading['is_alert'] = \
+                    threshold_value[2] <= this_reading['temperature'] <= threshold_value[3]
+                this_reading['is_critical'] = \
+                    threshold_value[4] <= this_reading['temperature'] <= threshold_value[5]
                 this_reading['temperature'] = this_reading['temperature']/10
-
                 environment_status["temperature"][slot] = this_reading
 
         return environment_status
@@ -626,59 +580,64 @@ class IOSXRDriver(NetworkDriver):
         for n in sh_lldp:
             local_interface = n.split()[1]
             if local_interface not in lldp.keys():
-                lldp[local_interface] = list()
+                lldp[local_interface] = []
 
-            lldp[local_interface].append({'hostname': unicode(n.split()[0]), 'port': unicode(n.split()[4]), })
+            lldp[local_interface].append({
+                'hostname': napalm_base.helpers.convert(
+                    unicode, n.split()[0]),
+                'port': napalm_base.helpers.convert(
+                    unicode, n.split()[4])
+            })
 
         return lldp
 
-    def get_lldp_neighbors_detail(self, interface = ''):
+    def get_lldp_neighbors_detail(self, interface=''):
 
-        lldp_neighbors = dict()
+        lldp_neighbors = {}
 
         rpc_command = '<Get><Operational><LLDP></LLDP></Operational></Get>'
 
-        result_tree = ET.fromstring(self.device.make_rpc_call(rpc_command))
+        result_tree = ETREE.fromstring(self.device.make_rpc_call(rpc_command))
 
-        for neighbor in result_tree.findall('.//Neighbors/DetailTable/Detail/Entry'):
-            if neighbor is None:
-                continue
-            try:
-                interface_name      = unicode(neighbor.find('ReceivingInterfaceName').text)
-                parent_interface    = unicode(neighbor.find('ReceivingParentInterfaceName').text)
-                device_id           = unicode(neighbor.find('DeviceID').text)
-                chassis_id          = unicode(neighbor.find('ChassisID').text)
-                port_id             = unicode(neighbor.find('PortIDDetail').text)
-                port_descr          = unicode(neighbor.find('Detail/PortDescription').text)
-                system_name         = unicode(neighbor.find('Detail/SystemName').text)
-                system_descr        = unicode(neighbor.find('Detail/SystemDescription').text)
-                system_capabilities = unicode(neighbor.find('Detail/SystemCapabilities').text)
-                enabled_capabilities= unicode(neighbor.find('Detail/EnabledCapabilities').text)
-                # few other optional...
-                # time_remaining = neighbor.find('Detail/TimeRemaining').text
-                # media_attachement_unit_type = neighbor.find('Detail/MediaAttachmentUnitType').text
-                # port_vlan_id = neighbor.find('Detail/PortVlanID').text
-
-                if interface_name not in lldp_neighbors.keys():
-                    lldp_neighbors[interface_name] = list()
-                lldp_neighbors[interface_name].append({
-                    'parent_interface'              : parent_interface,
-                    'remote_chassis_id'             : chassis_id,
-                    'remote_port'                   : port_id,
-                    'remote_port_description'       : port_descr,
-                    'remote_system_name'            : system_name,
-                    'remote_system_description'     : system_descr,
-                    'remote_system_capab'           : system_capabilities,
-                    'remote_system_enable_capab'    :  enabled_capabilities
-                })
-            except Exception:
-                continue # jump to next neighbor
+        for neighbor in result_tree.xpath('.//Neighbors/DetailTable/Detail/Entry'):
+            interface_name = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'ReceivingInterfaceName'))
+            parent_interface = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'ReceivingParentInterfaceName'))
+            chassis_id_raw = napalm_base.helpers.find_txt(neighbor, 'ChassisID')
+            chassis_id = napalm_base.helpers.convert(
+                napalm_base.helpers.mac, chassis_id_raw, chassis_id_raw)
+            port_id = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'PortIDDetail'))
+            port_descr = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'Detail/PortDescription'))
+            system_name = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'Detail/SystemName'))
+            system_descr = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'Detail/SystemDescription'))
+            system_capabilities = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'Detail/SystemCapabilities'))
+            enabled_capabilities = napalm_base.helpers.convert(
+                unicode, napalm_base.helpers.find_txt(neighbor, 'Detail/EnabledCapabilities'))
+
+            if interface_name not in lldp_neighbors.keys():
+                lldp_neighbors[interface_name] = []
+            lldp_neighbors[interface_name].append({
+                'parent_interface': parent_interface,
+                'remote_chassis_id': chassis_id,
+                'remote_port': port_id,
+                'remote_port_description': port_descr,
+                'remote_system_name': system_name,
+                'remote_system_description': system_descr,
+                'remote_system_capab': system_capabilities,
+                'remote_system_enable_capab':  enabled_capabilities
+            })
 
         return lldp_neighbors
 
-    def cli(self, commands = None):
+    def cli(self, commands=None):
 
-        cli_output = dict()
+        cli_output = {}
 
         if type(commands) is not list:
             raise TypeError('Please enter a valid list of commands!')
@@ -687,28 +646,20 @@ class IOSXRDriver(NetworkDriver):
             try:
                 cli_output[unicode(command)] = unicode(self.device._execute_show(command))
             except TimeoutError:
-                cli_output[unicode(command)] = 'Execution of command "{command}" took too long! Please adjust your params!'.format(
-                    command = command
-                )
+                cli_output[unicode(command)] = 'Execution of command \
+                    "{command}" took too long! Please adjust your params!'.format(command=command)
                 raise CommandTimeoutException(str(cli_output))
-            except Exception as e:
-                cli_output[unicode(command)] = 'Unable to execute command "{cmd}": {err}'.format(
-                    cmd = command,
-                    err = e
-                )
-                raise CommandErrorException(str(cli_output))
 
         return cli_output
 
-
-    def get_bgp_config(self, group = '', neighbor = ''):
+    def get_bgp_config(self, group='', neighbor=''):
 
         bgp_config = {}
 
         # a helper
         def build_prefix_limit(af_table, limit, prefix_percent, prefix_timeout):
-            prefix_limit = dict()
-            inet  = False
+            prefix_limit = {}
+            inet = False
... 1526 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/napalm-iosxr.git



More information about the Python-modules-commits mailing list