[Python-modules-commits] [napalm-junos] 02/06: Import napalm-junos_0.4.2.orig.tar.gz

Vincent Bernat bernat at moszumanska.debian.org
Wed Nov 2 18:53:41 UTC 2016


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

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

commit b7eef5c8d53c0751b7d7e03c6023e8463d98b24d
Author: Vincent Bernat <bernat at debian.org>
Date:   Tue Nov 1 21:15:46 2016 +0100

    Import napalm-junos_0.4.2.orig.tar.gz
---
 PKG-INFO                           |   6 +-
 napalm_junos.egg-info/PKG-INFO     |   6 +-
 napalm_junos.egg-info/SOURCES.txt  |   1 +
 napalm_junos.egg-info/requires.txt |   2 +-
 napalm_junos/__init__.py           |  14 +-
 napalm_junos/junos.py              | 822 ++++++++++++++++++++++---------------
 napalm_junos/utils/__init__.py     |   2 +-
 napalm_junos/utils/junos_views.yml | 180 +++++---
 requirements.txt                   |   2 +-
 setup.cfg                          |   7 +
 setup.py                           |   6 +-
 11 files changed, 644 insertions(+), 404 deletions(-)

diff --git a/PKG-INFO b/PKG-INFO
index c66b72d..268abf9 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,10 +1,10 @@
 Metadata-Version: 1.1
 Name: napalm-junos
-Version: 0.2.1
+Version: 0.4.2
 Summary: Network Automation and Programmability Abstraction Layer with Multivendor support
 Home-page: https://github.com/napalm-automation/napalm-junos
-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_junos.egg-info/PKG-INFO b/napalm_junos.egg-info/PKG-INFO
index c66b72d..268abf9 100644
--- a/napalm_junos.egg-info/PKG-INFO
+++ b/napalm_junos.egg-info/PKG-INFO
@@ -1,10 +1,10 @@
 Metadata-Version: 1.1
 Name: napalm-junos
-Version: 0.2.1
+Version: 0.4.2
 Summary: Network Automation and Programmability Abstraction Layer with Multivendor support
 Home-page: https://github.com/napalm-automation/napalm-junos
-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_junos.egg-info/SOURCES.txt b/napalm_junos.egg-info/SOURCES.txt
index 8062c9d..08b5e5a 100644
--- a/napalm_junos.egg-info/SOURCES.txt
+++ b/napalm_junos.egg-info/SOURCES.txt
@@ -1,5 +1,6 @@
 MANIFEST.in
 requirements.txt
+setup.cfg
 setup.py
 napalm_junos/__init__.py
 napalm_junos/junos.py
diff --git a/napalm_junos.egg-info/requires.txt b/napalm_junos.egg-info/requires.txt
index 9baf4f6..528542d 100644
--- a/napalm_junos.egg-info/requires.txt
+++ b/napalm_junos.egg-info/requires.txt
@@ -1,2 +1,2 @@
-napalm-base
+napalm-base==0.17.0
 junos-eznc
diff --git a/napalm_junos/__init__.py b/napalm_junos/__init__.py
index d6e7728..c9096b6 100644
--- a/napalm_junos/__init__.py
+++ b/napalm_junos/__init__.py
@@ -12,5 +12,15 @@
 # License for the specific language governing permissions and limitations under
 # the License.
 
-"""napalm_iosxr package."""
-from junos import JunOSDriver
+"""napalm_junos package."""
+
+# Import stdlib
+import pkg_resources
+
+# Import local modules
+from junos import JunOSDriver  # noqa
+
+try:
+    __version__ = pkg_resources.get_distribution('napalm-junos').version
+except pkg_resources.DistributionNotFound:
+    __version__ = "Not installed"
diff --git a/napalm_junos/junos.py b/napalm_junos/junos.py
index e6d291c..58edef0 100644
--- a/napalm_junos/junos.py
+++ b/napalm_junos/junos.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,25 +13,47 @@
 # License for the specific language governing permissions and limitations under
 # the License.
 
+"""Driver for JunOS devices."""
+
+# import stdlib
 import re
 import collections
-from lxml.builder import E
+from copy import deepcopy
 
-from napalm_junos.utils import junos_views
-from napalm_base.base import NetworkDriver
+# import third party lib
+from lxml.builder import E
 
 from jnpr.junos import Device
 from jnpr.junos.utils.config import Config
-from jnpr.junos.exception import ConfigLoadError, ConnectTimeoutError
-from napalm_base.exceptions import ConnectionException, ReplaceConfigException, MergeConfigException,\
-                                   CommandErrorException
+from jnpr.junos.exception import ConfigLoadError
+from jnpr.junos.exception import RpcTimeoutError
+from jnpr.junos.exception import ConnectTimeoutError
 
+# 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
+from napalm_base.exceptions import MergeConfigException
+from napalm_base.exceptions import CommandErrorException
+from napalm_base.exceptions import ReplaceConfigException
+from napalm_base.exceptions import CommandTimeoutException
+
+# import local modules
+from napalm_junos.utils import junos_views
 
 
 class JunOSDriver(NetworkDriver):
+    """JunOSDriver class - inherits NetworkDriver from napalm_base."""
 
     def __init__(self, hostname, username, password, timeout=60, optional_args=None):
+        """
+        Initialise JunOS driver.
+
+        Optional args:
+            * port (int): custom port
+            * config_lock (True/False): lock configuration DB after the connection is established.
+        """
         self.hostname = hostname
         self.username = username
         self.password = password
@@ -46,26 +69,34 @@ class JunOSDriver(NetworkDriver):
         self.device = Device(hostname, user=username, password=password, port=self.port)
 
     def open(self):
+        """Open the connection wit the device."""
         try:
             self.device.open()
         except ConnectTimeoutError as cte:
             raise ConnectionException(cte.message)
         self.device.timeout = self.timeout
+        if hasattr(self.device, "cu"):
+            # make sure to remove the cu attr from previous session
+            # ValueError: requested attribute name cu already exists
+            del self.device.cu
         self.device.bind(cu=Config)
         if self.config_lock:
             self.lock()
 
     def close(self):
+        """Close the connection."""
         if self.config_lock:
             self.unlock()
         self.device.close()
 
     def lock(self):
+        """Lock the config DB."""
         if not self.locked:
             self.device.cu.lock()
             self.locked = True
 
     def unlock(self):
+        """Unlock the config DB."""
         if self.locked:
             self.device.cu.unlock()
             self.locked = False
@@ -92,14 +123,17 @@ class JunOSDriver(NetworkDriver):
                 raise MergeConfigException(e.message)
 
     def load_replace_candidate(self, filename=None, config=None):
+        """Open the candidate config and merge."""
         self.config_replace = True
         self._load_candidate(filename, config, True)
 
     def load_merge_candidate(self, filename=None, config=None):
+        """Open the candidate config and replace."""
         self.config_replace = False
         self._load_candidate(filename, config, False)
 
     def compare_config(self):
+        """Compare candidate config with running."""
         diff = self.device.cu.diff()
 
         if diff is None:
@@ -108,44 +142,27 @@ class JunOSDriver(NetworkDriver):
             return diff.strip()
 
     def commit_config(self):
+        """Commit configuration."""
         self.device.cu.commit()
         if not self.config_lock:
             self.unlock()
 
     def discard_config(self):
+        """Discard changes (rollback 0)."""
         self.device.cu.rollback(rb_id=0)
         if not self.config_lock:
             self.unlock()
 
     def rollback(self):
+        """Rollback to previous commit."""
         self.device.cu.rollback(rb_id=1)
         self.commit_config()
 
-
-    # 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):
-
+        """Return facts of the device."""
         output = self.device.facts
 
-        uptime = 0
+        uptime = '0'
         if 'RE0' in output:
             uptime = output['RE0']['up_time']
 
@@ -165,8 +182,7 @@ class JunOSDriver(NetworkDriver):
         }
 
     def get_interfaces(self):
-
-        # init result dict
+        """Return interfaces details."""
         result = {}
 
         interfaces = junos_views.junos_iface_table(self.device)
@@ -179,7 +195,10 @@ class JunOSDriver(NetworkDriver):
                 'is_enabled': interfaces[iface]['is_enabled'],
                 'description': (interfaces[iface]['description'] or u''),
                 'last_flapped': float((interfaces[iface]['last_flapped'] or -1)),
-                'mac_address': unicode((interfaces[iface]['mac_address'] or '')),
+                'mac_address': napalm_base.helpers.convert(
+                    napalm_base.helpers.mac,
+                    interfaces[iface]['mac_address'],
+                    unicode(interfaces[iface]['mac_address'])),
                 'speed': -1
             }
             # result[iface]['last_flapped'] = float(result[iface]['last_flapped'])
@@ -187,7 +206,7 @@ class JunOSDriver(NetworkDriver):
             match = re.search(r'(\d+)(\w*)', interfaces[iface]['speed'] or u'')
             if match is None:
                 continue
-            speed_value = self._convert(int, match.group(1), -1)
+            speed_value = napalm_base.helpers.convert(int, match.group(1), -1)
             if speed_value == -1:
                 continue
             speed_unit = match.group(2)
@@ -198,21 +217,23 @@ class JunOSDriver(NetworkDriver):
         return result
 
     def get_interfaces_counters(self):
+        """Return interfaces counters."""
         query = junos_views.junos_iface_counter_table(self.device)
         query.get()
-        interface_counters = dict()
+        interface_counters = {}
         for interface, counters in query.items():
             interface_counters[interface] = {k: v if v is not None else -1 for k, v in counters}
         return interface_counters
 
     def get_environment(self):
+        """Return environment details."""
         environment = junos_views.junos_enviroment_table(self.device)
         routing_engine = junos_views.junos_routing_engine_table(self.device)
         temperature_thresholds = junos_views.junos_temperature_thresholds(self.device)
         environment.get()
         routing_engine.get()
         temperature_thresholds.get()
-        environment_data = dict()
+        environment_data = {}
 
         for sensor_object, object_data in environment.items():
             structured_object_data = {k: v for k, v in object_data}
@@ -220,10 +241,10 @@ class JunOSDriver(NetworkDriver):
             if structured_object_data['class'] == 'Power':
                 # Create a dict for the 'power' key
                 try:
-                    environment_data['power'][sensor_object] = dict()
+                    environment_data['power'][sensor_object] = {}
                 except KeyError:
-                    environment_data['power'] = dict()
-                    environment_data['power'][sensor_object] = dict()
+                    environment_data['power'] = {}
+                    environment_data['power'][sensor_object] = {}
 
                 # Set these values to -1, because Junos does not provide them
                 environment_data['power'][sensor_object]['capacity'] = -1.0
@@ -232,23 +253,25 @@ class JunOSDriver(NetworkDriver):
             if structured_object_data['class'] == 'Fans':
                 # Create a dict for the 'fans' key
                 try:
-                    environment_data['fans'][sensor_object] = dict()
+                    environment_data['fans'][sensor_object] = {}
                 except KeyError:
-                    environment_data['fans'] = dict()
-                    environment_data['fans'][sensor_object] = dict()
+                    environment_data['fans'] = {}
+                    environment_data['fans'][sensor_object] = {}
 
-            if structured_object_data['status'] == 'OK' and structured_object_data['class'] == 'Power':
+            status = structured_object_data['status']
+            env_class = structured_object_data['class']
+            if (status == 'OK' and env_class == 'Power'):
                 # If status is Failed, Absent or Testing, set status to False.
                 environment_data['power'][sensor_object]['status'] = True
 
-            elif structured_object_data['status'] != 'OK' and structured_object_data['class'] == 'Power':
+            elif (status != 'OK' and env_class == 'Power'):
                 environment_data['power'][sensor_object]['status'] = False
 
-            elif structured_object_data['status'] == 'OK' and structured_object_data['class'] == 'Fans':
+            elif (status == 'OK' and env_class == 'Fans'):
                 # If status is Failed, Absent or Testing, set status to False.
                 environment_data['fans'][sensor_object]['status'] = True
 
-            elif structured_object_data['status'] != 'OK' and structured_object_data['class'] == 'Fans':
+            elif (status != 'OK' and env_class == 'Fans'):
                 environment_data['fans'][sensor_object]['status'] = False
 
             for temperature_object, temperature_data in temperature_thresholds.items():
@@ -256,57 +279,76 @@ class JunOSDriver(NetworkDriver):
                 if structured_object_data['class'] == 'Temp':
                     # Create a dict for the 'temperature' key
                     try:
-                        environment_data['temperature'][sensor_object] = dict()
+                        environment_data['temperature'][sensor_object] = {}
                     except KeyError:
-                        environment_data['temperature'] = dict()
-                        environment_data['temperature'][sensor_object] = dict()
-
-                    environment_data['temperature'][sensor_object]['temperature'] = float(structured_object_data['temperature'])
+                        environment_data['temperature'] = {}
+                        environment_data['temperature'][sensor_object] = {}
+                    # Check we have a temperature field in this class (See #66)
+                    if structured_object_data['temperature']:
+                        environment_data['temperature'][sensor_object]['temperature'] = \
+                            float(structured_object_data['temperature'])
                     # Set a default value (False) to the key is_critical and is_alert
                     environment_data['temperature'][sensor_object]['is_alert'] = False
                     environment_data['temperature'][sensor_object]['is_critical'] = False
                     # Check if the working temperature is equal to or higher than alerting threshold
-                    if structured_temperature_data['red-alarm'] <= structured_object_data['temperature']:
+                    temp = structured_object_data['temperature']
+                    if structured_temperature_data['red-alarm'] <= temp:
                         environment_data['temperature'][sensor_object]['is_critical'] = True
                         environment_data['temperature'][sensor_object]['is_alert'] = True
-                    elif structured_temperature_data['yellow-alarm'] <= structured_object_data['temperature']:
+                    elif structured_temperature_data['yellow-alarm'] <= temp:
                         environment_data['temperature'][sensor_object]['is_alert'] = True
 
         for routing_engine_object, routing_engine_data in routing_engine.items():
             structured_routing_engine_data = {k: v for k, v in routing_engine_data}
             # Create dicts for 'cpu' and 'memory'.
             try:
-                environment_data['cpu'][routing_engine_object] = dict()
-                environment_data['memory'] = dict()
+                environment_data['cpu'][routing_engine_object] = {}
+                environment_data['memory'] = {}
             except KeyError:
-                environment_data['cpu'] = dict()
-                environment_data['cpu'][routing_engine_object] = dict()
-                environment_data['memory'] = dict()
+                environment_data['cpu'] = {}
+                environment_data['cpu'][routing_engine_object] = {}
+                environment_data['memory'] = {}
             # Calculate the CPU usage by using the CPU idle value.
-            environment_data['cpu'][routing_engine_object]['%usage'] = 100.0 - structured_routing_engine_data['cpu-idle']
+            environment_data['cpu'][routing_engine_object]['%usage'] = \
+                100.0 - structured_routing_engine_data['cpu-idle']
             try:
-                environment_data['memory']['available_ram'] = int(structured_routing_engine_data['memory-dram-size'])
+                environment_data['memory']['available_ram'] = \
+                    int(structured_routing_engine_data['memory-dram-size'])
             except ValueError:
-                environment_data['memory']['available_ram'] = int(''.join(i for i in structured_routing_engine_data['memory-dram-size'] if i.isdigit()))
+                environment_data['memory']['available_ram'] = \
+                    int(
+                        ''.join(
+                            i for i in structured_routing_engine_data['memory-dram-size']
+                            if i.isdigit()
+                        )
+                    )
             # Junos gives us RAM in %, so calculation has to be made.
             # Sadly, bacause of this, results are not 100% accurate to the truth.
-            environment_data['memory']['used_ram'] = (environment_data['memory']['available_ram'] / 100 * structured_routing_engine_data['memory-buffer-utilization'])
+            environment_data['memory']['used_ram'] = \
+                (environment_data['memory']['available_ram'] / 100 *
+                    structured_routing_engine_data['memory-buffer-utilization'])
 
         return environment_data
 
     @staticmethod
     def _get_address_family(table):
         """
-        Function to derive address family from a junos table name
+        Function to derive address family from a junos table name.
+
         :params table: The name of the routing table
         :returns: address family
         """
         address_family_mapping = {
             'inet': 'ipv4',
-            'inet6': 'ipv6'
+            'inet6': 'ipv6',
+            'inetflow': 'flow'
         }
         family = table.split('.')[-2]
-        return address_family_mapping[family]
+        try:
+            address_family = address_family_mapping[family]
+        except KeyError:
+            address_family = family
+        return address_family
 
     def _parse_route_stats(self, neighbor):
         data = {}
@@ -337,10 +379,11 @@ class JunOSDriver(NetworkDriver):
             return value
 
     def get_bgp_neighbors(self):
+        """Return BGP neighbors details."""
         instances = junos_views.junos_route_instance_table(self.device)
         uptime_table = junos_views.junos_bgp_uptime_table(self.device)
         bgp_neighbors = junos_views.junos_bgp_table(self.device)
-        keys =['local_as', 'remote_as', 'is_up', 'is_enabled', 'description', 'remote_id']
+        keys = ['local_as', 'remote_as', 'is_up', 'is_enabled', 'description', 'remote_id']
         bgp_neighbor_data = {}
         for instance, instance_data in instances.get().items():
             if instance.startswith('__'):
@@ -350,11 +393,16 @@ class JunOSDriver(NetworkDriver):
             bgp_neighbor_data[instance_name] = {'peers': {}}
             for neighbor, data in bgp_neighbors.get(instance=instance).items():
                 neighbor_data = {k: v for k, v in data}
-                peer_ip = neighbor.split('+')[0]
+                peer_ip = napalm_base.helpers.ip(neighbor.split('+')[0])
                 if 'router_id' not in bgp_neighbor_data[instance_name]:
                     # we only need to set this once
-                    bgp_neighbor_data[instance_name]['router_id'] = unicode(neighbor_data['local_id'])
-                peer = {key:self._parse_value(value) for key, value in neighbor_data.iteritems() if key in keys}
+                    bgp_neighbor_data[instance_name]['router_id'] = \
+                        unicode(neighbor_data['local_id'])
+                peer = {
+                    key: self._parse_value(value)
+                    for key, value in neighbor_data.iteritems()
+                    if key in keys
+                }
                 peer['address_family'] = self._parse_route_stats(neighbor_data)
                 bgp_neighbor_data[instance_name]['peers'][peer_ip] = peer
             for neighbor, uptime in uptime_table.get(instance=instance).items():
@@ -365,29 +413,30 @@ class JunOSDriver(NetworkDriver):
         return bgp_neighbor_data
 
     def get_lldp_neighbors(self):
+        """Return LLDP neighbors details."""
         lldp = junos_views.junos_lldp_table(self.device)
         lldp.get()
 
         result = lldp.items()
 
-        neighbors = dict()
+        neighbors = {}
         for neigh in result:
             if neigh[0] not in neighbors.keys():
-                neighbors[neigh[0]] = list()
+                neighbors[neigh[0]] = []
             neighbors[neigh[0]].append({x[0]: unicode(x[1]) for x in neigh[1]})
 
         return neighbors
 
-
     def get_lldp_neighbors_detail(self, interface=''):
-
-        lldp_neighbors = dict()
+        """Detailed view of the LLDP neighbors."""
+        lldp_neighbors = {}
 
         lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device)
         lldp_table.get()
         interfaces = lldp_table.get().keys()
 
-        old_junos = self._convert(int, self.device.facts.get('version', '0.0').split('.')[0], '0') < 13
+        old_junos = napalm_base.helpers.convert(
+            int, self.device.facts.get('version', '0.0').split('.')[0], '0') < 13
 
         lldp_table.GET_RPC = 'get-lldp-interface-neighbors'
         if old_junos:
@@ -400,45 +449,37 @@ class JunOSDriver(NetworkDriver):
                 lldp_table.get(interface_device=interface)
             for item in lldp_table:
                 if interface not in lldp_neighbors.keys():
-                    lldp_neighbors[interface] = list()
+                    lldp_neighbors[interface] = []
                 lldp_neighbors[interface].append({
-                    'parent_interface'          : item.parent_interface,
-                    'remote_port'               : item.remote_port,
-                    'remote_chassis_id'         : item.remote_chassis_id,
-                    'remote_port'               : item.remote_port,
-                    'remote_port_description'   : item.remote_port_description,
-                    'remote_system_name'        : item.remote_system_name,
-                    'remote_system_description' : item.remote_system_description,
-                    'remote_system_capab'       : item.remote_system_capab,
+                    'parent_interface': item.parent_interface,
+                    'remote_port': item.remote_port,
+                    'remote_chassis_id': napalm_base.helpers.convert(
+                        napalm_base.helpers.mac, item.remote_chassis_id, item.remote_chassis_id),
+                    'remote_port_description': napalm_base.helpers.convert(
+                        unicode, item.remote_port_description),
+                    'remote_system_name': item.remote_system_name,
+                    'remote_system_description': item.remote_system_description,
+                    'remote_system_capab': item.remote_system_capab,
                     'remote_system_enable_capab': item.remote_system_enable_capab
                 })
 
         return lldp_neighbors
 
+    def cli(self, commands=None):
+        """Execute raw CLI commands and returns their output."""
+        cli_output = {}
 
-    def cli(self, commands = None):
-
-        cli_output = dict()
-
-        if type(commands) is not list:
+        if not isinstance(commands, list):
             raise TypeError('Please enter a valid list of commands!')
 
         for command in commands:
-            try:
-                cli_output[unicode(command)] = unicode(self.device.cli(command))
-            except Exception as e:
-                cli_output[unicode(command)] = 'Unable to execute command "{cmd}": {err}'.format(
-                    cmd = command,
-                    err = e
-                )
-                raise CommandErrorException(str(cli_output))
+            cli_output[unicode(command)] = unicode(self.device.cli(command))
 
         return cli_output
 
-
     def get_bgp_config(self, group='', neighbor=''):
-
-        def update_dict(d, u): # for deep dictionary update
+        """Return BGP configuration."""
+        def update_dict(d, u):  # for deep dictionary update
             for k, v in u.iteritems():
                 if isinstance(d, collections.Mapping):
                     if isinstance(v, collections.Mapping):
@@ -451,11 +492,10 @@ class JunOSDriver(NetworkDriver):
             return d
 
         def build_prefix_limit(**args):
-
             """
-            This helper will transform the lements of a dictionary into nested dictionaries:
-            Example:
+            Transform the lements of a dictionary into nested dictionaries.
 
+            Example:
                 {
                     'inet_unicast_limit': 500,
                     'inet_unicast_teardown_threshold': 95,
@@ -475,14 +515,12 @@ class JunOSDriver(NetworkDriver):
                         }
                     }
                 }
-
             """
-
-            prefix_limit = dict()
+            prefix_limit = {}
 
             for key, value in args.iteritems():
                 key_levels = key.split('_')
-                length     = len(key_levels)-1
+                length = len(key_levels)-1
                 temp_dict = {
                     key_levels[length]: value
                 }
@@ -519,7 +557,6 @@ class JunOSDriver(NetworkDriver):
         }
 
         _PEER_FIELDS_DATATYPE_MAP_ = {
-            'group': unicode,
             'authentication_key': unicode,
             'route_reflector_client': bool,
             'nhs': bool
@@ -546,69 +583,26 @@ class JunOSDriver(NetworkDriver):
             list: []
         }
 
-        bgp_config = dict()
+        bgp_config = {}
 
         if group:
             bgp = junos_views.junos_bgp_config_group_table(self.device)
-            bgp.get(group = group)
+            bgp.get(group=group)
         else:
             bgp = junos_views.junos_bgp_config_table(self.device)
             bgp.get()
-            neighbor = '' # if no group is set, no neighbor should be set either
+            neighbor = ''  # if no group is set, no neighbor should be set either
         bgp_items = bgp.items()
 
-        peers = junos_views.junos_bgp_config_peers_table(self.device)
-        peers.get() # unfortunately cannot add filters for group name of neighbor address
-        peers_items = peers.items()
-
-        bgp_neighbors = dict()
-
-        for bgp_group_neighbor in peers_items:
-            bgp_peer_address = bgp_group_neighbor[0]
-            if neighbor and bgp_peer_address != neighbor:
-                continue  # if filters applied, jump over all other neighbors
-            bgp_group_details = bgp_group_neighbor[1]
-            bgp_peer_details = {
-                field: _DATATYPE_DEFAULT_.get(datatype) \
-                for field, datatype in _PEER_FIELDS_DATATYPE_MAP_.iteritems() \
-                if '_prefix_limit' not in field
-            }
-            for elem in bgp_group_details:
-                if not('_prefix_limit' not in elem[0] and elem[1] is not None):
-                    continue
-                datatype = _PEER_FIELDS_DATATYPE_MAP_.get(elem[0])
-                default = _DATATYPE_DEFAULT_.get(datatype)
-                key = elem[0]
-                value = elem[1]
-                if key in ['export_policy', 'import_policy']:
-                    if isinstance(value, list):
-                        value = ' '.join(value)
-                bgp_peer_details.update({
-                    key: self._convert(datatype, value, default)
-                })
-            prefix_limit_fields = dict()
-            for elem in bgp_group_details:
-                if '_prefix_limit' in elem[0] and elem[1] is not None:
-                    datatype = _PEER_FIELDS_DATATYPE_MAP_.get(elem[0])
-                    default = _DATATYPE_DEFAULT_.get(datatype)
-                    prefix_limit_fields.update({
-                        elem[0].replace('_prefix_limit', ''): self._convert(datatype, elem[1], default)
-                    })
-            bgp_peer_details['prefix_limit'] = build_prefix_limit(**prefix_limit_fields)
-            # and all these things only because PyEZ cannto convert to a specifc datatype when retrieving config...
-            group = bgp_peer_details.pop('group')
-            if group not in bgp_neighbors.keys():
-                bgp_neighbors[group] = dict()
-            bgp_neighbors[group][bgp_peer_address] = bgp_peer_details
-            if neighbor and bgp_peer_address == neighbor:
-                break # found the desired neighbor
+        if neighbor:
+            neighbor_ip = napalm_base.helpers.ip(neighbor)
 
         for bgp_group in bgp_items:
             bgp_group_name = bgp_group[0]
             bgp_group_details = bgp_group[1]
             bgp_config[bgp_group_name] = {
-                field: _DATATYPE_DEFAULT_.get(datatype) \
-                for field, datatype in _GROUP_FIELDS_DATATYPE_MAP_.iteritems() \
+                field: _DATATYPE_DEFAULT_.get(datatype)
+                for field, datatype in _GROUP_FIELDS_DATATYPE_MAP_.iteritems()
                 if '_prefix_limit' not in field
             }
             for elem in bgp_group_details:
@@ -621,75 +615,123 @@ class JunOSDriver(NetworkDriver):
                 if key in ['export_policy', 'import_policy']:
                     if isinstance(value, list):
                         value = ' '.join(value)
+                if key == 'local_address':
+                    value = napalm_base.helpers.convert(
+                        napalm_base.helpers.ip, value, value)
+                if key == 'neighbors':
+                    bgp_group_peers = value
+                    continue
                 bgp_config[bgp_group_name].update({
-                    key: self._convert(datatype, value, default)
+                    key: napalm_base.helpers.convert(datatype, value, default)
                 })
-            prefix_limit_fields = dict()
+            prefix_limit_fields = {}
             for elem in bgp_group_details:
                 if '_prefix_limit' in elem[0] and elem[1] is not None:
                     datatype = _GROUP_FIELDS_DATATYPE_MAP_.get(elem[0])
                     default = _DATATYPE_DEFAULT_.get(datatype)
                     prefix_limit_fields.update({
-                        elem[0].replace('_prefix_limit', ''): self._convert(datatype, elem[1], default)
+                        elem[0].replace('_prefix_limit', ''):
+                            napalm_base.helpers.convert(datatype, elem[1], default)
                     })
             bgp_config[bgp_group_name]['prefix_limit'] = build_prefix_limit(**prefix_limit_fields)
-            bgp_config[bgp_group_name]['neighbors'] = bgp_neighbors.get(bgp_group_name, {})
 
-        return bgp_config
+            bgp_config[bgp_group_name]['neighbors'] = {}
+            for bgp_group_neighbor in bgp_group_peers.items():
+                bgp_peer_address = napalm_base.helpers.ip(bgp_group_neighbor[0])
+                if neighbor and bgp_peer_address != neighbor:
+                    continue  # if filters applied, jump over all other neighbors
+                bgp_group_details = bgp_group_neighbor[1]
+                bgp_peer_details = {
+                    field: _DATATYPE_DEFAULT_.get(datatype)
+                    for field, datatype in _PEER_FIELDS_DATATYPE_MAP_.iteritems()
+                    if '_prefix_limit' not in field
+                }
+                for elem in bgp_group_details:
+                    if not('_prefix_limit' not in elem[0] and elem[1] is not None):
+                        continue
+                    datatype = _PEER_FIELDS_DATATYPE_MAP_.get(elem[0])
+                    default = _DATATYPE_DEFAULT_.get(datatype)
+                    key = elem[0]
+                    value = elem[1]
+                    if key in ['export_policy', 'import_policy']:
+                        if isinstance(value, list):
+                            value = ' '.join(value)
+                    if key == 'local_address':
+                        value = napalm_base.helpers.convert(
+                            napalm_base.helpers.ip, value, value)
+                    bgp_peer_details.update({
+                        key: napalm_base.helpers.convert(datatype, value, default)
+                    })
+                prefix_limit_fields = {}
+                for elem in bgp_group_details:
+                    if '_prefix_limit' in elem[0] and elem[1] is not None:
+                        datatype = _PEER_FIELDS_DATATYPE_MAP_.get(elem[0])
+                        default = _DATATYPE_DEFAULT_.get(datatype)
+                        prefix_limit_fields.update({
+                            elem[0].replace('_prefix_limit', ''):
+                                napalm_base.helpers.convert(datatype, elem[1], default)
+                        })
+                bgp_peer_details['prefix_limit'] = build_prefix_limit(**prefix_limit_fields)
+                bgp_config[bgp_group_name]['neighbors'][bgp_peer_address] = bgp_peer_details
+                if neighbor and bgp_peer_address == neighbor_ip:
+                    break  # found the desired neighbor
 
-    def get_bgp_neighbors_detail(self, neighbor_address = ''):
+        return bgp_config
 
-        bgp_neighbors = dict()
+    def get_bgp_neighbors_detail(self, neighbor_address=''):
+        """Detailed view of the BGP neighbors operational data."""
+        bgp_neighbors = {}
 
-        bgp_neighbors_table  = junos_views.junos_bgp_neighbors_table(self.device)
+        bgp_neighbors_table = junos_views.junos_bgp_neighbors_table(self.device)
 
         bgp_neighbors_table.get(
-            neighbor_address = neighbor_address
+            neighbor_address=neighbor_address
         )
         bgp_neighbors_items = bgp_neighbors_table.items()
 
         default_neighbor_details = {
-            'up'                        : False,
-            'local_as'                  : 0,
-            'remote_as'                 : 0,
-            'local_address'             : u'',
-            'routing_table'             : u'',
-            'local_address_configured'  : False,
-            'local_port'                : 0,
-            'remote_address'            : u'',
-            'remote_port'               : 0,
-            'multihop'                  : False,
-            'multipath'                 : False,
-            'remove_private_as'         : False,
-            'import_policy'             : u'',
-            'export_policy'             : u'',
-            'input_messages'            : 0,
-            'output_messages'           : 0,
-            'input_updates'             : 0,
-            'output_updates'            : 0,
-            'messages_queued_out'       : 0,
-            'connection_state'          : u'',
-            'previous_connection_state' : u'',
-            'last_event'                : u'',
-            'suppress_4byte_as'         : False,
-            'local_as_prepend'          : False,
-            'holdtime'                  : 0,
-            'configured_holdtime'       : 0,
-            'keepalive'                 : 0,
-            'configured_keepalive'      : 0,
-            'active_prefix_count'       : 0,
-            'received_prefix_count'     : 0,
-            'accepted_prefix_count'     : 0,
-            'suppressed_prefix_count'   : 0,
-            'advertise_prefix_count'    : 0,
-            'flap_count'                : 0
+            'up': False,
+            'local_as': 0,
+            'remote_as': 0,
+            'router_id': u'',
+            'local_address': u'',
+            'routing_table': u'',
+            'local_address_configured': False,
+            'local_port': 0,
+            'remote_address': u'',
+            'remote_port': 0,
+            'multihop': False,
+            'multipath': False,
+            'remove_private_as': False,
+            'import_policy': u'',
+            'export_policy': u'',
+            'input_messages': -1,
+            'output_messages': -1,
+            'input_updates': -1,
+            'output_updates': -1,
+            'messages_queued_out': -1,
+            'connection_state': u'',
+            'previous_connection_state': u'',
+            'last_event': u'',
+            'suppress_4byte_as': False,
+            'local_as_prepend': False,
+            'holdtime': 0,
+            'configured_holdtime': 0,
+            'keepalive': 0,
+            'configured_keepalive': 0,
+            'active_prefix_count': -1,
+            'received_prefix_count': -1,
+            'accepted_prefix_count': -1,
+            'suppressed_prefix_count': -1,
+            'advertised_prefix_count': -1,
+            'flap_count': 0
         }
 
-        _OPTION_KEY_MAP_ = {
+        OPTION_KEY_MAP = {
             'RemovePrivateAS': 'remove_private_as',
-            'Multipath'      : 'multipath',
-            'Multihop'       : 'multihop',
-            'AddressFamily'  : 'local_address_configured'
+            'Multipath': 'multipath',
+            'Multihop': 'multihop',
+            'AddressFamily': 'local_address_configured'
             # 'AuthKey'        : 'authentication_key_set'
             # but other vendors do not specify if auth key is set
             # other options:
@@ -698,9 +740,7 @@ class JunOSDriver(NetworkDriver):
 
         for bgp_neighbor in bgp_neighbors_items:
             remote_as = int(bgp_neighbor[0])
-            if remote_as not in bgp_neighbors.keys():
-                bgp_neighbors[remote_as] = list()
-            neighbor_details = default_neighbor_details.copy()
+            neighbor_details = deepcopy(default_neighbor_details)
             neighbor_details.update(
                 {elem[0]: elem[1] for elem in bgp_neighbor[1] if elem[1] is not None}
             )
@@ -708,33 +748,46 @@ class JunOSDriver(NetworkDriver):
             if isinstance(options, str):
                 options_list = options.split()
                 for option in options_list:
-                    key = _OPTION_KEY_MAP_.get(option)
-                    if key is None:
-                        continue
-                    neighbor_details[key] = True
+                    key = OPTION_KEY_MAP.get(option)
+                    if key is not None:
+                        neighbor_details[key] = True
             four_byte_as = neighbor_details.pop('4byte_as', 0)
             local_address = neighbor_details.pop('local_address', '')
             local_details = local_address.split('+')
-            neighbor_details['local_address'] = unicode(local_details[0])
+            neighbor_details['local_address'] = napalm_base.helpers.convert(
+                napalm_base.helpers.ip, local_details[0], local_details[0])
             if len(local_details) == 2:
-                neighbor_details['local_port']= int(local_details[1])
+                neighbor_details['local_port'] = int(local_details[1])
             else:
-                neighbor_details['local_port']=179
+                neighbor_details['local_port'] = 179
             neighbor_details['suppress_4byte_as'] = (remote_as != four_byte_as)
             peer_address = neighbor_details.pop('peer_address', '')
             remote_details = peer_address.split('+')
-            neighbor_details['remote_address'] = unicode(remote_details[0])
+            neighbor_details['remote_address'] = napalm_base.helpers.convert(
+                napalm_base.helpers.ip, remote_details[0], remote_details[0])
             if len(remote_details) == 2:
-                neighbor_details['remote_port']    = int(remote_details[1])
+                neighbor_details['remote_port'] = int(remote_details[1])
             else:
                 neighbor_details['remote_port'] = 179
-            bgp_neighbors[remote_as].append(neighbor_details)
+            neighbors_rib = neighbor_details.pop('rib')
+            neighbors_rib_items = neighbors_rib.items()
+            for rib_entry in neighbors_rib_items:
+                _table = unicode(rib_entry[0])
+                if _table not in bgp_neighbors.keys():
+                    bgp_neighbors[_table] = {}
+                if remote_as not in bgp_neighbors[_table].keys():
+                    bgp_neighbors[_table][remote_as] = []
+                neighbor_rib_details = deepcopy(neighbor_details)
+                neighbor_rib_details.update({
+                    elem[0]: elem[1] for elem in rib_entry[1]
+                })
+                neighbor_rib_details['routing_table'] = unicode(_table)
+                bgp_neighbors[_table][remote_as].append(neighbor_rib_details)
 
         return bgp_neighbors
 
-
     def get_arp_table(self):
-
+        """Return the ARP table."""
         # could use ArpTable
         # from jnpr.junos.op.phyport import ArpTable
         # and simply use it
@@ -744,7 +797,7 @@ class JunOSDriver(NetworkDriver):
         #   - group by VLAN ID
         #   - hostname & TTE fields as well
 
-        arp_table = list()
+        arp_table = []
 
         arp_table_raw = junos_views.junos_arp_table(self.device)
         arp_table_raw.get()
@@ -754,15 +807,14 @@ class JunOSDriver(NetworkDriver):
             arp_entry = {
                 elem[0]: elem[1] for elem in arp_table_entry[1]
             }
-            tte = arp_entry.pop('tte')
-            arp_entry['age'] = tte
-            # must compute age based on TTE
+            arp_entry['mac'] = napalm_base.helpers.mac(arp_entry.get('mac'))
+            arp_entry['ip'] = napalm_base.helpers.ip(arp_entry.get('ip'))
             arp_table.append(arp_entry)
 
         return arp_table
 
     def get_ntp_peers(self):
-
+        """Return the NTP peers configured on the device."""
         ntp_table = junos_views.junos_ntp_peers_config_table(self.device)
         ntp_table.get()
 
@@ -771,15 +823,27 @@ class JunOSDriver(NetworkDriver):
         if not ntp_peers:
             return {}
 
-        return {unicode(peer[0]):{} for peer in ntp_peers}
+        return {napalm_base.helpers.ip(peer[0]): {} for peer in ntp_peers}
 
-    def get_ntp_stats(self):
+    def get_ntp_servers(self):
+        """Return the NTP servers configured on the device."""
+        ntp_table = junos_views.junos_ntp_servers_config_table(self.device)
+        ntp_table.get()
+
+        ntp_servers = ntp_table.items()
 
+        if not ntp_servers:
+            return {}
+
+        return {napalm_base.helpers.ip(server[0]): {} for server in ntp_servers}
+
... 831 lines suppressed ...

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



More information about the Python-modules-commits mailing list