Walid Osama | 18 Apr 16:57 2014
Picon

Problem running Ryu on mininet image

I'm trying to run Ryu - as the instructions said on the ryu website -  on my 
mininet image or any linux distribution as I don't have the option to use 
the precompiled ryu linux distribution.
I have encountered many problems and I have searched online for a lot of 
solutions to to no avail..
Here's the error I encounter

 mininet <at> mininet-vm:~/ryu$ PYTHONPATH=. ./bin/ryu-manager 
ryu/app/simple_switch.py
Traceback (most recent call last):
File "./bin/ryu-manager", line 18, in <module>
from ryu.cmd.manager import main
File "/home/mininet/ryu/ryu/cmd/manager.py", line 31, in <module>
from ryu import cfg
File "/home/mininet/ryu/ryu/cfg.py", line 17, in <module>
import oslo.config.cfg
ImportError: No module named oslo.config.cfg

I tried these solutions
1- Reinstalling Ryu
2- Trying another linux distribution
3- # apt-get install python-pip python-dev libxml2-dev libxslt-dev zlib1g-
dev
   # pip install ryu

I have found a similar problem online solved but the asker didn't specify 
how he solved the problem..
Here's his final response
"The problem was about missing packages such as python-oslo, python-netaddr 
etc. Now Ryu is running after installing those packages ""
(Continue reading)

Yuichi Ito | 18 Apr 09:38 2014
Picon

[PATCH] sw test tool: Fix to compare OFPMatch using masks without byte boundary

Mask lengths without byte boundary are fixed as follows:

 - VLAN_VID, from 16 bits (2 bytes) to 12 + 1 bits
 - IPV6_EXTHDR, from 16 bits (2 bytes) to 9 bits

Reported-by: Arne Goetje <arne_goetje@...>
Signed-off-by: Yuichi Ito <ito.yuichi0@...>
---
 ryu/tests/switch/tester.py |   15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/ryu/tests/switch/tester.py b/ryu/tests/switch/tester.py
index 8954b21..c557191 100644
--- a/ryu/tests/switch/tester.py
+++ b/ryu/tests/switch/tester.py
 <at>  <at>  -13,6 +13,7  <at>  <at> 
 # See the License for the specific language governing permissions and
 # limitations under the License.

+import binascii
 import inspect
 import json
 import logging
 <at>  <at>  -782,6 +783,8  <at>  <at>  class OfTester(app_manager.RyuApp):

         def __reasm_match(match):
             """ reassemble match_fields. """
+            mask_lengths = {'vlan_vid': 12 + 1,
+                            'ipv6_exthdr': 9}
             match_fields = list()
(Continue reading)

LIU, Kun | 18 Apr 01:58 2014
Picon

How to make NAT in a RYU-controlled Open vSwitch bridge ?

Hi, all,

  I managed to make VMs(with IP address in the same sub-net) in a RYU-controlled network ping each other successfully,  now I want to make the VMs could connect the Internet, here is my test: I assigned ip address 10.0.1.x to the VMs while assigned the gateway ip address 10.0.1.1 to the Open vSwitch bridge, and set iptables rules(SNAT) in the physical machine that run the Open vSwitch bridge. However, the result is confusing, when the packets from VMs get to the bridge successfully, it seems that the bridge only take actions like Output, SetField, etc, but cannot pass the packet to the physical machine’s OS kernel to handle the packets and do NAT, is that true? In my test, I ping the 10.0.1.1 from one VM(ip: 10.0.1.2), the ICMP request packets get to the Open vSwitch bridge, but the physical machine does no reply them.

  Is there any one can help me, please ? Thanks a lot.

 

 

Best regards,

Kun Liu

 

------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
_______________________________________________
Ryu-devel mailing list
Ryu-devel@...
https://lists.sourceforge.net/lists/listinfo/ryu-devel
minoton64jp . | 17 Apr 15:56 2014
Picon

[PATCH] packet lib: ipv6: Fix to calculate AH length

RFC2402 says:

    All IPv6 extension headers, as per RFC 1883, encode the "Hdr Ext Len" field by first
    subtracting 1 (64-bit word) from the header length (measured in 64-bit words).
    AH is an IPv6 extension header.  However, since its length is measured in 32-bit words,
    the "Payload Length" is calculated by subtracting 2 (32 bit words).

This patch fixes as follows:

    return (int(size) - 1) * 8 ->
    return (int(size) + 2) * 4
                      ^ ^    ^

Signed-off-by: TAKAHASHI Minoru <takahashi.minoru7-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
---
 ryu/lib/packet/ipv6.py |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ryu/lib/packet/ipv6.py b/ryu/lib/packet/ipv6.py
index 960f1ac..6b29a7c 100644
--- a/ryu/lib/packet/ipv6.py
+++ b/ryu/lib/packet/ipv6.py
<at> <at> -420,7 +420,7 <at> <at> class auth(header):
 
     <at> classmethod
     def _get_size(cls, size):
-        return (int(size) - 1) * 8
+        return (int(size) + 2) * 4
 
     <at> classmethod
     def parser(cls, buf):
--
1.7.10.4


------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
_______________________________________________
Ryu-devel mailing list
Ryu-devel@...
https://lists.sourceforge.net/lists/listinfo/ryu-devel
Takfarinas Saber | 16 Apr 15:26 2014
Picon

Problem while running stack.sh

Hi everybody,
I'm trying to use Ryu. I followed the tutoriel in https://github.com/osrg/ryu/wiki/RYU-OpenStack-Grizzly-environment-VM-image-file-HOWTO and everything worked find until the step of running the shell ./stack.sh.
It returns this error:
Waiting for Quantum to start...
+ timeout 60 sh -c 'while ! http_proxy= wget -q -O- http://192.168.0.10:9696; do sleep 1; done'
+ die 375 'Quantum did not start'
+ local exitcode=0
+ set +o xtrace
[ERROR] stack.sh:375 Quantum did not start

I wonder what I can do to solve this issue.
Thank you in advance for your help.

Regards,
Takfarinas
Ubunto 12.04 LTS

Specs:
  • 4th Generation Intel® Core™ i7-4702HQ Processor (6M Cache, up to 3.20 GHz)
  • 16GB1 DDR3L at 1600MHz
  • 256GB Solid State Drive Full Mini Card
------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
_______________________________________________
Ryu-devel mailing list
Ryu-devel@...
https://lists.sourceforge.net/lists/listinfo/ryu-devel
ISHIDA Wataru | 16 Apr 06:13 2014
Picon

[PATCH 2/3] bgp: use ryu bgp packet library instead of original one


Signed-off-by: ISHIDA Wataru <ishida.wataru-Zyj7fXuS5i5L9jVzuh4AOg <at> public.gmane.org>
---
 ryu/services/protocols/bgp/api/core.py             |    4 +-
 ryu/services/protocols/bgp/api/rtconf.py           |   12 +-
 ryu/services/protocols/bgp/base.py                 |   14 +-
 ryu/services/protocols/bgp/core.py                 |   29 +-
 .../protocols/bgp/core_managers/peer_manager.py    |   34 +-
 .../protocols/bgp/core_managers/table_manager.py   |   82 +++--
 ryu/services/protocols/bgp/info_base/base.py       |   17 +-
 ryu/services/protocols/bgp/info_base/ipv4.py       |    6 +-
 ryu/services/protocols/bgp/info_base/rtc.py        |    2 +-
 ryu/services/protocols/bgp/info_base/vpnv4.py      |    6 +-
 ryu/services/protocols/bgp/info_base/vpnv6.py      |    6 +-
 ryu/services/protocols/bgp/info_base/vrf.py        |   26 +-
 ryu/services/protocols/bgp/info_base/vrf4.py       |   14 +-
 ryu/services/protocols/bgp/info_base/vrf6.py       |   14 +-
 .../bgp/operator/commands/show/neighbor.py         |    8 +-
 .../protocols/bgp/operator/internal_api.py         |   25 +-
 ryu/services/protocols/bgp/operator/views/bgp.py   |   28 +-
 ryu/services/protocols/bgp/peer.py                 |  336 +++++++++++---------
 ryu/services/protocols/bgp/processor.py            |   38 +--
 ryu/services/protocols/bgp/rtconf/base.py          |   26 +-
 ryu/services/protocols/bgp/rtconf/common.py        |    8 +-
 ryu/services/protocols/bgp/rtconf/neighbors.py     |   61 ++--
 ryu/services/protocols/bgp/rtconf/vrfs.py          |   28 +-
 ryu/services/protocols/bgp/speaker.py              |  167 +++++-----
 ryu/services/protocols/bgp/utils/bgp.py            |   33 +-
 ryu/services/protocols/bgp/utils/rtfilter.py       |   23 +-
 26 files changed, 568 insertions(+), 479 deletions(-)

diff --git a/ryu/services/protocols/bgp/api/core.py b/ryu/services/protocols/bgp/api/core.py
index b90ff89..d8ee144 100644
--- a/ryu/services/protocols/bgp/api/core.py
+++ b/ryu/services/protocols/bgp/api/core.py
 <at>  <at>  -79,9 +79,9  <at>  <at>  def reset_neighor(ip_address):
     return True
 
 
-#==============================================================================
+# =============================================================================
 # Common configuration related APIs
-#==============================================================================
+# =============================================================================
 
  <at> register(name='comm_conf.get')
 def get_common_conf():
diff --git a/ryu/services/protocols/bgp/api/rtconf.py b/ryu/services/protocols/bgp/api/rtconf.py
index 98f51d9..bca6cc7 100644
--- a/ryu/services/protocols/bgp/api/rtconf.py
+++ b/ryu/services/protocols/bgp/api/rtconf.py
 <at>  <at>  -33,9 +33,9  <at>  <at>  from ryu.services.protocols.bgp.rtconf.vrfs import VrfConf
 LOG = logging.getLogger('bgpspeaker.api.rtconf')
 
 
-#==============================================================================
+# =============================================================================
 # Neighbor configuration related APIs
-#==============================================================================
+# =============================================================================
 
 
 def _get_neighbor_conf(neigh_ip_address):
 <at>  <at>  -112,9 +112,9  <at>  <at>  def get_neighbors_conf():
     return CORE_MANAGER.neighbors_conf.settings
 
 
-#==============================================================================
+# =============================================================================
 # VRF configuration related APIs
-#==============================================================================
+# =============================================================================
 
  <at> register(name='vrf.create')
 def create_vrf(**kwargs):
 <at>  <at>  -168,9 +168,9  <at>  <at>  def get_vrfs_conf():
     vrfs_conf = CORE_MANAGER.vrfs_conf
     return vrfs_conf.settings
 
-#==============================================================================
+# =============================================================================
 # network configuration related APIs
-#==============================================================================
+# =============================================================================
 
 
  <at> register(name='network.add')
diff --git a/ryu/services/protocols/bgp/base.py b/ryu/services/protocols/bgp/base.py
index 489ba3a..85795c5 100644
--- a/ryu/services/protocols/bgp/base.py
+++ b/ryu/services/protocols/bgp/base.py
 <at>  <at>  -23,7 +23,11  <at>  <at>  import traceback
 import weakref
 
 from eventlet.timeout import Timeout
-from ryu.services.protocols.bgp.protocols.bgp import nlri
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
 from ryu.services.protocols.bgp.utils.circlist import CircularListType
 from ryu.services.protocols.bgp.utils.evtlet import LoopingCall
 
 <at>  <at>  -42,10 +46,10  <at>  <at>  OrderedDict = OrderedDict
 
 
 # Currently supported address families.
-SUPPORTED_GLOBAL_RF = set([nlri.RF_IPv4_UC,
-                           nlri.RF_IPv4_VPN,
-                           nlri.RF_RTC_UC,
-                           nlri.RF_IPv6_VPN
+SUPPORTED_GLOBAL_RF = set([RF_IPv4_UC,
+                           RF_IPv4_VPN,
+                           RF_RTC_UC,
+                           RF_IPv6_VPN
                            ])
 
 
diff --git a/ryu/services/protocols/bgp/core.py b/ryu/services/protocols/bgp/core.py
index 42bbe15..f38ece1 100644
--- a/ryu/services/protocols/bgp/core.py
+++ b/ryu/services/protocols/bgp/core.py
 <at>  <at>  -21,9 +21,12  <at>  <at> 
 """
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp import exceptions
-from ryu.services.protocols.bgp.protocols.bgp import nlri
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
+from ryu.lib.packet.bgp import BGP_ERROR_CEASE
+from ryu.lib.packet.bgp import BGP_ERROR_SUB_CONNECTION_RESET
+from ryu.lib.packet.bgp import BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_INCOMPLETE
+
 from ryu.services.protocols.bgp.base import Activity
 from ryu.services.protocols.bgp.base import add_bgp_error_metadata
 from ryu.services.protocols.bgp.base import BGPSException
 <at>  <at>  -45,7 +48,7  <at>  <at>  LOG = logging.getLogger('bgpspeaker.core')
 CORE_IP = '0.0.0.0'
 
 # Required dictates that Origin attribute be incomplete
-EXPECTED_ORIGIN = pathattr.Origin.INCOMPLETE
+EXPECTED_ORIGIN = BGP_ATTR_ORIGIN_INCOMPLETE
 
 
  <at> add_bgp_error_metadata(code=CORE_ERROR_CODE, sub_code=1,
 <at>  <at>  -222,9 +225,9  <at>  <at>  class CoreService(Factory, Activity):
         server_thread.wait()
         processor_thread.wait()
 
-    #=========================================================================
+    # ========================================================================
     # RTC address family related utilities
-    #=========================================================================
+    # ========================================================================
 
     def update_rtfilters(self):
         """Updates RT filters for each peer.
 <at>  <at>  -271,7 +274,7  <at>  <at>  class CoreService(Factory, Activity):
             - `old_rts`: (set) of RTs that peers is no longer interested in.
         """
         for table in self._table_manager._global_tables.itervalues():
-            if table.route_family == nlri.RF_RTC_UC:
+            if table.route_family == RF_RTC_UC:
                 continue
             self._spawn('rt_filter_chg_%s' % peer,
                         self._rt_mgr.on_rt_filter_chg_sync_peer,
 <at>  <at>  -340,9 +343,9  <at>  <at>  class CoreService(Factory, Activity):
 
         return rtfilter_map
 
-    #=========================================================================
+    # ========================================================================
     # Peer or Neighbor related handles/utilities.
-    #=========================================================================
+    # ========================================================================
     def register_flexinet_sink(self, sink):
         self._sinks.add(sink)
 
 <at>  <at>  -408,8 +411,8  <at>  <at>  class CoreService(Factory, Activity):
             LOG.debug('Closed connection to %s:%s as it is not a recognized'
                       ' peer.' % (peer_addr, peer_port))
             # Send connection rejected notification as per RFC
-            code = exceptions.ConnRejected.CODE
-            subcode = exceptions.ConnRejected.SUB_CODE
+            code = BGP_ERROR_CEASE
+            subcode = BGP_ERROR_SUB_CONNECTION_RESET
             bgp_proto.send_notification(code, subcode)
         elif not (peer.in_idle() or peer.in_active() or peer.in_connect()):
             LOG.debug('Closing connection to %s:%s as we have connection'
 <at>  <at>  -417,8 +420,8  <at>  <at>  class CoreService(Factory, Activity):
                       ' i.e. connection resolution' %
                       (peer_addr, peer_port))
             # Send Connection Collision Resolution notification as per RFC.
-            code = exceptions.CollisionResolution.CODE
-            subcode = exceptions.CollisionResolution.SUB_CODE
+            code = BGP_ERROR_CEASE
+            subcode = BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION
             bgp_proto.send_notification(code, subcode)
         else:
             self._spawn_activity(bgp_proto, peer)
diff --git a/ryu/services/protocols/bgp/core_managers/peer_manager.py b/ryu/services/protocols/bgp/core_managers/peer_manager.py
index 1b92386..505ffc8 100644
--- a/ryu/services/protocols/bgp/core_managers/peer_manager.py
+++ b/ryu/services/protocols/bgp/core_managers/peer_manager.py
 <at>  <at>  -3,11 +3,15  <at>  <at>  import logging
 from ryu.services.protocols.bgp.base import SUPPORTED_GLOBAL_RF
 from ryu.services.protocols.bgp.model import OutgoingRoute
 from ryu.services.protocols.bgp.peer import Peer
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
-from ryu.services.protocols.bgp.protocols.bgp import nlri
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_COMMUNITIES
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
 from ryu.services.protocols.bgp.utils.bgp \
     import clone_path_and_update_med_for_target_neighbor
-
 LOG = logging.getLogger('bgpspeaker.core_managers.peer_manager')
 
 
 <at>  <at>  -64,7 +68,7  <at>  <at>  class PeerManager(object):
         non_rtc_peer_list = set()
         for peer in self._peers.itervalues():
             if (peer.in_established() and
-                    not peer.is_mpbgp_cap_valid(nlri.RF_RTC_UC)):
+                    not peer.is_mpbgp_cap_valid(RF_RTC_UC)):
                 non_rtc_peer_list.add(peer)
         return non_rtc_peer_list
 
 <at>  <at>  -115,8 +119,8  <at>  <at>  class PeerManager(object):
                     # wasn't set at all now it could have changed and we may
                     # need to set new value there
                     p = sent_route.path
-                    if p.med_set_by_target_neighbor\
-                            or p.get_pattr(pathattr.Med.ATTR_NAME) is None:
+                    if p.med_set_by_target_neighbor or p.get_pattr(
+                            BGP_ATTR_TYPE_MULTI_EXIT_DISC) is None:
                         sent_route.path = \
                             clone_path_and_update_med_for_target_neighbor(
                                 sent_route.path, peer.med
 <at>  <at>  -131,7 +135,7  <at>  <at>  class PeerManager(object):
 
         Skips making request to peer that have valid RTC capability.
         """
-        assert route_family != nlri.RF_RTC_UC
+        assert route_family != RF_RTC_UC
         for peer in self._peers.itervalues():
             # First check if peer is in established state
             if (peer.in_established and
 <at>  <at>  -139,7 +143,7  <at>  <at>  class PeerManager(object):
                 # family
                     peer.is_mbgp_cap_valid(route_family) and
                 # Check if peer has valid capability for RTC
-                    not peer.is_mbgp_cap_valid(nlri.RF_RTC_UC)):
+                    not peer.is_mbgp_cap_valid(RF_RTC_UC)):
                 peer.request_route_refresh(route_family)
 
     def make_route_refresh_request(self, peer_ip, *route_families):
 <at>  <at>  -185,7 +189,7  <at>  <at>  class PeerManager(object):
         match this setting.
         """
         # First check if for this peer mpbgp-rtc is valid.
-        if not peer.is_mbgp_cap_valid(nlri.RF_RTC_UC):
+        if not peer.is_mbgp_cap_valid(RF_RTC_UC):
             return
 
         neigh_conf = self._neighbors_conf.get_neighbor_conf(peer.ip_address)
 <at>  <at>  -209,7 +213,7  <at>  <at>  class PeerManager(object):
                 peer.communicate_path(best_path)
 
         # Also communicate EOR as per RFC
-        peer.enque_end_of_rib(nlri.RF_RTC_UC)
+        peer.enque_end_of_rib(RF_RTC_UC)
 
     def comm_all_best_paths(self, peer):
         """Shares/communicates current best paths with this peers.
 <at>  <at>  -221,7 +225,7  <at>  <at>  class PeerManager(object):
                   ' 1/132')
         # We will enqueue best path from all global destination.
         for route_family, table in self._table_manager.iter:
-            if route_family == nlri.RF_RTC_UC:
+            if route_family == RF_RTC_UC:
                 continue
             if peer.is_mbgp_cap_valid(route_family):
                 for dest in table.itervalues():
 <at>  <at>  -240,10 +244,10  <at>  <at>  class PeerManager(object):
         # Filter based on standard community
         # If new best path has community attribute, it should be taken into
         # account when sending UPDATE to peers.
-        comm_attr = new_best_path.get_pattr(pathattr.Community.ATTR_NAME)
+        comm_attr = new_best_path.get_pattr(BGP_ATTR_TYPE_COMMUNITIES)
         if comm_attr:
             comm_attr_na = comm_attr.has_comm_attr(
-                pathattr.Community.NO_ADVERTISE
+                BGPPathAttributeCommunities.NO_ADVERTISE
             )
             # If we have NO_ADVERTISE attribute is present, we do not send
             # UPDATE to any peers
 <at>  <at>  -277,7 +281,7  <at>  <at>  class PeerManager(object):
         if path_rts:
             # We add Default_RTC_NLRI to path RTs so that we can send it to
             # peers that have expressed interest in all paths
-            path_rts.append(nlri.RtNlri.DEFAULT_RT)
+            path_rts.append(RouteTargetMembershipNLRI.DEFAULT_RT)
             # All peers that do not have RTC capability qualify
             qualified_peers = set(self._get_non_rtc_peers())
             # Peers that have RTC capability and have common RT with the path
 <at>  <at>  -299,7 +303,7  <at>  <at>  class PeerManager(object):
         for route_family in SUPPORTED_GLOBAL_RF:
             # Since we are dealing with peers that do not support RTC,
             # ignore this address family
-            if route_family == nlri.RF_RTC_UC:
+            if route_family == RF_RTC_UC:
                 continue
 
             self.req_rr_to_non_rtc_peers(route_family)
diff --git a/ryu/services/protocols/bgp/core_managers/table_manager.py b/ryu/services/protocols/bgp/core_managers/table_manager.py
index 640b610..a701644 100644
--- a/ryu/services/protocols/bgp/core_managers/table_manager.py
+++ b/ryu/services/protocols/bgp/core_managers/table_manager.py
 <at>  <at>  -14,8 +14,21  <at>  <at>  from ryu.services.protocols.bgp.info_base.vrf6 import Vrf6Table
 from ryu.services.protocols.bgp.rtconf import vrfs
 from ryu.services.protocols.bgp.rtconf.vrfs import VRF_RF_IPV4
 from ryu.services.protocols.bgp.rtconf.vrfs import VRF_RF_IPV6
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
-from ryu.services.protocols.bgp.protocols.bgp import nlri
+
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import BGPPathAttributeNextHop
+from ryu.lib.packet.bgp import BGPPathAttributeOrigin
+from ryu.lib.packet.bgp import BGPPathAttributeAsPath
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
+from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_IGP
+from ryu.lib.packet.bgp import IPAddrPrefix
+from ryu.lib.packet.bgp import IP6AddrPrefix
+
 from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4
 from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4_prefix
 from ryu.services.protocols.bgp.utils.validation import is_valid_ipv6
 <at>  <at>  -150,16 +163,16  <at>  <at>  class TableCoreManager(object):
             )
 
         global_table = None
-        if route_family == nlri.RF_IPv4_UC:
+        if route_family == RF_IPv4_UC:
             global_table = self.get_ipv4_table()
 
-        elif route_family == nlri.RF_IPv4_VPN:
+        elif route_family == RF_IPv4_VPN:
             global_table = self.get_vpn4_table()
 
-        elif route_family == nlri.RF_IPv6_VPN:
+        elif route_family == RF_IPv6_VPN:
             global_table = self.get_vpn6_table()
 
-        elif route_family == nlri.RF_RTC_UC:
+        elif route_family == RF_RTC_UC:
             global_table = self.get_rtc_table()
 
         return global_table
 <at>  <at>  -184,12 +197,12  <at>  <at>  class TableCoreManager(object):
         Creates the table if it does not exist.
         """
 
-        vpn_table = self._global_tables.get(nlri.RF_IPv4_UC)
+        vpn_table = self._global_tables.get(RF_IPv4_UC)
         # Lazy initialize the table.
         if not vpn_table:
             vpn_table = Ipv4Table(self._core_service, self._signal_bus)
-            self._global_tables[nlri.RF_IPv4_UC] = vpn_table
-            self._tables[(None, nlri.RF_IPv4_UC)] = vpn_table
+            self._global_tables[RF_IPv4_UC] = vpn_table
+            self._tables[(None, RF_IPv4_UC)] = vpn_table
 
         return vpn_table
 
 <at>  <at>  -198,12 +211,12  <at>  <at>  class TableCoreManager(object):
 
         Creates the table if it does not exist.
         """
-        vpn_table = self._global_tables.get(nlri.RF_IPv6_VPN)
+        vpn_table = self._global_tables.get(RF_IPv6_VPN)
         # Lazy initialize the table.
         if not vpn_table:
             vpn_table = Vpnv6Table(self._core_service, self._signal_bus)
-            self._global_tables[nlri.RF_IPv6_VPN] = vpn_table
-            self._tables[(None, nlri.RF_IPv6_VPN)] = vpn_table
+            self._global_tables[RF_IPv6_VPN] = vpn_table
+            self._tables[(None, RF_IPv6_VPN)] = vpn_table
 
         return vpn_table
 
 <at>  <at>  -212,12 +225,12  <at>  <at>  class TableCoreManager(object):
 
         Creates the table if it does not exist.
         """
-        vpn_table = self._global_tables.get(nlri.RF_IPv4_VPN)
+        vpn_table = self._global_tables.get(RF_IPv4_VPN)
         # Lazy initialize the table.
         if not vpn_table:
             vpn_table = Vpnv4Table(self._core_service, self._signal_bus)
-            self._global_tables[nlri.RF_IPv4_VPN] = vpn_table
-            self._tables[(None, nlri.RF_IPv4_VPN)] = vpn_table
+            self._global_tables[RF_IPv4_VPN] = vpn_table
+            self._tables[(None, RF_IPv4_VPN)] = vpn_table
 
         return vpn_table
 
 <at>  <at>  -226,12 +239,12  <at>  <at>  class TableCoreManager(object):
 
         Creates the table if it does not exist.
         """
-        rtc_table = self._global_tables.get(nlri.RF_RTC_UC)
+        rtc_table = self._global_tables.get(RF_RTC_UC)
         # Lazy initialization of the table.
         if not rtc_table:
             rtc_table = RtcTable(self._core_service, self._signal_bus)
-            self._global_tables[nlri.RF_RTC_UC] = rtc_table
-            self._tables[(None, nlri.RF_RTC_UC)] = rtc_table
+            self._global_tables[RF_RTC_UC] = rtc_table
+            self._tables[(None, RF_RTC_UC)] = rtc_table
         return rtc_table
 
     def get_next_vpnv4_label(self):
 <at>  <at>  -379,7 +392,7  <at>  <at>  class TableCoreManager(object):
         for route_family in SUPPORTED_GLOBAL_RF:
             # TODO(PH): We currently do not install RT_NLRI paths based on
             # extended path attributes (RT)
-            if route_family == nlri.RF_RTC_UC:
+            if route_family == RF_RTC_UC:
                 continue
             table = self.get_global_table_by_route_family(route_family)
             uninteresting_dest_count += \
 <at>  <at>  -407,9 +420,9  <at>  <at>  class TableCoreManager(object):
         interested_tables = set()
 
         # Get route family of VRF to when this VPN Path can be imported to
-        route_family = nlri.RF_IPv4_UC
-        if vpn_path.route_family != nlri.RF_IPv4_VPN:
-            route_family = nlri.RF_IPv6_UC
+        route_family = RF_IPv4_UC
+        if vpn_path.route_family != RF_IPv4_VPN:
+            route_family = RF_IPv6_UC
         for rt in path_rts:
             rt_rf_id = rt + ':' + str(route_family)
             vrf_rt_tables = self._tables_for_rt.get(rt_rf_id)
 <at>  <at>  -454,7 +467,8  <at>  <at>  class TableCoreManager(object):
                                         'exist.' % route_dist)
             if not is_valid_ipv4_prefix(prefix) or not is_valid_ipv4(next_hop):
                 raise BgpCoreError(desc='Invalid Ipv4 prefix or nexthop.')
-            prefix = nlri.Ipv4(prefix)
+            ip, masklen = prefix.split('/')
+            prefix = IPAddrPrefix(int(masklen), ip)
         elif route_family == VRF_RF_IPV6:
             vrf_table = self._tables.get(table_id)
             if vrf_table is None:
 <at>  <at>  -462,24 +476,26  <at>  <at>  class TableCoreManager(object):
                                         'exist.' % route_dist)
             if not is_valid_ipv6_prefix(prefix) or not is_valid_ipv6(next_hop):
                 raise BgpCoreError(desc='Invalid Ipv6 prefix or nexthop.')
-            prefix = nlri.Ipv6(prefix)
+            ip6, masklen = prefix.split('/')
+            prefix = IP6AddrPrefix(int(masklen), ip6)
         return vrf_table.insert_vrf_path(
             prefix, next_hop=next_hop,
             gen_lbl=True
         )
 
     def add_to_ipv4_global_table(self, prefix):
-        _nlri = nlri.Ipv4(prefix)
+        ip, masklen = prefix.split('/')
+        _nlri = IPAddrPrefix(int(masklen), ip)
         src_ver_num = 1
         peer = None
         # set mandatory path attributes
-        nexthop = pathattr.NextHop("0.0.0.0")
-        origin = pathattr.Origin('igp')
-        aspath = pathattr.AsPath([[]])
+        nexthop = BGPPathAttributeNextHop("0.0.0.0")
+        origin = BGPPathAttributeOrigin(BGP_ATTR_ORIGIN_IGP)
+        aspath = BGPPathAttributeAsPath([[]])
 
         pathattrs = OrderedDict()
-        pathattrs[origin.ATTR_NAME] = origin
-        pathattrs[aspath.ATTR_NAME] = aspath
+        pathattrs[BGP_ATTR_TYPE_ORIGIN] = origin
+        pathattrs[BGP_ATTR_TYPE_AS_PATH] = aspath
 
         new_path = Ipv4Path(peer, _nlri, src_ver_num,
                             pattrs=pathattrs, nexthop=nexthop)
 <at>  <at>  -510,13 +526,15  <at>  <at>  class TableCoreManager(object):
             if not vrf_table:
                 raise BgpCoreError(desc='Vrf for route distinguisher %s does '
                                         'not exist.' % route_dist)
-            prefix = nlri.Ipv4(prefix)
+            ip, masklen = prefix.split('/')
+            prefix = IPAddrPrefix(int(masklen), ip)
         else:
             vrf_table = self._tables.get(table_id)
             if not vrf_table:
                 raise BgpCoreError(desc='Vrf for route distinguisher %s does '
                                         'not exist.' % route_dist)
-            prefix = nlri.Ipv6(prefix)
+            ip6, masklen = prefix.split('/')
+            prefix = IP6AddrPrefix(int(masklen), ip)
             # We do not check if we have a path to given prefix, we issue
         # withdrawal. Hence multiple withdrawals have not side effect.
         return vrf_table.insert_vrf_path(prefix, is_withdraw=True)
diff --git a/ryu/services/protocols/bgp/info_base/base.py b/ryu/services/protocols/bgp/info_base/base.py
index 408be52..c735c30 100644
--- a/ryu/services/protocols/bgp/info_base/base.py
+++ b/ryu/services/protocols/bgp/info_base/base.py
 <at>  <at>  -24,9 +24,9  <at>  <at>  from abc import abstractmethod
 from copy import copy
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RtNlri
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import ExtCommunity
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RouteTargetMembershipNLRI
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
 
 from ryu.services.protocols.bgp.base import OrderedDict
 from ryu.services.protocols.bgp.constants import VPN_TABLE
 <at>  <at>  -169,7 +169,7  <at>  <at>  class Table(object):
     def _validate_nlri(self, nlri):
         """Validated *nlri* is the type that this table stores/supports.
         """
-        if not nlri or not (nlri.route_family == self.route_family):
+        if not nlri or not (nlri.ROUTE_FAMILY == self.route_family):
             raise ValueError('Invalid Vpnv4 prefix given.')
 
     def _validate_path(self, path):
 <at>  <at>  -661,10 +661,10  <at>  <at>  class Path(object):
             - `is_withdraw`: (bool) True if this represents a withdrawal.
         """
         self.med_set_by_target_neighbor = med_set_by_target_neighbor
-        if nlri.route_family != self.__class__.ROUTE_FAMILY:
+        if nlri.ROUTE_FAMILY != self.__class__.ROUTE_FAMILY:
             raise ValueError('NLRI and Path route families do not'
                              ' match (%s, %s).' %
-                             (nlri.route_family, self.__class__.ROUTE_FAMILY))
+                             (nlri.ROUTE_FAMILY, self.__class__.ROUTE_FAMILY))
 
         # Currently paths injected directly into VRF has only one source
         # src_peer can be None to denote NC else has to be instance of Peer.
 <at>  <at>  -760,7 +760,8  <at>  <at>  class Path(object):
         return clone
 
     def get_rts(self):
-        extcomm_attr = self._path_attr_map.get(ExtCommunity.ATTR_NAME)
+        extcomm_attr = self._path_attr_map.get(
+            BGP_ATTR_TYPE_EXTENDED_COMMUNITIES)
         if extcomm_attr is None:
             rts = []
         else:
 <at>  <at>  -775,7 +776,7  <at>  <at>  class Path(object):
         curr_rts = self.get_rts()
         # Add default RT to path RTs so that we match interest for peers who
         # advertised default RT
-        curr_rts.append(RtNlri.DEFAULT_RT)
+        curr_rts.append(RouteTargetMembershipNLRI.DEFAULT_RT)
 
         return not interested_rts.isdisjoint(curr_rts)
 
diff --git a/ryu/services/protocols/bgp/info_base/ipv4.py b/ryu/services/protocols/bgp/info_base/ipv4.py
index e7bdd8f..f61bf7c 100644
--- a/ryu/services/protocols/bgp/info_base/ipv4.py
+++ b/ryu/services/protocols/bgp/info_base/ipv4.py
 <at>  <at>  -7,8 +7,8  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Ipv4
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
+from ryu.lib.packet.bgp import IPAddrPrefix
+from ryu.lib.packet.bgp import RF_IPv4_UC
 
 from ryu.services.protocols.bgp.info_base.base import Path
 from ryu.services.protocols.bgp.info_base.base import Table
 <at>  <at>  -63,7 +63,7  <at>  <at>  class Ipv4Path(Path):
     """Represents a way of reaching an VPNv4 destination."""
     ROUTE_FAMILY = RF_IPv4_UC
     VRF_PATH_CLASS = None  # defined in init - anti cyclic import hack
-    NLRI_CLASS = Ipv4
+    NLRI_CLASS = IPAddrPrefix
 
     def __init__(self, *args, **kwargs):
         super(Ipv4Path, self).__init__(*args, **kwargs)
diff --git a/ryu/services/protocols/bgp/info_base/rtc.py b/ryu/services/protocols/bgp/info_base/rtc.py
index fd65b13..6f6e332 100644
--- a/ryu/services/protocols/bgp/info_base/rtc.py
+++ b/ryu/services/protocols/bgp/info_base/rtc.py
 <at>  <at>  -19,7 +19,7  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
+from ryu.lib.packet.bgp import RF_RTC_UC
 
 from ryu.services.protocols.bgp.info_base.base import Destination
 from ryu.services.protocols.bgp.info_base.base import NonVrfPathProcessingMixin
diff --git a/ryu/services/protocols/bgp/info_base/vpnv4.py b/ryu/services/protocols/bgp/info_base/vpnv4.py
index 06bac84..26eeb96 100644
--- a/ryu/services/protocols/bgp/info_base/vpnv4.py
+++ b/ryu/services/protocols/bgp/info_base/vpnv4.py
 <at>  <at>  -19,8 +19,8  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Ipv4
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_VPN
+from ryu.lib.packet.bgp import IPAddrPrefix
+from ryu.lib.packet.bgp import RF_IPv4_VPN
 
 from ryu.services.protocols.bgp.info_base.vpn import VpnDest
 from ryu.services.protocols.bgp.info_base.vpn import VpnPath
 <at>  <at>  -51,7 +51,7  <at>  <at>  class Vpnv4Path(VpnPath):
     """Represents a way of reaching an VPNv4 destination."""
     ROUTE_FAMILY = RF_IPv4_VPN
     VRF_PATH_CLASS = None  # defined in init - anti cyclic import hack
-    NLRI_CLASS = Ipv4
+    NLRI_CLASS = IPAddrPrefix
 
     def __init__(self, *args, **kwargs):
         super(Vpnv4Path, self).__init__(*args, **kwargs)
diff --git a/ryu/services/protocols/bgp/info_base/vpnv6.py b/ryu/services/protocols/bgp/info_base/vpnv6.py
index 69950e7..d66e273 100644
--- a/ryu/services/protocols/bgp/info_base/vpnv6.py
+++ b/ryu/services/protocols/bgp/info_base/vpnv6.py
 <at>  <at>  -19,8 +19,8  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Ipv6
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_VPN
+from ryu.lib.packet.bgp import IP6AddrPrefix
+from ryu.lib.packet.bgp import RF_IPv6_VPN
 
 from ryu.services.protocols.bgp.info_base.vpn import VpnDest
 from ryu.services.protocols.bgp.info_base.vpn import VpnPath
 <at>  <at>  -51,7 +51,7  <at>  <at>  class Vpnv6Path(VpnPath):
     """Represents a way of reaching an VPNv4 destination."""
     ROUTE_FAMILY = RF_IPv6_VPN
     VRF_PATH_CLASS = None  # defined in init - anti cyclic import hack
-    NLRI_CLASS = Ipv6
+    NLRI_CLASS = IP6AddrPrefix
 
     def __init__(self, *args, **kwargs):
         super(Vpnv6Path, self).__init__(*args, **kwargs)
diff --git a/ryu/services/protocols/bgp/info_base/vrf.py b/ryu/services/protocols/bgp/info_base/vrf.py
index b2618a9..30b53a2 100644
--- a/ryu/services/protocols/bgp/info_base/vrf.py
+++ b/ryu/services/protocols/bgp/info_base/vrf.py
 <at>  <at>  -20,6 +20,15  <at>  <at> 
 import abc
 import logging
 
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
+from ryu.lib.packet.bgp import BGPPathAttributeOrigin
+from ryu.lib.packet.bgp import BGPPathAttributeAsPath
+from ryu.lib.packet.bgp import BGPPathAttributeExtendedCommunities
+from ryu.lib.packet.bgp import BGPPathAttributeMultiExitDisc
+
 from ryu.services.protocols.bgp.base import OrderedDict
 from ryu.services.protocols.bgp.constants import VPN_TABLE
 from ryu.services.protocols.bgp.constants import VRF_TABLE
 <at>  <at>  -30,7 +39,6  <at>  <at>  from ryu.services.protocols.bgp.utils.stats import LOCAL_ROUTES
 from ryu.services.protocols.bgp.utils.stats import REMOTE_ROUTES
 from ryu.services.protocols.bgp.utils.stats import RESOURCE_ID
 from ryu.services.protocols.bgp.utils.stats import RESOURCE_NAME
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
 
 LOG = logging.getLogger('bgpspeaker.info_base.vrf')
 
 <at>  <at>  -201,15 +209,15  <at>  <at>  class VrfTable(Table):
             # in the path. Hence we do not add these attributes here.
             from ryu.services.protocols.bgp.core import EXPECTED_ORIGIN
 
-            pattrs[pathattr.Origin.ATTR_NAME] = \
-                pathattr.Origin(EXPECTED_ORIGIN)
-            pattrs[pathattr.AsPath.ATTR_NAME] = pathattr.AsPath([])
-            pattrs[pathattr.ExtCommunity.ATTR_NAME] = pathattr.ExtCommunity(
+            pattrs[BGP_ATTR_TYPE_ORIGIN] = BGPPathAttributeOrigin(
+                EXPECTED_ORIGIN)
+            pattrs[BGP_ATTR_TYPE_AS_PATH] = BGPPathAttributeAsPath([])
+            pattrs[BGP_ATTR_TYPE_EXTENDED_COMMUNITIES] = \
+                BGPPathAttributeExtendedCommunities(
                 rt_list=vrf_conf.export_rts, soo_list=vrf_conf.soo_list)
             if vrf_conf.multi_exit_disc:
-                pattrs[pathattr.Med.ATTR_NAME] = pathattr.Med(
-                    vrf_conf.multi_exit_disc
-                )
+                pattrs[BGP_ATTR_TYPE_MULTI_EXIT_DISC] = \
+                    BGPPathAttributeMultiExitDisc(vrf_conf.multi_exit_disc)
 
             table_manager = self._core_service.table_manager
             if gen_lbl and next_hop:
 <at>  <at>  -526,5 +534,5  <at>  <at>  class VrfRtImportMap(ImportMap):
         self._rt = rt
 
     def match(self, vrf_path):
-        extcomm = vrf_path.pathattr_map.get('extcommunity')
+        extcomm = vrf_path.pathattr_map.get(BGP_ATTR_TYPE_EXTENDED_COMMUNITIES)
         return extcomm is not None and self._rt in extcomm.rt_list
diff --git a/ryu/services/protocols/bgp/info_base/vrf4.py b/ryu/services/protocols/bgp/info_base/vrf4.py
index 4e2d7f2..1a00b39 100644
--- a/ryu/services/protocols/bgp/info_base/vrf4.py
+++ b/ryu/services/protocols/bgp/info_base/vrf4.py
 <at>  <at>  -21,10 +21,10  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Ipv4
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Vpnv4
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import IPAddrPrefix
+from ryu.lib.packet.bgp import LabelledVPNIPAddrPrefix
 
 from ryu.services.protocols.bgp.info_base.vpnv4 import Vpnv4Path
 from ryu.services.protocols.bgp.info_base.vrf import VrfDest
 <at>  <at>  -39,7 +39,7  <at>  <at>  class Vrf4Path(VrfPath):
     """Represents a way of reaching an IP destination with a VPN."""
     ROUTE_FAMILY = RF_IPv4_UC
     VPN_PATH_CLASS = Vpnv4Path
-    VPN_NLRI_CLASS = Vpnv4
+    VPN_NLRI_CLASS = LabelledVPNIPAddrPrefix
 
 
 class Vrf4Dest(VrfDest):
 <at>  <at>  -50,11 +50,11  <at>  <at>  class Vrf4Table(VrfTable):
     """Virtual Routing and Forwarding information base for IPv4."""
     ROUTE_FAMILY = RF_IPv4_UC
     VPN_ROUTE_FAMILY = RF_IPv4_VPN
-    NLRI_CLASS = Ipv4
+    NLRI_CLASS = IPAddrPrefix
     VRF_PATH_CLASS = Vrf4Path
     VRF_DEST_CLASS = Vrf4Dest
 
 
 class Vrf4NlriImportMap(VrfNlriImportMap):
     VRF_PATH_CLASS = Vrf4Path
-    NLRI_CLASS = Ipv4
+    NLRI_CLASS = IPAddrPrefix
diff --git a/ryu/services/protocols/bgp/info_base/vrf6.py b/ryu/services/protocols/bgp/info_base/vrf6.py
index c011d79..f293932 100644
--- a/ryu/services/protocols/bgp/info_base/vrf6.py
+++ b/ryu/services/protocols/bgp/info_base/vrf6.py
 <at>  <at>  -21,10 +21,10  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Ipv6
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import Vpnv6
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import IP6AddrPrefix
+from ryu.lib.packet.bgp import LabelledVPNIP6AddrPrefix
 
 from ryu.services.protocols.bgp.info_base.vpnv6 import Vpnv6Path
 from ryu.services.protocols.bgp.info_base.vrf import VrfDest
 <at>  <at>  -39,7 +39,7  <at>  <at>  class Vrf6Path(VrfPath):
     """Represents a way of reaching an IP destination with a VPN."""
     ROUTE_FAMILY = RF_IPv6_UC
     VPN_PATH_CLASS = Vpnv6Path
-    VPN_NLRI_CLASS = Vpnv6
+    VPN_NLRI_CLASS = LabelledVPNIP6AddrPrefix
 
 
 class Vrf6Dest(VrfDest):
 <at>  <at>  -51,11 +51,11  <at>  <at>  class Vrf6Table(VrfTable):
     """Virtual Routing and Forwarding information base for IPv6."""
     ROUTE_FAMILY = RF_IPv6_UC
     VPN_ROUTE_FAMILY = RF_IPv6_VPN
-    NLRI_CLASS = Ipv6
+    NLRI_CLASS = IP6AddrPrefix
     VRF_PATH_CLASS = Vrf6Path
     VRF_DEST_CLASS = Vrf6Dest
 
 
 class Vrf6NlriImportMap(VrfNlriImportMap):
     VRF_PATH_CLASS = Vrf6Path
-    NLRI_CLASS = Ipv6
+    NLRI_CLASS = IP6AddrPrefix
diff --git a/ryu/services/protocols/bgp/operator/commands/show/neighbor.py b/ryu/services/protocols/bgp/operator/commands/show/neighbor.py
index 2e8b871..bd3fda7 100644
--- a/ryu/services/protocols/bgp/operator/commands/show/neighbor.py
+++ b/ryu/services/protocols/bgp/operator/commands/show/neighbor.py
 <at>  <at>  -8,10 +8,10  <at>  <at>  from ryu.services.protocols.bgp.operator.command import STATUS_OK
 from ryu.services.protocols.bgp.operator.commands.responses import \
     WrongParamResp
 from ryu.services.protocols.bgp.operator.views.bgp import CoreServiceDetailView
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
 
 LOG = logging.getLogger('bgpspeaker.operator.commands.show.summary')
 
diff --git a/ryu/services/protocols/bgp/operator/internal_api.py b/ryu/services/protocols/bgp/operator/internal_api.py
index ab7255a..b83ce0d 100644
--- a/ryu/services/protocols/bgp/operator/internal_api.py
+++ b/ryu/services/protocols/bgp/operator/internal_api.py
 <at>  <at>  -1,9 +1,13  <at>  <at> 
 import logging
 import traceback
 
-from ryu.services.protocols.bgp.protocols.bgp import nlri
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import AsPath
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import Med
+from ryu.lib.packet.bgp import RouteFamily
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
+
 from ryu.services.protocols.bgp.base import add_bgp_error_metadata
 from ryu.services.protocols.bgp.base import BGPSException
 from ryu.services.protocols.bgp.base import SUPPORTED_GLOBAL_RF
 <at>  <at>  -67,10 +71,11  <at>  <at>  class InternalApi(object):
 
     def get_single_rib_routes(self, addr_family):
         rfs = {
-            'ipv4': nlri.get_rf(1, 1),
-            'vpnv4': nlri.get_rf(1, 128),
-            'vpnv6': nlri.get_rf(2, 128),
-            'rtfilter': nlri.get_rf(1, 132)
+            'ipv4': RF_IPv4_UC,
+            'ipv6': RF_IPv6_UC,
+            'vpnv4': RF_IPv4_VPN,
+            'vpnv6': RF_IPv6_VPN,
+            'rtfilter': RF_RTC_UC
         }
         if addr_family not in rfs:
             raise WrongParamError('Unknown or unsupported family')
 <at>  <at>  -89,13 +94,13  <at>  <at>  class InternalApi(object):
                'prefix': dst.nlri.formatted_nlri_str}
 
         def _path_to_dict(dst, path):
-            aspath = path.get_pattr(AsPath.ATTR_NAME).path_seg_list
+            aspath = path.get_pattr(BGP_ATTR_TYPE_AS_PATH).path_seg_list
             if aspath is None or len(aspath) == 0:
                 aspath = ''
 
             nexthop = path.nexthop
             # Get the MED path attribute
-            med = path.get_pattr(Med.ATTR_NAME)
+            med = path.get_pattr(BGP_ATTR_TYPE_MULTI_EXIT_DISC)
             med = med.value if med else ''
             # Get best path reason
             bpr = dst.best_path_reason if path == dst.best_path else ''
 <at>  <at>  -134,7 +139,7  <at>  <at>  class InternalApi(object):
             if afi is None and safi is None:
                 route_families.extend(SUPPORTED_GLOBAL_RF)
             else:
-                route_family = nlri.get_rf(afi, safi)
+                route_family = RouteFamily(afi, safi)
                 if (route_family not in SUPPORTED_GLOBAL_RF):
                     raise WrongParamError('Not supported address-family'
                                           ' %s, %s' % (afi, safi))
diff --git a/ryu/services/protocols/bgp/operator/views/bgp.py b/ryu/services/protocols/bgp/operator/views/bgp.py
index 6f53d4f..f78f2a9 100644
--- a/ryu/services/protocols/bgp/operator/views/bgp.py
+++ b/ryu/services/protocols/bgp/operator/views/bgp.py
 <at>  <at>  -5,8 +5,11  <at>  <at>  from ryu.services.protocols.bgp.operator.views.base import \
 from ryu.services.protocols.bgp.operator.views.base import OperatorDetailView
 from ryu.services.protocols.bgp.operator.views import fields
 
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
-
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_LOCAL_PREF
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
 
 class CoreServiceDetailView(OperatorDetailView):
     rf_state = fields.RelatedViewField(
 <at>  <at>  -144,18 +147,19  <at>  <at>  class PathDetailView(OperatorDetailView):
         ret = super(PathDetailView, self).encode()
         ret['nlri'] = self.rel('nlri').encode()
         ret['route_family'] = self.rel('route_family').encode()
-        as_path = self.get_field('pathattr_map').get(pathattr.AsPath.ATTR_NAME)
-        origin = self.get_field('pathattr_map').get(pathattr.Origin.ATTR_NAME)
-        metric = self.get_field('pathattr_map').get(pathattr.Med.ATTR_NAME)
+        as_path = self.get_field('pathattr_map').get(BGP_ATTR_TYPE_AS_PATH)
+        origin = self.get_field('pathattr_map').get(BGP_ATTR_TYPE_ORIGIN)
+        metric = self.get_field('pathattr_map').get(
+            BGP_ATTR_TYPE_MULTI_EXIT_DISC)
         local_pref = self.get_field('pathattr_map').get(
-            pathattr.LocalPref.ATTR_NAME
+            BGP_ATTR_TYPE_LOCAL_PREF
         )
 
         ret['as_path'] = as_path.value if as_path else None
         ret['origin'] = origin.value if origin else None
         ret['metric'] = metric.value if metric else None
         ret['local_pref'] = local_pref.value if local_pref else None
-        ext = ret['pathattr_map'].get(pathattr.ExtCommunity.ATTR_NAME)
+        ext = ret['pathattr_map'].get(BGP_ATTR_TYPE_EXTENDED_COMMUNITIES)
         del ret['pathattr_map']
         if ext:
             ret['rt_list'] = ext.rt_list
 <at>  <at>  -215,11 +219,13  <at>  <at>  class VpnNlriDetailView(IpNlriDetailView):
 
 class NlriDetailView(OperatorDetailView):
     def __new__(cls, obj, filter_func=None):
-        from ryu.services.protocols.bgp.protocols.bgp.nlri import Vpnv4, Vpnv6
-        from ryu.services.protocols.bgp.protocols.bgp.nlri import Ipv4, Ipv6
-        if isinstance(obj, (Vpnv4, Vpnv6)):
+        from ryu.lib.packet.bgp import LabelledVPNIPAddrPrefix
+        from ryu.lib.packet.bgp import LabelledVPNIP6AddrPrefix
+        from ryu.lib.packet.bgp import IPAddrPrefix, IP6AddrPrefix
+        if isinstance(obj, (LabelledVPNIPAddrPrefix,
+                            LabelledVPNIP6AddrPrefix)):
             return VpnNlriDetailView(obj)
-        elif isinstance(obj, (Ipv4, Ipv6)):
+        elif isinstance(obj, (IPAddrPrefix, IP6AddrPrefix)):
             return IpNlriDetailView(obj)
         else:
             return OperatorDetailView(obj, filter_func)
diff --git a/ryu/services/protocols/bgp/peer.py b/ryu/services/protocols/bgp/peer.py
index f2e78a6..4bca616 100644
--- a/ryu/services/protocols/bgp/peer.py
+++ b/ryu/services/protocols/bgp/peer.py
 <at>  <at>  -36,11 +36,39  <at>  <at>  from ryu.services.protocols.bgp.speaker import BgpProtocol
 from ryu.services.protocols.bgp.utils import bgp as bgp_utils
 from ryu.services.protocols.bgp.utils.evtlet import EventletIOFactory
 from ryu.services.protocols.bgp.utils import stats
-from ryu.services.protocols.bgp.protocols.bgp import exceptions
-from ryu.services.protocols.bgp.protocols.bgp import messages
-from ryu.services.protocols.bgp.protocols.bgp import nlri
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
 
+from ryu.lib.packet import bgp
+
+from ryu.lib.packet.bgp import RouteFamily
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
+
+from ryu.lib.packet.bgp import BGPOpen
+from ryu.lib.packet.bgp import BGPUpdate
+from ryu.lib.packet.bgp import BGPRouteRefresh
+
+from ryu.lib.packet.bgp import BGP_MSG_UPDATE
+from ryu.lib.packet.bgp import BGP_MSG_KEEPALIVE
+from ryu.lib.packet.bgp import BGP_MSG_ROUTE_REFRESH
+
+from ryu.lib.packet.bgp import BGPPathAttributeNextHop
+from ryu.lib.packet.bgp import BGPPathAttributeAsPath
+from ryu.lib.packet.bgp import BGPPathAttributeLocalPref
+from ryu.lib.packet.bgp import BGPPathAttributeExtendedCommunities
+from ryu.lib.packet.bgp import BGPPathAttributeMpReachNLRI
+from ryu.lib.packet.bgp import BGPPathAttributeMpUnreachNLRI
+
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_NEXT_HOP
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MP_REACH_NLRI
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MP_UNREACH_NLRI
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_COMMUNITIES
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
 
 LOG = logging.getLogger('bgpspeaker.peer')
 
 <at>  <at>  -110,7 +138,7  <at>  <at>  class PeerState(object):
         }
         self._signal_bus = signal_bus
 
-        #TODO(JK): refactor other counters to use signals also
+        # TODO(JK): refactor other counters to use signals also
         self._signal_bus.register_listener(
             ('error', 'bgp', self.peer),
             self._remember_last_bgp_error
 <at>  <at>  -264,12 +292,12  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         # State per route family, {RouteFamily: PeerRf,}.
         self.rf_state = {}
         # Get vpnv4 route family settings.
-        prf = PeerRf(self, nlri.RF_IPv4_VPN,
+        prf = PeerRf(self, RF_IPv4_VPN,
                      enabled=self._neigh_conf.cap_mbgp_vpnv4)
-        self.rf_state[nlri.RF_IPv4_VPN] = prf
+        self.rf_state[RF_IPv4_VPN] = prf
         # Get vpnv6 route family settings.
-        prf = PeerRf(self, nlri.RF_IPv6_VPN, self._neigh_conf.cap_mbgp_vpnv6)
-        self.rf_state[nlri.RF_IPv6_VPN] = prf
+        prf = PeerRf(self, RF_IPv6_VPN, self._neigh_conf.cap_mbgp_vpnv6)
+        self.rf_state[RF_IPv6_VPN] = prf
 
         # Bound protocol instance
         self._protocol = None
 <at>  <at>  -378,8 +406,8  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 # when we stop the protocol, hence we call connection_lost
                 # here as we triggered socket to close.
                 self._protocol.send_notification(
-                    exceptions.AdminShutdown.CODE,
-                    exceptions.AdminShutdown.SUB_CODE
+                    BGP_ERROR_CEASE,
+                    BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN
                 )
                 self._protocol.stop()
             # If this peer is not enabled any-more we stop trying to make any
 <at>  <at>  -415,7 +443,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
 
         Update appropriate counters and set appropriate timers.
         """
-        assert rr_msg.TYPE_CODE == messages.RouteRefresh.TYPE_CODE
+        assert rr_msg.TYPE_CODE == BGP_MSG_ROUTE_REFRESH
         self._protocol.send(rr_msg)
         LOG.debug('RouteRefresh %s>> %s' %
                   (self._neigh_conf.ip_address, rr_msg))
 <at>  <at>  -471,18 +499,18  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             # Check currently supported out-going msgs.
             assert isinstance(
                 outgoing_msg,
-                (messages.RouteRefresh, messages.Update, OutgoingRoute)
+                (BGPRouteRefresh, BGPUpdate, OutgoingRoute)
             ), ('Peer cannot process object: %s in its outgoing queue'
                 % outgoing_msg)
 
             # Send msg. to peer.
-            if isinstance(outgoing_msg, messages.RouteRefresh):
+            if isinstance(outgoing_msg, BGPRouteRefresh):
                 self._send_outgoing_route_refresh_msg(outgoing_msg)
             elif isinstance(outgoing_msg, OutgoingRoute):
                 self._send_outgoing_route(outgoing_msg)
 
             # EOR are enqueued as plain Update messages.
-            elif isinstance(outgoing_msg, messages.Update):
+            elif isinstance(outgoing_msg, BGPUpdate):
                 self._protocol.send(outgoing_msg)
                 LOG.debug('Update %s>> %s' % (self._neigh_conf.ip_address,
                                               outgoing_msg))
 <at>  <at>  -523,17 +551,17  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                      # We ignore request for route_family not valid
                      # for current session.
                      self._protocol.is_mbgp_cap_valid(route_family))):
-                rr_req = messages.RouteRefresh(route_family)
+                rr_req = BGPRouteRefresh(route_family.afi, route_family.safi)
                 self.enque_outgoing_msg(rr_req)
                 LOG.debug('Enqueued Route Refresh message to '
                           'peer %s for rf: %s' % (self, route_family))
 
     def enque_end_of_rib(self, route_family):
-        pattr_map = {}
         # MP_UNREACH_NLRI Attribute.
-        mpunreach_attr = pathattr.MpUnreachNlri(route_family, [])
-        pattr_map[pathattr.MpUnreachNlri.ATTR_NAME] = mpunreach_attr
-        update = messages.Update(pathattr_map=pattr_map)
+        mpunreach_attr = BGPPathAttributeMpUnreachNLRI(route_family.afi,
+                                                       route_family.safi,
+                                                       [])
+        update = BGPUpdate(path_attributes=[mpunreach_attr])
         self.enque_outgoing_msg(update)
 
     def _session_next_hop(self, route_family):
 <at>  <at>  -546,9 +574,13  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         """
         # By default we use BGPS's interface IP with this peer as next_hop.
         next_hop = self._neigh_conf.host_bind_ip
-        if route_family == nlri.RF_IPv6_VPN:
+        if route_family == RF_IPv6_VPN:
             # Next hop ipv4_mapped ipv6
-            next_hop = nlri.ipv4_mapped_ipv6(next_hop)
+            def _ipv4_mapped_ipv6(ipv4):
+                from netaddr import IPAddress
+                return str(IPAddress(ipv4).ipv6())
+
+            next_hop = _ipv4_mapped_ipv6(next_hop)
 
         return next_hop
 
 <at>  <at>  -556,8 +588,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         """Construct update message with Outgoing-routes path attribute
         appropriately cloned/copied/updated.
         """
-        is_bgp4_format = outgoing_route.bgp4_format
-        if is_bgp4_format:
+        if self._neigh_conf.cap_mbgp_ipv4:
             update = self._construct_bgp4_update(outgoing_route)
         else:
             update = self._construct_mpbgp_update(outgoing_route)
 <at>  <at>  -569,10 +600,10  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         path = outgoing_route.path
         # Get copy of path's path attributes.
         pathattr_map = path.pathattr_map
-        new_pathattr_map = OrderedDict()
+        new_pathattr = []
 
         if path.is_withdraw:
-            update = messages.Update(withdraw_list=path.nlri)
+            update = BGPUpdate(withdrawn_routes=[path.nlri])
             return update
         else:
             # Supported and un-supported/unknown attributes.
 <at>  <at>  -595,19 +626,19  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 # If the path came from a bgp peer and not from NC, according
                 # to RFC 4271 we should not modify next_hop.
                 next_hop = path.nexthop
-            nexthop_attr = pathattr.NextHop(next_hop)
+            nexthop_attr = BGPPathAttributeNextHop(next_hop)
             assert nexthop_attr, 'Missing NEXTHOP mandatory attribute.'
 
             # ORIGIN Attribute.
             # According to RFC this attribute value SHOULD NOT be changed by
             # any other speaker.
-            origin_attr = pathattr_map.get(pathattr.Origin.ATTR_NAME)
+            origin_attr = pathattr_map.get(BGP_ATTR_TYPE_ORIGIN)
             assert origin_attr, 'Missing ORIGIN mandatory attribute.'
 
             # AS_PATH Attribute.
             # Construct AS-path-attr using paths aspath attr. with local AS as
             # first item.
-            path_aspath = pathattr_map.get(pathattr.AsPath.ATTR_NAME)
+            path_aspath = pathattr_map.get(BGP_ATTR_TYPE_AS_PATH)
             assert path_aspath, 'Missing AS_PATH mandatory attribute.'
             # Deep copy aspath_attr value
             path_seg_list = path_aspath.path_seg_list
 <at>  <at>  -616,7 +647,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 # When a given BGP speaker advertises the route to an internal
                 # peer, the advertising speaker SHALL NOT modify the AS_PATH
                 # attribute associated with the route.
-                aspath_attr = pathattr.AsPath(path_seg_list)
+                aspath_attr = BGPPathAttributeAsPath(path_seg_list)
             else:
                 # When a given BGP speaker advertises the route to an external
                 # peer, the advertising speaker updates the AS_PATH attribute
 <at>  <at>  -644,15 +675,16  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                     path_seg_list[0].insert(0, self._core_service.asn)
                 else:
                     path_seg_list.insert(0, [self._core_service.asn])
-                aspath_attr = pathattr.AsPath(path_seg_list)
+                aspath_attr = BGPPathAttributeAsPath(path_seg_list)
 
             # MULTI_EXIT_DISC Attribute.
             # For eBGP session we can send multi-exit-disc if configured.
             multi_exit_disc = None
             if self.is_ebgp_peer():
-                multi_exit_disc = pathattr_map.get(pathattr.Med.ATTR_NAME)
+                multi_exit_disc = pathattr_map.get(
+                    BGP_ATTR_TYPE_MULTI_EXIT_DISC)
                 if not multi_exit_disc and self._neigh_conf.multi_exit_disc:
-                    multi_exit_disc = pathattr.Med(
+                    multi_exit_disc = BGPPathAttributeMultiExitDisc(
                         self._neigh_conf.multi_exit_disc
                     )
 
 <at>  <at>  -660,15 +692,15  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             if not self.is_ebgp_peer():
                 # For iBGP peers we are required to send local-pref attribute
                 # for connected or local prefixes. We send default local-pref.
-                localpref_attr = pathattr.LocalPref(100)
+                localpref_attr = BGPPathAttributeLocalPref(100)
 
             # COMMUNITY Attribute.
-            community_attr = pathattr_map.get(pathattr.Community.ATTR_NAME)
+            community_attr = pathattr_map.get(BGP_ATTR_TYPE_COMMUNITIES)
 
             # EXTENDED COMMUNITY Attribute.
             # Construct ExtCommunity path-attr based on given.
             path_extcomm_attr = pathattr_map.get(
-                pathattr.ExtCommunity.ATTR_NAME
+                BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
             )
             if path_extcomm_attr:
                 # SOO list can be configured per VRF and/or per Neighbor.
 <at>  <at>  -676,7 +708,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 soo_list = path_extcomm_attr.soo_list
                 if self._neigh_conf.soo_list:
                     soo_list.extend(self._neigh_conf.soo_list)
-                extcomm_attr = pathattr.ExtCommunity(
+                extcomm_attr = BGPPathAttributeExtendedCommunities(
                     path_extcomm_attr.rt_list,
                     soo_list
                 )
 <at>  <at>  -688,22 +720,22  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             # Ordering path attributes according to type as RFC says. We set
             # MPReachNLRI first as advised by experts as a new trend in BGP
             # implementation.
-            new_pathattr_map[pathattr.NextHop.ATTR_NAME] = nexthop_attr
-            new_pathattr_map[pathattr.Origin.ATTR_NAME] = origin_attr
-            new_pathattr_map[pathattr.AsPath.ATTR_NAME] = aspath_attr
+            new_pathattr.append(nexthop_attr)
+            new_pathattr.append(origin_attr)
+            new_pathattr.append(aspath_attr)
             if multi_exit_disc:
-                new_pathattr_map[pathattr.Med.ATTR_NAME] = multi_exit_disc
+                new_pathattr.append(multi_exit_disc)
             if localpref_attr:
-                new_pathattr_map[pathattr.LocalPref.ATTR_NAME] = localpref_attr
+                new_pathattr.append(localpref_attr)
             if community_attr:
-                new_pathattr_map[pathattr.Community.ATTR_NAME] = community_attr
+                new_pathattr.append(community_attr)
             if extcomm_attr:
-                new_pathattr_map[pathattr.ExtCommunity.ATTR_NAME] =\
-                    extcomm_attr
+                new_pathattr.append(extcomm_attr)
             if unkown_opttrans_attrs:
-                new_pathattr_map.update(unkown_opttrans_attrs)
-            update = messages.Update(pathattr_map=new_pathattr_map,
-                                     nlri_list=nlri_list)
+                new_pathattr.extend(unkown_opttrans_attrs.values())
+
+            update = BGPUpdate(path_attributes=new_pathattr,
+                               nlri=nlri_list)
             return update
 
     def _construct_mpbgp_update(self, outgoing_route):
 <at>  <at>  -715,16 +747,16  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         path = outgoing_route.path
         # Get copy of path's path attributes.
         pathattr_map = path.pathattr_map
-        new_pathattr_map = OrderedDict()
+        new_pathattr = []
 
         # If this is withdraw update we copy MpUnReach path-attribute and
         # create new Update message.
         if path.is_withdraw:
             # MP_UNREACH_NLRI Attribute.
-            mpunreach_attr = pathattr.MpUnreachNlri(
-                path.route_family, [path.nlri]
+            mpunreach_attr = BGPPathAttributeMpUnreachNLRI(
+                path.route_family.afi, path.route_family.safi, [path.nlri]
             )
-            new_pathattr_map[pathattr.MpUnreachNlri.ATTR_NAME] = mpunreach_attr
+            new_pathattr.append(mpunreach_attr)
         else:
             # Supported and un-supported/unknown attributes.
             origin_attr = None
 <at>  <at>  -746,20 +778,23  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 # to RFC 4271 we should not modify next_hop.
                 next_hop = path.nexthop
             # We construct mpreach-nlri attribute.
-            mpnlri_attr = pathattr.MpReachNlri(
-                path.route_family, next_hop, [path.nlri]
+            mpnlri_attr = BGPPathAttributeMpReachNLRI(
+                path.route_family.afi,
+                path.route_family.safi,
+                next_hop,
+                [path.nlri]
             )
 
             # ORIGIN Attribute.
             # According to RFC this attribute value SHOULD NOT be changed by
             # any other speaker.
-            origin_attr = pathattr_map.get(pathattr.Origin.ATTR_NAME)
+            origin_attr = pathattr_map.get(BGP_ATTR_TYPE_ORIGIN)
             assert origin_attr, 'Missing ORIGIN mandatory attribute.'
 
             # AS_PATH Attribute.
             # Construct AS-path-attr using paths aspath attr. with local AS as
             # first item.
-            path_aspath = pathattr_map.get(pathattr.AsPath.ATTR_NAME)
+            path_aspath = pathattr_map.get(BGP_ATTR_TYPE_AS_PATH)
             assert path_aspath, 'Missing AS_PATH mandatory attribute.'
             # Deep copy aspath_attr value
             path_seg_list = path_aspath.path_seg_list
 <at>  <at>  -768,7 +803,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 # When a given BGP speaker advertises the route to an internal
                 # peer, the advertising speaker SHALL NOT modify the AS_PATH
                 # attribute associated with the route.
-                aspath_attr = pathattr.AsPath(path_seg_list)
+                aspath_attr = BGPPathAttributeAsPath(path_seg_list)
             else:
                 # When a given BGP speaker advertises the route to an external
                 # peer, the advertising speaker updates the AS_PATH attribute
 <at>  <at>  -796,13 +831,14  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                     path_seg_list[0].insert(0, self._core_service.asn)
                 else:
                     path_seg_list.insert(0, [self._core_service.asn])
-                aspath_attr = pathattr.AsPath(path_seg_list)
+                aspath_attr = BGPPathAttributeAsPath(path_seg_list)
 
             # MULTI_EXIT_DISC Attribute.
             # For eBGP session we can send multi-exit-disc if configured.
             multi_exit_disc = None
             if self.is_ebgp_peer():
-                multi_exit_disc = pathattr_map.get(pathattr.Med.ATTR_NAME)
+                multi_exit_disc = pathattr_map.get(
+                    BGP_ATTR_TYPE_MULTI_EXIT_DISC)
 
             # LOCAL_PREF Attribute.
             if not self.is_ebgp_peer():
 <at>  <at>  -811,12 +847,12  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 localpref_attr = pathattr.LocalPref(100)
 
             # COMMUNITY Attribute.
-            community_attr = pathattr_map.get(pathattr.Community.ATTR_NAME)
+            community_attr = pathattr_map.get(BGP_ATTR_TYPE_COMMUNITIES)
 
             # EXTENDED COMMUNITY Attribute.
             # Construct ExtCommunity path-attr based on given.
             path_extcomm_attr = pathattr_map.get(
-                pathattr.ExtCommunity.ATTR_NAME
+                BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
             )
             if path_extcomm_attr:
                 # SOO list can be configured per VRF and/or per Neighbor.
 <at>  <at>  -824,9 +860,8  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 soo_list = path_extcomm_attr.soo_list
                 if self._neigh_conf.soo_list:
                     soo_list.extend(self._neigh_conf.soo_list)
-                extcomm_attr = pathattr.ExtCommunity(
-                    path_extcomm_attr.rt_list,
-                    soo_list
+                extcomm_attr = BGPPathAttributeExtendedCommunities(
+                    path_extcomm_attr.rt_list+soo_list
                 )
 
             # UNKOWN Attributes.
 <at>  <at>  -836,22 +871,21  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             # Ordering path attributes according to type as RFC says. We set
             # MPReachNLRI first as advised by experts as a new trend in BGP
             # implementation.
-            new_pathattr_map[pathattr.MpReachNlri.ATTR_NAME] = mpnlri_attr
-            new_pathattr_map[pathattr.Origin.ATTR_NAME] = origin_attr
-            new_pathattr_map[pathattr.AsPath.ATTR_NAME] = aspath_attr
+            new_pathattr.append(mpnlri_attr)
+            new_pathattr.append(origin_attr)
+            new_pathattr.append(aspath_attr)
             if multi_exit_disc:
-                new_pathattr_map[pathattr.Med.ATTR_NAME] = multi_exit_disc
+                new_pathattr.append(multi_exit_disc)
             if localpref_attr:
-                new_pathattr_map[pathattr.LocalPref.ATTR_NAME] = localpref_attr
+                new_pathattr.append(localpref_attr)
             if community_attr:
-                new_pathattr_map[pathattr.Community.ATTR_NAME] = community_attr
+                new_pathattr.append(community_attr)
             if extcomm_attr:
-                new_pathattr_map[pathattr.ExtCommunity.ATTR_NAME] =\
-                    extcomm_attr
+                new_pathattr.append(extcomm_attr)
             if unkown_opttrans_attrs:
-                new_pathattr_map.update(unkown_opttrans_attrs)
+                new_pathattr.extend(unkown_opttrans_attrs.values())
 
-        update = messages.Update(pathattr_map=new_pathattr_map)
+        update = BGPUpdate(path_attributes=new_pathattr)
         return update
 
     def _connect_loop(self, client_factory):
 <at>  <at>  -923,8 +957,8  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             LOG.debug('Processing of outgoing msg. started for %s.' % self)
 
     def _send_collision_err_and_stop(self, protocol):
-        code = exceptions.CollisionResolution.CODE
-        subcode = exceptions.CollisionResolution.SUB_CODE
+        code = BGP_ERROR_CEASE
+        subcode = BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION
         self._signal_bus.bgp_error(self, code, subcode, None)
         protocol.send_notification(code, subcode)
         protocol.stop()
 <at>  <at>  -1011,12 +1045,22  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         asnum = self._common_conf.local_as
         bgpid = self._common_conf.router_id
         holdtime = self._neigh_conf.hold_time
-        open_msg = messages.Open(
-            const.BGP_VERSION_NUM,
-            asnum,
-            holdtime,
-            bgpid,
-            self._neigh_conf.get_configured_capabilites()
+
+        def flatten(L):
+            if isinstance(L, list):
+                for i in xrange(len(L)):
+                    for e in flatten(L[i]):
+                        yield e
+            else:
+                yield L
+        opts = list(flatten(
+            self._neigh_conf.get_configured_capabilites().values()))
+        open_msg = BGPOpen(
+            my_as=asnum,
+            bgp_identifier=bgpid,
+            version=const.BGP_VERSION_NUM,
+            hold_time=holdtime,
+            opt_param=opts
         )
         return open_msg
 
 <at>  <at>  -1028,35 +1072,35  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         library.
         """
         # TODO(PH): finish providing implementation, currently low priority
-        assert update_msg.TYPE_CODE == messages.Update.TYPE_CODE
+        assert update_msg.type == BGP_MSG_UPDATE
         # An UPDATE message may be received only in the Established state.
         # Receiving an UPDATE message in any other state is an error.
         if self.state.bgp_state != const.BGP_FSM_ESTABLISHED:
             LOG.error('Received UPDATE message when not in ESTABLISHED'
                       ' state.')
-            raise exceptions.FiniteStateMachineError()
+            raise bgp.FiniteStateMachineError()
 
         mp_reach_attr = update_msg.get_path_attr(
-            pathattr.MpReachNlri.ATTR_NAME
+            BGP_ATTR_TYPE_MP_REACH_NLRI
         )
         mp_unreach_attr = update_msg.get_path_attr(
-            pathattr.MpUnreachNlri.ATTR_NAME
+            BGP_ATTR_TYPE_MP_UNREACH_NLRI
         )
 
         # non-MPBGP Update msg.
         if not (mp_reach_attr or mp_unreach_attr):
             LOG.info('Received UPDATE msg. with no MpReachNlri or '
                      'MpUnReachNlri attribute.')
-            if not self.is_mpbgp_cap_valid(nlri.RF_IPv4_UC):
+            if not self.is_mpbgp_cap_valid(RF_IPv4_UC):
                 LOG.error('Got UPDATE message with un-available'
-                          ' afi/safi %s' % nlri.RF_IPv4_UC)
-            nlri_list = update_msg.nlri_list
+                          ' afi/safi %s' % RF_IPv4_UC)
+            nlri_list = update_msg.nlri
             if len(nlri_list) > 0:
                 # Check for missing well-known mandatory attributes.
-                aspath = update_msg.get_path_attr(pathattr.AsPath.ATTR_NAME)
+                aspath = update_msg.get_path_attr(BGP_ATTR_TYPE_AS_PATH)
                 if not aspath:
-                    raise exceptions.MissingWellKnown(
-                        pathattr.AsPath.TYPE_CODE)
+                    raise bgp.MissingWellKnown(
+                        BGP_ATTR_TYPE_AS_PATH)
 
                 # We do not have a setting to enable/disable first-as check.
                 # We by default do first-as check below.
 <at>  <at>  -1064,17 +1108,15  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                         not aspath.has_matching_leftmost(self.remote_as)):
                     LOG.error('First AS check fails. Raise appropriate'
                               ' exception.')
-                    raise exceptions.MalformedAsPath()
+                    raise bgp.MalformedAsPath()
 
-                origin = update_msg.get_path_attr(pathattr.Origin.ATTR_NAME)
+                origin = update_msg.get_path_attr(BGP_ATTR_TYPE_ORIGIN)
                 if not origin:
-                    raise exceptions.MissingWellKnown(
-                        pathattr.Origin.TYPE_CODE)
+                    raise bgp.MissingWellKnown(BGP_ATTR_TYPE_ORIGIN)
 
-                nexthop = update_msg.get_path_attr(pathattr.NextHop.ATTR_NAME)
+                nexthop = update_msg.get_path_attr(BGP_ATTR_TYPE_NEXT_HOP)
                 if not nexthop:
-                    raise exceptions.MissingWellKnown(
-                        pathattr.NextHop.TYPE_CODE)
+                    raise bgp.MissingWellKnown(BGP_ATTR_TYPE_NEXT_HOP)
 
             return True
 
 <at>  <at>  -1084,7 +1126,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 LOG.error('Got UPDATE message with un-available afi/safi for'
                           ' MP_UNREACH path attribute (non-negotiated'
                           ' afi/safi) %s' % mp_unreach_attr.route_family)
-                # raise exceptions.OptAttrError()
+                # raise bgp.OptAttrError()
 
         if mp_reach_attr:
             # Check if received MP_REACH path attribute is of available
 <at>  <at>  -1093,23 +1135,23  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 LOG.error('Got UPDATE message with un-available afi/safi for'
                           ' MP_UNREACH path attribute (non-negotiated'
                           ' afi/safi) %s' % mp_reach_attr.route_family)
-                # raise exceptions.OptAttrError()
+                # raise bgp.OptAttrError()
 
             # Check for missing well-known mandatory attributes.
-            aspath = update_msg.get_path_attr(pathattr.AsPath.ATTR_NAME)
+            aspath = update_msg.get_path_attr(BGP_ATTR_TYPE_AS_PATH)
             if not aspath:
-                raise exceptions.MissingWellKnown(pathattr.AsPath.TYPE_CODE)
+                raise bgp.MissingWellKnown(BGP_ATTR_TYPE_AS_PATH)
 
             # We do not have a setting to enable/disable first-as check.
             # We by default do first-as check below.
             if (self.is_ebgp_peer() and
                     not aspath.has_matching_leftmost(self.remote_as)):
                 LOG.error('First AS check fails. Raise appropriate exception.')
-                raise exceptions.MalformedAsPath()
+                raise bgp.MalformedAsPath()
 
-            origin = update_msg.get_path_attr(pathattr.Origin.ATTR_NAME)
+            origin = update_msg.get_path_attr(BGP_ATTR_TYPE_ORIGIN)
             if not origin:
-                raise exceptions.MissingWellKnown(pathattr.Origin.TYPE_CODE)
+                raise bgp.MissingWellKnown(BGP_ATTR_TYPE_ORIGIN)
 
             # Validate Next hop.
             # TODO(PH): Currently ignore other cases.
 <at>  <at>  -1142,15 +1184,13  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             return
 
         # Increment count of update received.
-        mp_reach_attr = update_msg.get_path_attr(
-            pathattr.MpReachNlri.ATTR_NAME
-        )
+        mp_reach_attr = update_msg.get_path_attr(BGP_ATTR_TYPE_MP_REACH_NLRI)
         mp_unreach_attr = update_msg.get_path_attr(
-            pathattr.MpUnreachNlri.ATTR_NAME
+            BGP_ATTR_TYPE_MP_UNREACH_NLRI
         )
 
-        nlri_list = update_msg.nlri_list
-        withdraw_list = update_msg.withdraw_list
+        nlri_list = update_msg.nlri
+        withdraw_list = update_msg.withdrawn_routes
 
         if mp_reach_attr:
             # Extract advertised paths from given message.
 <at>  <at>  -1181,7 +1221,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         """
         umsg_pattrs = update_msg.pathattr_map
 
-        msg_rf = nlri.RF_IPv4_UC
+        msg_rf = RF_IPv4_UC
         # Check if this route family is among supported route families.
         if msg_rf not in SUPPORTED_GLOBAL_RF:
             LOG.info(('Received route for route family %s which is'
 <at>  <at>  -1189,16 +1229,16  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                      (msg_rf, update_msg))
             return
 
-        aspath = umsg_pattrs.get(pathattr.AsPath.ATTR_NAME)
+        aspath = umsg_pattrs.get(BGP_ATTR_TYPE_AS_PATH)
         # Check if AS_PATH has loops.
         if aspath.has_local_as(self._common_conf.local_as):
             LOG.error('Update message AS_PATH has loops. Ignoring this'
                       ' UPDATE. %s' % update_msg)
             return
 
-        next_hop = update_msg.get_path_attr(pathattr.NextHop.ATTR_NAME)
+        next_hop = update_msg.get_path_attr(BGP_ATTR_TYPE_NEXT_HOP)
         # Nothing to do if we do not have any new NLRIs in this message.
-        msg_nlri_list = update_msg.nlri_list
+        msg_nlri_list = update_msg.nlri
         if not msg_nlri_list:
             LOG.debug('Update message did not have any new MP_REACH_NLRIs.')
             return
 <at>  <at>  -1240,7 +1280,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         Extracted withdraws are added to appropriate *Destination* for further
         processing.
         """
-        msg_rf = nlri.RF_IPv4_UC
+        msg_rf = RF_IPv4_UC
         # Check if this route family is among supported route families.
         if msg_rf not in SUPPORTED_GLOBAL_RF:
             LOG.info(
 <at>  <at>  -1280,7 +1320,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         processing.
         """
         umsg_pattrs = update_msg.pathattr_map
-        mpreach_nlri_attr = umsg_pattrs.pop(pathattr.MpReachNlri.ATTR_NAME)
+        mpreach_nlri_attr = umsg_pattrs.pop(BGP_ATTR_TYPE_MP_REACH_NLRI)
         assert mpreach_nlri_attr
 
         msg_rf = mpreach_nlri_attr.route_family
 <at>  <at>  -1291,17 +1331,17  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                      (msg_rf, update_msg))
             return
 
-        aspath = umsg_pattrs.get(pathattr.AsPath.ATTR_NAME)
+        aspath = umsg_pattrs.get(BGP_ATTR_TYPE_AS_PATH)
         # Check if AS_PATH has loops.
         if aspath.has_local_as(self._common_conf.local_as):
             LOG.error('Update message AS_PATH has loops. Ignoring this'
                       ' UPDATE. %s' % update_msg)
             return
 
-        if msg_rf in (nlri.RF_IPv4_VPN, nlri.RF_IPv6_UC):
+        if msg_rf in (RF_IPv4_VPN, RF_IPv6_UC):
             # Check if we have Extended Communities Attribute.
             # TODO(PH): Check if RT_NLRI afi/safi will ever have this attribute
-            ext_comm_attr = umsg_pattrs.get(pathattr.ExtCommunity.ATTR_NAME)
+            ext_comm_attr = umsg_pattrs.get(BGP_ATTR_TYPE_EXTENDED_COMMUNITIES)
             # Check if we have at-least one RT is of interest to us.
             if not ext_comm_attr:
                 LOG.info('Missing Extended Communities Attribute. '
 <at>  <at>  -1328,7 +1368,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
 
         next_hop = mpreach_nlri_attr.next_hop
         # Nothing to do if we do not have any new NLRIs in this message.
-        msg_nlri_list = mpreach_nlri_attr.nlri_list
+        msg_nlri_list = mpreach_nlri_attr.nlri
         if not msg_nlri_list:
             LOG.debug('Update message did not have any new MP_REACH_NLRIs.')
             return
 <at>  <at>  -1342,7 +1382,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                 nexthop=next_hop
             )
             LOG.debug('Extracted paths from Update msg.: %s' % new_path)
-            if msg_rf == nlri.RF_RTC_UC \
+            if msg_rf == RF_RTC_UC \
                     and self._init_rtc_nlri_path is not None:
                 self._init_rtc_nlri_path.append(new_path)
             else:
 <at>  <at>  -1408,7 +1448,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
 #         assert (route_family in SUPPORTED_GLOBAL_RF)
 #         assert self.is_mbgp_cap_valid(route_family)
 
-        if route_family == nlri.RF_RTC_UC:
+        if route_family == RF_RTC_UC:
             self._unschedule_sending_init_updates()
 
             # Learn all rt_nlri at the same time As RT are learned and RT
 <at>  <at>  -1434,19 +1474,19  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         KEEPALIVE, UPDATE and ROUTE_REFRESH messages. UPDATE and ROUTE_REFRESH
         messages are handled only after session is established.
         """
-        if msg.MSG_NAME == messages.Keepalive.MSG_NAME:
+        if msg.type == BGP_MSG_KEEPALIVE:
             # If we receive a Keep Alive message in open_confirm state, we
             # transition to established state.
             if self.state.bgp_state == const.BGP_FSM_OPEN_CONFIRM:
                 self.state.bgp_state = const.BGP_FSM_ESTABLISHED
                 self._enqueue_init_updates()
 
-        elif msg.MSG_NAME == messages.Update.MSG_NAME:
+        elif msg.type == BGP_MSG_UPDATE:
             assert self.state.bgp_state == const.BGP_FSM_ESTABLISHED
             # Will try to process this UDPATE message further
             self._handle_update_msg(msg)
 
-        elif msg.MSG_NAME == messages.RouteRefresh.MSG_NAME:
+        elif msg.type == BGP_MSG_ROUTE_REFRESH:
             # If its route-refresh message
             assert self.state.bgp_state == const.BGP_FSM_ESTABLISHED
             self._handle_route_refresh_msg(msg)
 <at>  <at>  -1456,7 +1496,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
             # nothing is done inside peer, so should not see them here.
             raise ValueError('Peer does not support handling of %s'
                              ' message during % state' %
-                             (msg.MSG_NAME, self.state.bgp_state()))
+                             (msg, self.state.bgp_state()))
 
     def _handle_err_sor_msg(self, afi, safi):
         # Check if ERR capability is enabled for this peer.
 <at>  <at>  -1474,7 +1514,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         if rst != 0:
             # Set a timer to clean the stale paths at configured time.
             # Clean/track inconsistent/stale routes.
-            route_family = nlri.get_rf(afi, safi)
+            route_family = RouteFamily(afi, safi)
             if route_family in SUPPORTED_GLOBAL_RF:
                 self._refresh_stalepath_timer = self._spawn_after(
                     'err-refresh-stale-path-timer', rst,
 <at>  <at>  -1498,7 +1538,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         # If this is end of RIB (EOR) message.
         elif demarcation == 2:
             # Clean/track inconsistent/stale routes.
-            route_family = nlri.get_rf(afi, safi)
+            route_family = RouteFamily(afi, safi)
             if route_family in SUPPORTED_GLOBAL_RF:
                 tm = self._core_service.table_manager
                 tm.clean_stale_routes(self, route_family)
 <at>  <at>  -1508,7 +1548,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                       demarcation)
 
     def _handle_route_refresh_req(self, afi, safi):
-        rr_af = nlri.get_rf(afi, safi)
+        rr_af = RouteFamily(afi, safi)
         self.state.incr(PeerCounterNames.RECV_REFRESH)
 
         # Check if peer has asked for route-refresh for af that was advertised
 <at>  <at>  -1524,7 +1564,9  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         sor = None
         if self._protocol.is_enhanced_rr_cap_valid():
             # If enhanced route-refresh is valid/enabled, enqueue SOR.
-            sor = messages.RouteRefresh(af, demarcation=1)
+            afi = af.afi
+            safi = af.safi
+            sor = BGPRouteRefresh(afi, safi, reserved=1)
             self.enque_first_outgoing_msg(sor)
 
         # Ask core to re-send sent routes
 <at>  <at>  -1539,7 +1581,9  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         sent.
         """
         if self._protocol.is_enhanced_rr_cap_valid() and not sor.eor_sent:
-            eor = messages.RouteRefresh(sor.route_family, demarcation=2)
+            afi = sor.route_family.afi
+            safi = sor.route_family.safi
+            eor = BGPRouteRefresh(afi, safi, reserved=2)
             self.enque_outgoing_msg(eor)
             sor.eor_sent = True
 
 <at>  <at>  -1589,7 +1633,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
     def _enqueue_init_updates(self):
         """Enqueues current routes to be shared with this peer."""
         assert self.state.bgp_state == const.BGP_FSM_ESTABLISHED
-        if self.is_mbgp_cap_valid(nlri.RF_RTC_UC):
+        if self.is_mbgp_cap_valid(RF_RTC_UC):
             # Enqueues all best-RTC_NLRIs to be sent as initial update to this
             # peer.
             self._peer_manager.comm_all_rt_nlris(self)
 <at>  <at>  -1610,7 +1654,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                   ' 1/132')
         # We will enqueue best path from all global destination.
         for route_family, table in global_tables.iteritems():
-            if route_family == nlri.RF_RTC_UC:
+            if route_family == RF_RTC_UC:
                 continue
             if self.is_mbgp_cap_valid(route_family):
                 for dest in table.itervalues():
 <at>  <at>  -1643,8 +1687,8  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
 
         # If RTC capability is available and path afi/saif is other than  RT
         # nlri
-        if path_rf != nlri.RF_RTC_UC and \
-                self.is_mpbgp_cap_valid(nlri.RF_RTC_UC):
+        if path_rf != RF_RTC_UC and \
+                self.is_mpbgp_cap_valid(RF_RTC_UC):
             rtfilter = self._peer_manager.curr_peer_rtfilter(self)
             # If peer does not have any rtfilter or if rtfilter does not have
             # any RTs common with path RTs we do not share this path with the
 <at>  <at>  -1657,14 +1701,14  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
 
         # Transmit side loop detection: We check if leftmost AS matches
         # peers AS, if so we do not send UPDATE message to this peer.
-        as_path = path.get_pattr(pathattr.AsPath.ATTR_NAME)
+        as_path = path.get_pattr(BGP_ATTR_TYPE_AS_PATH)
         if as_path and as_path.has_matching_leftmost(self.remote_as):
             LOG.debug('Skipping sending path as AS_PATH has peer AS %s' %
                       self.remote_as)
             return
 
         if self._neigh_conf.multi_exit_disc:
-            med_attr = path.get_pattr(pathattr.Med.ATTR_NAME)
+            med_attr = path.get_pattr(BGP_ATTR_TYPE_MULTI_EXIT_DISC)
             if not med_attr:
                 path = bgp_utils.clone_path_and_update_med_for_target_neighbor(
                     path,
 <at>  <at>  -1675,10 +1719,7  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
         if path.source is None:
             # Construct OutgoingRoute specific for this peer and put it in
             # its sink.
-            bgp4_format = False
-            if self._neigh_conf.cap_mbgp_ipv4:
-                bgp4_format = True
-            outgoing_route = OutgoingRoute(path, bgp4_format=bgp4_format)
+            outgoing_route = OutgoingRoute(path)
             self.enque_outgoing_msg(outgoing_route)
 
         # If path from a bgp-peer is new best path, we share it with
 <at>  <at>  -1698,10 +1739,10  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
 
             # If new best path has community attribute, it should be taken into
             # account when sending UPDATE to peers.
-            comm_attr = path.get_pattr(pathattr.Community.ATTR_NAME)
+            comm_attr = path.get_pattr(BGP_ATTR_TYPE_COMMUNITIES)
             if comm_attr:
                 comm_attr_na = comm_attr.has_comm_attr(
-                    pathattr.Community.NO_ADVERTISE
+                    BGPPathAttributeCommunities.NO_ADVERTISE
                 )
                 # If we have NO_ADVERTISE attribute present, we do not send
                 # UPDATE to any peers
 <at>  <at>  -1712,10 +1753,11  <at>  <at>  class Peer(Source, Sink, NeighborConfListener, Activity):
                     return
 
                 comm_attr_ne = comm_attr.has_comm_attr(
-                    pathattr.Community.NO_EXPORT
+                    BGPPathAttributeCommunities.NO_EXPORT
                 )
                 comm_attr_nes = comm_attr.has_comm_attr(
-                    pathattr.Community.NO_EXPORT_SUBCONFED)
+                    BGPPathAttributeCommunities.NO_EXPORT_SUBCONFED
+                )
                 # If NO_EXPORT_SUBCONFED/NO_EXPORT is one of the attribute, we
                 # do not advertise to eBGP peers as we do not have any
                 # confederation feature at this time.
diff --git a/ryu/services/protocols/bgp/processor.py b/ryu/services/protocols/bgp/processor.py
index db5ae9b..e56224d 100644
--- a/ryu/services/protocols/bgp/processor.py
+++ b/ryu/services/protocols/bgp/processor.py
 <at>  <at>  -18,12 +18,6  <at>  <at> 
 
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import AsPath
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import LocalPref
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import Med
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import Origin
-
 from ryu.services.protocols.bgp.base import Activity
 from ryu.services.protocols.bgp.base import add_bgp_error_metadata
 from ryu.services.protocols.bgp.base import BGP_PROCESSOR_ERROR_CODE
 <at>  <at>  -31,6 +25,14  <at>  <at>  from ryu.services.protocols.bgp.base import BGPSException
 from ryu.services.protocols.bgp.utils import circlist
 from ryu.services.protocols.bgp.utils.evtlet import EventletIOFactory
 
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_LOCAL_PREF
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
+from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_IGP
+from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_EGP
+from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_INCOMPLETE
 
 LOG = logging.getLogger('bgpspeaker.processor')
 
 <at>  <at>  -150,9 +152,9  <at>  <at>  class BgpProcessor(Activity):
         # Wake-up processing thread if sleeping.
         self.dest_que_evt.set()
 
-#==============================================================================
+# =============================================================================
 # Best path computation related utilities.
-#==============================================================================
+# =============================================================================
 
 # Various reasons a path is chosen as best path.
 BPR_UNKNOWN = 'Unknown'
 <at>  <at>  -289,8 +291,8  <at>  <at>  def _cmp_by_local_pref(path1, path2):
     # TODO(PH): Revisit this when BGPS has concept of policy to be applied to
     # in-bound NLRIs.
     # Default local-pref values is 100
-    lp1 = path1.get_pattr(LocalPref.ATTR_NAME)
-    lp2 = path2.get_pattr(LocalPref.ATTR_NAME)
+    lp1 = path1.get_pattr(BGP_ATTR_TYPE_LOCAL_PREF)
+    lp2 = path2.get_pattr(BGP_ATTR_TYPE_LOCAL_PREF)
     if not (lp1 and lp2):
         return None
 
 <at>  <at>  -335,8 +337,8  <at>  <at>  def _cmp_by_aspath(path1, path2):
     Shortest as-path length is preferred. If both path have same lengths,
     we return None.
     """
-    as_path1 = path1.get_pattr(AsPath.ATTR_NAME)
-    as_path2 = path2.get_pattr(AsPath.ATTR_NAME)
+    as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
+    as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
     assert as_path1 and as_path2
     l1 = as_path1.get_as_path_len()
     l2 = as_path2.get_as_path_len()
 <at>  <at>  -356,18 +358,18  <at>  <at>  def _cmp_by_origin(path1, path2):
     If both paths have same origin, we return None.
     """
     def get_origin_pref(origin):
-        if origin.value == Origin.IGP:
+        if origin.value == BGP_ATTR_ORIGIN_IGP:
             return 3
-        elif origin.value == Origin.EGP:
+        elif origin.value == BGP_ATTR_ORIGIN_EGP:
             return 2
-        elif origin.value == Origin.INCOMPLETE:
+        elif origin.value == BGP_ATTR_ORIGIN_INCOMPLETE:
             return 1
         else:
             LOG.error('Invalid origin value encountered %s.' % origin)
             return 0
 
-    origin1 = path1.get_pattr(Origin.ATTR_NAME)
-    origin2 = path2.get_pattr(Origin.ATTR_NAME)
+    origin1 = path1.get_pattr(BGP_ATTR_TYPE_ORIGIN)
+    origin2 = path2.get_pattr(BGP_ATTR_TYPE_ORIGIN)
     assert origin1 is not None and origin2 is not None
 
     # If both paths have same origins
 <at>  <at>  -394,7 +396,7  <at>  <at>  def _cmp_by_med(path1, path2):
     RFC says lower MED is preferred over higher MED value.
     """
     def get_path_med(path):
-        med = path.get_pattr(Med.ATTR_NAME)
+        med = path.get_pattr(BGP_ATTR_TYPE_MULTI_EXIT_DISC)
         if not med:
             return 0
         return med.value
diff --git a/ryu/services/protocols/bgp/rtconf/base.py b/ryu/services/protocols/bgp/rtconf/base.py
index 36febbc..7b625fd 100644
--- a/ryu/services/protocols/bgp/rtconf/base.py
+++ b/ryu/services/protocols/bgp/rtconf/base.py
 <at>  <at>  -28,8 +28,6  <at>  <at>  from ryu.services.protocols.bgp.base import BGPSException
 from ryu.services.protocols.bgp.base import get_validator
 from ryu.services.protocols.bgp.base import RUNTIME_CONF_ERROR_CODE
 from ryu.services.protocols.bgp.base import validate
-
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import ExtCommunity
 from ryu.services.protocols.bgp.utils import validation
 from ryu.services.protocols.bgp.utils.validation import is_valid_old_asn
 
 <at>  <at>  -73,9 +71,9  <at>  <at>  MAX_NUM_EXPORT_RT = 250
 MAX_NUM_SOO = 10
 
 
-#==============================================================================
+# =============================================================================
 # Runtime configuration errors or exceptions.
-#==============================================================================
+# =============================================================================
 
  <at> add_bgp_error_metadata(code=RUNTIME_CONF_ERROR_CODE, sub_code=1,
                         def_desc='Error with runtime-configuration.')
 <at>  <at>  -139,9 +137,9  <at>  <at>  class ConfigValueError(RuntimeConfigError):
             super(ConfigValueError, self).__init__(desc=kwargs.get('desc'))
 
 
-#==============================================================================
+# =============================================================================
 # Configuration base classes.
-#==============================================================================
+# =============================================================================
 
 class BaseConf(object):
     """Base class for a set of configuration values.
 <at>  <at>  -225,8 +223,8  <at>  <at>  class BaseConf(object):
             self._settings[req_attr] = req_attr_value
 
     def add_listener(self, evt, callback):
-#         if (evt not in self.get_valid_evts()):
-#             raise RuntimeConfigError(desc=('Unknown event %s' % evt))
+        #   if (evt not in self.get_valid_evts()):
+        #       raise RuntimeConfigError(desc=('Unknown event %s' % evt))
 
         listeners = self._listeners.get(evt, None)
         if not listeners:
 <at>  <at>  -523,9 +521,9  <at>  <at>  class ConfEvent(object):
                    (self.src, self.name, self.value))
 
 
-#==============================================================================
+# =============================================================================
 # Runtime configuration setting validators and their registry.
-#==============================================================================
+# =============================================================================
 
  <at> validate(name=ConfWithId.ID)
 def validate_conf_id(identifier):
 <at>  <at>  -658,9 +656,7  <at>  <at>  def validate_soo_list(soo_list):
     if not (len(soo_list) <= MAX_NUM_SOO):
         raise ConfigValueError(desc='Max. SOO is limited to %s' %
                                MAX_NUM_SOO)
-    try:
-        ExtCommunity.validate_supported_attributes(soo_list)
-    except ValueError:
+    if not all(validation.is_valid_ext_comm_attr(attr) for attr in soo_list):
         raise ConfigValueError(conf_name=SITE_OF_ORIGINS,
                                conf_value=soo_list)
     # Check if we have duplicates
 <at>  <at>  -691,9 +687,9  <at>  <at>  def validate_advertise_peer_as(advertise_peer_as):
     return advertise_peer_as
 
 
-#==============================================================================
+# =============================================================================
 # Other utils.
-#==============================================================================
+# =============================================================================
 
 def compute_optional_conf(conf_name, default_value, **all_config):
     """Returns *conf_name* settings if provided in *all_config*, else returns
diff --git a/ryu/services/protocols/bgp/rtconf/common.py b/ryu/services/protocols/bgp/rtconf/common.py
index b4fc5ca..05d3a7a 100644
--- a/ryu/services/protocols/bgp/rtconf/common.py
+++ b/ryu/services/protocols/bgp/rtconf/common.py
 <at>  <at>  -229,9 +229,9  <at>  <at>  class CommonConf(BaseConf):
             MAX_PATH_EXT_RTFILTER_ALL, DEFAULT_MAX_PATH_EXT_RTFILTER_ALL,
             **kwargs)
 
-    #==========================================================================
+    # =========================================================================
     # Required attributes
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def local_as(self):
 <at>  <at>  -241,9 +241,9  <at>  <at>  class CommonConf(BaseConf):
     def router_id(self):
         return self._settings[ROUTER_ID]
 
-    #==========================================================================
+    # =========================================================================
     # Optional attributes with valid defaults.
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def bgp_conn_retry_time(self):
diff --git a/ryu/services/protocols/bgp/rtconf/neighbors.py b/ryu/services/protocols/bgp/rtconf/neighbors.py
index c65af61..ab7fa48 100644
--- a/ryu/services/protocols/bgp/rtconf/neighbors.py
+++ b/ryu/services/protocols/bgp/rtconf/neighbors.py
 <at>  <at>  -19,6 +19,18  <at>  <at> 
 from abc import abstractmethod
 import logging
 
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import BGPOptParamCapabilityEnhancedRouteRefresh
+from ryu.lib.packet.bgp import BGPOptParamCapabilityMultiprotocol
+from ryu.lib.packet.bgp import BGPOptParamCapabilityRouteRefresh
+from ryu.lib.packet.bgp import BGP_CAP_ENHANCED_ROUTE_REFRESH
+from ryu.lib.packet.bgp import BGP_CAP_MULTIPROTOCOL
+from ryu.lib.packet.bgp import BGP_CAP_ROUTE_REFRESH
+
 from ryu.services.protocols.bgp.base import OrderedDict
 from ryu.services.protocols.bgp.rtconf.base import ADVERTISE_PEER_AS
 from ryu.services.protocols.bgp.rtconf.base import BaseConf
 <at>  <at>  -45,17 +57,6  <at>  <at>  from ryu.services.protocols.bgp.rtconf.base import SITE_OF_ORIGINS
 from ryu.services.protocols.bgp.rtconf.base import validate
 from ryu.services.protocols.bgp.rtconf.base import validate_med
 from ryu.services.protocols.bgp.rtconf.base import validate_soo_list
-
-from ryu.services.protocols.bgp.protocols.bgp.capabilities import \
-    EnhancedRouteRefreshCap
-from ryu.services.protocols.bgp.protocols.bgp.capabilities import \
-    MultiprotocolExtentionCap
-from ryu.services.protocols.bgp.protocols.bgp.capabilities import \
-    RouteRefreshCap
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
 from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4
 from ryu.services.protocols.bgp.utils.validation import is_valid_old_asn
 
 <at>  <at>  -224,9 +225,9  <at>  <at>  class NeighborConf(ConfWithId, ConfWithStats):
         self_valid_evts.update(NeighborConf.VALID_EVT)
         return self_valid_evts
 
-    #==========================================================================
+    # =========================================================================
     # Required attributes
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def remote_as(self):
 <at>  <at>  -244,9 +245,9  <at>  <at>  class NeighborConf(ConfWithId, ConfWithStats):
     def host_bind_port(self):
         return self._settings[LOCAL_PORT]
 
-    #==========================================================================
+    # =========================================================================
     # Optional attributes with valid defaults.
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def hold_time(self):
 <at>  <at>  -288,9 +289,9  <at>  <at>  class NeighborConf(ConfWithId, ConfWithStats):
             self._notify_listeners(NeighborConf.UPDATE_ENABLED_EVT,
                                    enable)
 
-    #==========================================================================
+    # =========================================================================
     # Optional attributes with no valid defaults.
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def multi_exit_disc(self):
 <at>  <at>  -334,27 +335,35  <at>  <at>  class NeighborConf(ConfWithId, ConfWithStats):
         capabilities = OrderedDict()
         mbgp_caps = []
         if self.cap_mbgp_ipv4:
-            mbgp_caps.append(MultiprotocolExtentionCap(RF_IPv4_UC))
+            mbgp_caps.append(
+                BGPOptParamCapabilityMultiprotocol(
+                    RF_IPv4_UC.afi, RF_IPv4_UC.safi))
 
         if self.cap_mbgp_vpnv4:
-            mbgp_caps.append(MultiprotocolExtentionCap(RF_IPv4_VPN))
+            mbgp_caps.append(
+                BGPOptParamCapabilityMultiprotocol(
+                    RF_IPv4_VPN.afi, RF_IPv4_VPN.safi))
 
         if self.cap_mbgp_vpnv6:
-            mbgp_caps.append(MultiprotocolExtentionCap(RF_IPv6_VPN))
+            mbgp_caps.append(
+                BGPOptParamCapabilityMultiprotocol(
+                    RF_IPv6_VPN.afi, RF_IPv6_VPN.safi))
 
         if self.cap_rtc:
-            mbgp_caps.append(MultiprotocolExtentionCap(RF_RTC_UC))
+            mbgp_caps.append(
+                BGPOptParamCapabilityMultiprotocol(
+                    RF_RTC_UC.afi, RF_RTC_UC.safi))
 
         if mbgp_caps:
-            capabilities[MultiprotocolExtentionCap.CODE] = mbgp_caps
+            capabilities[BGP_CAP_MULTIPROTOCOL] = mbgp_caps
 
         if self.cap_refresh:
-            capabilities[RouteRefreshCap.CODE] = [
-                RouteRefreshCap.get_singleton()]
+            capabilities[BGP_CAP_ROUTE_REFRESH] = [
+                BGPOptParamCapabilityRouteRefresh()]
 
         if self.cap_enhanced_refresh:
-            capabilities[EnhancedRouteRefreshCap.CODE] = [
-                EnhancedRouteRefreshCap.get_singleton()]
+            capabilities[BGP_CAP_ENHANCED_ROUTE_REFRESH] = [
+                BGPOptParamCapabilityEnhancedRouteRefresh()]
 
         return capabilities
 
diff --git a/ryu/services/protocols/bgp/rtconf/vrfs.py b/ryu/services/protocols/bgp/rtconf/vrfs.py
index 6b7b60c..48b4809 100644
--- a/ryu/services/protocols/bgp/rtconf/vrfs.py
+++ b/ryu/services/protocols/bgp/rtconf/vrfs.py
 <at>  <at>  -20,9 +20,11  <at>  <at> 
 import abc
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import ExtCommunity
-from ryu.services.protocols.bgp.utils import validation
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv6_UC
+from ryu.lib.packet.bgp import BGPPathAttributeExtendedCommunities
 
+from ryu.services.protocols.bgp.utils import validation
 from ryu.services.protocols.bgp.base import get_validator
 from ryu.services.protocols.bgp.rtconf.base import BaseConf
 from ryu.services.protocols.bgp.rtconf.base import BaseConfListener
 <at>  <at>  -40,8 +42,6  <at>  <at>  from ryu.services.protocols.bgp.rtconf.base import SITE_OF_ORIGINS
 from ryu.services.protocols.bgp.rtconf.base import validate
 from ryu.services.protocols.bgp.rtconf.base import validate_med
 from ryu.services.protocols.bgp.rtconf.base import validate_soo_list
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_UC
 
 
 LOG = logging.getLogger('bgpspeaker.rtconf.vrfs')
 <at>  <at>  -73,11 +73,8  <at>  <at>  def validate_import_rts(import_rts):
     if not (len(import_rts) <= MAX_NUM_IMPORT_RT):
         raise ConfigValueError(desc='Max. import RT is limited to %s' %
                                MAX_NUM_IMPORT_RT)
-    try:
-        ExtCommunity.validate_supported_attributes(import_rts)
-    except ValueError:
-        raise ConfigValueError(conf_name=IMPORT_RTS,
-                               conf_value=import_rts)
+    if not all(validation.is_valid_ext_comm_attr(rt) for rt in import_rts):
+        raise ConfigValueError(conf_name=IMPORT_RTS, conf_value=import_rts)
     # Check if we have duplicates
     unique_rts = set(import_rts)
     if len(unique_rts) != len(import_rts):
 <at>  <at>  -94,9 +91,8  <at>  <at>  def validate_export_rts(export_rts):
     if not (len(export_rts) <= MAX_NUM_EXPORT_RT):
         raise ConfigValueError(desc='Max. import RT is limited to %s' %
                                MAX_NUM_EXPORT_RT)
-    try:
-        ExtCommunity.validate_supported_attributes(export_rts)
-    except Exception:
+
+    if not all(validation.is_valid_ext_comm_attr(rt) for rt in export_rts):
         raise ConfigValueError(conf_name=EXPORT_RTS, conf_value=export_rts)
     # Check if we have duplicates
     unique_rts = set(export_rts)
 <at>  <at>  -169,17 +165,17  <at>  <at>  class VrfConf(ConfWithId, ConfWithStats):
         import_maps = kwargs.pop(IMPORT_MAPS, [])
         self._settings[IMPORT_MAPS] = import_maps
 
-    #==========================================================================
+    # =========================================================================
     # Required attributes
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def route_dist(self):
         return self._settings[ROUTE_DISTINGUISHER]
 
-    #==========================================================================
+    # =========================================================================
     # Optional attributes with valid defaults.
-    #==========================================================================
+    # =========================================================================
 
      <at> property
     def import_rts(self):
diff --git a/ryu/services/protocols/bgp/speaker.py b/ryu/services/protocols/bgp/speaker.py
index 6744044..af8f991 100644
--- a/ryu/services/protocols/bgp/speaker.py
+++ b/ryu/services/protocols/bgp/speaker.py
 <at>  <at>  -21,6 +21,24  <at>  <at>  import socket
 import struct
 import traceback
 
+from ryu.lib.packet import bgp
+from ryu.lib.packet.bgp import RouteFamily
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import BGPMessage
+from ryu.lib.packet.bgp import BGPOpen
+from ryu.lib.packet.bgp import BGPUpdate
+from ryu.lib.packet.bgp import BGPKeepAlive
+from ryu.lib.packet.bgp import BGPNotification
+from ryu.lib.packet.bgp import BGPRouteRefresh
+from ryu.lib.packet.bgp import BGP_MSG_OPEN
+from ryu.lib.packet.bgp import BGP_MSG_UPDATE
+from ryu.lib.packet.bgp import BGP_MSG_KEEPALIVE
+from ryu.lib.packet.bgp import BGP_MSG_NOTIFICATION
+from ryu.lib.packet.bgp import BGP_MSG_ROUTE_REFRESH
+from ryu.lib.packet.bgp import BGP_CAP_ENHANCED_ROUTE_REFRESH
+from ryu.lib.packet.bgp import BGP_CAP_MULTIPROTOCOL
+from ryu.lib.packet.bgp import BGP_CAP_ROUTE_REFRESH
+
 from ryu.services.protocols.bgp.base import Activity
 from ryu.services.protocols.bgp.base import add_bgp_error_metadata
 from ryu.services.protocols.bgp.base import BGPSException
 <at>  <at>  -30,25 +48,8  <at>  <at>  from ryu.services.protocols.bgp.constants import BGP_FSM_OPEN_CONFIRM
 from ryu.services.protocols.bgp.constants import BGP_FSM_OPEN_SENT
 from ryu.services.protocols.bgp.constants import BGP_VERSION_NUM
 from ryu.services.protocols.bgp.protocol import Protocol
-from ryu.services.protocols.bgp.protocols.bgp.capabilities import \
-    EnhancedRouteRefreshCap
-from ryu.services.protocols.bgp.protocols.bgp.capabilities import \
-    MultiprotocolExtentionCap
-from ryu.services.protocols.bgp.protocols.bgp.capabilities import \
-    RouteRefreshCap
-import ryu.services.protocols.bgp.protocols.bgp.exceptions as exceptions
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import BgpExc
-from ryu.services.protocols.bgp.protocols.bgp import messages
-from ryu.services.protocols.bgp.protocols.bgp.messages import Keepalive
-from ryu.services.protocols.bgp.protocols.bgp.messages import Notification
-from ryu.services.protocols.bgp.protocols.bgp.messages import Open
-from ryu.services.protocols.bgp.protocols.bgp.messages import RouteRefresh
-from ryu.services.protocols.bgp.protocols.bgp.messages import Update
-from ryu.services.protocols.bgp.protocols.bgp import nlri
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
 from ryu.services.protocols.bgp.utils.validation import is_valid_old_asn
 
-
 LOG = logging.getLogger('bgpspeaker.speaker')
 
 # BGP min. and max. message lengths as per RFC.
 <at>  <at>  -56,7 +57,7  <at>  <at>  BGP_MIN_MSG_LEN = 19
 BGP_MAX_MSG_LEN = 4096
 
 # Keep-alive singleton.
-_KEEP_ALIVE = Keepalive()
+_KEEP_ALIVE = BGPKeepAlive()
 
 
  <at> add_bgp_error_metadata(code=CORE_ERROR_CODE, sub_code=2,
 <at>  <at>  -74,11 +75,11  <at>  <at>  def nofitication_factory(code, subcode):
     - `code`: (int) BGP error code
     - `subcode`: (int) BGP error sub-code
     """
-    reason = Notification.REASONS.get((code, subcode))
-    if not reason:
+    notification = BGPNotification(code, subcode)
+    if not notification.reason:
         raise ValueError('Invalid code/sub-code.')
 
-    return Notification(code, subcode)
+    return notification
 
 
 class BgpProtocol(Protocol, Activity):
 <at>  <at>  -174,8 +175,8  <at>  <at>  class BgpProtocol(Protocol, Activity):
         peer_cap = self.recv_open_msg.caps
         # Both local and peer should advertise ERR capability for it to be
         # enabled.
-        if (local_cap.get(EnhancedRouteRefreshCap.CODE) and
-                peer_cap.get(EnhancedRouteRefreshCap.CODE)):
+        if (local_cap.get(BGP_CAP_ENHANCED_ROUTE_REFRESH) and
+                peer_cap.get(BGP_CAP_ENHANCED_ROUTE_REFRESH)):
             err_cap_enabled = True
 
         return err_cap_enabled
 <at>  <at>  -183,14 +184,13  <at>  <at>  class BgpProtocol(Protocol, Activity):
     def _check_route_fmly_adv(self, open_msg, route_family):
         match_found = False
 
-        local_caps = open_msg.caps
-        mbgp_cap = local_caps.get(MultiprotocolExtentionCap.CODE)
-        # Check MP_BGP capability was advertised.
-        if mbgp_cap:
-            # Iterate over all advertised mp_bgp caps to find a match.
-            for peer_cap in mbgp_cap:
-                if (route_family.afi == peer_cap.route_family.afi and
-                        route_family.safi == peer_cap.route_family.safi):
+        local_caps = open_msg.opt_param
+        for cap in local_caps:
+            # Check MP_BGP capability was advertised.
+            if cap.cap_code == BGP_CAP_MULTIPROTOCOL:
+                # Iterate over all advertised mp_bgp caps to find a match.
+                if (route_family.afi == cap.afi and
+                        route_family.safi == cap.safi):
                     match_found = True
 
         return match_found
 <at>  <at>  -218,8 +218,8  <at>  <at>  class BgpProtocol(Protocol, Activity):
         local_caps = self.sent_open_msg.caps
         remote_caps = self.recv_open_msg.caps
 
-        local_mbgp_cap = local_caps.get(MultiprotocolExtentionCap.CODE)
-        remote_mbgp_cap = remote_caps.get(MultiprotocolExtentionCap.CODE)
+        local_mbgp_cap = local_caps.get(BGP_CAP_MULTIPROTOCOL)
+        remote_mbgp_cap = remote_caps.get(BGP_CAP_MULTIPROTOCOL)
         # Check MP_BGP capabilities were advertised.
         if local_mbgp_cap and remote_mbgp_cap:
             local_families = {
 <at>  <at>  -236,7 +236,7  <at>  <at>  class BgpProtocol(Protocol, Activity):
 
         afs = []
         for afi, safi in afi_safi:
-            afs.append(nlri.get_rf(afi, safi))
+            afs.append(RouteFamily(afi, safi))
         return afs
 
     def is_mbgp_cap_valid(self, route_family):
 <at>  <at>  -262,7 +262,7  <at>  <at>  class BgpProtocol(Protocol, Activity):
     def data_received(self, next_bytes):
         try:
             self._data_received(next_bytes)
-        except BgpExc as exc:
+        except bgp.BgpExc as exc:
             LOG.error(
                 "BGPExc Exception while receiving data: "
                 "%s \n Traceback %s \n"
 <at>  <at>  -310,7 +310,7  <at>  <at>  class BgpProtocol(Protocol, Activity):
             # authentication.
             if (auth != BgpProtocol.MESSAGE_MARKER):
                 LOG.error('Invalid message marker received: %s' % auth)
-                raise exceptions.NotSync()
+                raise bgp.NotSync()
 
             # Check if we have valid bgp message length.
             check = lambda: length < BGP_MIN_MSG_LEN\
 <at>  <at>  -318,36 +318,27  <at>  <at>  class BgpProtocol(Protocol, Activity):
 
             # RFC says: The minimum length of the OPEN message is 29
             # octets (including the message header).
-            check2 = lambda: ptype == Open.TYPE_CODE\
-                and length < Open.MIN_LENGTH
+            check2 = lambda: ptype == BGP_MSG_OPEN\
+                and length < BGPOpen._MIN_LEN
 
             # RFC says: A KEEPALIVE message consists of only the
             # message header and has a length of 19 octets.
-            check3 = lambda: ptype == Keepalive.TYPE_CODE\
-                and length != BGP_MIN_MSG_LEN
+            check3 = lambda: ptype == BGP_MSG_KEEPALIVE\
+                and length != BGPKeepAlive._MIN_LEN
 
             # RFC says: The minimum length of the UPDATE message is 23
             # octets.
-            check4 = lambda: ptype == Update.TYPE_CODE\
-                and length < Update.MIN_LENGTH
+            check4 = lambda: ptype == BGP_MSG_UPDATE\
+                and length < BGPUpdate._MIN_LEN
 
             if check() or check2() or check3() or check4():
-                raise exceptions.BadLen(ptype, length)
+                raise bgp.BadLen(ptype, length)
 
             # If we have partial message we wait for rest of the message.
             if len(self._recv_buff) < length:
                 return
-
-            # If we have full message, we get its payload/data.
-            payload = self._recv_buff[BGP_MIN_MSG_LEN:length]
-
-            # Update buffer to not contain any part of the current message.
-            self._recv_buff = self._recv_buff[length:]
-
-            # Try to decode payload into specified message type.
-            # If we have any error parsing the message, we send appropriate
-            # bgp notification message.
-            msg = messages.decode(ptype, payload, length)
+            msg, rest = BGPMessage.parser(self._recv_buff)
+            self._recv_buff = rest
 
             # If we have a valid bgp message we call message handler.
             self._handle_msg(msg)
 <at>  <at>  -365,14 +356,9  <at>  <at>  class BgpProtocol(Protocol, Activity):
         RFC ref: http://tools.ietf.org/html/rfc4486
         http://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml
         """
-        reason = Notification.REASONS.get((code, subcode))
-        if not reason:
-            # Not checking for type of parameters to allow some flexibility
-            # via. duck-typing.
-            raise ValueError('Unsupported code/sub-code given.')
-
-        notification = Notification(code, subcode, reason)
-        self._socket.sendall(notification.encode())
+        notification = BGPNotification(code, subcode)
+        reason = notification.reason
+        self._socket.sendall(notification.serialize())
         self._signal_bus.bgp_error(self._peer, code, subcode, reason)
         LOG.error(
             'Sent notification to %r>> %s' %
 <at>  <at>  -385,8 +371,8  <at>  <at>  class BgpProtocol(Protocol, Activity):
             raise BgpProtocolException('Tried to send message to peer when '
                                        'this protocol instance is not started'
                                        ' or is no longer is started state.')
-        self._socket.sendall(msg.encode())
-        if msg.MSG_NAME == Notification.MSG_NAME:
+        self._socket.sendall(msg.serialize())
+        if msg.type == BGP_MSG_NOTIFICATION:
             LOG.error('Sent notification to %s>> %s' %
                       (self.get_peername(), msg))
 
 <at>  <at>  -394,7 +380,7  <at>  <at>  class BgpProtocol(Protocol, Activity):
 
         else:
             LOG.debug('Sent msg. %s to %s>> %s' %
-                      (msg.MSG_NAME, self.get_peername(), msg))
+                      (msg.__class__, self.get_peername(), msg))
 
     def stop(self):
         Activity.stop(self)
 <at>  <at>  -407,28 +393,31  <at>  <at>  class BgpProtocol(Protocol, Activity):
         settings. RTC or RR/ERR are MUST capability if peer does not support
         either one of them we have to end session.
         """
-        assert open_msg.TYPE_CODE == Open.TYPE_CODE
+        assert open_msg.type == BGP_MSG_OPEN
         # Validate remote ASN.
-        remote_asnum = open_msg.asnum
+        remote_asnum = open_msg.my_as
         # Since 4byte AS is not yet supported, we validate AS as old style AS.
         if (not is_valid_old_asn(remote_asnum) or
                 remote_asnum != self._peer.remote_as):
-            raise exceptions.BadPeerAs()
+            raise bgp.BadPeerAs()
 
         # Validate bgp version number.
         if open_msg.version != BGP_VERSION_NUM:
-            raise exceptions.UnsupportedVersion(BGP_VERSION_NUM)
-
-        adv_caps = open_msg.caps
-        rr_cap_adv = adv_caps.get(RouteRefreshCap.CODE)
-        err_cap_adv = adv_caps.get(EnhancedRouteRefreshCap.CODE)
+            raise bgp.UnsupportedVersion(BGP_VERSION_NUM)
+
+        adv_caps = open_msg.opt_param
+        for cap in adv_caps:
+            if cap.cap_code == BGP_CAP_ROUTE_REFRESH:
+                rr_cap_adv = cap
+            elif cap.cap_code == BGP_CAP_ENHANCED_ROUTE_REFRESH:
+                err_cap_adv = cap
         # If either RTC or RR/ERR are MUST capability if peer does not support
         # either one of them we have to end session as we have to request peer
         # to send prefixes for new VPNs that may be created automatically.
         # TODO(PH): Check with experts if error is suitable in this case
         if not (rr_cap_adv or err_cap_adv or
                 self._check_route_fmly_adv(open_msg, RF_RTC_UC)):
-            raise exceptions.UnsupportedOptParam()
+            raise bgp.UnsupportedOptParam()
 
     def _handle_msg(self, msg):
         """When a BGP message is received, send it to peer.
 <at>  <at>  -438,10 +427,10  <at>  <at>  class BgpProtocol(Protocol, Activity):
         *Notification* message we close connection with peer.
         """
         LOG.debug('Received %s msg. from %s<< \n%s' %
-                  (msg.MSG_NAME, str(self.get_peername()), msg))
+                  (msg.__class__, str(self.get_peername()), msg))
 
         # If we receive open message we try to bind to protocol
-        if (msg.MSG_NAME == Open.MSG_NAME):
+        if (msg.type == BGP_MSG_OPEN):
             if self.state == BGP_FSM_OPEN_SENT:
                 # Validate open message.
                 self._validate_open_msg(msg)
 <at>  <at>  -458,18 +447,18  <at>  <at>  class BgpProtocol(Protocol, Activity):
                     # resolution choose different instance of protocol and this
                     # instance has to close. Before closing it sends
                     # appropriate notification msg. to peer.
-                    raise exceptions.CollisionResolution()
+                    raise bgp.CollisionResolution()
 
                 # If peer sends Hold Time as zero, then according to RFC we do
                 # not set Hold Time and Keep Alive timer.
-                if msg.holdtime == 0:
+                if msg.hold_time == 0:
                     LOG.info('The Hold Time sent by the peer is zero, hence '
                              'not setting any Hold Time and Keep Alive'
                              ' timers.')
                 else:
                     # Start Keep Alive timer considering Hold Time preference
                     # of the peer.
-                    self._start_timers(msg.holdtime)
+                    self._start_timers(msg.hold_time)
                     self._send_keepalive()
 
                 # Peer does not see open message.
 <at>  <at>  -480,8 +469,8  <at>  <at>  class BgpProtocol(Protocol, Activity):
                           'OpenSent')
                 # Received out-of-order open message
                 # We raise Finite state machine error
-                raise exceptions.FiniteStateMachineError()
-        elif msg.MSG_NAME == Notification.MSG_NAME:
+                raise bgp.FiniteStateMachineError()
+        elif msg.type == BGP_MSG_NOTIFICATION:
             if self._peer:
                 self._signal_bus.bgp_notification_received(self._peer, msg)
             # If we receive notification message
 <at>  <at>  -491,14 +480,14  <at>  <at>  class BgpProtocol(Protocol, Activity):
             return
 
         # If we receive keepalive or update message, we reset expire timer.
-        if (msg.MSG_NAME == Keepalive.MSG_NAME or
-                msg.MSG_NAME == Update.MSG_NAME):
+        if (msg.type == BGP_MSG_KEEPALIVE or
+                msg.type == BGP_MSG_UPDATE):
             if self._expiry:
                 self._expiry.reset()
 
         # Call peer message handler for appropriate messages.
-        if (msg.MSG_NAME in
-                (Keepalive.MSG_NAME, Update.MSG_NAME, RouteRefresh.MSG_NAME)):
+        if (msg.type in
+                (BGP_MSG_UPDATE, BGP_MSG_KEEPALIVE, BGP_MSG_ROUTE_REFRESH)):
             self._peer.handle_msg(msg)
         # We give chance to other threads to run.
         self.pause(0)
 <at>  <at>  -529,8 +518,8  <at>  <at>  class BgpProtocol(Protocol, Activity):
         """Hold timer expired event handler.
         """
         LOG.info('Negotiated hold time %s expired.' % self._holdtime)
-        code = exceptions.HoldTimerExpired.CODE
-        subcode = exceptions.HoldTimerExpired.SUB_CODE
+        code = BGP_ERROR_HOLD_TIMER_EXPIRED
+        subcode = BGP_ERROR_SUB_HOLD_TIMER_EXPIRED
         self.send_notification(code, subcode)
         self.connection_lost('Negotiated hold time %s expired.' %
                              self._holdtime)
 <at>  <at>  -554,7 +543,7  <at>  <at>  class BgpProtocol(Protocol, Activity):
                 self.data_received(next_bytes)
         except socket.error as err:
             conn_lost_reason = 'Connection to peer lost: %s.' % err
-        except BgpExc as ex:
+        except bgp.BgpExc as ex:
             conn_lost_reason = 'Connection to peer lost, reason: %s.' % ex
         except Exception as e:
             LOG.debug(traceback.format_exc())
 <at>  <at>  -570,7 +559,7  <at>  <at>  class BgpProtocol(Protocol, Activity):
         assert self.state == BGP_FSM_CONNECT
         # We have a connection with peer we send open message.
         open_msg = self._peer.create_open_msg()
-        self._holdtime = open_msg.holdtime
+        self._holdtime = open_msg.hold_time
         self.state = BGP_FSM_OPEN_SENT
         if not self.is_reactive:
             self._peer.state.bgp_state = self.state
diff --git a/ryu/services/protocols/bgp/utils/bgp.py b/ryu/services/protocols/bgp/utils/bgp.py
index fe22c45..4e7391b 100644
--- a/ryu/services/protocols/bgp/utils/bgp.py
+++ b/ryu/services/protocols/bgp/utils/bgp.py
 <at>  <at>  -19,14 +19,16  <at>  <at> 
 import logging
 import socket
 
-from ryu.services.protocols.bgp.protocols.bgp.messages import Update
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RtNlri
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import Med
+from ryu.lib.packet.bgp import BGPUpdate
+from ryu.lib.packet.bgp import RF_IPv4_UC
+from ryu.lib.packet.bgp import RF_IPv4_VPN
+from ryu.lib.packet.bgp import RF_IPv6_VPN
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import RouteTargetMembershipNLRI
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
+from ryu.lib.packet.bgp import BGPPathAttributeMultiExitDisc
+from ryu.lib.packet.bgp import BGPPathAttributeMpUnreachNLRI
+from ryu.lib.packet.bgp import BGPPathAttributeUnknown
 from ryu.services.protocols.bgp.info_base.rtc import RtcPath
 from ryu.services.protocols.bgp.info_base.ipv4 import Ipv4Path
 from ryu.services.protocols.bgp.info_base.vpnv4 import Vpnv4Path
 <at>  <at>  -43,7 +45,7  <at>  <at>  _ROUTE_FAMILY_TO_PATH_MAP = {RF_IPv4_UC: Ipv4Path,
 
 
 def create_path(src_peer, nlri, **kwargs):
-    route_family = nlri.route_family
+    route_family = nlri.ROUTE_FAMILY
     assert route_family in _ROUTE_FAMILY_TO_PATH_MAP.keys()
     path_cls = _ROUTE_FAMILY_TO_PATH_MAP.get(route_family)
     return path_cls(src_peer, nlri, src_peer.version_num, **kwargs)
 <at>  <at>  -57,7 +59,7  <at>  <at>  def clone_path_and_update_med_for_target_neighbor(path, med):
                          route_family)
     path_cls = _ROUTE_FAMILY_TO_PATH_MAP.get(route_family)
     pattrs = path.pathattr_map
-    pattrs[Med.ATTR_NAME] = Med(med)
+    pattrs[BGP_ATTR_TYPE_MULTI_EXIT_DISC] = BGPPathAttributeMultiExitDisc(med)
     return path_cls(
         path.source, path.nlri, path.source_version_num,
         pattrs=pattrs, nexthop=path.nexthop,
 <at>  <at>  -77,7 +79,7  <at>  <at>  def clone_rtcpath_update_rt_as(path, new_rt_as):
     if not path or path.route_family != RF_RTC_UC:
         raise ValueError('Expected RT_NLRI path')
     old_nlri = path.nlri
-    new_rt_nlri = RtNlri(new_rt_as, old_nlri.route_target)
+    new_rt_nlri = RouteTargetMembershipNLRI(new_rt_as, old_nlri.route_target)
     return RtcPath(path.source, new_rt_nlri, path.source_version_num,
                    pattrs=path.pathattr_map, nexthop=path.nexthop,
                    is_withdraw=path.is_withdraw)
 <at>  <at>  -106,7 +108,7  <at>  <at>  def get_unknow_opttrans_attr(path):
     path_attrs = path.pathattr_map
     unknown_opt_tran_attrs = {}
     for _, attr in path_attrs.iteritems():
-        if (isinstance(attr, pathattr.UnRcgPathAttr) and
+        if (isinstance(attr, BGPPathAttributeUnknown) and
                 attr.is_optional_transitive()):
             unknown_opt_tran_attrs[attr.type_code] = attr
     return unknown_opt_tran_attrs
 <at>  <at>  -114,9 +116,10  <at>  <at>  def get_unknow_opttrans_attr(path):
 
 def create_end_of_rib_update():
     """Construct end-of-rib (EOR) Update instance."""
-    mpunreach_attr = pathattr.MpUnreachNlri(RF_IPv4_VPN, [])
-    pathattr_map = {pathattr.MpUnreachNlri.ATTR_NAME: mpunreach_attr}
-    eor = Update(pathattr_map)
+    mpunreach_attr = BGPPathAttributeMpUnreachNLRI(RF_IPv4_VPN.afi,
+                                                   RF_IPv4_VPN.safi,
+                                                   [])
+    eor = BGPUpdate(path_attributes=[mpunreach_attr])
     return eor
 
 
diff --git a/ryu/services/protocols/bgp/utils/rtfilter.py b/ryu/services/protocols/bgp/utils/rtfilter.py
index cfc9f89..aa8d42a 100644
--- a/ryu/services/protocols/bgp/utils/rtfilter.py
+++ b/ryu/services/protocols/bgp/utils/rtfilter.py
 <at>  <at>  -18,10 +18,12  <at>  <at> 
 """
 import logging
 
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RtNlri
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import AsPath
-from ryu.services.protocols.bgp.protocols.bgp.pathattr import Origin
+from ryu.lib.packet.bgp import RF_RTC_UC
+from ryu.lib.packet.bgp import RouteTargetMembershipNLRI
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
+from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
+from ryu.lib.packet.bgp import BGPPathAttributeAsPath
+from ryu.lib.packet.bgp import BGPPathAttributeOrigin
 from ryu.services.protocols.bgp.base import OrderedDict
 from ryu.services.protocols.bgp.info_base.rtc import RtcPath
 
 <at>  <at>  -75,14 +77,15  <at>  <at>  class RouteTargetManager(object):
 
     def _add_rt_nlri_for_as(self, rtc_as, route_target, is_withdraw=False):
         from ryu.services.protocols.bgp.core import EXPECTED_ORIGIN
-        rt_nlri = RtNlri(rtc_as, route_target)
+        rt_nlri = RouteTargetMembershipNLRI(rtc_as, route_target)
         # Create a dictionary for path-attrs.
         pattrs = OrderedDict()
         if not is_withdraw:
             # MpReachNlri and/or MpUnReachNlri attribute info. is contained
             # in the path. Hence we do not add these attributes here.
-            pattrs[Origin.ATTR_NAME] = Origin(EXPECTED_ORIGIN)
-            pattrs[AsPath.ATTR_NAME] = AsPath([])
+            pattrs[BGP_ATTR_TYPE_ORIGIN] = BGPPathAttributeOrigin(
+                EXPECTED_ORIGIN)
+            pattrs[BGP_ATTR_TYPE_AS_PATH] = BGPPathAttributeAsPath([])
 
         # Create Path instance and initialize appropriately.
         path = RtcPath(None, rt_nlri, 0, is_withdraw=is_withdraw,
 <at>  <at>  -152,7 +155,7  <at>  <at>  class RouteTargetManager(object):
             else:
                 # New RT could be Default RT, which means we need to share this
                 # path
-                desired_rts.add(RtNlri.DEFAULT_RT)
+                desired_rts.add(RouteTargetMembershipNLRI.DEFAULT_RT)
                 # If we have RT filter has new RTs that are common with path
                 # RTs, then we send this path to peer
                 if desired_rts.intersection(new_rts):
 <at>  <at>  -172,8 +175,8  <at>  <at>  class RouteTargetManager(object):
         interested_rts.update(self._vrfs_conf.vrf_interested_rts)
         # Remove default RT as it is not a valid RT for paths
         # TODO(PH): Check if we have better alternative than add and remove
-        interested_rts.add(RtNlri.DEFAULT_RT)
-        interested_rts.remove(RtNlri.DEFAULT_RT)
+        interested_rts.add(RouteTargetMembershipNLRI.DEFAULT_RT)
+        interested_rts.remove(RouteTargetMembershipNLRI.DEFAULT_RT)
         return interested_rts
 
     def update_interested_rts(self):
--

-- 
1.7.9.5


------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
ISHIDA Wataru | 16 Apr 06:14 2014
Picon

[PATCH 3/3] bgp: remove original bgp packet library


Signed-off-by: ISHIDA Wataru <ishida.wataru-Zyj7fXuS5i5L9jVzuh4AOg <at> public.gmane.org>
---
 .../protocols/bgp/protocols/bgp/__init__.py        |    7 -
 .../protocols/bgp/protocols/bgp/capabilities.py    |  280 -----
 .../protocols/bgp/protocols/bgp/exceptions.py      |  349 -------
 .../protocols/bgp/protocols/bgp/messages.py        |  536 ----------
 ryu/services/protocols/bgp/protocols/bgp/nlri.py   |  841 ---------------
 .../protocols/bgp/protocols/bgp/pathattr.py        | 1076 --------------------
 6 files changed, 3089 deletions(-)
 delete mode 100644 ryu/services/protocols/bgp/protocols/bgp/__init__.py
 delete mode 100644 ryu/services/protocols/bgp/protocols/bgp/capabilities.py
 delete mode 100644 ryu/services/protocols/bgp/protocols/bgp/exceptions.py
 delete mode 100644 ryu/services/protocols/bgp/protocols/bgp/messages.py
 delete mode 100644 ryu/services/protocols/bgp/protocols/bgp/nlri.py
 delete mode 100644 ryu/services/protocols/bgp/protocols/bgp/pathattr.py

diff --git a/ryu/services/protocols/bgp/protocols/bgp/__init__.py b/ryu/services/protocols/bgp/protocols/bgp/__init__.py
deleted file mode 100644
index 99c5338..0000000
--- a/ryu/services/protocols/bgp/protocols/bgp/__init__.py
+++ /dev/null
 <at>  <at>  -1,7 +0,0  <at>  <at> 
-try:
-    from collections import OrderedDict
-except ImportError:
-    from ordereddict import OrderedDict
-
-# Pointer to active/available OrderedDict.
-OrderedDict = OrderedDict
diff --git a/ryu/services/protocols/bgp/protocols/bgp/capabilities.py b/ryu/services/protocols/bgp/protocols/bgp/capabilities.py
deleted file mode 100644
index ed2acaa..0000000
--- a/ryu/services/protocols/bgp/protocols/bgp/capabilities.py
+++ /dev/null
 <at>  <at>  -1,280 +0,0  <at>  <at> 
-# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-# implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-This module provides BGP protocol capabilities classes and utility methods to
-encode and decode them.
-"""
-
-from abc import ABCMeta
-from abc import abstractmethod
-import logging
-import struct
-
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import \
-    MalformedOptionalParam
-from ryu.services.protocols.bgp.protocols.bgp.nlri import get_rf
-from ryu.services.protocols.bgp.protocols.bgp.nlri import \
-    RouteFamily as route_fmly
-
-
-# Logger instance for this module
-LOG = logging.getLogger('bgpspeaker.bgp.proto.capabilities')
-
-# Registry for bgp capability class by their code.
-# <Key>: <Value> - <capability-code>: <capability-class>
-_BGP_CAPABILITY_REGISTRY = {}
-
-
-def _register_bgp_capabilities(cls):
-    """Utility decorator used to register bgp supported/recognized
-    capabilities.
-
-    Capabilities classes are registered by their capability-code.
-    """
-    assert issubclass(cls, Capability)
-    assert hasattr(cls, 'CODE')
-    assert _BGP_CAPABILITY_REGISTRY.get(cls.CODE) is None
-    _BGP_CAPABILITY_REGISTRY[cls.CODE] = cls
-    return cls
-
-
-def is_recognized_cap_codes(cap_code):
-    return cap_code in _BGP_CAPABILITY_REGISTRY
-
-
-def decode(byte_value):
-    """Decodes given `byte_value` into appropriate capabilities.
-
-        Parameter:
-            - `byte_value`: (str) byte representation of one capability
-            advertisement
-        Returns:
-            - list of capabilities decoded from given bytes
-        Note: Different routers pack capability in one capability
-        advertisement/optional parameter or group them into several capability
-        advertisements. Hence we return a list of one or more decoded
-        capabilities.
-    """
-    idx = 0
-    total_len = len(byte_value)
-    caps = []
-    # Parse one of more capabilities packed inside given capability-
-    # advertisement payload
-    while idx < total_len:
-        cap_code, clen = struct.unpack_from('BB', byte_value, idx)
-        idx += 2
-        cap = byte_value[idx:idx + clen]
-        idx += clen
-
-        cap_cls = _BGP_CAPABILITY_REGISTRY.get(cap_code)
-        if cap_cls:
-            cap = cap_cls.from_bytes(cap)
-            caps.append(cap)
-        else:
-            # RFC 5492 says: If a BGP speaker receives from its peer a
-            # capability that it does not itself support or recognize, it MUST
-            # ignore that capability.  In particular, the Unsupported
-            # Capability NOTIFICATION message MUST NOT be generated and the BGP
-            # session MUST NOT be terminated in  response to reception of a
-            # capability that is not supported by the local speaker.
-            cap = UnSupportedCap(cap_code, cap)
-
-    return caps
-
-
-class Capability(object):
-    """Super class of all bgp capability optional parameters.
-    """
-    __metaclass__ = ABCMeta
-    CODE = -1
-    NAME = 'abstract-cap'
-
-     <at> abstractmethod
-    def packvalue(self):
-        """Encode this bgp capability."""
-        raise NotImplementedError()
-
-    def encode(self):
-        """Encodes this bgp capability with header and body."""
-        body = self.packvalue()
-        return struct.pack('BB', self.__class__.CODE, len(body)) + body
-
-    def __repr__(self):
-        return '<%s>' % self.__class__.NAME
-
-
-class UnSupportedCap(Capability):
-    """Represents unknown capability.
-
-    According to RFC 5492 it is recommended to that we do not sent NOTIFICATION
-    message for "Unsupported Capability".
-    """
-    NAME = 'unsupported-cap'
-
-    def __init__(self, code, value):
-        self.CODE = code
-        self._value = value
-
-    def packvalue(self):
-        return self._value
-
-    def __repr__(self):
-        return '<UnSupportedCap(code=%s)>' % self.CODE
-
-
- <at> _register_bgp_capabilities
-class MultiprotocolExtentionCap(Capability):
-    """This class represents bgp multi-protocol extension capability.
-    """
-    CODE = 1
-    NAME = 'mbgp'
-
-    def __init__(self, route_family):
-        if not route_fmly.is_valid(route_family):
-            raise ValueError('Invalid argument %s' % route_family)
-
-        Capability.__init__(self)
-        self.route_family = route_family
-
-    def packvalue(self):
-        return struct.pack('!HH', self.route_family.afi,
-                           self.route_family.safi)
-
-     <at> classmethod
-    def from_bytes(cls, value):
-        afi, _, safi = struct.unpack_from('!HBB', value)
-        return cls(get_rf(afi, safi))
-
-    def __repr__(self):
-        return ('<MultiprotocolExtenstionCap(af=%s, saf=%s)>' %
-                (self.route_family.afi, self.route_family.safi))
-
-    def __eq__(self, other):
-        if (other.__class__.CODE == self.__class__.CODE and
-                other.route_family.afi == self.route_family.afi and
-                other.route_family.safi == self.route_family.safi):
-            return True
-        return False
-
-
-class ZeroLengthCap(Capability):
-    """This is a super class represent all bgp capability with zero length."""
-    CODE = -1
-    NAME = 'zero-length'
-
-    def packvalue(self):
-        return ''
-
-     <at> classmethod
-    def from_bytes(cls, value):
-        if len(value) > 0:
-            LOG.error('Zero length capability has non-zero length value!')
-            raise MalformedOptionalParam()
-        return cls.get_singleton()
-
-     <at> staticmethod
-    def get_singleton():
-        raise NotImplementedError()
-
-
- <at> _register_bgp_capabilities
-class RouteRefreshCap(ZeroLengthCap):
-    CODE = 2
-    NAME = 'route-refresh'
-
-    def __str__(self):
-        return RouteRefreshCap.NAME
-
-     <at> staticmethod
-    def get_singleton():
-        return _ROUTE_REFRESH_CAP
-
-
- <at> _register_bgp_capabilities
-class OldRouteRefreshCap(ZeroLengthCap):
-    CODE = 128
-    NAME = 'old-route-refresh'
-
-    def __str__(self):
-        return OldRouteRefreshCap.NAME
-
-     <at> staticmethod
-    def get_singleton():
-        return _OLD_ROUTE_REFRESH_CAP
-
-
-# Since four byte as capability is not fully supported, we do not register it
-# as supported/recognized capability.
- <at> _register_bgp_capabilities
-class GracefulRestartCap(Capability):
-    CODE = 64
-    NAME = 'graceful-restart'
-
-    def __init__(self, value):
-        # TODO(PH): Provide implementation
-        Capability.__init__(self)
-        self.value = value
-
-    def packvalue(self):
-        # TODO(PH): Provide implementation
-        return self.value
-
-     <at> classmethod
-    def from_bytes(cls, value):
-        return cls(value)
-
-
-# Since four byte as capability is not fully supported, we do not register it
-# as supported/recognized capability.
- <at> _register_bgp_capabilities
-class FourByteAsCap(Capability):
-    CODE = 65
-    NAME = '4byteas'
-
-    def __init__(self, four_byte_as):
-        Capability.__init__(self)
-        self.four_byte_as = four_byte_as
-
-    def packvalue(self):
-        return struct.pack('!I', self.four_byte_as)
-
-     <at> classmethod
-    def from_bytes(cls, value):
-        value, = struct.unpack('!I', value)
-        return cls(value)
-
-    def __repr__(self):
-        return '<FourByteAsCap(%s)>' % self.four_byte_as
-
-    def __eq__(self, other):
-        if (other and other.four_byte_as == self.four_byte_as):
-            return True
-        return False
-
-
- <at> _register_bgp_capabilities
-class EnhancedRouteRefreshCap(ZeroLengthCap):
-    CODE = 70
-    NAME = 'enhanced-refresh'
-
-     <at> staticmethod
-    def get_singleton():
-        return _ENHANCED_ROUTE_REFRESH_CAP
-
-# Zero length capability singletons
-_ROUTE_REFRESH_CAP = RouteRefreshCap()
-_ENHANCED_ROUTE_REFRESH_CAP = EnhancedRouteRefreshCap()
-_OLD_ROUTE_REFRESH_CAP = OldRouteRefreshCap()
diff --git a/ryu/services/protocols/bgp/protocols/bgp/exceptions.py b/ryu/services/protocols/bgp/protocols/bgp/exceptions.py
deleted file mode 100644
index dba5ed6..0000000
--- a/ryu/services/protocols/bgp/protocols/bgp/exceptions.py
+++ /dev/null
 <at>  <at>  -1,349 +0,0  <at>  <at> 
-import struct
-
-
-class BgpExc(Exception):
-    """Base bgp exception."""
-
-    CODE = 0
-    """BGP error code."""
-
-    SUB_CODE = 0
-    """BGP error sub-code."""
-
-    SEND_ERROR = True
-    """Flag if set indicates Notification message should be sent to peer."""
-
-    def __init__(self, data=''):
-        self.data = data
-
-    def __str__(self):
-        return '<%s %r>' % (self.__class__.__name__, self.data)
-
-
-class BadNotification(BgpExc):
-    SEND_ERROR = False
-
-#=============================================================================
-# Message Header Errors
-#=============================================================================
-
-
-class NotSync(BgpExc):
-    CODE = 1
-    SUB_CODE = 1
-
-
-class BadLen(BgpExc):
-    CODE = 1
-    SUB_CODE = 2
-
-    def __init__(self, msg_type_code, message_length):
-        self.msg_type_code = msg_type_code
-        self.length = message_length
-        self.data = struct.pack('!H', self.length)
-
-    def __str__(self):
-        return '<BadLen %d msgtype=%d>' % (self.length, self.msg_type_code)
-
-
-class BadMsg(BgpExc):
-    """Error to indicate un-recognized message type.
-
-    RFC says: If the Type field of the message header is not recognized, then
-    the Error Subcode MUST be set to Bad Message Type.  The Data field MUST
-    contain the erroneous Type field.
-    """
-    CODE = 1
-    SUB_CODE = 3
-
-    def __init__(self, msg_type):
-        self.msg_type = msg_type
-        self.data = struct.pack('B', msg_type)
-
-    def __str__(self):
-        return '<BadMsg %d>' % (self.msg,)
-
-#=============================================================================
-# OPEN Message Errors
-#=============================================================================
-
-
-class MalformedOptionalParam(BgpExc):
-    """If recognized optional parameters are malformed.
-
-    RFC says: If one of the Optional Parameters in the OPEN message is
-    recognized, but is malformed, then the Error Subcode MUST be set to 0
-    (Unspecific).
-    """
-    CODE = 2
-    SUB_CODE = 0
-
-
-class UnsupportedVersion(BgpExc):
-    """Error to indicate unsupport bgp version number.
-
-    RFC says: If the version number in the Version field of the received OPEN
-    message is not supported, then the Error Subcode MUST be set to Unsupported
-    Version Number.  The Data field is a 2-octet unsigned integer, which
-    indicates the largest, locally-supported version number less than the
-    version the remote BGP peer bid (as indicated in the received OPEN
-    message), or if the smallest, locally-supported version number is greater
-    than the version the remote BGP peer bid, then the smallest, locally-
-    supported version number.
-    """
-    CODE = 2
-    SUB_CODE = 1
-
-    def __init__(self, locally_support_version):
-        self.data = struct.pack('H', locally_support_version)
-
-
-class BadPeerAs(BgpExc):
-    """Error to indicate open message has incorrect AS number.
-
-    RFC says: If the Autonomous System field of the OPEN message is
-    unacceptable, then the Error Subcode MUST be set to Bad Peer AS.  The
-    determination of acceptable Autonomous System numbers is configure peer AS.
-    """
-    CODE = 2
-    SUB_CODE = 2
-
-
-class BadBgpId(BgpExc):
-    """Error to indicate incorrect BGP Identifier.
-
-    RFC says: If the BGP Identifier field of the OPEN message is syntactically
-    incorrect, then the Error Subcode MUST be set to Bad BGP Identifier.
-    Syntactic correctness means that the BGP Identifier field represents a
-    valid unicast IP host address.
-    """
-    CODE = 2
-    SUB_CODE = 3
-
-
-class UnsupportedOptParam(BgpExc):
-    """Error to indicate unsupported optional parameters.
-
-    RFC says: If one of the Optional Parameters in the OPEN message is not
-    recognized, then the Error Subcode MUST be set to Unsupported Optional
-    Parameters.
-    """
-    CODE = 2
-    SUB_CODE = 4
-
-
-class AuthFailure(BgpExc):
-    CODE = 2
-    SUB_CODE = 5
-
-
-class UnacceptableHoldTime(BgpExc):
-    """Error to indicate Unacceptable Hold Time in open message.
-
-    RFC says: If the Hold Time field of the OPEN message is unacceptable, then
-    the Error Subcode MUST be set to Unacceptable Hold Time.
-    """
-    CODE = 2
-    SUB_CODE = 6
-
-#=============================================================================
-# UPDATE message related errors
-#=============================================================================
-
-
-class MalformedAttrList(BgpExc):
-    """Error to indicate UPDATE message is malformed.
-
-    RFC says: Error checking of an UPDATE message begins by examining the path
-    attributes.  If the Withdrawn Routes Length or Total Attribute Length is
-    too large (i.e., if Withdrawn Routes Length + Total Attribute Length + 23
-    exceeds the message Length), then the Error Subcode MUST be set to
-    Malformed Attribute List.
-    """
-    CODE = 3
-    SUB_CODE = 1
-
-
-class UnRegWellKnowAttr(BgpExc):
-    CODE = 3
-    SUB_CODE = 2
-
-
-class MissingWellKnown(BgpExc):
-    """Error to indicate missing well-known attribute.
-
-    RFC says: If any of the well-known mandatory attributes are not present,
-    then the Error Subcode MUST be set to Missing Well-known Attribute.  The
-    Data field MUST contain the Attribute Type Code of the missing, well-known
-    attribute.
-    """
-    CODE = 3
-    SUB_CODE = 3
-
-    def __init__(self, pattr_type_code):
-        self.pattr_type_code = pattr_type_code
-        self.data = struct.pack('B', pattr_type_code)
-
-
-class AttrFlagError(BgpExc):
-    """Error to indicate recognized path attributes have incorrect flags.
-
-    RFC says: If any recognized attribute has Attribute Flags that conflict
-    with the Attribute Type Code, then the Error Subcode MUST be set to
-    Attribute Flags Error.  The Data field MUST contain the erroneous attribute
-    (type, length, and value).
-    """
-    CODE = 3
-    SUB_CODE = 4
-
-
-class AttrLenError(BgpExc):
-    CODE = 3
-    SUB_CODE = 5
-
-
-class InvalidOriginError(BgpExc):
-    """Error indicates undefined Origin attribute value.
-
-    RFC says: If the ORIGIN attribute has an undefined value, then the Error
-    Sub- code MUST be set to Invalid Origin Attribute.  The Data field MUST
-    contain the unrecognized attribute (type, length, and value).
-    """
-    CODE = 3
-    SUB_CODE = 6
-
-
-class RoutingLoop(BgpExc):
-    CODE = 3
-    SUB_CODE = 7
-
-
-class InvalidNextHop(BgpExc):
-    CODE = 3
-    SUB_CODE = 8
-
-
-class OptAttrError(BgpExc):
-    """Error indicates Optional Attribute is malformed.
-
-    RFC says: If an optional attribute is recognized, then the value of this
-    attribute MUST be checked.  If an error is detected, the attribute MUST be
-    discarded, and the Error Subcode MUST be set to Optional Attribute Error.
-    The Data field MUST contain the attribute (type, length, and value).
-    """
-    CODE = 3
-    SUB_CODE = 9
-
-
-class InvalidNetworkField(BgpExc):
-    CODE = 3
-    SUB_CODE = 10
-
-
-class MalformedAsPath(BgpExc):
-    """Error to indicate if AP_PATH attribute is syntactically incorrect.
-
-    RFC says: The AS_PATH attribute is checked for syntactic correctness.  If
-    the path is syntactically incorrect, then the Error Subcode MUST be set to
-    Malformed AS_PATH.
-    """
-    CODE = 3
-    SUB_CODE = 11
-
-
-#=============================================================================
-# Hold Timer Expired
-#=============================================================================
-
-
-class HoldTimerExpired(BgpExc):
-    """Error to indicate Hold Timer expired.
-
-    RFC says: If a system does not receive successive KEEPALIVE, UPDATE, and/or
-    NOTIFICATION messages within the period specified in the Hold Time field of
-    the OPEN message, then the NOTIFICATION message with the Hold Timer Expired
-    Error Code is sent and the BGP connection is closed.
-    """
-    CODE = 4
-    SUB_CODE = 1
-
-#=============================================================================
-# Finite State Machine Error
-#=============================================================================
-
-
-class FiniteStateMachineError(BgpExc):
-    """Error to indicate any Finite State Machine Error.
-
-    RFC says: Any error detected by the BGP Finite State Machine (e.g., receipt
-    of an unexpected event) is indicated by sending the NOTIFICATION message
-    with the Error Code Finite State Machine Error.
-    """
-    CODE = 5
-    SUB_CODE = 1
-
-
-#=============================================================================
-# Cease Errors
-#=============================================================================
-
-class MaxPrefixReached(BgpExc):
-    CODE = 6
-    SUB_CODE = 1
-
-
-class AdminShutdown(BgpExc):
-    """Error to indicate Administrative shutdown.
-
-    RFC says: If a BGP speaker decides to administratively shut down its
-    peering with a neighbor, then the speaker SHOULD send a NOTIFICATION
-    message  with the Error Code Cease and the Error Subcode 'Administrative
-    Shutdown'.
-    """
-    CODE = 6
-    SUB_CODE = 2
-
-
-class PeerDeConfig(BgpExc):
-    CODE = 6
-    SUB_CODE = 3
-
-
-class AdminReset(BgpExc):
-    CODE = 6
-    SUB_CODE = 4
-
-
-class ConnRejected(BgpExc):
-    """Error to indicate Connection Rejected.
-
-    RFC says: If a BGP speaker decides to disallow a BGP connection (e.g., the
-    peer is not configured locally) after the speaker accepts a transport
-    protocol connection, then the BGP speaker SHOULD send a NOTIFICATION
-    message with the Error Code Cease and the Error Subcode "Connection
-    Rejected".
-    """
-    CODE = 6
-    SUB_CODE = 5
-
-
-class OtherConfChange(BgpExc):
-    CODE = 6
-    SUB_CODE = 6
-
-
-class CollisionResolution(BgpExc):
-    """Error to indicate Connection Collision Resolution.
-
-    RFC says: If a BGP speaker decides to send a NOTIFICATION message with the
-    Error Code Cease as a result of the collision resolution procedure (as
-    described in [BGP-4]), then the subcode SHOULD be set to "Connection
-    Collision Resolution".
-    """
-    CODE = 6
-    SUB_CODE = 7
-
-
-class OutOfResource(BgpExc):
-    CODE = 6
-    SUB_CODE = 8
diff --git a/ryu/services/protocols/bgp/protocols/bgp/messages.py b/ryu/services/protocols/bgp/protocols/bgp/messages.py
deleted file mode 100644
index 6d74b1c..0000000
--- a/ryu/services/protocols/bgp/protocols/bgp/messages.py
+++ /dev/null
 <at>  <at>  -1,536 +0,0  <at>  <at> 
-# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-# implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-This module provides BGP protocol message classes and utility methods to encode
-and decode them.
-
-This file is adapted from pybgp open source project.
-"""
-from abc import ABCMeta
-from abc import abstractmethod
-from copy import copy
-import cStringIO
-import logging
-import socket
-import struct
-
-from ryu.services.protocols.bgp.protocols.bgp import capabilities
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import BadBgpId
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import BadLen
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import BadMsg
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import BadNotification
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import \
-    MalformedAttrList
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import \
-    UnacceptableHoldTime
-from ryu.services.protocols.bgp.protocols.bgp import nlri
-from ryu.services.protocols.bgp.protocols.bgp.nlri import get_rf
-from ryu.services.protocols.bgp.protocols.bgp import OrderedDict
-from ryu.services.protocols.bgp.protocols.bgp import pathattr
-from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4
-from ryu.services.protocols.bgp.utils.validation import is_valid_old_asn
-
-
-LOG = logging.getLogger('bgpspeaker.bgp.proto.messages')
-
-# BGP capability optional parameter type
-CAP_OPT_PARA_TYPE = 2
-
-# Registry for bgp message class by their type code.
-# <key>: <value> - <type-code>: <msg class>
-_BGP_MESSAGE_REGISTRY = {}
-
-
-def _register_bgp_message(cls):
-    """Used as class decorator for registering bgp message class by their
-    type-code.
-    """
-    assert _BGP_MESSAGE_REGISTRY.get(cls.TYPE_CODE) is None
-    assert hasattr(cls, 'from_bytes')
-    _BGP_MESSAGE_REGISTRY[cls.TYPE_CODE] = cls
-    return cls
-
-
-class BgpMessage(object):
-    """Super class of all bgp messages.
-    """
-    __metaclass__ = ABCMeta
-    TYPE_CODE = 0
-    MSG_NAME = 'abstract-msg'
-    HEADER_SIZE = 19
-
-     <at> abstractmethod
-    def packvalue(self):
-        """Encodes the body of this bgp message."""
-        raise NotImplementedError()
-
-    def encode(self):
-        """Encodes this bgp message with header and body."""
-        body = self.packvalue()
-        return struct.pack('!16sHB', '\xff' * 16, 19 + len(body),
-                           self.__class__.TYPE_CODE) + body
-
-
-class RecognizedBgpMessage(BgpMessage):
-    """Represents recognized/supported bgp message.
-
-    Declares a factory method to create an instance from bytes.
-    """
-     <at> classmethod
-    def from_bytes(cls, recv_bytes, total_msg_length):
-        raise NotImplementedError()
-
-
- <at> _register_bgp_message
-class Open(RecognizedBgpMessage):
-    """Represents bgp OPEN message.
-
-    This is the first message sent by each peer after TCP connection is
-    established.
-    """
-    MSG_NAME = 'open'
-    TYPE_CODE = 1
-    MIN_LENGTH = 29
-
-    def __init__(self, version, asnum, holdtime, bgpid, caps,
-                 unrec_params=None):
-        # Validate arguments.
-        if version < 1:
-            raise ValueError('Invalid version number %s' % version)
-        if not is_valid_old_asn(asnum):
-            raise ValueError('Invalid AS number %s' % asnum)
-        if holdtime <= 2:
-            raise ValueError('Holdtime has to be greater than 2 sec.')
-        if not caps:
-            raise ValueError('Invalid capabilities.')
-        if not is_valid_ipv4(bgpid):
-            raise ValueError('Invalid bgp ID, should be valid IPv4, '
-                             'but given %s' % bgpid)
-
-        BgpMessage.__init__(self)
-        self._version = version
-        self._holdtime = holdtime
-        self._asnum = asnum
-        self._bgpid = bgpid
-        self._caps = caps
-        self._unrec_params = unrec_params
-        if not unrec_params:
-            self._unrec_params = OrderedDict()
-
-     <at> property
-    def version(self):
-        return self._version
-
-     <at> property
-    def holdtime(self):
-        return self._holdtime
-
-     <at> property
-    def asnum(self):
-        return self._asnum
-
-     <at> property
-    def bgpid(self):
-        return self._bgpid
-
-     <at> property
-    def caps(self):
-        return copy(self._caps)
-
-     <at> property
-    def unrec_params(self):
-        return copy(self._unrec_params)
-
-     <at> classmethod
-    def from_bytes(cls, recv_bytes, total_msg_len):
-        # Validate OPEN message length.
-        if len(recv_bytes) < 10:
-            raise BadLen(Open.TYPE_CODE, len(recv_bytes) + cls.HEADER_SIZE)
-
-        version, asnum, holdtime, bgpid, paramlen = \
-            struct.unpack_from('!BHH4sB', recv_bytes)
-
-        if len(recv_bytes) != (10 + paramlen):
-            # TODO(PH): Check what RFC says to do here.
-            LOG.debug('Open message: too short.')
-
-        offset = 10
-
-        # BGP implementation MUST reject Hold Time values of one or two
-        # seconds.
-        if holdtime <= 2:
-            raise UnacceptableHoldTime()
-
-        # BGP Identifier field MUST represents a valid unicast IP host address.
-        bgpid = socket.inet_ntoa(bgpid)
-        if not is_valid_ipv4(bgpid):
-            raise BadBgpId()
-
-        # Parse optional parameters.
-        caps = OrderedDict()
-        unrec_params = OrderedDict()
-        while offset < len(recv_bytes):
-            ptype, plen = struct.unpack_from('BB', recv_bytes, offset)
-            offset += 2
-            value = recv_bytes[offset:offset + plen]
-            offset += plen
-
-            # Parse capabilities optional parameter.
-            if ptype == CAP_OPT_PARA_TYPE:
-                bgp_caps = capabilities.decode(value)
-                # store decoded bgp capabilities by their capability-code
-                for cap in bgp_caps:
-                    cap_code = cap.CODE
-                    if cap_code in caps:
-                        caps[cap_code].append(cap)
-                    else:
-                        caps[cap_code] = [cap]
-            else:
-                # Other unrecognized optional parameters.
-                unrec_params[ptype] = value
-
-        # Un-recognized capabilities are passed on, its up to application to
-        # check if unrec-optional-paramters are a problem and send NOTIFICATION
-        return cls(version, asnum, holdtime, bgpid, caps, unrec_params)
-
-    def packvalue(self):
-        params = cStringIO.StringIO()
-        # Capabilities optional parameters.
-        for capability in self.caps.itervalues():
-            for cap in capability:
-                encoded_cap = cStringIO.StringIO()
-                encoded_cap.write(cap.encode())
-                encoded_cap_value = encoded_cap.getvalue()
-                encoded_cap.close()
-                params.write(struct.pack('BB',
-                                         CAP_OPT_PARA_TYPE,
-                                         len(encoded_cap_value)))
-                params.write(encoded_cap_value)
-
-        # Other optional parameters.
-        for ptype, pvalue in self.unrec_params.items():
-            params.write(struct.pack('BB', ptype, len(pvalue)))
-            params.write(pvalue)
-
-        bgpid = socket.inet_aton(self.bgpid)
-        params_value = params.getvalue()
-        params.close()
-        return struct.pack('!BHH4sB', self.version, self.asnum, self.holdtime,
-                           bgpid, len(params_value)) + params_value
-
-    def __str__(self):
-        str_rep = cStringIO.StringIO()
-        str_rep.write('Open message Ver=%s As#=%s Hold Time=%s Bgp Id=%s' %
-                      (self.version, self.asnum, self.holdtime, self.bgpid))
-        for param, value in self.unrec_params.items():
-            str_rep.write(' unrec_param %s=%r' % (param, value))
-        for cap, value in self.caps.items():
-            str_rep.write(' cap %s=%r' % (cap, value))
-        return str_rep.getvalue()
-
-
- <at> _register_bgp_message
-class Keepalive(BgpMessage):
-    MSG_NAME = 'keepalive'
-    TYPE_CODE = 4
-
-     <at> classmethod
-    def from_bytes(cls, recv_bytes, total_msg_len):
-        # Validate KeepAlive msg. length
-        if len(recv_bytes):
-            LOG.info("Received keepalive msg. with data! %r" % (recv_bytes,))
-            raise BadLen(
-                Keepalive.TYPE_CODE,
-                len(recv_bytes) + cls.HEADER_SIZE
-            )
-
-        self = cls()
-        return self
-
-    def packvalue(self):
-        return ''
-
-    def __str__(self):
-        return 'Keepalive message'
-
-
- <at> _register_bgp_message
-class RouteRefresh(BgpMessage):
-    MSG_NAME = 'route-refresh'
-    TYPE_CODE = 5
-
-    def __init__(self, route_family, demarcation=0):
-        BgpMessage.__init__(self)
-        self._route_family = route_family
-        self._demarcation = demarcation
-        self.eor_sent = False
-
-     <at> property
-    def route_family(self):
-        return self._route_family
-
-     <at> property
-    def demarcation(self):
-        return self._demarcation
-
-     <at> classmethod
-    def from_bytes(cls, recv_bytes, total_msg_len):
-        # Validate length of RouteRefresh message.
-        if len(recv_bytes) != 4:
-            raise BadLen(
-                RouteRefresh.TYPE_CODE,
-                len(recv_bytes) + cls.HEADER_SIZE
-            )
-
-        afi, reserved, safi = struct.unpack_from('!HBB', recv_bytes)
-        route_family = get_rf(afi, safi)
-        return cls(route_family, reserved)
-
-    def packvalue(self):
-        return struct.pack('!HBB', self.route_family.afi, self.demarcation,
-                           self._route_family.safi)
-
-    def __str__(self):
-        return 'Route-refresh message (%s, %s)' % \
-            (self.route_family, self.demarcation)
-
-
- <at> _register_bgp_message
-class Notification(BgpMessage):
-    MSG_NAME = 'notification'
-    TYPE_CODE = 3
-    REASONS = {
-        (1, 1): 'Message Header Error: not synchronised',
-        (1, 2): 'Message Header Error: bad message len',
-        (1, 3): 'Message Header Error: bad message type',
-        (2, 1): 'Open Message Error: unsupported version',
-        (2, 2): 'Open Message Error: bad peer AS',
-        (2, 3): 'Open Message Error: bad BGP identifier',
-        (2, 4): 'Open Message Error: unsupported optional param',
-        (2, 5): 'Open Message Error: authentication failure',
-        (2, 6): 'Open Message Error: unacceptable hold time',
-        (2, 7): 'Open Message Error: Unsupported Capability',
-        (2, 8): 'Open Message Error: Unassigned',
-        (3, 1): 'Update Message Error: malformed attribute list',
-        (3, 2): 'Update Message Error: unrecognized well-known attr',
-        (3, 3): 'Update Message Error: missing well-known attr',
-        (3, 4): 'Update Message Error: attribute flags error',
-        (3, 5): 'Update Message Error: attribute length error',
-        (3, 6): 'Update Message Error: invalid origin attr',
-        (3, 7): 'Update Message Error: as routing loop',
-        (3, 8): 'Update Message Error: invalid next hop attr',
-        (3, 9): 'Update Message Error: optional attribute error',
-        (3, 10): 'Update Message Error: invalid network field',
-        (3, 11): 'Update Message Error: malformed AS_PATH',
-        (4, 1): 'Hold Timer Expired',
-        (5, 1): 'Finite State Machine Error',
-        (6, 1): 'Cease: Maximum Number of Prefixes Reached',
-        (6, 2): 'Cease: Administrative Shutdown',
-        (6, 3): 'Cease: Peer De-configured',
-        (6, 4): 'Cease: Administrative Reset',
-        (6, 5): 'Cease: Connection Rejected',
-        (6, 6): 'Cease: Other Configuration Change',
-        (6, 7): 'Cease: Connection Collision Resolution',
-        (6, 8): 'Cease: Out of Resources',
-    }
-
-    def __init__(self, code, subcode, data=''):
-        BgpMessage.__init__(self)
-        self._code = code
-        self._subcode = subcode
-        self._data = data
-
-     <at> property
-    def code(self):
-        return self._code
-
-     <at> property
-    def subcode(self):
-        return self._subcode
-
-     <at> property
-    def data(self):
-        return self._data
-
-     <at> classmethod
-    def from_bytes(cls, recv_bytes, total_msg_len):
-        # Validate NOTIFICATION msg. length.
-        if len(recv_bytes) < 2:
-            LOG.error('Received NOTIFICATION msg. with bad length %s' %
-                      (len(recv_bytes) + cls.HEADER_SIZE))
-            raise BadNotification()
-
-        code, subcode = struct.unpack_from('BB', recv_bytes)
-        data = recv_bytes[2:]
-
-        # Check code or sub-code are recognized.
-        if not Notification.REASONS.get((code, subcode)):
-            LOG.error('Received notification msg. with unrecognized Error '
-                      'code or Sub-code (%s, %s)' % (code, subcode))
-            raise BadNotification()
-
-        return cls(code, subcode, data)
-
-    def __str__(self):
-        c, s = self.code, self.subcode
-        if (c, s) in self.REASONS:
-            return ('Notification "%s" params %r' %
-                    (self.REASONS[c, s], self.data))
-        return ('Notification message code=%d subcode=%d params=%r' %
-                (self.code, self.subcode, self.data))
-
-    def packvalue(self):
-        v = struct.pack('BB', self.code, self.subcode)
-        if self.data:
-            v += self.data
-        return v
-
-
- <at> _register_bgp_message
-class Update(BgpMessage):
-    MSG_NAME = 'update'
-    TYPE_CODE = 2
-    WITHDRAW_NLRI = 'withdraw_nlri'
-    PATH_ATTR_AND_NLRI = 'path_attr_and_nlri'
-    MIN_LENGTH = 23
-
-    def __init__(self, pathattr_map=None, nlri_list=None, withdraw_list=None):
-        """Initailizes a new `Update` instance.
-
-        Parameter:
-            - `pathattr_map`: (OrderedDict) key -> attribute name,
-            value -> attribute.
-            - `nlri_list`: (list/iterable) NLRIs.
-            - `withdraw_list`: (list/iterable) Withdraw routes.
-        """
-        if nlri_list is None:
-            nlri_list = []
-        if withdraw_list is None:
-            withdraw_list = []
-        if not pathattr_map:
-            pathattr_map = OrderedDict()
-
-        self._nlri_list = list(nlri_list)
-        self._withdraw_list = list(withdraw_list)
-        self._pathattr_map = copy(pathattr_map)
-
-     <at> property
-    def nlri_list(self):
-        return self._nlri_list[:]
-
-     <at> property
-    def withdraw_list(self):
-        return self._withdraw_list[:]
-
-     <at> property
-    def pathattr_map(self):
-        return copy(self._pathattr_map)
-
-    def get_path_attr(self, attr_name):
-        return self._pathattr_map.get(attr_name)
-
-     <at> classmethod
-    def from_bytes(cls, recv_bytes, total_msg_len):
-        # Validate UPDATE message length
-        if len(recv_bytes) < 4:
-            raise BadLen(Update.TYPE_CODE, len(recv_bytes) + cls.HEADER_SIZE)
-        withdraw_list = None
-        nlri_list = None
-        pathattr_map = OrderedDict()
-
-        d = {}
-        idx = 0
-        # Compute withdraw route length + total attribute length.
-        recv_len = 0
-        for kind in (Update.WITHDRAW_NLRI, Update.PATH_ATTR_AND_NLRI):
-            plen, = struct.unpack_from('!H', recv_bytes, idx)
-            idx += 2
-            d[kind] = recv_bytes[idx: (idx + plen)]
-            idx += plen
-            recv_len += plen
-
-        if d[Update.WITHDRAW_NLRI]:
-            withdraw_list = nlri.parse(d[Update.WITHDRAW_NLRI])
-        # TODO(PH): We have to test how ipv4 nlri packed after path-attr are
-        # getting parsed.
-        nlri_list = nlri.parse(recv_bytes[idx:])
-
-        idx = 0
-        recv_bytes = d[Update.PATH_ATTR_AND_NLRI]
-        while idx < len(recv_bytes):
-            used, pattr = pathattr.decode(recv_bytes, idx)
-            # TODO(PH) Can optimize here by checking if path attribute is
-            # MpReachNlri and stop parsing if RT are not interesting.
-            idx += used
-            pathattr_map[pattr.ATTR_NAME] = pattr
-
-        return cls(pathattr_map=pathattr_map,
-                   nlri_list=nlri_list, withdraw_list=withdraw_list)
-
-    def __repr__(self):
-        str_rep = cStringIO.StringIO()
-        str_rep.write('<Update message withdraw=%r' % (self._withdraw_list,))
-        for ptype, pattr in self._pathattr_map.items():
-            str_rep.write('\n path attr %s, %s' % (ptype, pattr,))
-#             if ptype in (MpReachNlri.ATTR_NAME, MpUnreachNlri):
-#                 for nnlri in pattr.nlri_list:
-#                     str_rep.write('\n  nlri=%s' % (nnlri,))
-        for nnlri in self._nlri_list:
-            str_rep.write('\nmp nlri %s' % (nnlri,))
-
-        str_rep.write('>')
-
-        return str_rep.getvalue()
-
-    def __cmp__(self, other):
-        if isinstance(other, Update):
-            return cmp(
-                (self._pathattr_map, self._withdraw_list, self._nlri_list),
-                (other.pathattr_map, other.withdraw_list, other.nlri_list),
-            )
-        return -1
-
-    def packvalue(self):
-        bvalue = ''
-
-        bwithdraw = ''
-        for awithdraw in self._withdraw_list:
-            bwithdraw += awithdraw.encode()
-
-        bvalue += struct.pack('!H', len(bwithdraw))
-        bvalue += bwithdraw
-
-        pattr = ''
-        for _, attr in self._pathattr_map.items():
-            if attr is not None:
-                pattr += attr.encode()
-        bvalue += struct.pack('!H', len(pattr))
-        bvalue += pattr
-
-        for anlri in self._nlri_list:
-            bvalue += anlri.encode()
-
-        return bvalue
-
-
-def decode(ptype, payload, msg_len):
-    """Decodes given payload into bgp message instance of given type.
-    """
-    bgp_msg_class = _BGP_MESSAGE_REGISTRY.get(ptype)
-    if not bgp_msg_class:
-        raise BadMsg(ptype)
-
-    return bgp_msg_class.from_bytes(payload, msg_len)
diff --git a/ryu/services/protocols/bgp/protocols/bgp/nlri.py b/ryu/services/protocols/bgp/protocols/bgp/nlri.py
deleted file mode 100644
index bed279d..0000000
--- a/ryu/services/protocols/bgp/protocols/bgp/nlri.py
+++ /dev/null
 <at>  <at>  -1,841 +0,0  <at>  <at> 
-# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-# implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""
-  Module related to BGP Network layer reachability information (NLRI).
-"""
-
-from abc import ABCMeta
-import logging
-import socket
-import struct
-from types import IntType
-
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import OptAttrError
-from ryu.services.protocols.bgp.utils.other import bytes2hex
-from ryu.services.protocols.bgp.utils.other import hex2byte
-from ryu.services.protocols.bgp.utils.validation import is_valid_ext_comm_attr
-from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4
-from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4_prefix
-from ryu.services.protocols.bgp.utils.validation import is_valid_ipv6_prefix
-from ryu.services.protocols.bgp.utils.validation import is_valid_mpls_label
-from ryu.services.protocols.bgp.utils.validation import is_valid_old_asn
-from ryu.services.protocols.bgp.utils.validation import is_valid_route_disc
-
-
-LOG = logging.getLogger('protocols.bgp.nlri')
-
-# Registry for bgp message class by their type code.
-# <key>: <value> - <afi, safi>: <nlri class>
-_NLRI_REGISTRY = {}
-
-
-def _register_nlri(cls):
-    """Used as class decorator for registering NLRI classes by their afi/safi.
-    """
-    assert _NLRI_REGISTRY.get((cls.AFI, cls.SAFI)) is None
-    _NLRI_REGISTRY[(cls.AFI, cls.SAFI)] = cls
-    return cls
-
-
-#
-# AddressFamily
-#
-class AddressFamily(object):
-    """Subclasses of this class hold methods for a specific AF and
-    help the calling code to stay AF-independent.
-
-    Each subclass need have just a singleton instance (see below).
-    """
-
-    def __init__(self, afi):
-        self.afi = afi
-
-    def __hash__(self):
-        return hash(self.afi)
-
-    def __cmp__(self, other):
-        afi1 = None
-        afi2 = None
-        if isinstance(other, IntType):
-            afi2 = other
-        else:
-            afi2 = other.afi
-        if isinstance(self, IntType):
-            afi1 = self
-        else:
-            afi1 = self.afi
-        return cmp(afi1, afi2)
-
-
-class AfiIpv4(AddressFamily):
-    def __init__(self):
-        super(AfiIpv4, self).__init__(1)
-
-    def __repr__(self):
-        return "IPv4"
-
-
-class AfiIpv6(AddressFamily):
-    def __init__(self):
-        super(AfiIpv6, self).__init__(2)
-
-    def __repr__(self):
-        return "IPv6"
-
-
-#
-# SubAddressFamily
-#
-# An sub-address family as defined by BGP.
-#
-class SubAddressFamily(object):
-
-    def __init__(self, safi):
-        self.safi = safi
-
-    def __hash__(self):
-        return hash(self.safi)
-
-    def __cmp__(self, other):
-        safi1 = None
-        safi2 = None
-        if isinstance(self, IntType):
-            safi1 = self
-        else:
-            safi1 = self.safi
-        if isinstance(other, IntType):
-            safi2 = other
-        else:
-            safi2 = other.safi
-        return cmp(safi1, safi2)
-
-
-class SafiNlriUnicast(SubAddressFamily):
-    def __init__(self):
-        super(SafiNlriUnicast, self).__init__(1)
-
-    def __repr__(self):
-        return "SafiNlriUnicast"
-
-
-class SafiVpn(SubAddressFamily):
-    def __init__(self):
-        super(SafiVpn, self).__init__(128)
-
-    def __repr__(self):
-        return "SafiVpn"
-
-
-class SafiRtc(SubAddressFamily):
-    def __init__(self):
-        super(SafiRtc, self).__init__(132)
-
-    def __repr__(self):
-        return "SafiRtc"
-
-NLRI_UC = SafiNlriUnicast()
-SAF_VPN = SafiVpn()
-SAF_RTC = SafiRtc()
-
-# Singleton objects for each AF.
-AF_IPv4 = AfiIpv4()
-AF_IPv6 = AfiIpv6()
-
-# Constants to represent address family and sub-address family.
-ADD_FMLY = 'afi'
-SUB_ADD_FMLY = 'safi'
-
-
-#
-# RouteFamily
-#
-class RouteFamily(object):
-    """The family that a given route (or Network Layer Reachability
-    Information) belongs to.
-
-    Basically represents a combination of AFI/SAFI.
-    """
-    __slots__ = ('_add_fmly', '_sub_add_fmly')
-
-    def __init__(self, add_fmly, sub_add_fmly):
-        # Validate i/p.
-        if not add_fmly or not sub_add_fmly:
-            raise ValueError('Invalid arguments.')
-
-        self._add_fmly = add_fmly
-        self._sub_add_fmly = sub_add_fmly
-
-     <at> property
-    def afi(self):
-        return self._add_fmly.afi
-
-     <at> property
-    def safi(self):
-        return self._sub_add_fmly.safi
-
-    def __repr__(self):
-        return ('RouteFamily(afi=%s, safi=%s)' % (self.afi, self.safi))
-
-    def __cmp__(self, other):
-        other_rf = (other.afi, other.safi)
-        self_rf = (self.afi, self.safi)
-        return cmp(self_rf, other_rf)
-
-     <at> staticmethod
-    def is_valid(other):
-        if other and (hasattr(other, 'afi') and hasattr(other, 'safi')):
-            return True
-        return False
-
-# Various route family singletons.
-RF_IPv4_UC = RouteFamily(AF_IPv4, NLRI_UC)
-RF_IPv6_UC = RouteFamily(AF_IPv6, NLRI_UC)
-RF_IPv4_VPN = RouteFamily(AF_IPv4, SAF_VPN)
-RF_IPv6_VPN = RouteFamily(AF_IPv6, SAF_VPN)
-RF_RTC_UC = RouteFamily(AF_IPv4, SAF_RTC)
-
-_rf_by_afi_safi = {
-    (1, 1): RF_IPv4_UC,
-    (2, 1): RF_IPv6_UC,
-    (1, 128): RF_IPv4_VPN,
-    (2, 128): RF_IPv6_VPN,
-    (1, 132): RF_RTC_UC
-}
-
-
-def get_rf(afi, safi):
-    """Returns *RouteFamily* singleton instance for given *afi* and *safi*."""
-    if not isinstance(afi, IntType):
-        afi = int(afi)
-    if not isinstance(safi, IntType):
-        safi = int(safi)
-    return _rf_by_afi_safi.get((afi, safi))
-
-
-# TODO(PH): Consider trade-offs of making this extend Internable.
-class Nlri(object):
-    """Represents super class of all Network Layer Reachability Information.
-    """
-    __meta__ = ABCMeta
-    __slots__ = ()
-
-    # Sub-classes should set afi/safi constants appropriately.
-    AFI = 0
-    SAFI = 0
-
-     <at> classmethod
-    def encode(self):
-        raise NotImplementedError()
-
-     <at> property
-    def route_family(self):
-        return get_rf(self.__class__.AFI, self.__class__.SAFI)
-
-
- <at> _register_nlri
-class Vpnv4(Nlri):
-    """Vpnv4 NLRI.
-    """
-    __slots__ = ('_labels', '_route_disc', '_prefix')
-
-    AFI = 1
-    SAFI = 128
-
-    def __init__(self, labels, route_disc, prefix):
-        Nlri.__init__(self)
-        if not labels:
-            labels = []
-
-        # Validate given params
-        for label in labels:
-            if not is_valid_mpls_label(label):
-                raise ValueError('Invalid label %s' % label)
-        if (not is_valid_ipv4_prefix(prefix) or
-                not is_valid_route_disc(route_disc)):
-            raise ValueError('Invalid parameter value(s).')
-
-        self._labels = labels
-        self._route_disc = route_disc
-        self._prefix = prefix
-
-     <at> property
-    def label_list(self):
-        return self._labels[:]
-
-     <at> property
-    def route_disc(self):
-        return self._route_disc
-
-     <at> property
-    def prefix(self):
-        return self._prefix
-
-     <at> property
-    def formatted_nlri_str(self):
-        return "%s:%s" % (self._route_disc, self.prefix)
-
-    def __repr__(self):
-        if self._labels:
-            l = ','.join([str(l) for l in self._labels])
-        else:
-            l = 'none'
-
-        return ('Vpnv4(label=%s, route_disc=%s, prefix=%s)' %
-                (l, self.route_disc, self.prefix))
-
-    def __str__(self):
-        return 'Vpnv4 %s:%s, %s' % (self.route_disc, self.prefix, self._labels)
-
-    def __cmp__(self, other):
-        return cmp(
-            (self._labels, self.route_disc, self.prefix),
-            (other.label_list, other.route_disc, other.prefix),
-        )
-
-    def encode(self):
-        plen = 0
-        v = ''
-        labels = self._labels[:]
-
-        if not labels:
-            return '\0'
-
-        labels = [l << 4 for l in labels]
-        labels[-1] |= 1
-
-        for l in labels:
-            lo = l & 0xff
-            hi = (l & 0xffff00) >> 8
-            v += struct.pack('>HB', hi, lo)
-            plen += 24
-
-        l, r = self.route_disc.split(':')
-        if '.' in l:
-            ip = socket.inet_aton(l)
-            route_disc = struct.pack('!H4sH', 1, ip, int(r))
-        else:
-            route_disc = struct.pack('!HHI', 0, int(l), int(r))
-
-        v += route_disc
-        plen += 64
-
-        ip, masklen = self.prefix.split('/')
-        ip = socket.inet_aton(ip)
-        masklen = int(masklen)
-
-        plen += masklen
-        if masklen > 24:
-            v += ip
-        elif masklen > 16:
-            v += ip[:3]
-        elif masklen > 8:
-            v += ip[:2]
-        elif masklen > 0:
-            v += ip[:1]
-        else:
-            pass
-
-        return struct.pack('B', plen) + v
-
-     <at> classmethod
-    def from_bytes(cls, plen, val):
-
-        if plen == 0:
-            # TODO(PH): Confirm this is valid case and implementation.
-            return cls([], '0:0', '0.0.0.0/0')
-
-        idx = 0
-
-        # plen is the length, in bits, of all the MPLS labels,
-        # plus the 8-byte RD, plus the IP prefix
-        labels = []
-        while True:
-            ls, = struct.unpack_from('3s', val, idx)
-            idx += 3
-            plen -= 24
-
-            if ls == '\x80\x00\x00':
-                # special null label for vpnv4 withdraws
-                labels = None
-                break
-
-            label, = struct.unpack_from('!I', '\x00' + ls)
-            bottom = label & 1
-
-            labels.append(label >> 4)
-            if bottom:
-                break
-            # TODO(PH): We are breaking after first label as we support only
-            # one label for now. Revisit if we need to support stack of labels.
-            break
-
-        rdtype, route_disc = struct.unpack_from('!H6s', val, idx)
-        if rdtype == 1:
-            rdip, num = struct.unpack('!4sH', route_disc)
-            rdip = socket.inet_ntoa(rdip)
-            route_disc = '%s:%s' % (rdip, num)
-        else:
-            num1, num2 = struct.unpack('!HI', route_disc)
-            route_disc = '%s:%s' % (num1, num2)
-
-        idx += 8
-        plen -= 64
-
-        ipl = pb(plen)
-        ip = val[idx:idx + ipl]
-        idx += ipl
-
-        prefix = unpack_ipv4(ip, plen)
-
-        return cls(labels, route_disc, prefix)
-
-
- <at> _register_nlri
-class Vpnv6(Nlri):
-    """Vpnv4 NLRI.
-    """
-    __slots__ = ('_labels', '_route_disc', '_prefix')
-
-    AFI = 2
-    SAFI = 128
-
-    def __init__(self, labels, route_disc, prefix):
-        Nlri.__init__(self)
-        if not labels:
-            labels = []
-
-        # Validate given params
-        for label in labels:
-            if not is_valid_mpls_label(label):
-                raise ValueError('Invalid label %s' % label)
-        if (not is_valid_route_disc(route_disc) or
-                not is_valid_ipv6_prefix(prefix)):
-            raise ValueError('Invalid parameter value(s).')
-
-        self._labels = labels
-        self._route_disc = route_disc
-        self._prefix = prefix
-
-     <at> property
-    def label_list(self):
-        return self._labels[:]
-
-     <at> property
-    def route_disc(self):
-        return self._route_disc
-
-     <at> property
-    def prefix(self):
-        return self._prefix
-
-     <at> property
-    def formatted_nlri_str(self):
-        return "%s:%s" % (self._route_disc, self.prefix)
-
-    def __repr__(self):
-        if self._labels:
-            l = ','.join([str(l) for l in self._labels])
-        else:
-            l = 'none'
-
-        return ('Vpnv6(label=%s, route_disc=%s, prefix=%s)' %
-                (l, self.route_disc, self.prefix))
-
-    def __str__(self):
-        return 'Vpnv6 %s:%s, %s' % (self.route_disc, self.prefix, self._labels)
-
-    def __cmp__(self, other):
-        return cmp(
-            (self._labels, self.route_disc, Ipv6(self.prefix).encode()),
-            (other.label_list, other.route_disc, Ipv6(other.prefix).encode()),
-        )
-
-    def encode(self):
-        plen = 0
-        v = ''
-        labels = self._labels[:]
-
-        if not labels:
-            return '\0'
-
-        labels = [l << 4 for l in labels]
-        labels[-1] |= 1
-
-        for l in labels:
-            lo = l & 0xff
-            hi = (l & 0xffff00) >> 8
-            v += struct.pack('>HB', hi, lo)
-            plen += 24
-
-        l, r = self.route_disc.split(':')
-        if '.' in l:
-            ip = socket.inet_aton(l)
-            route_disc = struct.pack('!H4sH', 1, ip, int(r))
-        else:
-            route_disc = struct.pack('!HHI', 0, int(l), int(r))
-        v += route_disc
-        plen += 64
-
-        ip, masklen = self.prefix.split('/')
-        ip = socket.inet_pton(socket.AF_INET6, ip)
-        masklen = int(masklen)
-
-        plen += masklen
-        v += ip[:pb6(masklen)]
-
-        return struct.pack('B', plen) + v
-
-     <at> classmethod
-    def from_bytes(cls, plen, val):
-        if plen == 0:
-            # TODO(PH): Confirm this is valid case and implementation.
-            return cls([], '0:0', '::/0')
-
-        idx = 0
-
-        # plen is the length, in bits, of all the MPLS labels,
-        # plus the 8-byte RD, plus the IP prefix
-        labels = []
-        while True:
-            ls, = struct.unpack_from('3s', val, idx)
-            idx += 3
-            plen -= 24
-
-            if ls == '\x80\x00\x00':
-                # special null label for vpnv4 withdraws
-                labels = None
-                break
-
-            label, = struct.unpack_from('!I', '\x00' + ls)
-            bottom = label & 1
-
-            labels.append(label >> 4)
-            if bottom:
-                break
-            # TODO(PH): We are breaking after first label as we support only
-            # one label for now. Revisit if we need to support stack of labels.
-            break
-
-        rdtype, route_disc = struct.unpack_from('!H6s', val, idx)
-        if rdtype == 1:
-            rdip, num = struct.unpack('!4sH', route_disc)
-            rdip = socket.inet_ntoa(rdip)
-            route_disc = '%s:%s' % (rdip, num)
-        else:
-            num1, num2 = struct.unpack('!HI', route_disc)
-            route_disc = '%s:%s' % (num1, num2)
-
-        idx += 8
-        plen -= 64
-
-        ipl = pb6(plen)
-        ip = val[idx:idx + ipl]
-        idx += ipl
-
-        prefix = unpack_ipv6(ip, plen)
-
-        return cls(labels, route_disc, prefix)
-
-
- <at> _register_nlri
-class Ipv4(Nlri):
-    __slots__ = ('_prefix')
-
-    AFI = 1
-    SAFI = 1
-
-    def __init__(self, prefix):
-        if not is_valid_ipv4_prefix(prefix):
-            raise ValueError('Invalid prefix %s.' % prefix)
-        Nlri.__init__(self)
-        self._prefix = prefix
-
-     <at> property
-    def prefix(self):
-        return self._prefix
-
-     <at> property
-    def formatted_nlri_str(self):
-        return self._prefix
-
-    def __cmp__(self, other):
-        aip, alen = self.prefix.split('/')
-        alen = int(alen)
-        aip = socket.inet_aton(aip)
-
-        bip, blen = other.prefix.split('/')
-        blen = int(blen)
-        bip = socket.inet_aton(bip)
-
-        return cmp((aip, alen), (bip, blen))
-
-    def encode(self):
-        plen = 0
-        v = ''
-
-        ip, masklen = self.prefix.split('/')
-        ip = socket.inet_aton(ip)
-        masklen = int(masklen)
-
-        plen += masklen
-        if masklen > 24:
-            v += ip
-        elif masklen > 16:
-            v += ip[:3]
-        elif masklen > 8:
-            v += ip[:2]
-        elif masklen > 0:
-            v += ip[:1]
-        else:
-            pass
-
-        return struct.pack('B', plen) + v
-
-    def __repr__(self):
-        return 'Ipv4(%s)' % (self.prefix)
-
-    def __str__(self):
-        return 'Ipv4 ' + self.prefix
-
-     <at> classmethod
-    def from_bytes(cls, plen, val):
-        return cls(unpack_ipv4(val, plen))
-
-
- <at> _register_nlri
-class Ipv6(Nlri):
-    __slots__ = ('_prefix')
-
-    AFI = 2
-    SAFI = 1
-
-    def __init__(self, prefix):
-        if not is_valid_ipv6_prefix(prefix):
-            raise ValueError('Invalid prefix %s.' % prefix)
-        Nlri.__init__(self)
-        self._prefix = prefix
-
-     <at> property
-    def prefix(self):
-        return self._prefix
-
-     <at> property
-    def formatted_nlri_str(self):
-        return self._prefix
-
-    def __cmp__(self, other):
-        abin = self.encode()
-        bbin = other.encode()
-        return cmp(abin, bbin)
-
-    def encode(self):
-        plen = 0
-        v = ''
-
-        ip, masklen = self.prefix.split('/')
-        ip = socket.inet_pton(socket.AF_INET6, ip)
-        masklen = int(masklen)
-
-        plen += masklen
-        ip_slice = pb6(masklen)
-        v += ip[:ip_slice]
-
-        return struct.pack('B', plen) + v
-
-    def __repr__(self):
-        return 'Ipv6(%s)' % (self.prefix)
-
-    def __str__(self):
-        return 'Ipv6 ' + self.prefix
-
-     <at> classmethod
-    def from_bytes(cls, plen, val):
-        return cls(unpack_ipv6(val, plen))
-
-
- <at> _register_nlri
-class RtNlri(Nlri):
-    """Route Target Membership NLRI.
-
-    Route Target membership NLRI is advertised in BGP UPDATE messages using
-    the MP_REACH_NLRI and MP_UNREACH_NLRI attributes.
-    """
-    __slots__ = ('_origin_as', '_route_target')
-
-    AFI = 1
-    SAFI = 132
-    DEFAULT_AS = '0:0'
-    DEFAULT_RT = '0:0'
-
-    def __init__(self, origin_as, route_target):
-        Nlri.__init__(self)
-        # If given is not default_as and default_rt
-        if not (origin_as is RtNlri.DEFAULT_AS and
-                route_target is RtNlri.DEFAULT_RT):
-            # We validate them
-            if (not is_valid_old_asn(origin_as) or
-                    not is_valid_ext_comm_attr(route_target)):
-                raise ValueError('Invalid params.')
-        self._origin_as = origin_as
-        self._route_target = route_target
-
-     <at> property
-    def origin_as(self):
-        return self._origin_as
-
-     <at> property
-    def route_target(self):
-        return self._route_target
-
-     <at> property
-    def formatted_nlri_str(self):
-        return "%s:%s" % (self.origin_as, self.route_target)
-
-    def is_default_rtnlri(self):
-        if (self._origin_as is RtNlri.DEFAULT_AS and
-                self._route_target is RtNlri.DEFAULT_RT):
-            return True
-        return False
-
-    def __str__(self):
-        return 'RtNlri ' + str(self._origin_as) + ':' + self._route_target
-
-    def __repr__(self):
-        return 'RtNlri(%s, %s)' % (self._origin_as, self._route_target)
-
-    def __cmp__(self, other):
-        return cmp(
-            (self._origin_as, self._route_target),
-            (other.origin_as, other.route_target),
-        )
-
-     <at> classmethod
-    def from_bytes(cls, plen, val):
-        idx = 0
-        if plen == 0 and not val:
-            return cls(RtNlri.DEFAULT_AS, RtNlri.DEFAULT_RT)
-
-        # Extract origin AS.
-        origin_as, = struct.unpack_from('!I', val, idx)
-        idx += 4
-
-        # Extract route target.
-        route_target = ''
-        etype, esubtype, payload = struct.unpack_from('BB6s', val, idx)
-        # RFC says: The value of the high-order octet of the Type field for the
-        # Route Target Community can be 0x00, 0x01, or 0x02.  The value of the
-        # low-order octet of the Type field for this community is 0x02.
-        # TODO(PH): Remove this exception when it breaks something Here we make
-        # exception as Routem packs lower-order octet as 0x00
-        if etype in (0, 2) and esubtype in (0, 2):
-            # If we have route target community in AS number format.
-            asnum, i = struct.unpack('!HI', payload)
-            route_target = ('%s:%s' % (asnum, i))
-        elif etype == 1 and esubtype == 2:
-            # If we have route target community in IP address format.
-            ip_addr, i = struct.unpack('!4sH', payload)
-            ip_addr = socket.inet_ntoa(ip_addr)
-            route_target = ('%s:%s' % (ip_addr, i))
-        elif etype == 0 and esubtype == 1:
-            # TODO(PH): Parsing of RtNlri 1:1:100:1
-            asnum, i = struct.unpack('!HI', payload)
-            route_target = ('%s:%s' % (asnum, i))
-
-        return cls(origin_as, route_target)
-
-    def encode(self):
-        rt_nlri = ''
-        if not self.is_default_rtnlri():
-            rt_nlri += struct.pack('!I', self.origin_as)
-            # Encode route target
-            first, second = self.route_target.split(':')
-            if '.' in first:
-                ip_addr = socket.inet_aton(first)
-                rt_nlri += struct.pack('!BB4sH', 1, 2, ip_addr, int(second))
-            else:
-                rt_nlri += struct.pack('!BBHI', 0, 2, int(first), int(second))
-
-        # RT Nlri is 12 octets
-        return struct.pack('B', (8 * 12)) + rt_nlri
-
-
-def pb(masklen):
-    if masklen > 24:
-        return 4
-    elif masklen > 16:
-        return 3
-    elif masklen > 8:
-        return 2
-    elif masklen > 0:
-        return 1
-    return 0
-
-_v6_bits = range(120, -8, -8)
-_v6_bytes = [i / 8 for i in range(128, 0, -8)]
-
-
-def pb6(masklen):
-    for idx, bits in enumerate(_v6_bits):
-        if masklen > bits:
-            return _v6_bytes[idx]
-    return 0
-
-
-def unpack_ipv4(pi, masklen):
-    pi += '\x00' * 4
-    return '%s/%s' % (socket.inet_ntoa(pi[:4]), masklen)
-
-
-def unpack_ipv6(pi, masklen):
-    pi += '\x00' * 16
-    ip = socket.inet_ntop(socket.AF_INET6, pi[:16])
-    return '%s/%s' % (ip, masklen)
-
-
-def ipv4_mapped_ipv6(ipv4):
-    if not is_valid_ipv4(ipv4):
-        raise ValueError('Invalid ipv4 address given %s.' % ipv4)
-    ipv4n = socket.inet_pton(socket.AF_INET, ipv4)
-    ipv6_hex = '00' * 10 + 'ff' * 2 + bytes2hex(ipv4n)
-    ipv6n = hex2byte(ipv6_hex)
-    ipv6 = socket.inet_ntop(socket.AF_INET6, ipv6n)
-    return ipv6
-
-
-# TODO(PH): Consider refactoring common functionality new methods
-# Look at previous commit
-def parse(received, afi=1, safi=1):
-    recv_nlri_list = []
-
-    klass = _NLRI_REGISTRY.get((afi, safi))
-    if not klass:
-        raise ValueError('Asked to parse unsupported NLRI afi/safi: '
-                         '(%s, %s)' % (afi, safi))
-
-    try:
-        idx = 0
-        while idx < len(received):
-            plen, = struct.unpack_from('B', received, idx)
-            idx += 1
-            nbytes, rest = divmod(plen, 8)
-            if rest:
-                nbytes += 1
-            val = received[idx:idx + nbytes]
-            idx += nbytes
-            recv_nlri_list.append(klass.from_bytes(plen, val))
-    except Exception:
-        raise OptAttrError()
-
-    return recv_nlri_list
diff --git a/ryu/services/protocols/bgp/protocols/bgp/pathattr.py b/ryu/services/protocols/bgp/protocols/bgp/pathattr.py
deleted file mode 100644
index 04499d4..0000000
--- a/ryu/services/protocols/bgp/protocols/bgp/pathattr.py
+++ /dev/null
 <at>  <at>  -1,1076 +0,0  <at>  <at> 
-# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-# implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-This module provides BGP Path Attributes classes and utility methods to
-encode and decode them.
-
-This file was adapted from pybgp open source project.
-"""
-from abc import ABCMeta
-from abc import abstractmethod
-import copy
-import logging
-import socket
-import StringIO
-import struct
-
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import AttrFlagError
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import AttrLenError
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import InvalidNextHop
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import \
-    InvalidOriginError
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import MalformedAsPath
-from ryu.services.protocols.bgp.protocols.bgp.exceptions import OptAttrError
-from ryu.services.protocols.bgp.protocols.bgp import nlri
-from ryu.services.protocols.bgp.protocols.bgp.nlri import get_rf
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv4_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_IPv6_VPN
-from ryu.services.protocols.bgp.protocols.bgp.nlri import RF_RTC_UC
-from ryu.services.protocols.bgp.utils.internable import Internable
-from ryu.services.protocols.bgp.utils import validation
-from ryu.services.protocols.bgp.utils.validation import is_valid_ipv4
-from ryu.services.protocols.bgp.utils.validation import is_valid_ipv6
-
-
-LOG = logging.getLogger('protocols.bgp.pathattr')
-
-# BGP Attribute flags
-EXTENDED_LEN_BGP_ATTR = 0x10
-PARTIAL_BGP_ATTR = 0x20
-TRANSITIVE_BGP_ATTR = 0x40
-OPTIONAL_BGP_ATTR = 0x80
-
-# BGP flag mask
-DEFAULT_FLAGS_MASK = 0x3f
-
-# BGP recognized path attribute class registry by type-code.
-# i.e. <key, value>: <type-code, path-attr-class>
-_PATH_ATTR_REGISTRY = {}
-
-
-def _register_path_attr(cls):
-    """Used as decorator for registering recognized bgp path attribute class
-     by their type-code.
-    """
-    assert issubclass(cls, RcgPathAttr)
-    assert hasattr(cls, 'TYPE_CODE') and hasattr(cls, 'FLAGS')
-    assert _PATH_ATTR_REGISTRY.get(cls.TYPE_CODE) is None
-    _PATH_ATTR_REGISTRY[cls.TYPE_CODE] = cls
-    return cls
-
-
-def decode(received, idx=0):
-    """Decodes given bytes into corresponding BGP path attribute.
-    """
-    iidx = idx
-    flagb, path_attr_type = struct.unpack_from('BB', received, idx)
-    idx += 2
-    used = 2
-
-    if flagb & 16:
-        length, = struct.unpack_from('>H', received, idx)
-        idx += 2
-        used += 2
-    else:
-        length, = struct.unpack_from('!B', received, idx)
-        idx += 1
-        used += 1
-
-    recv_data = received[idx:(idx + length)]
-    used += length
-
-    # Check if this attribute type is recognized.
-    path_attr_class = _PATH_ATTR_REGISTRY.get(path_attr_type)
-    path_attr = None
-    if path_attr_class:
-        # Check if flags match expected from known/recognized attribute type.
-        if not path_attr_class.check_flags(flagb):
-            LOG.error(
-                "Flags(%s) of pathattr %s received in update don't "
-                "match expected flags(%s)"
-                % (
-                    flagb,
-                    str(path_attr_class),
-                    path_attr_class.FLAGS
-                )
-            )
-            raise AttrFlagError(data=received[iidx:used])
-
-        try:
-            path_attr = path_attr_class.from_bytes(recv_data)
-        except (AttrLenError, InvalidOriginError, InvalidNextHop,
-                OptAttrError) as e:
-            # Set attribute type, length and value as data/payload.
-            e.data = received[iidx:used]
-            raise e
-    else:
-        path_attr = UnRcgPathAttr(recv_data, flagb, path_attr_type)
-
-    return used, path_attr
-
-
-class PathAttr(Internable):
-    """Abstract base class for bgp path attributes.
-
-    Defines interface for all path attributes and provides some default util.
-    methods.
-    """
-    __metaclass__ = ABCMeta
-    __slots__ = ('_flags')
-    TYPE_CODE = 0
-    ATTR_NAME = 'default'
-
-    def __init__(self, flags):
-        super(PathAttr, self).__init__()
-        self._flags = flags
-
-     <at> property
-    def flags(self):
-        return self._flags
-
-     <at> abstractmethod
-    def packvalue(self):
-        """Encodes path-attribute value/pay-load into binary format."""
-        raise NotImplementedError()
-
-    def encode(self):
-        """Wraps packed path-attribute value with headers, such as,
-        flags, type-code and length.
-        """
-        valueb = self.packvalue()
-        flags = self._flags
-        type_code = self.__class__.TYPE_CODE
-
-        if len(valueb) > 255:
-            flags = flags | 16
-            return struct.pack('!BBH', flags, type_code, len(valueb)) + valueb
-
-        flags = flags & (0xff ^ 16)
-        return struct.pack('BBB', flags, type_code, len(valueb)) + valueb
-
-    def str_flags(self):
-        """Returns a list of attribute category for this bgp attribute."""
-
-        if self._flags:
-            flag_cat = []
-            if self._flags & OPTIONAL_BGP_ATTR:
-                flag_cat.append('optional')
-            else:
-                flag_cat.append('well-known')
-
-            if self._flags & TRANSITIVE_BGP_ATTR:
-                flag_cat.append('transitive')
-            else:
-                flag_cat.append('non-transitive')
-
-            if self._flags & PARTIAL_BGP_ATTR:
-                flag_cat.append('partial')
-            else:
-                flag_cat.append('complete')
-
-            if self._flags & EXTENDED_LEN_BGP_ATTR:
-                flag_cat.append('ext-length')
-            else:
-                flag_cat.append('regular-length')
-
-            return ','.join(flag_cat)
-
-        return 'None'
-
-    def __repr__(self):
-        return '<%s type/num=%s/%s flags %s>' % (
-            self.__class__.__name__, 'unknown', self.__class__.TYPE_CODE,
-            self.str_flags())
-
-    def __cmp__(self, other):
-        if isinstance(other, PathAttr):
-            if other.__class__ == self.__class__:
-                return cmp(self._flags, other._flags)
-
-        return -1
-
-    def __hash__(self):
-        return hash(self._flags, self.__class__.TYPE_CODE)
-
-
-class RcgPathAttr(PathAttr):
-    """Base class for all recognized path attributes."""
-    # Flags for this type of known path attribute.
-    # Sub-classes should provide value as per RFC.
-    FLAGS = None
-
-    # There are some flags we don't care about. By default we don't care about
-    # extended-length bit and partial bit, so mask is 0x3f (0011 1111)
-    FLAGS_MASK = DEFAULT_FLAGS_MASK
-
-    def __init__(self):
-        PathAttr.__init__(self, self.__class__.FLAGS)
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        raise NotImplementedError()
-
-     <at> classmethod
-    def check_flags(cls, flags):
-        """Check if provided flags match flags required by RFC (cls.FLAGS).
-
-            RFC path attribute higher order bit rules:
-            0    1     2    3    4    5    6    7
-
-            Well Known
-            0    1 - always
-                    0 - always
-                        0 - attribute length 1 octet
-                        1 - attribute length 2 octet
-
-            Optional
-            1    1 - Transitive
-                    1 - Partial
-                    0 - Complete
-                0 - Non-Transitive
-                    0 - always
-        """
-        return cls.FLAGS | cls.FLAGS_MASK == flags | cls.FLAGS_MASK
-
-
-class UnRcgPathAttr(PathAttr):
-    """Class for all un-supported/un-recognized bgp path-attributes.
-    """
-    __slots__ = ('_type_code', '_value')
-    ATTR_NAME = 'unknown'
-
-    def __init__(self, value, flags, type_code):
-        PathAttr.__init__(self, flags)
-        self._type_code = type_code
-        self._value = value
-
-     <at> property
-    def value(self):
-        return self._value
-
-     <at> property
-    def type_code(self):
-        return self._type_code
-
-    def packvalue(self):
-        return self._value
-
-    def encode(self):
-        all_flags = self._flags
-        valueb = self.packvalue()
-
-        if len(valueb) > 255:
-            all_flags = all_flags | 16
-            return struct.pack('!BBH', all_flags, self.type_code,
-                               len(valueb)) + valueb
-
-        all_flags = all_flags & (0xff ^ 16)
-        return struct.pack('BBB', all_flags, self.type_code,
-                           len(valueb)) + valueb
-
-    def is_optional_transitive(self):
-        """Returns true if this is an optional path attribute.
-        """
-        return self._flags & OPTIONAL_BGP_ATTR
-
-    def is_transitive(self):
-        """Returns true if this is an transitive path attribute.
-        """
-        return self._flags & TRANSITIVE_BGP_ATTR
-
-    def __repr__(self):
-        return '<%s type/num=%s/%s flags %s value %r>' % (
-            self.__class__.__name__, 'unknown', self.type_code, self.flags,
-            self.value)
-
-
- <at> _register_path_attr
-class Origin(RcgPathAttr):
-    """ORIGIN is a well-known mandatory bgp path-attribute."""
-    __slots__ = ('_value')
-    TYPE_CODE = 1
-    ATTR_NAME = 'origin'
-    # 010 - well known, transitive, complete
-    FLAGS = TRANSITIVE_BGP_ATTR
-
-    # Various Origin values.
-    IGP = 'igp'
-    EGP = 'egp'
-    INCOMPLETE = 'incomplete'
-
-    def __init__(self, value='incomplete'):
-        RcgPathAttr.__init__(self)
-        if value not in (Origin.IGP, Origin.EGP, Origin.INCOMPLETE):
-            raise ValueError('Invalid Origin attribute value.')
-        self._value = value
-
-     <at> property
-    def value(self):
-        return self._value
-
-     <at> classmethod
-    def from_bytes(cls, value):
-        """Decodes bgp path-attribute with type-code 1, i.e. ORIGIN.
-        """
-        if value == '\x00':
-            value = Origin.IGP
-        elif value == '\x01':
-            value = Origin.EGP
-        elif value == '\x02':
-            value = Origin.INCOMPLETE
-        else:
-            raise InvalidOriginError()
-
-        return cls(value)
-
-    def packvalue(self):
-        if self.value == Origin.IGP:
-            return '\x00'
-        elif self.value == Origin.EGP:
-            return '\x01'
-        elif self.value == Origin.INCOMPLETE:
-            return '\x02'
-        return self.value
-
-    def __repr__(self):
-        return '<Origin ' + self.value + '>'
-
-    def __str__(self):
-        return str(self.value)
-
-
- <at> _register_path_attr
-class AsPath(RcgPathAttr):
-    """AS_PATH is a well-known mandatory bgp path attribute.
-    """
-    __slots__ = ('_path_seg_list')
-    TYPE_CODE = 2
-    ATTR_NAME = 'aspath'
-    # Higher order bits: 010 - well known, transitive, complete
-    FLAGS = TRANSITIVE_BGP_ATTR
-    SEG_TYP_AS_SET = 1
-    SEG_TYP_AS_SEQ = 2
-
-    def __init__(self, path_seg_list):
-        RcgPathAttr.__init__(self)
-        self._path_seg_list = None
-        if isinstance(path_seg_list, str):
-            self._path_seg_list = []
-            for seg in path_seg_list.split():
-                if seg.startswith('set(') and seg.endswith(')'):
-                    seg = set([int(s) for s in seg[4:-1].split(',')])
-                else:
-                    seg = [int(s) for s in seg.split(',')]
-                self._path_seg_list.append(seg)
-        else:
-            self._path_seg_list = path_seg_list[:]
-
-     <at> property
-    def path_seg_list(self):
-        return copy.deepcopy(self._path_seg_list)
-
-    def get_as_path_len(self):
-        count = 0
-        for seg in self._path_seg_list:
-            if isinstance(seg, list):
-                # Segment type 2 stored in list and all AS counted.
-                count += len(seg)
-            else:
-                # Segment type 1 stored in set and count as one.
-                count += 1
-
-        return count
-
-    def has_local_as(self, local_as):
-        """Check if *local_as* is already present on path list."""
-        for as_path_seg in self._path_seg_list:
-            for as_num in as_path_seg:
-                if as_num == local_as:
-                    return True
-        return False
-
-    def has_matching_leftmost(self, remote_as):
-        """Check if leftmost AS matches *remote_as*."""
-        if not self._path_seg_list or not remote_as:
-            return False
-
-        leftmost_seg = self.path_seg_list[0]
-        if leftmost_seg and leftmost_seg[0] == remote_as:
-            return True
-
-        return False
-
-     <at> property
-    def value(self):
-        ret = []
-        for as_path_seg in self._path_seg_list:
-            for as_num in as_path_seg:
-                ret.append(as_num)
-        return ret
-
-    def __repr__(self):
-        rstring = StringIO.StringIO()
-        rstring.write('<AsPath')
-        for as_path_seg in self._path_seg_list:
-            if isinstance(as_path_seg, set):
-                rstring.write(' set(')
-                rstring.write(','.join([str(asnum) for asnum in as_path_seg]))
-                rstring.write(')')
-            else:
-                rstring.write(' ')
-                rstring.write(','.join([str(asnum) for asnum in as_path_seg]))
-        rstring.write('>')
-        return rstring.getvalue()
-
-    def __str__(self):
-        ret = '['
-        for as_path_seg in self._path_seg_list:
-            ret += ', '.join([str(asnum) for asnum in as_path_seg])
-        return ret + ']'
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes bgp path-attribute with type-code 2, i.e. AS_PATH.
-        """
-        path_seg_list = []
-        iidx = 0
-
-        while iidx < len(val):
-            segtype, numas = struct.unpack_from('BB', val, iidx)
-            iidx += 2
-
-            if segtype == AsPath.SEG_TYP_AS_SET:
-                container = set()
-                add = container.add
-            elif segtype == AsPath.SEG_TYP_AS_SEQ:
-                container = []
-                add = container.append
-            else:
-                raise MalformedAsPath()
-
-            for _ in range(numas):
-                asnum, = struct.unpack_from('!H', val, iidx)
-                iidx += 2
-                add(asnum)
-            path_seg_list.append(container)
-
-        return cls(path_seg_list)
-
-    def packvalue(self):
-        valueb = ''
-        for seg in self._path_seg_list:
-            if isinstance(seg, set):
-                segtype = 1
-            elif isinstance(seg, (tuple, list)):
-                segtype = 2
-            else:
-                raise Exception('unknown segment type %r' % (seg,))
-
-            valueb += struct.pack('BB', segtype, len(seg))
-            try:
-                iter(seg)
-            except TypeError:
-                valueb += struct.pack('!H', int(seg))
-            else:
-                for asnum in seg:
-                    if not isinstance(asnum, int):
-                        asnum = int(asnum)
-                    valueb += struct.pack('!H', asnum)
-
-        return valueb
-
-
- <at> _register_path_attr
-class NextHop(RcgPathAttr):
-    """NEXT_HOP is well-known mandatory bgp path-attribute.
-    """
-    __slots__ = ()
-    TYPE_CODE = 3
-    ATTR_NAME = 'nexthop'
-    # Higher order bits: 010 - well known, transitive, complete
-    FLAGS = TRANSITIVE_BGP_ATTR
-
-    def __init__(self, ip_address):
-        if not is_valid_ipv4(ip_address):
-            raise ValueError('Invalid ipv4 address %s.' % ip_address)
-        RcgPathAttr.__init__(self)
-        self._ip_address = ip_address
-
-     <at> property
-    def ip_address(self):
-        return self._ip_address
-
-    def __repr__(self):
-        return '<nexthop %s>' % (self.ip_address)
-
-    def __str__(self):
-        return str(self.ip_address)
-
-     <at> classmethod
-    def from_bytes(cls, value):
-        """Decodes bgp path-attribute with type-code 3, i.e. NEXT_HOP.
-        """
-        value = socket.inet_ntoa(value)
-        return cls(value)
-
-    def packvalue(self):
-        return socket.inet_aton(self._ip_address)
-
-
- <at> _register_path_attr
-class IntAttr(RcgPathAttr):
-    """Super class of all bgp path-attribute whose value is an unsigned
-    integer.
-    """
-    __slots__ = ('_value')
-
-    def __init__(self, value):
-        if not value:
-            value = 0
-        self._value = value
-        RcgPathAttr.__init__(self)
-
-     <at> property
-    def value(self):
-        return self._value
-
-    def __repr__(self):
-        return '<%s(%d)>' % (self.__class__.__name__, self.value)
-
-    def __str__(self):
-        return str(self.value)
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decode bgp path-attributes whose value is an unsigned integer.
-        """
-        value, = struct.unpack_from('!I', val)
-        return cls(value)
-
-    def packvalue(self):
-        return struct.pack('!I', self.value)
-
-
- <at> _register_path_attr
-class Med(IntAttr):
-    """MED is optional non-transitive bgp path-attribute."""
-    __slots__ = ()
-    TYPE_CODE = 4
-    ATTR_NAME = 'med'
-    # Higher order bits: 100 - optional, non-transitive, complete
-    FLAGS = OPTIONAL_BGP_ATTR
-
-    def __init__(self, value):
-        IntAttr.__init__(self, value)
-
-
- <at> _register_path_attr
-class LocalPref(IntAttr):
-    """LOCAL_PREF is a well-known discretionary attribute."""
-    __slots__ = ()
-    TYPE_CODE = 5
-    ATTR_NAME = 'localpref'
-    # Higher order bits: 010 - well-known, transitive, complete
-    FLAGS = TRANSITIVE_BGP_ATTR
-
-    def __init__(self, value):
-        IntAttr.__init__(self, value)
-
-
- <at> _register_path_attr
-class Originator(RcgPathAttr):
-    """ORIGINATOR_ID is a optional non-transitive attribute."""
-    __slots__ = ('_value')
-    TYPE_CODE = 9
-    ATTR_NAME = 'originator'
-    FLAGS = OPTIONAL_BGP_ATTR
-
-    def __init__(self, value):
-        RcgPathAttr.__init__(self)
-        self._value = value
-
-     <at> property
-    def value(self):
-        return self._value
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes bgp path-attribute with type code 9, i.e. ORIGINATOR_ID.
-        """
-        if len(val) == 4:
-            value = socket.inet_ntoa(val)
-        else:
-            raise Exception('Invalid originator')
-
-        return cls(value)
-
-    def packvalue(self):
-        return socket.inet_aton(self.value)
-
-
- <at> _register_path_attr
-class ClusterList(RcgPathAttr):
-    """CLUSTER_LIST is a optional non-transitive bgp path-attribute.
-    """
-    __slots__ = ('_cluster_list')
-    TYPE_CODE = 10
-    ATTR_NAME = 'cluster-list'
-    FLAGS = OPTIONAL_BGP_ATTR
-
-    def __init__(self, cluster_list):
-        if not cluster_list:
-            raise ValueError('Invalid cluster list.')
-        # TODO(PH): add more validation of input here.
-        RcgPathAttr.__init__(self)
-        self._cluster_list = cluster_list
-
-     <at> property
-    def cluster_list(self):
-        return self._cluster_list
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes bgp path-attribute with type-code 10, i.e. CLUSTER_LIST.
-        """
-        cluster_list = []
-        iidx = 0
-        while iidx < len(val):
-            cluster_list.append(
-                socket.inet_ntoa(struct.unpack_from('4s', val, iidx)[0])
-            )
-            iidx += 4
-        return cls(cluster_list)
-
-    def packvalue(self):
-        valueb = ''
-        for c in self.cluster_list:
-            valueb += socket.inet_aton(c)
-        return valueb
-
-
- <at> _register_path_attr
-class MpReachNlri(RcgPathAttr):
-    """MP_REACH_NLRI is a optional non-transitive bgp path-attribute.
-    """
-    __slots__ = ('_route_family', '_next_hop', '_nlri_list', '_reserved')
-    TYPE_CODE = 14
-    ATTR_NAME = 'mp-reach-nlri'
-    NEXT_HOP = 'nh'
-    NLRI = 'nlri'
-    RESERVED = 'reserved'
-    # Higher order bits: 100 - optional, non-transitive, complete
-    FLAGS = OPTIONAL_BGP_ATTR
-
-    def __init__(self, route_family, next_hop, nlri_list, reserved=None):
-        if not (hasattr(route_family, 'afi') and
-                hasattr(route_family, 'safi')):
-            raise ValueError('Invalid parameter value for route_family %s.' %
-                             route_family)
-
-        if not next_hop:
-            raise ValueError('Invalid next_hop %s' % next_hop)
-
-        # MpReachNlri attribute should have next-hop belonging to same
-        # route-family
-        if ((route_family == RF_IPv4_VPN and not is_valid_ipv4(next_hop)) or
-                (route_family == RF_IPv6_VPN and not is_valid_ipv6(next_hop))):
-            raise ValueError('Next hop should belong to %s route family' %
-                             route_family)
-
-        if not nlri_list:
-            nlri_list = []
-
-        RcgPathAttr.__init__(self)
-        self._route_family = route_family
-        self._next_hop = next_hop
-        self._nlri_list = nlri_list
-        self._reserved = reserved
-
-     <at> property
-    def route_family(self):
-        return self._route_family
-
-     <at> property
-    def next_hop(self):
-        return self._next_hop
-
-     <at> property
-    def nlri_list(self):
-        return self._nlri_list[:]
-
-     <at> property
-    def reserved(self):
-        return self._reserved
-
-    def __repr__(self):
-        return '<MpReachNlri route_family=%r next_hop=%r nlri_list=%r>' % (
-            self.route_family, self.next_hop, self._nlri_list)
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes bgp path-attribute with type code 14, i.e MP_REACH_NLRI.
-        """
-        afi, safi, nhlen = struct.unpack_from('!HBB', val)
-        fmt = '%dsB' % (nhlen,)
-        next_hop, reserved = struct.unpack_from(fmt, val, 4)
-
-        if afi == 1 and safi is 128:
-            # Vpnv4
-            _, _, nhip = struct.unpack('!II4s', next_hop)
-            next_hop = socket.inet_ntop(socket.AF_INET, nhip)
-        elif afi == 1 and safi == 132:
-            # RtNlri
-            nhip, = struct.unpack('!4s', next_hop)
-            next_hop = socket.inet_ntop(socket.AF_INET, nhip)
-        elif afi == 2 and safi == 128:
-            # Vpnv6
-            _, _, nhip = struct.unpack('!II16s', next_hop)
-            next_hop = socket.inet_ntop(socket.AF_INET6, nhip)
-        else:
-            LOG.error('Received NLRI for afi/safi (%s/%s), which is not'
-                      ' supported yet!' % (afi, safi))
-            raise OptAttrError()
-
-        n_nlri = nlri.parse(val[5 + nhlen:], afi, safi)
-        route_family = get_rf(afi, safi)
-        return cls(route_family, next_hop, n_nlri, reserved)
-
-    def packvalue(self):
-        afi = self._route_family.afi
-        safi = self._route_family.safi
-        if self._route_family == RF_IPv4_VPN:
-            next_hop = '\0' * 8
-            next_hop += socket.inet_aton(self.next_hop)
-        elif self._route_family == RF_RTC_UC:
-            next_hop = socket.inet_aton(self.next_hop)
-        elif self._route_family == RF_IPv6_VPN:
-            next_hop = '\0' * 8
-            next_hop += socket.inet_pton(socket.AF_INET6, self.next_hop)
-        else:
-            next_hop = self.next_hop
-
-        valueb = struct.pack('!HBB', afi, safi, len(next_hop))
-        valueb += next_hop
-        valueb += chr(self.reserved or 0)
-
-        for n_nlri in self._nlri_list:
-            valueb += n_nlri.encode()
-        return valueb
-
-
- <at> _register_path_attr
-class MpUnreachNlri(RcgPathAttr):
-    """MP_UNREACH_NLRI is a optional non-transitive bgp path-attribute.
-    """
-    __slots__ = ('_route_family', '_nlri_list')
-    TYPE_CODE = 15
-    ATTR_NAME = 'mp-unreach-nlri'
-    NLRI = 'withdraw_nlri'
-    # Higher order bits: 100 - optional, non-transitive, complete
-    FLAGS = OPTIONAL_BGP_ATTR
-
-    def __init__(self, route_family, nlri_list):
-        if not (hasattr(route_family, 'afi') and
-                hasattr(route_family, 'safi')):
-            raise ValueError('Invalid parameter value for route_family %s' %
-                             route_family)
-        if not nlri_list:
-            nlri_list = []
-
-        RcgPathAttr.__init__(self)
-        self._route_family = route_family
-        self._nlri_list = nlri_list
-
-     <at> property
-    def nlri_list(self):
-        return self._nlri_list[:]
-
-     <at> property
-    def route_family(self):
-        return self._route_family
-
-    def __repr__(self):
-        return '<MpUneachNlri route_family=%r nlri_list=%r>' % (
-            self._route_family, self._nlri_list)
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes bgp path-attribute of type-code 15, i.e. MP_UNREACH_NLRI.
-        """
-        afi, safi = struct.unpack_from('!HB', val)
-        route_family = get_rf(afi, safi)
-        w_nlri = nlri.parse(val[3:], afi, safi)
-        return cls(route_family, w_nlri)
-
-    def packvalue(self):
-        afi = self._route_family.afi
-        safi = self._route_family.safi
-
-        valueb = struct.pack('!HB', afi, safi)
-
-        for w_nlri in self._nlri_list:
-            valueb += w_nlri.encode()
-        return valueb
-
-
- <at> _register_path_attr
-class Community(RcgPathAttr):
-    """COMMUNITY is a optional transitive bgp path-attribute.
-    """
-    __slots__ = ('_attr_list')
-    TYPE_CODE = 8
-    ATTR_NAME = 'community'
-    FLAGS = TRANSITIVE_BGP_ATTR | OPTIONAL_BGP_ATTR
-
-    # String constants of well-known-communities
-    NO_EXPORT = int('0xFFFFFF01', 16)
-    NO_ADVERTISE = int('0xFFFFFF02', 16)
-    NO_EXPORT_SUBCONFED = int('0xFFFFFF03', 16)
-    WELL_KNOW_COMMUNITIES = (NO_EXPORT, NO_ADVERTISE, NO_EXPORT_SUBCONFED)
-
-    def __init__(self, *attrs):
-        if not attrs:
-            raise ValueError('Invalid parameter for community attribute '
-                             'list %r.' % attrs)
-        self._attr_list = []
-        for attr in attrs:
-            if not isinstance(attr, int):
-                raise ValueError('Invalid community attribute value %s.' %
-                                 attr)
-            self._attr_list.append(attr)
-
-        RcgPathAttr.__init__(self)
-
-     <at> property
-    def attr_list(self):
-        return self._attr_list[:]
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes path attribute of type code 8, i.e. Community attribute.
-        """
-        att_list = []
-        iidx = 0
-        while iidx < len(val):
-            comm_attr, = struct.unpack_from('!I', val, iidx)
-            att_list.append(comm_attr)
-            iidx += 4
-        return cls(*att_list)
-
-    def packvalue(self):
-        commu_attr = ''
-        for attr in self._attr_list:
-            commu_attr += struct.pack('!I', int(attr))
-        return commu_attr
-
-     <at> staticmethod
-    def is_no_export(comm_attr):
-        """Returns True if given value matches well-known community NO_EXPORT
-         attribute value.
-         """
-        return comm_attr == Community.NO_EXPORT
-
-     <at> staticmethod
-    def is_no_advertise(comm_attr):
-        """Returns True if given value matches well-known community
-        NO_ADVERTISE attribute value.
-        """
-        return comm_attr == Community.NO_ADVERTISE
-
-     <at> staticmethod
-    def is_no_export_subconfed(comm_attr):
-        """Returns True if given value matches well-known community
-         NO_EXPORT_SUBCONFED attribute value.
-         """
-        return comm_attr == Community.NO_EXPORT_SUBCONFED
-
-    def has_comm_attr(self, attr):
-        """Returns True if given community attribute is present."""
-
-        for comm_attr in self._attr_list:
-            if comm_attr == attr:
-                return True
-
-        return False
-
-    def _community_repr(self, comm_attr):
-        """Matches given value with all well-known community attribute values.
-
-        Returns string representation of the well-known attribute if we
-        have a match else returns given value.
-        """
-
-        if self.is_no_export(comm_attr):
-            return 'NO_EXPORT'
-        elif self.is_no_advertise(comm_attr):
-            return 'NO_ADVERTISE'
-        elif self.is_no_export_subconfed(comm_attr):
-            return 'NO_EXPORT_SUBCONFED'
-        return (str(comm_attr >> 16) + ':' +
-                str(comm_attr & int('0x0000ffff', 16)))
-
-    def __repr__(self):
-        attr_list_repr = (','.join([self._community_repr(ca)
-                                    for ca in self._attr_list]))
-        return ('<Community([%s])>' % attr_list_repr)
-
-
- <at> _register_path_attr
-class ExtCommunity(RcgPathAttr):
-    """EXTENDED COMMUNITIES is a optional and transitive bgp path-attribute.
-    """
-    __slots__ = ('_rt_list', '_soo_list', '_unknowns')
-    TYPE_CODE = 16
-    ATTR_NAME = 'extcommunity'
-    RT = 'route_target'
-    SOO = 'site_of_origin'
-    UNKNOWN = 'unknown_community'
-    # Higher order bits: 110 - optional, transitive, complete
-    FLAGS = TRANSITIVE_BGP_ATTR | OPTIONAL_BGP_ATTR
-
-    def __str__(self):
-        return 'rt_list: {0}, soo_list: {1}'.format(
-            self.rt_list,
-            self.soo_list
-        )
-
-    def __init__(self, rt_list, soo_list, unknowns=None):
-        if not rt_list and not soo_list:
-            raise ValueError('Have to provide at-least one RT/SOO attribute.')
-        if not rt_list:
-            rt_list = []
-        if not soo_list:
-            soo_list = []
-        if not unknowns:
-            unknowns = {}
-
-        ExtCommunity.validate_supported_attributes(rt_list)
-        ExtCommunity.validate_supported_attributes(soo_list)
-
-        RcgPathAttr.__init__(self)
-        self._rt_list = list(rt_list)
-        self._soo_list = list(soo_list)
-        self._unknowns = unknowns
-
-     <at> property
-    def rt_list(self):
-        """Returns a list of extracted/configured route target community."""
-        # TODO(PH): Make sure we do not raise Exception here but return empty
-        #  list instead.
-        return self._rt_list[:]
-
-     <at> property
-    def soo_list(self):
-        """Returns route origin community."""
-        return self._soo_list[:]
-
-    def __repr__(self):
-        return '<%s type/num=%s/%s flags %s, rts: %s, soo: %s>' % (
-            self.__class__.__name__, self.__class__.ATTR_NAME,
-            self.__class__.TYPE_CODE,
-            self.str_flags(), self.rt_list, self.soo_list)
-
-    def has_unknown_communities(self):
-        """Returns True if we have extracted/configured community other than
-         route target or route origin community.
-         """
-        return True if self._unknowns else False
-
-     <at> classmethod
-    def validate_supported_attributes(cls, attr_list):
-        """Validate *attr_list* has all valid RTs or SOO attribute
-        representations.
-
-        RTs and SOO are represented as string in following format:
-        *global_admin_part:local_admin_part*
-        """
-        for attr in attr_list:
-            if not validation.is_valid_ext_comm_attr(attr):
-                raise ValueError('Attribute %s is not a valid RT/SOO' % attr)
-
-     <at> classmethod
-    def from_bytes(cls, val):
-        """Decodes ext-community path-attribute.
-        """
-        rt_list = []
-        soo_list = []
-        unknowns = {}
-        iidx = 0
-        while iidx < len(val):
-            etype, esubtype, payload = struct.unpack_from('BB6s', val, iidx)
-            # RFC says: The value of the high-order octet of the Type field for
-            # the Route Target Community can be 0x00, 0x01, or 0x02.  The value
-            # of the low-order octet of the Type field for this community is
-            # 0x02. TODO(PH): Remove this exception when it breaks something
-            # Here we make exception as Routem packs lower-order octet as 0x00
-            if etype in (0, 2) and esubtype in (0, 2):
-                # If we have route target community in AS number format.
-                asnum, i = struct.unpack('!HI', payload)
-                rt_list.append('%s:%s' % (asnum, i))
-            elif etype == 1 and esubtype == 2:
-                # If we have route target community in IP address format.
-                ip_addr, i = struct.unpack('!4sH', payload)
-                ip_addr = socket.inet_ntoa(ip_addr)
-                rt_list.append('%s:%s' % (ip_addr, i))
-            elif etype in (0, 2) and esubtype == 3:
-                # If we have route origin community in AS number format.
-                asnum, nnum = struct.unpack('!HI', payload)
-                soo_list.append('%s:%s' % (asnum, nnum))
-            elif etype == 1 and esubtype == 3:
-                # If we have route origin community in IP address format.
-                ip_addr, nnum = struct.unpack('!4sH', payload)
-                ip_addr = socket.inet_ntoa(ip_addr)
-                soo_list.append('%s:%s' % (ip_addr, nnum))
-            else:
-                # All other communities, other than RT and SOO are unknown.
-                unknown_list = unknowns.get(etype)
-                if unknown_list is None:
-                    unknown_list = []
-                    unknowns[etype] = unknown_list
-                unknown_list.append(
-                    '%s:%s' % (etype, val[iidx + 1:iidx + 8].encode('hex'))
-                )
-            iidx += 8
-
-        return cls(rt_list, soo_list, unknowns)
-
-    def packvalue(self):
-        excomb = ''
-        # Pack route target community attrs.
-        for route_target in self._rt_list:
-            first, second = route_target.split(':')
-            if '.' in first:
-                ip_addr = socket.inet_aton(first)
-                excomb += struct.pack('!BB4sH', 1, 2, ip_addr,
-                                      int(second))
-            else:
-                excomb += struct.pack('!BBHI', 0, 2, int(first),
-                                      int(second))
-        # Pack route origin community attrs.
-        for route_origin in self._soo_list:
-            first, second = route_origin.split(':')
-            if '.' in first:
-                ip_addr = socket.inet_aton(first)
-                excomb += struct.pack('!BB4sH', 1, 3, ip_addr,
-                                      int(second))
-            else:
-                excomb += struct.pack('!BBHI', 0, 3, int(first),
-                                      int(second))
-        for type, attr_list in self._unknowns.items():
-            # Pack all unknown ext. attrs.
-            excomb += struct.pack('B', int(type))
-            excomb += attr_list.decode('hex')
-        return excomb
--

-- 
1.7.9.5


------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
ISHIDA Wataru | 16 Apr 05:30 2014
Picon

[PATCH 1/3] bgp: add stuff for integration with bgp speaker


Signed-off-by: ISHIDA Wataru <ishida.wataru@...>
---
 ryu/lib/packet/bgp.py |  726 +++++++++++++++++++++++++++++++++++++++++++++----
 1 file changed, 675 insertions(+), 51 deletions(-)

diff --git a/ryu/lib/packet/bgp.py b/ryu/lib/packet/bgp.py
index 2d71917..974967d 100644
--- a/ryu/lib/packet/bgp.py
+++ b/ryu/lib/packet/bgp.py
 <at>  <at>  -25,23 +25,69  <at>  <at>  RFC 4271 BGP-4
 import abc
 import six
 import struct
+import copy

 from ryu.ofproto.ofproto_parser import msg_pack_into
 from ryu.lib.stringify import StringifyMixin
+from ryu.lib.packet import afi
+from ryu.lib.packet import safi
 from ryu.lib.packet import packet_base
 from ryu.lib.packet import stream_parser
 from ryu.lib import addrconv

-import safi
-import afi
-
-
 BGP_MSG_OPEN = 1
 BGP_MSG_UPDATE = 2
 BGP_MSG_NOTIFICATION = 3
 BGP_MSG_KEEPALIVE = 4
 BGP_MSG_ROUTE_REFRESH = 5  # RFC 2918

+_VERSION = 4
+_MARKER = 16 * '\xff'
+
+BGP_OPT_CAPABILITY = 2  # RFC 5492
+
+BGP_CAP_MULTIPROTOCOL = 1  # RFC 4760
+BGP_CAP_ROUTE_REFRESH = 2  # RFC 2918
+BGP_CAP_CARRYING_LABEL_INFO = 4  # RFC 3107
+BGP_CAP_FOUR_OCTET_AS_NUMBER = 65  # RFC 4893
+BGP_CAP_ENHANCED_ROUTE_REFRESH = 70  # https://tools.ietf.org/html/\
+# draft-ietf-idr-bgp-enhanced-route-refresh-05
+
+BGP_ATTR_FLAG_OPTIONAL = 1 << 7
+BGP_ATTR_FLAG_TRANSITIVE = 1 << 6
+BGP_ATTR_FLAG_PARTIAL = 1 << 5
+BGP_ATTR_FLAG_EXTENDED_LENGTH = 1 << 4
+
+BGP_ATTR_TYPE_ORIGIN = 1  # 0,1,2 (1 byte)
+BGP_ATTR_TYPE_AS_PATH = 2  # a list of AS_SET/AS_SEQUENCE  eg. {1 2 3} 4 5
+BGP_ATTR_TYPE_NEXT_HOP = 3  # an IPv4 address
+BGP_ATTR_TYPE_MULTI_EXIT_DISC = 4  # uint32 metric
+BGP_ATTR_TYPE_LOCAL_PREF = 5  # uint32
+BGP_ATTR_TYPE_ATOMIC_AGGREGATE = 6  # 0 bytes
+BGP_ATTR_TYPE_AGGREGATOR = 7  # AS number and IPv4 address
+BGP_ATTR_TYPE_COMMUNITIES = 8  # RFC 1997
+BGP_ATTR_TYPE_MP_REACH_NLRI = 14  # RFC 4760
+BGP_ATTR_TYPE_MP_UNREACH_NLRI = 15  # RFC 4760
+BGP_ATTR_TYPE_EXTENDED_COMMUNITIES = 16  # RFC 4360
+BGP_ATTR_TYPE_AS4_PATH = 17  # RFC 4893
+BGP_ATTR_TYPE_AS4_AGGREGATOR = 18  # RFC 4893
+
+BGP_ATTR_ORIGIN_IGP = 0x00
+BGP_ATTR_ORIGIN_EGP = 0x01
+BGP_ATTR_ORIGIN_INCOMPLETE = 0x02
+
+AS_TRANS = 23456  # RFC 4893
+
+# Well known commmunities  (RFC 1997)
+BGP_COMMUNITY_NO_EXPORT = 0xffffff01
+BGP_COMMUNITY_NO_ADVERTISE = 0xffffff02
+BGP_COMMUNITY_NO_EXPORT_SUBCONFED = 0xffffff03
+
+# RFC 4360
+# The low-order octet of Type field (subtype)
+BGP_EXTENDED_COMMUNITY_ROUTE_TARGET = 0x02
+BGP_EXTENDED_COMMUNITY_ROUTE_ORIGIN = 0x03
+
 # NOTIFICATION Error Code and SubCode
 # Note: 0 is a valid SubCode.  (Unspecific)

 <at>  <at>  -63,7 +109,7  <at>  <at>  BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER = 1  # Data: 2 octet version number
 BGP_ERROR_SUB_BAD_PEER_AS = 2
 BGP_ERROR_SUB_BAD_BGP_IDENTIFIER = 3
 BGP_ERROR_SUB_UNSUPPORTED_OPTIONAL_PARAMETER = 4
-# 5 is deprecated RFC 1771 Authentication Failure
+BGP_ERROR_SUB_AUTHENTICATION_FAILURE = 5  # deprecated RFC 1771
 BGP_ERROR_SUB_UNACCEPTABLE_HOLD_TIME = 6

 # NOTIFICATION Error Subcode for BGP_ERROR_UPDATE_MESSAGE_ERROR
 <at>  <at>  -73,12 +119,18  <at>  <at>  BGP_ERROR_SUB_MISSING_WELL_KNOWN_ATTRIBUTE = 3  # Data: ditto
 BGP_ERROR_SUB_ATTRIBUTE_FLAGS_ERROR = 4  # Data: the attr (type, len, value)
 BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR = 5  # Data: ditto
 BGP_ERROR_SUB_INVALID_ORIGIN_ATTRIBUTE = 6  # Data: ditto
-# 7 is deprecated RFC 1771 AS Routing Loop
+BGP_ERROR_SUB_ROUTING_LOOP = 7  # deprecated RFC 1771 AS Routing Loop
 BGP_ERROR_SUB_INVALID_NEXT_HOP_ATTRIBUTE = 8  # Data: ditto
 BGP_ERROR_SUB_OPTIONAL_ATTRIBUTE_ERROR = 9  # Data: ditto
 BGP_ERROR_SUB_INVALID_NETWORK_FIELD = 10
 BGP_ERROR_SUB_MALFORMED_AS_PATH = 11

+# NOTIFICATION Error Subcode for BGP_ERROR_HOLD_TIMER_EXPIRED
+BGP_ERROR_SUB_HOLD_TIMER_EXPIRED = 1
+
+# NOTIFICATION Error Subcode for BGP_ERROR_FSM_ERROR
+BGP_ERROR_SUB_FSM_ERROR = 1
+
 # NOTIFICATION Error Subcode for BGP_ERROR_CEASE  (RFC 4486)
 BGP_ERROR_SUB_MAXIMUM_NUMBER_OF_PREFIXES_REACHED = 1  # Data: optional
 BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN = 2
 <at>  <at>  -89,48 +141,369  <at>  <at>  BGP_ERROR_SUB_OTHER_CONFIGURATION_CHANGE = 6
 BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION = 7
 BGP_ERROR_SUB_OUT_OF_RESOURCES = 8

-_VERSION = 4
-_MARKER = 16 * '\xff'

-BGP_OPT_CAPABILITY = 2  # RFC 5492
+class BgpExc(Exception):
+    """Base bgp exception."""

-BGP_CAP_MULTIPROTOCOL = 1  # RFC 4760
-BGP_CAP_ROUTE_REFRESH = 2  # RFC 2918
-BGP_CAP_CARRYING_LABEL_INFO = 4  # RFC 3107
-BGP_CAP_FOUR_OCTET_AS_NUMBER = 65  # RFC 4893
-BGP_CAP_ENHANCED_ROUTE_REFRESH = 70  # https://tools.ietf.org/html/\
-                               # draft-ietf-idr-bgp-enhanced-route-refresh-05
+    CODE = 0
+    """BGP error code."""

-BGP_ATTR_FLAG_OPTIONAL = 1 << 7
-BGP_ATTR_FLAG_TRANSITIVE = 1 << 6
-BGP_ATTR_FLAG_PARTIAL = 1 << 5
-BGP_ATTR_FLAG_EXTENDED_LENGTH = 1 << 4
+    SUB_CODE = 0
+    """BGP error sub-code."""

-BGP_ATTR_TYPE_ORIGIN = 1  # 0,1,2 (1 byte)
-BGP_ATTR_TYPE_AS_PATH = 2  # a list of AS_SET/AS_SEQUENCE  eg. {1 2 3} 4 5
-BGP_ATTR_TYPE_NEXT_HOP = 3  # an IPv4 address
-BGP_ATTR_TYPE_MULTI_EXIT_DISC = 4  # uint32 metric
-BGP_ATTR_TYPE_LOCAL_PREF = 5  # uint32
-BGP_ATTR_TYPE_ATOMIC_AGGREGATE = 6  # 0 bytes
-BGP_ATTR_TYPE_AGGREGATOR = 7  # AS number and IPv4 address
-BGP_ATTR_TYPE_COMMUNITIES = 8  # RFC 1997
-BGP_ATTR_TYPE_MP_REACH_NLRI = 14  # RFC 4760
-BGP_ATTR_TYPE_MP_UNREACH_NLRI = 15  # RFC 4760
-BGP_ATTR_TYPE_EXTENDED_COMMUNITIES = 16  # RFC 4360
-BGP_ATTR_TYPE_AS4_PATH = 17  # RFC 4893
-BGP_ATTR_TYPE_AS4_AGGREGATOR = 18  # RFC 4893
+    SEND_ERROR = True
+    """Flag if set indicates Notification message should be sent to peer."""

-AS_TRANS = 23456  # RFC 4893
+    def __init__(self, data=''):
+        self.data = data

-# Well known commmunities  (RFC 1997)
-BGP_COMMUNITY_NO_EXPORT = 0xffffff01
-BGP_COMMUNITY_NO_ADVERTISE = 0xffffff02
-BGP_COMMUNITY_NO_EXPORT_SUBCONFED = 0xffffff03
+    def __str__(self):
+        return '<%s %r>' % (self.__class__.__name__, self.data)
+
+
+class BadNotification(BgpExc):
+    SEND_ERROR = False
+
+# ============================================================================
+# Message Header Errors
+# ============================================================================
+
+
+class NotSync(BgpExc):
+    CODE = BGP_ERROR_MESSAGE_HEADER_ERROR
+    SUB_CODE = BGP_ERROR_SUB_CONNECTION_NOT_SYNCHRONIZED
+
+
+class BadLen(BgpExc):
+    CODE = BGP_ERROR_MESSAGE_HEADER_ERROR
+    SUB_CODE = BGP_ERROR_SUB_BAD_MESSAGE_LENGTH
+
+    def __init__(self, msg_type_code, message_length):
+        self.msg_type_code = msg_type_code
+        self.length = message_length
+        self.data = struct.pack('!H', self.length)
+
+    def __str__(self):
+        return '<BadLen %d msgtype=%d>' % (self.length, self.msg_type_code)
+
+
+class BadMsg(BgpExc):
+    """Error to indicate un-recognized message type.
+
+    RFC says: If the Type field of the message header is not recognized, then
+    the Error Subcode MUST be set to Bad Message Type.  The Data field MUST
+    contain the erroneous Type field.
+    """
+    CODE = BGP_ERROR_MESSAGE_HEADER_ERROR
+    SUB_CODE = BGP_ERROR_SUB_BAD_MESSAGE_TYPE
+
+    def __init__(self, msg_type):
+        self.msg_type = msg_type
+        self.data = struct.pack('B', msg_type)
+
+    def __str__(self):
+        return '<BadMsg %d>' % (self.msg,)
+
+# ============================================================================
+# OPEN Message Errors
+# ============================================================================
+
+
+class MalformedOptionalParam(BgpExc):
+    """If recognized optional parameters are malformed.
+
+    RFC says: If one of the Optional Parameters in the OPEN message is
+    recognized, but is malformed, then the Error Subcode MUST be set to 0
+    (Unspecific).
+    """
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = 0
+
+
+class UnsupportedVersion(BgpExc):
+    """Error to indicate unsupport bgp version number.
+
+    RFC says: If the version number in the Version field of the received OPEN
+    message is not supported, then the Error Subcode MUST be set to Unsupported
+    Version Number.  The Data field is a 2-octet unsigned integer, which
+    indicates the largest, locally-supported version number less than the
+    version the remote BGP peer bid (as indicated in the received OPEN
+    message), or if the smallest, locally-supported version number is greater
+    than the version the remote BGP peer bid, then the smallest, locally-
+    supported version number.
+    """
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER
+
+    def __init__(self, locally_support_version):
+        self.data = struct.pack('H', locally_support_version)
+
+
+class BadPeerAs(BgpExc):
+    """Error to indicate open message has incorrect AS number.
+
+    RFC says: If the Autonomous System field of the OPEN message is
+    unacceptable, then the Error Subcode MUST be set to Bad Peer AS.  The
+    determination of acceptable Autonomous System numbers is configure peer AS.
+    """
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_BAD_PEER_AS
+
+
+class BadBgpId(BgpExc):
+    """Error to indicate incorrect BGP Identifier.
+
+    RFC says: If the BGP Identifier field of the OPEN message is syntactically
+    incorrect, then the Error Subcode MUST be set to Bad BGP Identifier.
+    Syntactic correctness means that the BGP Identifier field represents a
+    valid unicast IP host address.
+    """
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_BAD_BGP_IDENTIFIER
+
+
+class UnsupportedOptParam(BgpExc):
+    """Error to indicate unsupported optional parameters.
+
+    RFC says: If one of the Optional Parameters in the OPEN message is not
+    recognized, then the Error Subcode MUST be set to Unsupported Optional
+    Parameters.
+    """
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_UNSUPPORTED_OPTIONAL_PARAMETER
+
+
+class AuthFailure(BgpExc):
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_AUTHENTICATION_FAILURE
+
+
+class UnacceptableHoldTime(BgpExc):
+    """Error to indicate Unacceptable Hold Time in open message.
+
+    RFC says: If the Hold Time field of the OPEN message is unacceptable, then
+    the Error Subcode MUST be set to Unacceptable Hold Time.
+    """
+    CODE = BGP_ERROR_OPEN_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_UNACCEPTABLE_HOLD_TIME
+
+# ============================================================================
+# UPDATE message related errors
+# ============================================================================
+
+
+class MalformedAttrList(BgpExc):
+    """Error to indicate UPDATE message is malformed.
+
+    RFC says: Error checking of an UPDATE message begins by examining the path
+    attributes.  If the Withdrawn Routes Length or Total Attribute Length is
+    too large (i.e., if Withdrawn Routes Length + Total Attribute Length + 23
+    exceeds the message Length), then the Error Subcode MUST be set to
+    Malformed Attribute List.
+    """
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST
+
+
+class UnRegWellKnowAttr(BgpExc):
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_UNRECOGNIZED_WELL_KNOWN_ATTRIBUTE

-# RFC 4360
-# The low-order octet of Type field (subtype)
-BGP_EXTENDED_COMMUNITY_ROUTE_TARGET = 0x02
-BGP_EXTENDED_COMMUNITY_ROUTE_ORIGIN = 0x03
+
+class MissingWellKnown(BgpExc):
+    """Error to indicate missing well-known attribute.
+
+    RFC says: If any of the well-known mandatory attributes are not present,
+    then the Error Subcode MUST be set to Missing Well-known Attribute.  The
+    Data field MUST contain the Attribute Type Code of the missing, well-known
+    attribute.
+    """
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_MISSING_WELL_KNOWN_ATTRIBUTE
+
+    def __init__(self, pattr_type_code):
+        self.pattr_type_code = pattr_type_code
+        self.data = struct.pack('B', pattr_type_code)
+
+
+class AttrFlagError(BgpExc):
+    """Error to indicate recognized path attributes have incorrect flags.
+
+    RFC says: If any recognized attribute has Attribute Flags that conflict
+    with the Attribute Type Code, then the Error Subcode MUST be set to
+    Attribute Flags Error.  The Data field MUST contain the erroneous attribute
+    (type, length, and value).
+    """
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_ATTRIBUTE_FLAGS_ERROR
+
+
+class AttrLenError(BgpExc):
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR
+
+
+class InvalidOriginError(BgpExc):
+    """Error indicates undefined Origin attribute value.
+
+    RFC says: If the ORIGIN attribute has an undefined value, then the Error
+    Sub- code MUST be set to Invalid Origin Attribute.  The Data field MUST
+    contain the unrecognized attribute (type, length, and value).
+    """
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_INVALID_ORIGIN_ATTRIBUTE
+
+
+class RoutingLoop(BgpExc):
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_ROUTING_LOOP
+
+
+class InvalidNextHop(BgpExc):
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_INVALID_NEXT_HOP_ATTRIBUTE
+
+
+class OptAttrError(BgpExc):
+    """Error indicates Optional Attribute is malformed.
+
+    RFC says: If an optional attribute is recognized, then the value of this
+    attribute MUST be checked.  If an error is detected, the attribute MUST be
+    discarded, and the Error Subcode MUST be set to Optional Attribute Error.
+    The Data field MUST contain the attribute (type, length, and value).
+    """
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_OPTIONAL_ATTRIBUTE_ERROR
+
+
+class InvalidNetworkField(BgpExc):
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_INVALID_NETWORK_FIELD
+
+
+class MalformedAsPath(BgpExc):
+    """Error to indicate if AP_PATH attribute is syntactically incorrect.
+
+    RFC says: The AS_PATH attribute is checked for syntactic correctness.  If
+    the path is syntactically incorrect, then the Error Subcode MUST be set to
+    Malformed AS_PATH.
+    """
+    CODE = BGP_ERROR_UPDATE_MESSAGE_ERROR
+    SUB_CODE = BGP_ERROR_SUB_MALFORMED_AS_PATH
+
+
+# ============================================================================
+# Hold Timer Expired
+# ============================================================================
+
+
+class HoldTimerExpired(BgpExc):
+    """Error to indicate Hold Timer expired.
+
+    RFC says: If a system does not receive successive KEEPALIVE, UPDATE, and/or
+    NOTIFICATION messages within the period specified in the Hold Time field of
+    the OPEN message, then the NOTIFICATION message with the Hold Timer Expired
+    Error Code is sent and the BGP connection is closed.
+    """
+    CODE = BGP_ERROR_HOLD_TIMER_EXPIRED
+    SUB_CODE = BGP_ERROR_SUB_HOLD_TIMER_EXPIRED
+
+# ============================================================================
+# Finite State Machine Error
+# ============================================================================
+
+
+class FiniteStateMachineError(BgpExc):
+    """Error to indicate any Finite State Machine Error.
+
+    RFC says: Any error detected by the BGP Finite State Machine (e.g., receipt
+    of an unexpected event) is indicated by sending the NOTIFICATION message
+    with the Error Code Finite State Machine Error.
+    """
+    CODE = BGP_ERROR_FSM_ERROR
+    SUB_CODE = BGP_ERROR_SUB_FSM_ERROR
+
+
+# ============================================================================
+# Cease Errors
+# ============================================================================
+
+class MaxPrefixReached(BgpExc):
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_MAXIMUM_NUMBER_OF_PREFIXES_REACHED
+
+
+class AdminShutdown(BgpExc):
+    """Error to indicate Administrative shutdown.
+
+    RFC says: If a BGP speaker decides to administratively shut down its
+    peering with a neighbor, then the speaker SHOULD send a NOTIFICATION
+    message  with the Error Code Cease and the Error Subcode 'Administrative
+    Shutdown'.
+    """
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN
+
+
+class PeerDeConfig(BgpExc):
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_PEER_DECONFIGURED
+
+
+class AdminReset(BgpExc):
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_ADMINISTRATIVE_RESET
+
+
+class ConnRejected(BgpExc):
+    """Error to indicate Connection Rejected.
+
+    RFC says: If a BGP speaker decides to disallow a BGP connection (e.g., the
+    peer is not configured locally) after the speaker accepts a transport
+    protocol connection, then the BGP speaker SHOULD send a NOTIFICATION
+    message with the Error Code Cease and the Error Subcode "Connection
+    Rejected".
+    """
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_CONNECTION_RESET
+
+
+class OtherConfChange(BgpExc):
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_OTHER_CONFIGURATION_CHANGE
+
+
+class CollisionResolution(BgpExc):
+    """Error to indicate Connection Collision Resolution.
+
+    RFC says: If a BGP speaker decides to send a NOTIFICATION message with the
+    Error Code Cease as a result of the collision resolution procedure (as
+    described in [BGP-4]), then the subcode SHOULD be set to "Connection
+    Collision Resolution".
+    """
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION
+
+
+class OutOfResource(BgpExc):
+    CODE = BGP_ERROR_CEASE
+    SUB_CODE = BGP_ERROR_SUB_OUT_OF_RESOURCES
+
+
+class RouteFamily(StringifyMixin):
+    def __init__(self, afi, safi):
+        self.afi = afi
+        self.safi = safi
+
+    def __cmp__(self, other):
+        return cmp((other.afi, other.safi), (self.afi, self.safi))
+
+# Route Family Singleton
+RF_IPv4_UC = RouteFamily(afi.IP, safi.UNICAST)
+RF_IPv6_UC = RouteFamily(afi.IP6, safi.UNICAST)
+RF_IPv4_VPN = RouteFamily(afi.IP, safi.MPLS_VPN)
+RF_IPv6_VPN = RouteFamily(afi.IP6, safi.MPLS_VPN)
+RF_RTC_UC = RouteFamily(afi.IP, safi.ROUTE_TARGET_CONSTRTAINS)

 
 def pad(bin, len_):
 <at>  <at>  -288,6 +661,23  <at>  <at>  class _IPAddrPrefix(_AddrPrefix):
         return (addrconv.ipv4.bin_to_text(pad(addr, 4)),)

 
+class _IP6AddrPrefix(_AddrPrefix):
+    _TYPE = {
+        'ascii': [
+            'addr'
+        ]
+    }
+
+     <at> staticmethod
+    def _prefix_to_bin(addr):
+        (addr,) = addr
+        return addrconv.ipv6.text_to_bin(addr)
+
+     <at> staticmethod
+    def _prefix_from_bin(addr):
+        return (addrconv.ipv6.bin_to_text(pad(addr, 16)),)
+
+
 class _VPNAddrPrefix(_AddrPrefix):
     _RD_PACK_STR = '!Q'

 <at>  <at>  -321,18 +711,125  <at>  <at>  class _VPNAddrPrefix(_AddrPrefix):
         return (rd,) + super(_VPNAddrPrefix, cls)._prefix_from_bin(binrest)

 
+class IPAddrPrefix(_UnlabelledAddrPrefix, _IPAddrPrefix):
+    ROUTE_FAMILY = RF_IPv4_UC
+
+     <at> property
+    def prefix(self):
+        return self.addr
+
+
+class IP6AddrPrefix(_UnlabelledAddrPrefix, _IP6AddrPrefix):
+    ROUTE_FAMILY = RF_IPv6_UC
+
+     <at> property
+    def prefix(self):
+        return self.addr
+
+
 class LabelledVPNIPAddrPrefix(_LabelledAddrPrefix, _VPNAddrPrefix,
                               _IPAddrPrefix):
-    pass
+    ROUTE_FAMILY = RF_IPv4_VPN

 
-class IPAddrPrefix(_UnlabelledAddrPrefix, _IPAddrPrefix):
-    pass
+class LabelledVPNIP6AddrPrefix(_LabelledAddrPrefix, _VPNAddrPrefix,
+                               _IP6AddrPrefix):
+    ROUTE_FAMILY = RF_IPv6_VPN
+
+
+class RouteTargetMembershipNLRI(StringifyMixin):
+    """Route Target Membership NLRI.
+
+    Route Target membership NLRI is advertised in BGP UPDATE messages using
+    the MP_REACH_NLRI and MP_UNREACH_NLRI attributes.
+    """
+
+    ROUTE_FAMILY = RF_RTC_UC
+    DEFAULT_AS = '0:0'
+    DEFAULT_RT = '0:0'
+
+    def __init__(self, origin_as, route_target):
+        # If given is not default_as and default_rt
+        if not (origin_as is RtNlri.DEFAULT_AS and
+                route_target is RtNlri.DEFAULT_RT):
+            # We validate them
+            if (not is_valid_old_asn(origin_as) or
+                    not is_valid_ext_comm_attr(route_target)):
+                raise ValueError('Invalid params.')
+        self.origin_as = origin_as
+        self.route_target = route_target
+
+     <at> property
+    def formatted_nlri_str(self):
+        return "%s:%s" % (self.origin_as, self.route_target)
+
+    def is_default_rtnlri(self):
+        if (self._origin_as is RtNlri.DEFAULT_AS and
+                self._route_target is RtNlri.DEFAULT_RT):
+            return True
+        return False
+
+    def __cmp__(self, other):
+        return cmp(
+            (self._origin_as, self._route_target),
+            (other.origin_as, other.route_target),
+        )
+
+     <at> classmethod
+    def parser(cls, buf):
+        idx = 0
+
+        # Extract origin AS.
+        origin_as, = struct.unpack_from('!I', buf, idx)
+        idx += 4
+
+        # Extract route target.
+        route_target = ''
+        etype, esubtype, payload = struct.unpack_from('BB6s', buf, idx)
+        # RFC says: The value of the high-order octet of the Type field for the
+        # Route Target Community can be 0x00, 0x01, or 0x02.  The value of the
+        # low-order octet of the Type field for this community is 0x02.
+        # TODO(PH): Remove this exception when it breaks something Here we make
+        # exception as Routem packs lower-order octet as 0x00
+        if etype in (0, 2) and esubtype in (0, 2):
+            # If we have route target community in AS number format.
+            asnum, i = struct.unpack('!HI', payload)
+            route_target = ('%s:%s' % (asnum, i))
+        elif etype == 1 and esubtype == 2:
+            # If we have route target community in IP address format.
+            ip_addr, i = struct.unpack('!4sH', payload)
+            ip_addr = socket.inet_ntoa(ip_addr)
+            route_target = ('%s:%s' % (ip_addr, i))
+        elif etype == 0 and esubtype == 1:
+            # TODO(PH): Parsing of RtNlri 1:1:100:1
+            asnum, i = struct.unpack('!HI', payload)
+            route_target = ('%s:%s' % (asnum, i))
+
+        return cls(origin_as, route_target)
+
+    def serialize(self):
+        rt_nlri = ''
+        if not self.is_default_rtnlri():
+            rt_nlri += struct.pack('!I', self.origin_as)
+            # Encode route target
+            first, second = self.route_target.split(':')
+            if '.' in first:
+                ip_addr = socket.inet_aton(first)
+                rt_nlri += struct.pack('!BB4sH', 1, 2, ip_addr, int(second))
+            else:
+                rt_nlri += struct.pack('!BBHI', 0, 2, int(first), int(second))
+
+        # RT Nlri is 12 octets
+        return struct.pack('B', (8 * 12)) + rt_nlri

+_addr_class_key = lambda x: (x.afi, x.safi)

 _ADDR_CLASSES = {
-    (afi.IP, safi.UNICAST): IPAddrPrefix,
-    (afi.IP, safi.MPLS_VPN): LabelledVPNIPAddrPrefix,
+    _addr_class_key(RF_IPv4_UC): IPAddrPrefix,
+    _addr_class_key(RF_IPv6_UC): IP6AddrPrefix,
+    _addr_class_key(RF_IPv4_VPN): LabelledVPNIPAddrPrefix,
+    _addr_class_key(RF_IPv6_VPN): LabelledVPNIP6AddrPrefix,
+    _addr_class_key(RF_RTC_UC): RouteTargetMembershipNLRI,
 }

 
 <at>  <at>  -417,7 +914,7  <at>  <at>  class _OptParam(StringifyMixin, _TypeDisp, _Value):
             type_ = self._rev_lookup_type(self.__class__)
         self.type = type_
         self.length = length
-        if not value is None:
+        if value is not None:
             self.value = value

      <at> classmethod
 <at>  <at>  -463,9 +960,9  <at>  <at>  class _OptParamCapability(_OptParam, _TypeDisp):
         if cap_code is None:
             cap_code = self._rev_lookup_type(self.__class__)
         self.cap_code = cap_code
-        if not cap_value is None:
+        if cap_value is not None:
             self.cap_value = cap_value
-        if not cap_length is None:
+        if cap_length is not None:
             self.cap_length = cap_length

      <at> classmethod
 <at>  <at>  -516,6 +1013,11  <at>  <at>  class BGPOptParamCapabilityRouteRefresh(_OptParamEmptyCapability):
     pass

 
+ <at> _OptParamCapability.register_type(BGP_CAP_ENHANCED_ROUTE_REFRESH)
+class BGPOptParamCapabilityEnhancedRouteRefresh(_OptParamEmptyCapability):
+    pass
+
+
  <at> _OptParamCapability.register_type(BGP_CAP_FOUR_OCTET_AS_NUMBER)
 class BGPOptParamCapabilityFourOctetAsNumber(_OptParamCapability):
     _CAP_PACK_STR = '!I'
 <at>  <at>  -586,7 +1088,7  <at>  <at>  class _PathAttribute(StringifyMixin, _TypeDisp, _Value):
         self.flags = flags
         self.type = type_
         self.length = length
-        if not value is None:
+        if value is not None:
             self.value = value

      <at> classmethod
 <at>  <at>  -607,7 +1109,7  <at>  <at>  class _PathAttribute(StringifyMixin, _TypeDisp, _Value):

     def serialize(self):
         # fixup
-        if not self._ATTR_FLAGS is None:
+        if self._ATTR_FLAGS is not None:
             self.flags = self.flags \
                 & ~(BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANSITIVE) \
                 | self._ATTR_FLAGS
 <at>  <at>  -655,6 +1157,41  <at>  <at>  class _BGPPathAttributeAsPathCommon(_PathAttribute):
     _AS_PACK_STR = None
     _ATTR_FLAGS = BGP_ATTR_FLAG_TRANSITIVE

+     <at> property
+    def path_seg_list(self):
+        return copy.deepcopy(self.value)
+
+    def get_as_path_len(self):
+        count = 0
+        for seg in self.value:
+            if isinstance(seg, list):
+                # Segment type 2 stored in list and all AS counted.
+                count += len(seg)
+            else:
+                # Segment type 1 stored in set and count as one.
+                count += 1
+
+        return count
+
+    def has_local_as(self, local_as):
+        """Check if *local_as* is already present on path list."""
+        for as_path_seg in self.value:
+            for as_num in as_path_seg:
+                if as_num == local_as:
+                    return True
+        return False
+
+    def has_matching_leftmost(self, remote_as):
+        """Check if leftmost AS matches *remote_as*."""
+        if not self.value or not remote_as:
+            return False
+
+        leftmost_seg = self.path_seg_list[0]
+        if leftmost_seg and leftmost_seg[0] == remote_as:
+            return True
+
+        return False
+
      <at> classmethod
     def parse_value(cls, buf):
         result = []
 <at>  <at>  -808,6 +1345,12  <at>  <at>  class BGPPathAttributeCommunities(_PathAttribute):
     _VALUE_PACK_STR = '!I'
     _ATTR_FLAGS = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANSITIVE

+    # String constants of well-known-communities
+    NO_EXPORT = int('0xFFFFFF01', 16)
+    NO_ADVERTISE = int('0xFFFFFF02', 16)
+    NO_EXPORT_SUBCONFED = int('0xFFFFFF03', 16)
+    WELL_KNOW_COMMUNITIES = (NO_EXPORT, NO_ADVERTISE, NO_EXPORT_SUBCONFED)
+
     def __init__(self, communities,
                  flags=0, type_=None, length=None):
         super(BGPPathAttributeCommunities, self).__init__(flags=flags,
 <at>  <at>  -836,6 +1379,36  <at>  <at>  class BGPPathAttributeCommunities(_PathAttribute):
             buf += bincomm
         return buf

+     <at> staticmethod
+    def is_no_export(comm_attr):
+        """Returns True if given value matches well-known community NO_EXPORT
+         attribute value.
+         """
+        return comm_attr == Community.NO_EXPORT
+
+     <at> staticmethod
+    def is_no_advertise(comm_attr):
+        """Returns True if given value matches well-known community
+        NO_ADVERTISE attribute value.
+        """
+        return comm_attr == Community.NO_ADVERTISE
+
+     <at> staticmethod
+    def is_no_export_subconfed(comm_attr):
+        """Returns True if given value matches well-known community
+         NO_EXPORT_SUBCONFED attribute value.
+         """
+        return comm_attr == Community.NO_EXPORT_SUBCONFED
+
+    def has_comm_attr(self, attr):
+        """Returns True if given community attribute is present."""
+
+        for comm_attr in self.communities:
+            if comm_attr == attr:
+                return True
+
+        return False
+

 # Extended Communities
 # RFC 4360
 <at>  <at>  -1292,6 +1865,8  <at>  <at>  class BGPUpdate(BGPMessage):
     ========================== ===============================================
     """

+    _MIN_LEN = BGPMessage._HDR_LEN
+
     def __init__(self, type_=BGP_MSG_UPDATE,
                  withdrawn_routes_len=None,
                  withdrawn_routes=[],
 <at>  <at>  -1304,8 +1879,18  <at>  <at>  class BGPUpdate(BGPMessage):
         self.withdrawn_routes = withdrawn_routes
         self.total_path_attribute_len = total_path_attribute_len
         self.path_attributes = path_attributes
+        self._pathattr_map = {}
+        for attr in path_attributes:
+            self._pathattr_map[attr.type] = attr
         self.nlri = nlri

+     <at> property
+    def pathattr_map(self):
+        return self._pathattr_map
+
+    def get_path_attr(self, attr_name):
+        return self._pathattr_map.get(attr_name)
+
      <at> classmethod
     def parser(cls, buf):
         offset = 0
 <at>  <at>  -1422,6 +2007,41  <at>  <at>  class BGPNotification(BGPMessage):
     _PACK_STR = '!BB'
     _MIN_LEN = BGPMessage._HDR_LEN + struct.calcsize(_PACK_STR)

+    _REASONS = {
+        (1, 1): 'Message Header Error: not synchronised',
+        (1, 2): 'Message Header Error: bad message len',
+        (1, 3): 'Message Header Error: bad message type',
+        (2, 1): 'Open Message Error: unsupported version',
+        (2, 2): 'Open Message Error: bad peer AS',
+        (2, 3): 'Open Message Error: bad BGP identifier',
+        (2, 4): 'Open Message Error: unsupported optional param',
+        (2, 5): 'Open Message Error: authentication failure',
+        (2, 6): 'Open Message Error: unacceptable hold time',
+        (2, 7): 'Open Message Error: Unsupported Capability',
+        (2, 8): 'Open Message Error: Unassigned',
+        (3, 1): 'Update Message Error: malformed attribute list',
+        (3, 2): 'Update Message Error: unrecognized well-known attr',
+        (3, 3): 'Update Message Error: missing well-known attr',
+        (3, 4): 'Update Message Error: attribute flags error',
+        (3, 5): 'Update Message Error: attribute length error',
+        (3, 6): 'Update Message Error: invalid origin attr',
+        (3, 7): 'Update Message Error: as routing loop',
+        (3, 8): 'Update Message Error: invalid next hop attr',
+        (3, 9): 'Update Message Error: optional attribute error',
+        (3, 10): 'Update Message Error: invalid network field',
+        (3, 11): 'Update Message Error: malformed AS_PATH',
+        (4, 1): 'Hold Timer Expired',
+        (5, 1): 'Finite State Machine Error',
+        (6, 1): 'Cease: Maximum Number of Prefixes Reached',
+        (6, 2): 'Cease: Administrative Shutdown',
+        (6, 3): 'Cease: Peer De-configured',
+        (6, 4): 'Cease: Administrative Reset',
+        (6, 5): 'Cease: Connection Rejected',
+        (6, 6): 'Cease: Other Configuration Change',
+        (6, 7): 'Cease: Connection Collision Resolution',
+        (6, 8): 'Cease: Out of Resources',
+    }
+
     def __init__(self,
                  error_code,
                  error_subcode,
 <at>  <at>  -1450,6 +2070,10  <at>  <at>  class BGPNotification(BGPMessage):
         msg += self.data
         return msg

+     <at> property
+    def reason(self):
+        return self._REASONS.get((self.error_code, self.error_subcode))
+

  <at> BGPMessage.register_type(BGP_MSG_ROUTE_REFRESH)
 class BGPRouteRefresh(BGPMessage):
--

-- 
1.7.9.5

------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
Yuichi Ito | 16 Apr 03:38 2014
Picon

[PATCH 3/3] of14: set default attributes for group-related classes

Signed-off-by: Yuichi Ito <ito.yuichi0@...>
---
 ryu/ofproto/ofproto_v1_4_parser.py |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/ryu/ofproto/ofproto_v1_4_parser.py b/ryu/ofproto/ofproto_v1_4_parser.py
index 230ac9e..618b676 100644
--- a/ryu/ofproto/ofproto_v1_4_parser.py
+++ b/ryu/ofproto/ofproto_v1_4_parser.py
 <at>  <at>  -4958,7 +4958,7  <at>  <at>  class OFPActionGroup(OFPAction):
     group_id         Group identifier
     ================ ======================================================
     """
-    def __init__(self, group_id, type_=None, len_=None):
+    def __init__(self, group_id=0, type_=None, len_=None):
         super(OFPActionGroup, self).__init__()
         self.group_id = group_id

 <at>  <at>  -5429,7 +5429,8  <at>  <at>  class OFPGroupMod(MsgBase):
                                          ofp.OFPGT_SELECT, group_id, buckets)
             datapath.send_msg(req)
     """
-    def __init__(self, datapath, command, type_, group_id, buckets):
+    def __init__(self, datapath, command=ofproto.OFPGC_ADD,
+                 type_=ofproto.OFPGT_ALL, group_id=0, buckets=[]):
         super(OFPGroupMod, self).__init__(datapath)
         self.command = command
         self.type = type_
 <at>  <at>  -5562,7 +5563,8  <at>  <at>  class OFPPortMod(MsgBase):

 
 class OFPBucket(StringifyMixin):
-    def __init__(self, weight, watch_port, watch_group, actions, len_=None):
+    def __init__(self, weight=0, watch_port=ofproto.OFPP_ANY,
+                 watch_group=ofproto.OFPG_ANY, actions=None, len_=None):
         super(OFPBucket, self).__init__()
         self.weight = weight
         self.watch_port = watch_port
--

-- 
1.7.10.4

------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
Yuichi Ito | 16 Apr 03:37 2014
Picon

[PATCH 2/3] of13: set default attributes for group-related classes

Signed-off-by: Yuichi Ito <ito.yuichi0@...>
---
 ryu/ofproto/ofproto_v1_3_parser.py |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/ryu/ofproto/ofproto_v1_3_parser.py b/ryu/ofproto/ofproto_v1_3_parser.py
index 38eeb1f..13bf385 100644
--- a/ryu/ofproto/ofproto_v1_3_parser.py
+++ b/ryu/ofproto/ofproto_v1_3_parser.py
 <at>  <at>  -2687,7 +2687,7  <at>  <at>  class OFPActionGroup(OFPAction):
     group_id         Group identifier
     ================ ======================================================
     """
-    def __init__(self, group_id, type_=None, len_=None):
+    def __init__(self, group_id=0, type_=None, len_=None):
         super(OFPActionGroup, self).__init__()
         self.group_id = group_id

 <at>  <at>  -3178,7 +3178,8  <at>  <at>  class OFPActionExperimenter(OFPAction):

 
 class OFPBucket(StringifyMixin):
-    def __init__(self, weight, watch_port, watch_group, actions, len_=None):
+    def __init__(self, weight=0, watch_port=ofproto.OFPP_ANY,
+                 watch_group=ofproto.OFPG_ANY, actions=None, len_=None):
         super(OFPBucket, self).__init__()
         self.weight = weight
         self.watch_port = watch_port
 <at>  <at>  -3262,7 +3263,8  <at>  <at>  class OFPGroupMod(MsgBase):
                                          ofp.OFPGT_SELECT, group_id, buckets)
             datapath.send_msg(req)
     """
-    def __init__(self, datapath, command, type_, group_id, buckets):
+    def __init__(self, datapath, command=ofproto.OFPGC_ADD,
+                 type_=ofproto.OFPGT_ALL, group_id=0, buckets=[]):
         super(OFPGroupMod, self).__init__(datapath)
         self.command = command
         self.type = type_
--

-- 
1.7.10.4

------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech
Yuichi Ito | 16 Apr 03:37 2014
Picon

[PATCH 1/3] of12: set default attributes for group-related classes

Signed-off-by: Yuichi Ito <ito.yuichi0@...>
---
 ryu/ofproto/ofproto_v1_2_parser.py |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/ryu/ofproto/ofproto_v1_2_parser.py b/ryu/ofproto/ofproto_v1_2_parser.py
index 08b3ae8..2b2d48f 100644
--- a/ryu/ofproto/ofproto_v1_2_parser.py
+++ b/ryu/ofproto/ofproto_v1_2_parser.py
 <at>  <at>  -1163,7 +1163,7  <at>  <at>  class OFPActionGroup(OFPAction):
     group_id         Group identifier
     ================ ======================================================
     """
-    def __init__(self, group_id, type_=None, len_=None):
+    def __init__(self, group_id=0, type_=None, len_=None):
         super(OFPActionGroup, self).__init__()
         self.group_id = group_id

 <at>  <at>  -1594,7 +1594,8  <at>  <at>  class OFPActionExperimenter(OFPAction):

 
 class OFPBucket(StringifyMixin):
-    def __init__(self, weight, watch_port, watch_group, actions, len_=None):
+    def __init__(self, weight=0, watch_port=ofproto.OFPP_ANY,
+                 watch_group=ofproto.OFPG_ANY, actions=None, len_=None):
         super(OFPBucket, self).__init__()
         self.weight = weight
         self.watch_port = watch_port
 <at>  <at>  -1679,7 +1680,8  <at>  <at>  class OFPGroupMod(MsgBase):
                                          ofp.OFPGT_SELECT, group_id, buckets)
             datapath.send_msg(req)
     """
-    def __init__(self, datapath, command, type_, group_id, buckets):
+    def __init__(self, datapath, command=ofproto.OFPGC_ADD,
+                 type_=ofproto.OFPGT_ALL, group_id=0, buckets=[]):
         super(OFPGroupMod, self).__init__(datapath)
         self.command = command
         self.type = type_
--

-- 
1.7.10.4

------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech

Gmane