Custom Search
Showing posts with label OpenStack Neutron. Show all posts
Showing posts with label OpenStack Neutron. Show all posts

Thursday, April 23, 2015

OpenStack Neutron API Examples using curl

1)
export OS_USERNAME=admin
export OS_PASSWORD=secret123
export OS_TENANT_NAME=admin
export OS_AUTH_URL=http://127.0.0.1:35357/v2.0


2)
You can find endpoint of neutron service with following command
#keystone service-list
#keystone endpoint-list

3)
List networks

#curl -s -H "X-Auth-Token: $(keystone token-get | awk '/ id / {print $4}')" 192.168.56.102:9696/v2.0/networks | python -mjson.tool

List subnets
#curl -s -H "X-Auth-Token: $(keystone token-get | awk '/ id / {print $4}')" 192.168.56.102:9696/v2.0/subnets | python -mjson.tool

List security-groups
#curl -s -H "X-Auth-Token: $(keystone token-get | awk '/ id / {print $4}')" 192.168.56.102:9696/v2.0/security-groups | python -mjson.tool

List ports
#curl -s -H "X-Auth-Token: $(keystone token-get | awk '/ id / {print $4}')" 192.168.56.102:9696/v2.0/ports | python -mjson.tool

List routers

#curl -s -H "X-Auth-Token: $(keystone token-get | awk '/ id / {print $4}')" 192.168.56.102:9696/v2.0/routers | python -mjson.tool

List extensions

#curl -s -H "X-Auth-Token: $(keystone token-get | awk '/ id / {print $4}')" 192.168.56.102:9696/v2.0/extensions | python -mjson.tool



Tuesday, January 20, 2015

How to Test and Debug OpenContrail APIs using OpenStack neutron Client

1)
Fire API request using OpenStack neutron Client

#neutron net-list

2)
Check OpenContrail API Log

#tail -f /var/log/contrail/contrail-api-0.log

3)
Check OpenContrail APIs

http://opencontrail-api-server:9100/
http://opencontrail-api-server:9100/xxxxx





Tuesday, November 25, 2014

OpenStack Python Client How to add new CLI command

1)
Clone python-neutronclient
#git clone https://github.com/openstack/python-neutronclient.git
#cd python-neutronclient
#git checkout 2.3.6


2)
Export the credentials
export OS_USERNAME=admin
export OS_PASSWORD=secret123
export OS_TENANT_NAME=demo
export OS_AUTH_URL=http://127.0.0.1:35357/v2.0


3)
Run the CLI command from cloned dir

#python neutron net-list
Success: Working

4)
Try to execute a command which is not implemented yet
#python neutron ipam-list
Error: Unknown command [u'ipam-list']

5)
Create command to class Mapping for our new command "ipam-list"


#vim python-neutronclient/neutronclient/shell.py

* Add the name of the command and class (command to class map) to the COMMAND_V2 dictionary

Example:
--------------
COMMAND_V2 = {
    .... ....
    'ipam-list':None,
}


COMMANDS = {'2.0': COMMAND_V2}


* Then try to run the new command "ipam-list"
#python neutron ipam-list
Error: 'NoneType' object is not callable

6)
Create a file named "ipam.py" under python-neutronclient/neutronclient/neutron/v2_0/ and add following lines

import logging
from neutronclient.neutron.v2_0 import ListCommand

class ListIpam(ListCommand):
    resource = 'ipam'
    log = logging.getLogger(__name__ + '.ListIpam')
    _formatters = {}
    list_columns = ['id', 'name']


7)
Map the command "ipam-list" to new class "ListIpam"


#vim python-neutronclient/neutronclient/shell.py


from neutronclient.neutron.v2_0 import ipam

COMMAND_V2 = {
    .... ....
    'ipam-list':ipam.ListIpam,
}


* Then try to run the command
#python neutron ipam-list
Error: 'Client' object has no attribute 'list_ipams'

8)
Add method in client class
#vim python-neutronclient/neutronclient/v2_0/client.py
This file is responsible to generate REST API requests and send the same requests to your plugin running on neutron-server.
Add following codes

class Client(object):
    .... ....
    ipams_path = "/ipams"
   
    @APIParamsCall
    def list_ipams(self, **_params):
        return self.get(self.ipams_path, params=_params)


* Then try to run the new command
#python neutron ipam-list
Sucess: Working

10)
Diff

10,a)
$ git diff
diff --git a/neutronclient/shell.py b/neutronclient/shell.py
index f1f2e2e..bda3e12 100644
--- a/neutronclient/shell.py
+++ b/neutronclient/shell.py
@@ -61,6 +61,7 @@ from neutronclient.neutron.v2_0.vpn import ikepolicy
 from neutronclient.neutron.v2_0.vpn import ipsec_site_connection
 from neutronclient.neutron.v2_0.vpn import ipsecpolicy
 from neutronclient.neutron.v2_0.vpn import vpnservice
+from neutronclient.neutron.v2_0 import ipam
 from neutronclient.openstack.common.gettextutils import _
 from neutronclient.openstack.common import strutils
 from neutronclient.version import __version__
@@ -277,6 +278,7 @@ COMMAND_V2 = {
     'nec-packet-filter-create': packetfilter.CreatePacketFilter,
     'nec-packet-filter-update': packetfilter.UpdatePacketFilter,
     'nec-packet-filter-delete': packetfilter.DeletePacketFilter,
+    'ipam-list': ipam.ListIpam,
 }

 COMMANDS = {'2.0': COMMAND_V2}
diff --git a/neutronclient/v2_0/client.py b/neutronclient/v2_0/client.py
index a102781..6b2e972 100644
--- a/neutronclient/v2_0/client.py
+++ b/neutronclient/v2_0/client.py
@@ -221,6 +221,7 @@ class Client(object):
     firewall_path = "/fw/firewalls/%s"
     net_partitions_path = "/net-partitions"
     net_partition_path = "/net-partitions/%s"
+    ipams_path = "/ipams"

     # API has no way to report plurals, so we have to hard code them
     EXTED_PLURALS = {'routers': 'router',
@@ -1187,6 +1188,14 @@ class Client(object):
         """Delete the specified packet filter."""
         return self.delete(self.packet_filter_path % packet_filter_id)

+    @APIParamsCall
+    def list_ipams(self, **_params):
+        """
+        Fetches a list of all ipams for a tenant
+        """
+        # Pass filters in "params" argument to do_request
+        return self.get(self.ipams_path, params=_params)
+
     def __init__(self, **kwargs):
         """Initialize a new client for the Neutron v2.0 API."""
         super(Client, self).__init__()
 

10,b)
#cat neutronclient/neutron/v2_0/ipam.py

import logging
from neutronclient.neutron.v2_0 import ListCommand

class ListIpam(ListCommand):
    resource = 'ipam'
    log = logging.getLogger(__name__ + '.ListIpam')
    _formatters = {}
    list_columns = ['id', 'name']


11)
Ref: http://control-that-vm.blogspot.in/2014/06/writing-cli-commands-for-neutronclient.html



OpenStack OpenContrail Neutron Development Environment Setup

1)
clone neutron from github
#cd /home/saju/
#git clone https://github.com/openstack/neutron.git
#cd neutron
#git checkout stable/icehouse

2)
Create script to start/stop neutron-server from cloned dir
#vim neutron-server
import sys
from neutron.server import main

if __name__ == "__main__":
    sys.exit(main())

3)
Stop the neutron-server
#sudo service neutron-server stop
OR
#sudo /etc/init.d/neutron-server stop

4)
Start/Stop neutron-server from cloned dir
#sudo python neutron-server --config-file /etc/neutron/neutron.conf --log-file /var/log/neutron/server.log --config-file /etc/neutron/plugins/opencontrail/ContrailPlugin.ini

5)
a)
Copy the folder "neutron/neutron/plugins/opencontrail" from "juno" branch to "icehouse"

b)
Create a dir named "extensions" under /home/saju/neutron/neutron/plugins/opencontrail and create/copy following files
* __init__.py
* Copy the extension file "ipam.py" from /usr/lib/python2.7/dist-packages/neutron_plugin_contrail/extensions/ipam.py

c)
Create a dir named "plugins" under /home/saju/neutron/neutron/plugins/opencontrail and create/copy following files
* __init__.py
* Copy the IPAM plugin file "contrail_plugin_ipam.py" from /usr/lib/python2.7/dist-packages/neutron_plugin_contrail/plugins/opencontrail/contrail_plugin_ipam.py

6)
Config changes
a)
#sudo vim /etc/neutron/plugins/opencontrail/ContrailPlugin.ini
Enable only the IPAM extension
contrail_extensions = ipam:neutron.plugins.opencontrail.plugins.contrail_plugin_ipam.NeutronPluginContrailIpam

b)
#sudo vim /etc/neutron/neutron.conf
core_plugin = neutron.plugins.opencontrail.contrail_plugin.NeutronPluginContrailCoreV2
api_extensions_path = extensions:/home/saju/neutron/neutron/plugins/opencontrail/extensions

7)
Patch for neutron/plugins/opencontrail/contrail_plugin.py

diff --git a/neutron/plugins/opencontrail/contrail_plugin.py b/neutron/plugins/opencontrail/contrail_plugin.py
index 511c684..09576ce 100644
--- a/neutron/plugins/opencontrail/contrail_plugin.py
+++ b/neutron/plugins/opencontrail/contrail_plugin.py
@@ -23,6 +23,7 @@ from neutron.extensions import external_net
 from neutron.extensions import portbindings
 from neutron.extensions import securitygroup
 from neutron import neutron_plugin_base_v2
+from neutron.openstack.common import importutils
 from neutron.openstack.common import jsonutils
 from neutron.openstack.common import log as logging
 from neutron.plugins.opencontrail.common import exceptions as c_exc
@@ -30,14 +31,16 @@ from neutron.plugins.opencontrail.common import exceptions as c_exc

 LOG = logging.getLogger(__name__)

-opencontrail_opts = [
-    cfg.StrOpt('api_server_ip', default='127.0.0.1',
-               help='IP address to connect to opencontrail controller'),
-    cfg.IntOpt('api_server_port', default=8082,
-               help='Port to connect to opencontrail controller'),
-]
+#opencontrail_opts = [
+#    cfg.StrOpt('api_server_ip', default='127.0.0.1',
+#               help='IP address to connect to opencontrail controller'),
+#    cfg.IntOpt('api_server_port', default=8082,
+#               help='Port to connect to opencontrail controller'),
+#    cfg.DictOpt('contrail_extensions', default={},
+#                help='Enable Contrail extensions(policy, ipam)'),
+#]

-cfg.CONF.register_opts(opencontrail_opts, 'CONTRAIL')
+#cfg.CONF.register_opts(opencontrail_opts, 'CONTRAIL')

 CONTRAIL_EXCEPTION_MAP = {
     requests.codes.not_found: c_exc.ContrailNotFoundError,
@@ -49,6 +52,19 @@ CONTRAIL_EXCEPTION_MAP = {
 }


+vnc_opts = [
+    cfg.StrOpt('api_server_ip', default='127.0.0.1',
+               help='IP address to connect to VNC controller'),
+    cfg.StrOpt('api_server_port', default='8082',
+               help='Port to connect to VNC controller'),
+    cfg.DictOpt('contrail_extensions', default={},
+                help='Enable Contrail extensions(policy, ipam)'),
+]
+
+class InvalidContrailExtensionError(exc.ServiceUnavailable):
+    message = _("Invalid Contrail Extension: %(ext_name) %(ext_class)")
+
+
 class NeutronPluginContrailCoreV2(neutron_plugin_base_v2.NeutronPluginBaseV2,
                                   securitygroup.SecurityGroupPluginBase,
                                   portbindings_base.PortBindingBaseMixin,
@@ -56,16 +72,58 @@ class NeutronPluginContrailCoreV2(neutron_plugin_base_v2.NeutronPluginBaseV2,

     supported_extension_aliases = ["security-group", "router",
                                    "port-security", "binding", "agent",
-                                   "quotas", "external-net"]
+                                   "quotas", "external-net", "ipam"]
     PLUGIN_URL_PREFIX = '/neutron'
     __native_bulk_support = False

+    # patch VIF_TYPES
+    portbindings.__dict__['VIF_TYPE_VROUTER'] = 'vrouter'
+    portbindings.VIF_TYPES.append(portbindings.VIF_TYPE_VROUTER)
+
+    def _parse_class_args(self):
+        """Parse the contrailplugin.ini file.
+
+        Opencontrail supports extension such as ipam, policy, these extensions
+        can be configured in the plugin configuration file as shown below.
+        Plugin then loads the specified extensions.
+        contrail_extensions=ipam:,policy:
+        """
+
+        contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
+    print "===contrail_extensions:===", contrail_extensions
+        # If multiple class specified for same extension, last one will win
+        # according to DictOpt behavior
+        for ext_name, ext_class in contrail_extensions.items():
+            try:
+                if not ext_class:
+                    LOG.error(_('Malformed contrail extension...'))
+                    continue
+                self.supported_extension_aliases.append(ext_name)
+                if ext_class == 'None':
+                    continue
+                ext_class = importutils.import_class(ext_class)
+                ext_instance = ext_class()
+                ext_instance.set_core(self)
+                for method in dir(ext_instance):
+                    for prefix in ['get', 'update', 'delete', 'create']:
+                        if method.startswith('%s_' % prefix):
+                            setattr(self, method,
+                                    ext_instance.__getattribute__(method))
+            except Exception:
+                LOG.exception(_("Contrail Backend Error"))
+                # Converting contrail backend error to Neutron Exception
+                raise InvalidContrailExtensionError(
+                    ext_name=ext_name, ext_class=ext_class)
+
+
     def __init__(self):
         """Initialize the plugin class."""

         super(NeutronPluginContrailCoreV2, self).__init__()
         portbindings_base.register_port_dict_function()
-        self.base_binding_dict = self._get_base_binding_dict()
+        #self.base_binding_dict = self._get_base_binding_dict()
+    cfg.CONF.register_opts(vnc_opts, 'APISERVER')
+    self._parse_class_args()

     def _get_base_binding_dict(self):
         """return VIF type and details."""
@@ -88,8 +146,8 @@ class NeutronPluginContrailCoreV2(neutron_plugin_base_v2.NeutronPluginBaseV2,
     def _relay_request(self, url_path, data=None):
         """Send received request to api server."""

-        url = "http://%s:%d%s" % (cfg.CONF.CONTRAIL.api_server_ip,
-                                  cfg.CONF.CONTRAIL.api_server_port,
+        url = "http://%s:%s%s" % (cfg.CONF.APISERVER.api_server_ip,
+                                  cfg.CONF.APISERVER.api_server_port,
                                   url_path)

         return self._request_api_server(

8)
Export credentials


export OS_USERNAME=admin
export OS_PASSWORD=secret123
export OS_TENANT_NAME=demo
export OS_AUTH_URL=http://127.0.0.1:35357/v2.0


9)
Test the CLI command

#neutron ipam-list

Monday, November 24, 2014

AttributeError: 'NeutronPluginContrailCoreV2' object has no attribute 'get_ipams'

Fix
===



ERROR
======
* Neutron extension command failed

#neutron ipam-list
Request Failed: internal server error while processing your request.

#saju@myuuhost:~/neutron$ sudo python neutron-server --config-file /etc/neutron/neutron.conf --log-file /var/log/neutron/server.log --config-file /etc/neutron/plugins/opencontrail/ContrailPlugin.ini

/usr/lib/python2.7/dist-packages/eventlet/hubs/__init__.py:8: UserWarning: Module neutron was already imported from /home/saju/neutron/neutron/__init__.pyc, but /usr/lib/python2.7/dist-packages is being added to sys.path
  import pkg_resources
loc:===> /home/saju/neutron/neutron/__init__.pyc
2014-11-23 13:24:20.638    ERROR [neutron.api.extensions] Extension path 'extensions' doesn't exist!
2014-11-23 13:24:20.641  WARNING [neutron.api.extensions] Extension contrail not supported by any of loaded plugins
2014-11-23 13:24:20.644  WARNING [neutron.api.extensions] Extension policy not supported by any of loaded plugins
2014-11-23 13:24:20.646  WARNING [neutron.api.extensions] Extension route-table not supported by any of loaded plugins
2014-11-23 13:24:20.652  WARNING [neutron.api.extensions] Extension allowed-address-pairs not supported by any of loaded plugins
2014-11-23 13:24:20.655  WARNING [neutron.api.extensions] Extension dhcp_agent_scheduler not supported by any of loaded plugins
2014-11-23 13:24:20.659  WARNING [neutron.api.extensions] Extension extra_dhcp_opt not supported by any of loaded plugins
2014-11-23 13:24:20.662  WARNING [neutron.api.extensions] Extension extraroute not supported by any of loaded plugins
2014-11-23 13:24:20.672  WARNING [neutron.api.extensions] Extension fwaas not supported by any of loaded plugins
2014-11-23 13:24:20.675  WARNING [neutron.api.extensions] Extension flavor not supported by any of loaded plugins
2014-11-23 13:24:20.680  WARNING [neutron.api.extensions] Extension ext-gw-mode not supported by any of loaded plugins
2014-11-23 13:24:20.684  WARNING [neutron.api.extensions] Extension l3_agent_scheduler not supported by any of loaded plugins
2014-11-23 13:24:20.690  WARNING [neutron.api.extensions] Extension lbaas_agent_scheduler not supported by any of loaded plugins
2014-11-23 13:24:20.697  WARNING [neutron.api.extensions] Extension lbaas not supported by any of loaded plugins
2014-11-23 13:24:20.700  WARNING [neutron.api.extensions] Extension metering not supported by any of loaded plugins
2014-11-23 13:24:20.703  WARNING [neutron.api.extensions] Extension multi-provider not supported by any of loaded plugins
2014-11-23 13:24:20.709  WARNING [neutron.api.extensions] Extension provider not supported by any of loaded plugins
2014-11-23 13:24:20.713  WARNING [neutron.api.extensions] Extension routed-service-insertion not supported by any of loaded plugins
2014-11-23 13:24:20.714  WARNING [neutron.api.extensions] Extension router-service-type not supported by any of loaded plugins
2014-11-23 13:24:20.723  WARNING [neutron.api.extensions] Extension service-type not supported by any of loaded plugins
2014-11-23 13:24:20.729  WARNING [neutron.api.extensions] Extension vpnaas not supported by any of loaded plugins
2014-11-23 13:24:20.824  WARNING [keystoneclient.middleware.auth_token] Configuring auth_uri to point to the public identity endpoint is required; clients may not be able to authenticate against an admin endpoint
2014-11-23 13:24:20.825  WARNING [keystoneclient.middleware.auth_token] signing_dir is not owned by 0
2014-11-23 13:24:34.330    ERROR [neutron.api.v2.resource] index failed
Traceback (most recent call last):
  File "/home/saju/neutron/neutron/api/v2/resource.py", line 87, in resource
    result = method(request=request, **args)
  File "/home/saju/neutron/neutron/api/v2/base.py", line 304, in index
    return self._items(request, True, parent_id)
  File "/home/saju/neutron/neutron/api/v2/base.py", line 241, in _items
    obj_getter = getattr(self._plugin, self._plugin_handlers[self.LIST])
AttributeError: 'NeutronPluginContrailCoreV2' object has no attribute 'get_ipams'







WARNING [neutron.api.extensions] Extension ipam not supported by any of loaded plugins

Fix
===
Extension not loading and seeing WARNING "[neutron.api.extensions] Extension ipam not supported by any of loaded plugins" while starting the "neutron-server". 

* Add the name of the extension in class variable "supported_extension_aliases" in the plugin class

Example:
---------------
class NeutronPluginContrailCoreV2(neutron_plugin_base_v2.NeutronPluginBaseV2,
                                  securitygroup.SecurityGroupPluginBase,
                                  portbindings_base.PortBindingBaseMixin,
                                  external_net.External_net):

    supported_extension_aliases = ["security-group", "router",
                                   "port-security", "binding", "agent",
                                   "quotas", "external-net", "ipam"]



ERROR
======

#sudo python neutron-server --config-file /etc/neutron/neutron.conf --log-file /var/log/neutron/server.log --config-file /etc/neutron/plugins/opencontrail/ContrailPlugin.ini

/usr/lib/python2.7/dist-packages/eventlet/hubs/__init__.py:8: UserWarning: Module neutron was already imported from /home/saju/neutron/neutron/__init__.pyc, but /usr/lib/python2.7/dist-packages is being added to sys.path
  import pkg_resources
loc:===> /home/saju/neutron/neutron/__init__.pyc
2014-11-23 12:54:47.984    ERROR [neutron.api.extensions] Extension path 'extensions' doesn't exist!
2014-11-23 12:54:47.987  WARNING [neutron.api.extensions] Extension contrail not supported by any of loaded plugins
2014-11-23 12:54:47.989  WARNING [neutron.api.extensions] Extension ipam not supported by any of loaded plugins
2014-11-23 12:54:47.991  WARNING [neutron.api.extensions] Extension policy not supported by any of loaded plugins
2014-11-23 12:54:47.994  WARNING [neutron.api.extensions] Extension route-table not supported by any of loaded plugins
2014-11-23 12:54:48.0  WARNING [neutron.api.extensions] Extension allowed-address-pairs not supported by any of loaded plugins
2014-11-23 12:54:48.4  WARNING [neutron.api.extensions] Extension dhcp_agent_scheduler not supported by any of loaded plugins
2014-11-23 12:54:48.8  WARNING [neutron.api.extensions] Extension extra_dhcp_opt not supported by any of loaded plugins
2014-11-23 12:54:48.10  WARNING [neutron.api.extensions] Extension extraroute not supported by any of loaded plugins
2014-11-23 12:54:48.21  WARNING [neutron.api.extensions] Extension fwaas not supported by any of loaded plugins
2014-11-23 12:54:48.25  WARNING [neutron.api.extensions] Extension flavor not supported by any of loaded plugins
2014-11-23 12:54:48.31  WARNING [neutron.api.extensions] Extension ext-gw-mode not supported by any of loaded plugins
2014-11-23 12:54:48.35  WARNING [neutron.api.extensions] Extension l3_agent_scheduler not supported by any of loaded plugins
2014-11-23 12:54:48.42  WARNING [neutron.api.extensions] Extension lbaas_agent_scheduler not supported by any of loaded plugins
2014-11-23 12:54:48.52  WARNING [neutron.api.extensions] Extension lbaas not supported by any of loaded plugins
2014-11-23 12:54:48.56  WARNING [neutron.api.extensions] Extension metering not supported by any of loaded plugins
2014-11-23 12:54:48.59  WARNING [neutron.api.extensions] Extension multi-provider not supported by any of loaded plugins
2014-11-23 12:54:48.65  WARNING [neutron.api.extensions] Extension provider not supported by any of loaded plugins
2014-11-23 12:54:48.69  WARNING [neutron.api.extensions] Extension routed-service-insertion not supported by any of loaded plugins
2014-11-23 12:54:48.71  WARNING [neutron.api.extensions] Extension router-service-type not supported by any of loaded plugins
2014-11-23 12:54:48.79  WARNING [neutron.api.extensions] Extension service-type not supported by any of loaded plugins
2014-11-23 12:54:48.85  WARNING [neutron.api.extensions] Extension vpnaas not supported by any of loaded plugins
2014-11-23 12:54:48.163  WARNING [keystoneclient.middleware.auth_token] Configuring auth_uri to point to the public identity endpoint is required; clients may not be able to authenticate against an admin endpoint
2014-11-23 12:54:48.164  WARNING [keystoneclient.middleware.auth_token] signing_dir is not owned by 0










AttributeError: 'module' object has no attribute 'VIF_TYPE_VROUTER'

Fix:
===
a)
Open contrail_plugin.py
#vim neutron/plugins/opencontrail/contrail_plugin.py



b)
Add following statements at class level in class NeutronPluginContrailCoreV2
#patch VIF_TYPES
portbindings.__dict__['VIF_TYPE_VROUTER'] = 'vrouter'
portbindings.VIF_TYPES.append(portbindings.VIF_TYPE_VROUTER)

Example:
-----------------  
class  NeutronPluginContrailCoreV2(neutron_plugin_base_v2.NeutronPluginBaseV2,
                                      securitygroup.SecurityGroupPluginBase,
                                      portbindings_base.PortBindingBaseMixin,
                                      external_net.External_net):
        # patch VIF_TYPES
        portbindings.__dict__['VIF_TYPE_VROUTER'] = 'vrouter'
        portbindings.VIF_TYPES.append(portbindings.VIF_TYPE_VROUTER)


ERROR:
======
#sudo python neutron-server --config-file /etc/neutron/neutron.conf --log-file /var/log/neutron/server.log --config-file /etc/neutron/plugins/opencontrail/ContrailPlugin.ini

/usr/lib/python2.7/dist-packages/eventlet/hubs/__init__.py:8: UserWarning: Module neutron was already imported from /home/saju/neutron/neutron/__init__.pyc, but /usr/lib/python2.7/dist-packages is being added to sys.path
  import pkg_resources
loc:===> /home/saju/neutron/neutron/__init__.pyc
2014-11-23 11:02:30.650    ERROR [neutron.service] Unrecoverable error: please check log for details.
Traceback (most recent call last):
  File "/home/saju/neutron/neutron/service.py", line 105, in serve_wsgi
    service.start()
  File "/home/saju/neutron/neutron/service.py", line 74, in start
    self.wsgi_app = _run_wsgi(self.app_name)
  File "/home/saju/neutron/neutron/service.py", line 173, in _run_wsgi
    app = config.load_paste_app(app_name)
  File "/home/saju/neutron/neutron/common/config.py", line 170, in load_paste_app
    app = deploy.loadapp("config:%s" % config_path, name=app_name)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 247, in loadapp
    return loadobj(APP, uri, name=name, **kw)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 272, in loadobj
    return context.create()
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 710, in create
    return self.object_type.invoke(self)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 144, in invoke
    **context.local_conf)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/util.py", line 56, in fix_call
    val = callable(*args, **kw)
  File "/usr/lib/python2.7/dist-packages/paste/urlmap.py", line 25, in urlmap_factory
    app = loader.get_app(app_name, global_conf=global_conf)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 350, in get_app
    name=name, global_conf=global_conf).create()
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 710, in create
    return self.object_type.invoke(self)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 144, in invoke
    **context.local_conf)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/util.py", line 56, in fix_call
    val = callable(*args, **kw)
  File "/home/saju/neutron/neutron/auth.py", line 69, in pipeline_factory
    app = loader.get_app(pipeline[-1])
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 350, in get_app
    name=name, global_conf=global_conf).create()
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 710, in create
    return self.object_type.invoke(self)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/loadwsgi.py", line 146, in invoke
    return fix_call(context.object, context.global_conf, **context.local_conf)
  File "/usr/lib/python2.7/dist-packages/paste/deploy/util.py", line 56, in fix_call
    val = callable(*args, **kw)
  File "/home/saju/neutron/neutron/api/v2/router.py", line 71, in factory
    return cls(**local_config)
  File "/home/saju/neutron/neutron/api/v2/router.py", line 75, in __init__
    plugin = manager.NeutronManager.get_plugin()
  File "/home/saju/neutron/neutron/manager.py", line 222, in get_plugin
    return weakref.proxy(cls.get_instance().plugin)
  File "/home/saju/neutron/neutron/manager.py", line 216, in get_instance
    cls._create_instance()
  File "/home/saju/neutron/neutron/openstack/common/lockutils.py", line 249, in inner
    return f(*args, **kwargs)
  File "/home/saju/neutron/neutron/manager.py", line 202, in _create_instance
    cls._instance = cls()
  File "/home/saju/neutron/neutron/manager.py", line 114, in __init__
    plugin_provider)
  File "/home/saju/neutron/neutron/manager.py", line 142, in _get_plugin_instance
    return plugin_class()
  File "/home/saju/neutron/neutron/plugins/opencontrail/contrail_plugin.py", line 72, in __init__
    self.base_binding_dict = self._get_base_binding_dict()
  File "/home/saju/neutron/neutron/plugins/opencontrail/contrail_plugin.py", line 78, in _get_base_binding_dict
    portbindings.VIF_TYPE: portbindings.VIF_TYPE_VROUTER,
AttributeError: 'module' object has no attribute 'VIF_TYPE_VROUTER'
2014-11-23 11:02:30.657 CRITICAL [neutron] 'module' object has no attribute 'VIF_TYPE_VROUTER'

Sunday, November 23, 2014

OpenStack OpenContrail Neutron IPAM API examples

1)
List all IPAMs

#neutron --debug ipam-list

a)

curl request generated by above CLI command
#curl -s http://127.0.0.1:9696/v2.0/ipams.json -X GET -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" | python -mjson.tool

#curl -s http://127.0.0.1:9696/v2.0/ipams -X GET -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" | python -mjson.tool


2)
Show IPAM

#neutron --debug ipam-show 58f9369b-d3ef-428a-bbc9-2b8c0e06b752

a)

curl request generated by above CLI command 
#curl -s http://127.0.0.1:9696/v2.0/ipams/58f9369b-d3ef-428a-bbc9-2b8c0e06b752.json -X GET -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" | python -mjson.tool

#curl -s http://127.0.0.1:9696/v2.0/ipams/58f9369b-d3ef-428a-bbc9-2b8c0e06b752 -X GET -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" | python -mjson.tool


3)
Delete IPAM

#neutron --debug ipam-delete d47aa080-cf94-46cc-9c07-da11819dc7ca


a)
curl request generated by above CLI command
#curl -s http://127.0.0.1:9696/v2.0/ipams/d47aa080-cf94-46cc-9c07-da11819dc7ca.json -X DELETE -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" | python -mjson.tool

#curl -s http://127.0.0.1:9696/v2.0/ipams/d47aa080-cf94-46cc-9c07-da11819dc7ca -X DELETE -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" | python -mjson.tool


4)
Create IPAM

#neutron --debug ipam-create ipam1

a) 
curl request generated by above CLI command
#curl -s http://127.0.0.1:9696/v2.0/ipams.json -X POST -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" -d '{"ipam": {"name": "ipam1", "mgmt": {"method": "fixed"}}}'

#curl -s http://127.0.0.1:9696/v2.0/ipams -X POST -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" -d '{"ipam": {"name": "ipam1", "mgmt": {"method": "fixed"}}}' | python -mjson.tool


b)

Create IPAM with "mgmt" databy making custom curl request
#curl -i http://127.0.0.1:9696/v2.0/ipams.json -X POST -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" -d '{"ipam": {"name": "ipam28", "mgmt": {"ipam_method": null, "ipam_dns_method": "virtual-dns-server", "ipam_dns_server": {"tenant_dns_server_address": {"ip_address": []}, "virtual_dns_server_name": "default-domain:vdns"}, "dhcp_option_list": {"dhcp_option": [{"dhcp_option_value": "mydomain", "dhcp_option_name": "15"}, {"dhcp_option_value": "192.168.56.1", "dhcp_option_name": "4"}]}, "host_routes": null, "cidr_block": null}}}'

5)
Update IPAM


#neutron --debug ipam-update 07ae76d2-9fe4-466f-a98e-f82bc2b819d0 --name ipam5


a)

curl request generated by above CLI command
#curl -s http://127.0.0.1:9696/v2.0/ipams/07ae76d2-9fe4-466f-a98e-f82bc2b819d0.json -X PUT -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" -d '{"ipam": {"name": "ipam5"}}' | python -mjson.tool

#curl -s http://127.0.0.1:9696/v2.0/ipams/07ae76d2-9fe4-466f-a98e-f82bc2b819d0 -X PUT -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" -d '{"ipam": {"name": "ipam5"}}' | python -mjson.tool


b)
Update an IPAM's "mgmt" data by making custom curl request
#curl -i http://127.0.0.1:9696/v2.0/ipams/2e5810de-c681-4b0d-a346-99469f817b06.json -X PUT -H "X-Auth-Token:$TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient" -d '{"ipam": {"mgmt": {"ipam_method": null, "ipam_dns_method": "virtual-dns-server", "ipam_dns_server": {"tenant_dns_server_address": {"ip_address": []}, "virtual_dns_server_name": "default-domain:vdns"}, "dhcp_option_list": {"dhcp_option": [{"dhcp_option_value": "mydomain", "dhcp_option_name": "15"}, {"dhcp_option_value": "192.168.56.1", "dhcp_option_name": "4"}]}, "host_routes": null, "cidr_block": null}}}'

Wednesday, November 12, 2014

OpenStack how haproxy redirect CLI/API request to neutron server

1)
Neutron CLI will send request to haproxy running in port "9696"


You can find the haproxy setting in /etc/nova/nova.conf

#sudo vim /etc/nova/nova.conf
quantum_url = http://localhost:9696/
neutron_url = http://127.0.0.1:9696/



2)
Find ID of process which running on port 9696


#sudo netstat -tuplen | grep 9696
tcp        0      0 0.0.0.0:9696            0.0.0.0:*               LISTEN      0          10659       1800/haproxy

Note:
------
Process ID : 1800/haproxy

3)
Find the process by Process ID 1800


#ps -aux | grep 1800
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
haproxy   1800  0.2  0.0  21568  2148 ?        Ss   13:12   0:37 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -D -p /var/run/haproxy.pid

Note:
------
Location of haproxy binary: /usr/sbin/haproxy
haproxy config file: /etc/haproxy/haproxy.cfg

4)
Open haproxy config file /etc/haproxy/haproxy.cfg


#sudo vim /etc/haproxy/haproxy.cfg

#contrail-config-marker-start
listen contrail-config-stats :5937
   mode http
   stats enable
   stats uri /
   stats auth haproxy:contrail123

frontend quantum-server *:9696
    default_backend    quantum-server-backend


frontend  contrail-api *:8082
    default_backend    contrail-api-backend


frontend  contrail-discovery *:5998
    default_backend    contrail-discovery-backend

backend quantum-server-backend
    option nolinger
    balance     roundrobin
    server 127.0.0.1 127.0.0.1:9697 check inter 2000 rise 2 fall 3


    #server  10.84.14.2 10.84.14.2:9697 check

backend contrail-api-backend
    option nolinger
    balance     roundrobin
    server 127.0.0.1 127.0.0.1:9100 check inter 2000 rise 2 fall 3


    #server  10.84.14.2 10.84.14.2:9100 check
    #server  10.84.14.2 10.84.14.2:9101 check

backend contrail-discovery-backend
    option nolinger
    balance     roundrobin
    server 127.0.0.1 127.0.0.1:9110 check inter 2000 rise 2 fall 3

Note:
--------

Please note the Settings of quantum/neutron and contrail

4,a)

frontend quantum-server *:9696
    default_backend    quantum-server-backend

backend quantum-server-backend
    option nolinger
    balance     roundrobin
    server 127.0.0.1 127.0.0.1:9697 check inter 2000 rise 2 fall 3


* Means, haproxy will redirect all trafic flowing to port 9696 to 9697 (where neutron-server is running)

4,a1)
Find ID of process which running on port 9696

#sudo netstat -tuplen | grep 9696
tcp        0      0 0.0.0.0:9696            0.0.0.0:*               LISTEN      0          10659       1800/haproxy

4,a2)
Find name of the process which has ID:1800, it is haproxy.


#ps -aux | grep 1800
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
haproxy   1800  0.2  0.0  21568  2136 ?        Ss   13:12   0:42 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -D -p /var/run/haproxy.pid

4,a3)
Find ID of process which running on port 9697


#sudo netstat -tuplen | grep 9697
tcp        0      0 0.0.0.0:9697            0.0.0.0:*               LISTEN      120        428165      323/python

4,a4)
Find name of the process which has ID:323, it is neutron-server.


#ps -aux | grep 323
neutron    323  0.1  0.9 113236 46356 ?        Ss   16:56   0:02 /usr/bin/python /usr/bin/neutron-server --config-file /etc/neutron/neutron.conf --log-file /var/log/neutron/server.log --config-file /etc/neutron/plugins/opencontrail/ContrailPlugin.ini


4,b)

frontend  contrail-api *:8082
    default_backend    contrail-api-backend

backend contrail-api-backend
    option nolinger
    balance     roundrobin
    server 127.0.0.1 127.0.0.1:9100 check inter 2000 rise 2 fall 3


* Means, haproxy will redirect all trafic flowing to port 8082 to 9100 (where contrail-api is running)

4,b1)
Find ID of process which running on port 8082


#sudo netstat -tuplen | grep 8082
tcp        0      0 0.0.0.0:8082            0.0.0.0:*               LISTEN      0          10660       1800/haproxy

4,b2)
Find name of the process which has ID:1800, it is haproxy.


#ps -aux | grep 1800
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
haproxy   1800  0.2  0.0  21568  2136 ?        Ss   13:12   0:42 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -D -p /var/run/haproxy.pid

4,b3)
Find ID of process which running on port 9100


#sudo netstat -tuplen | grep 9100
tcp        0      0 0.0.0.0:9100            0.0.0.0:*               LISTEN      0          31764       1918/python

4,b4)
Find name of the process which has ID:1918, it is contrail-api.


#ps -aux | grep 1918

root      1918  0.6  1.1 324340 56180 ?        Sl   13:13   1:43 /usr/bin/python /usr/bin/contrail-api --conf_file /etc/contrail/contrail-api.conf --listen_port 9100 --worker_id 0

OpenStack How to debug neutron contrail plugin

1)
Add log

#sudo vim /usr/lib/python2.7/dist-packages/neutron_plugin_contrail/plugins/opencontrail/contrail_plugin.py
LOG.warn(_('your debug message here'))

2)
Restart server

#sudo service neutron-server restart

3)
Run the CLI command

#neutron net-list --debug

4)
Check the logs

#sudo tail -f /var/log/neutron/server.log

How to Debug OpenStack Neutron and Contrail APIs

1)
Export the credentials

export OS_USERNAME=admin
export OS_PASSWORD=secret123
export OS_TENANT_NAME=myproject1
export OS_AUTH_URL=http://192.168.56.101:35357/v2.0


2)
Verify the credentials

#keystone token-get

3)
List all Virtual Networks

a)
Using Contrail API

http://192.168.56.101:9100/virtual-networks

b)
Using CLI via Neutron

#neutron --help
#neutron net-list

Friday, October 31, 2014

Neutron Router is namespace

1)
http://pinrojas.com/2014/07/29/theres-real-magic-behind-openstack-neutron/

Routers and dnsmasq are independent namespaces with their own Linux Network Stack. Namespaces helps to manage traffic with overlapping private IPs between different routers associated to different tenants or projects. Routers helps to route traffic between tenant’s subnets and also to/from the external World. Also routers are using Linux iptables to filter traffic and also to make floating IP works through NAT (Network Address Translation) to chosen instances. dnsmasq is also working on a Linux Network Stack with DHCP and DNS processes serving exclusively to the associated tenant.

2)
https://developer.rackspace.com/blog/neutron-networking-l3-agent/

Neutron has an API extension to allow administrators and tenants to create "routers" that connect to L2 networks. Known as the "neutron-l3-agent", it uses the Linux IP stack and iptables to perform L3 forwarding and NAT. In order to support multiple routers with potentially overlapping IP addresses, neutron-l3-agent defaults to using Linux network namespaces to provide isolated forwarding contexts. Like the DHCP namespaces that exist for every network defined in Neutron, each router will have its own namespace with a name based on its UUID.

3)

http://docs.openstack.org/developer/neutron/devref/layer3.html

The neutron-l3-agent uses the Linux IP stack and iptables to perform L3 forwarding and NAT. In order to support multiple routers with potentially overlapping IP addresses, neutron-l3-agent defaults to using Linux network namespaces to provide isolated forwarding contexts. As a result, the IP addresses of routers will not be visible simply by running “ip addr list” or “ifconfig” on the node. Similarly, you will not be able to directly ping fixed IPs.

To do either of these things, you must run the command within a particular router’s network namespace. The namespace will have the name “qrouter-.

Magic behind OpenStack Neutron

Wednesday, October 29, 2014

OpenStack Networking

OpenStack Tenant, Provider and External networks


Create Tenant Network
http://docs.openstack.org/icehouse/install-guide/install/yum/content/neutron_initial-tenant-network.html

Create Provider Network

http://docs.openstack.org/user-guide/content/cli_networks.html

http://docs.openstack.org/api/openstack-network/2.0/content/provider_network_create.html

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux_OpenStack_Platform/5/html-single/Cloud_Administrator_Guide/index.html#section_provider_networks





Create External Network

http://docs.openstack.org/icehouse/install-guide/install/yum/content/neutron_initial-external-network.html

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux_OpenStack_Platform/5/html-single/Installation_and_Configuration_Guide/#Configuring_a_Provider_Network1

============

http://docs.openstack.org/admin-guide-cloud/content/tenant-provider-networks.html

http://docs.huihoo.com/openstack/docs.openstack.org/admin-guide-cloud/content/tenant-provider-networks.html

Provider Network
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux_OpenStack_Platform/5/html-single/Cloud_Administrator_Guide/index.html#section_provider_networks <=== IMP

External Network
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux_OpenStack_Platform/5/html-single/Installation_and_Configuration_Guide/#Configuring_a_Provider_Network1

https://developer.rackspace.com/blog/beginning-to-understand-neutron-provider-and-tenant-networks-in-openstack/

https://openstack.redhat.com/forum/discussion/632/provider-vs-flat-networks/p1

http://books.google.co.in/books?id=iXrKBAAAQBAJ&pg=PT194&lpg=PT194&dq=tenant+provider+external+network&source=bl&ots=IG1nzIeZ1u&sig=EpzHEdZ1kYQ98Nbzr1yqkqwmWEc&hl=en&sa=X&ei=o6BQVJXQC6XemAXSjYCoDQ&ved=0CDsQ6AEwBTgK#v=onepage&q=tenant%20provider%20external%20network&f=false

http://docs.openstack.org/icehouse/install-guide/install/apt-debian/content/neutron_initial-external-network.html

http://docs.openstack.org/training-guides/content/operator-network-node.html






Learning OpenStack Networking (Neutron) By James Denton

Wednesday, July 16, 2014

OpenStack neutron How to list iptables custom chains of Filter, NAT, Mangle and Raw iptables tables in a network namespace

1)
List all namespaces


#ip netns
qdhcp-7cc88da5-e38b-4a14-a64a-daa931f1d2d2
qrouter-e7189379-ccd9-44f6-804f-820173f30e26

2)
List all custom chains of Filter iptables table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -L -t filter

Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-INPUT  all  --  anywhere             anywhere           

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
neutron-filter-top  all  --  anywhere             anywhere           
neutron-l3-agent-FORWARD  all  --  anywhere             anywhere           

Chain OUTPUT
(policy ACCEPT)
target     prot opt source               destination        
neutron-filter-top  all  --  anywhere             anywhere           
neutron-l3-agent-OUTPUT  all  --  anywhere             anywhere           

Chain neutron-filter-top (2 references)
target     prot opt source               destination        
neutron-l3-agent-local  all  --  anywhere             anywhere           

Chain neutron-l3-agent-FORWARD (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-INPUT (1 references)
target     prot opt source               destination        
ACCEPT     tcp  --  anywhere             localhost            tcp dpt:9697

Chain neutron-l3-agent-OUTPUT (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-local (1 references)
target     prot opt source               destination

3)
List all custom chains of NAT iptables table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -L -t nat


Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-PREROUTING  all  --  anywhere             anywhere           

Chain INPUT (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-OUTPUT  all  --  anywhere             anywhere           

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-POSTROUTING  all  --  anywhere             anywhere           
neutron-postrouting-bottom  all  --  anywhere             anywhere           

Chain neutron-l3-agent-OUTPUT (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-POSTROUTING (1 references)
target     prot opt source               destination        
ACCEPT     all  --  anywhere             anywhere             ! ctstate DNAT

Chain neutron-l3-agent-PREROUTING (1 references)
target     prot opt source               destination        
REDIRECT   tcp  --  anywhere             169.254.169.254      tcp dpt:http redir ports 9697

Chain neutron-l3-agent-float-snat (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-snat (1 references)
target     prot opt source               destination        
neutron-l3-agent-float-snat  all  --  anywhere             anywhere           
SNAT       all  --  10.0.0.0/24          anywhere             to:172.24.4.2

Chain neutron-postrouting-bottom (1 references)
target     prot opt source               destination        
neutron-l3-agent-snat  all  --  anywhere             anywhere      

4)
List all custom chains of Mangle iptables table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -L -t mangle

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        

Chain INPUT (policy ACCEPT)
target     prot opt source               destination        

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

5)
List all custom chains of Raw iptables table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -L -t raw


Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination 

OpenStack Neutron How to list chains and rules of Filter, NAT, Mangle and Raw iptables tables in a network namespace

1)
List all namespaces


#ip netns

qdhcp-7cc88da5-e38b-4a14-a64a-daa931f1d2d2
qrouter-e7189379-ccd9-44f6-804f-820173f30e26

2)
List all iptables chains and rules of Filter, NAT, Mangle and Raw tables in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables-save


# Generated by iptables-save v1.4.21 on Wed Jul 16 17:53:18 2014
*raw
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [8:564]
COMMIT
# Completed on Wed Jul 16 17:53:18 2014
# Generated by iptables-save v1.4.21 on Wed Jul 16 17:53:18 2014
*nat
:PREROUTING ACCEPT [6:681]
:INPUT ACCEPT [2:393]
:OUTPUT ACCEPT [15:970]
:POSTROUTING ACCEPT [8:550]
:neutron-l3-agent-OUTPUT - [0:0]
:neutron-l3-agent-POSTROUTING - [0:0]
:neutron-l3-agent-PREROUTING - [0:0]
:neutron-l3-agent-float-snat - [0:0]
:neutron-l3-agent-snat - [0:0]
:neutron-postrouting-bottom - [0:0]
-A PREROUTING -j neutron-l3-agent-PREROUTING
-A OUTPUT -j neutron-l3-agent-OUTPUT
-A POSTROUTING -j neutron-l3-agent-POSTROUTING
-A POSTROUTING -j neutron-postrouting-bottom
-A neutron-l3-agent-POSTROUTING ! -i qg-77a4ae69-e3 ! -o qg-77a4ae69-e3 -m conntrack ! --ctstate DNAT -j ACCEPT
-A neutron-l3-agent-PREROUTING -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 9697
-A neutron-l3-agent-snat -j neutron-l3-agent-float-snat
-A neutron-l3-agent-snat -s 10.0.0.0/24 -j SNAT --to-source 172.24.4.2
-A neutron-postrouting-bottom -j neutron-l3-agent-snat
COMMIT
# Completed on Wed Jul 16 17:53:18 2014
# Generated by iptables-save v1.4.21 on Wed Jul 16 17:53:18 2014
*mangle
:PREROUTING ACCEPT [311:33164]
:INPUT ACCEPT [64:6090]
:FORWARD ACCEPT [247:27074]
:OUTPUT ACCEPT [86:7130]
:POSTROUTING ACCEPT [333:34204]
COMMIT
# Completed on Wed Jul 16 17:53:18 2014
# Generated by iptables-save v1.4.21 on Wed Jul 16 17:53:18 2014
*filter
:INPUT ACCEPT [29:3778]
:FORWARD ACCEPT [247:27074]
:OUTPUT ACCEPT [86:7130]
:neutron-filter-top - [0:0]
:neutron-l3-agent-FORWARD - [0:0]
:neutron-l3-agent-INPUT - [0:0]
:neutron-l3-agent-OUTPUT - [0:0]
:neutron-l3-agent-local - [0:0]
-A INPUT -j neutron-l3-agent-INPUT
-A FORWARD -j neutron-filter-top
-A FORWARD -j neutron-l3-agent-FORWARD
-A OUTPUT -j neutron-filter-top
-A OUTPUT -j neutron-l3-agent-OUTPUT
-A neutron-filter-top -j neutron-l3-agent-local
-A neutron-l3-agent-INPUT -d 127.0.0.1/32 -p tcp -m tcp --dport 9697 -j ACCEPT
COMMIT
# Completed on Wed Jul 16 17:53:18 2014

3)
List all chains and rules of Filter table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -t filter --list

Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-INPUT  all  --  anywhere             anywhere           

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
neutron-filter-top  all  --  anywhere             anywhere           
neutron-l3-agent-FORWARD  all  --  anywhere             anywhere           

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        
neutron-filter-top  all  --  anywhere             anywhere           
neutron-l3-agent-OUTPUT  all  --  anywhere             anywhere           

Chain neutron-filter-top (2 references)
target     prot opt source               destination        
neutron-l3-agent-local  all  --  anywhere             anywhere           

Chain neutron-l3-agent-FORWARD (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-INPUT (1 references)
target     prot opt source               destination        
ACCEPT     tcp  --  anywhere             localhost            tcp dpt:9697

Chain neutron-l3-agent-OUTPUT (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-local (1 references)
target     prot opt source               destination

4)
List all chains and rules of NAT table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -t nat --list


Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-PREROUTING  all  --  anywhere             anywhere           

Chain INPUT (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-OUTPUT  all  --  anywhere             anywhere           

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination        
neutron-l3-agent-POSTROUTING  all  --  anywhere             anywhere           
neutron-postrouting-bottom  all  --  anywhere             anywhere           

Chain neutron-l3-agent-OUTPUT (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-POSTROUTING (1 references)
target     prot opt source               destination        
ACCEPT     all  --  anywhere             anywhere             ! ctstate DNAT

Chain neutron-l3-agent-PREROUTING (1 references)
target     prot opt source               destination        
REDIRECT   tcp  --  anywhere             169.254.169.254      tcp dpt:http redir ports 9697

Chain neutron-l3-agent-float-snat (1 references)
target     prot opt source               destination        

Chain neutron-l3-agent-snat (1 references)
target     prot opt source               destination        
neutron-l3-agent-float-snat  all  --  anywhere             anywhere           
SNAT       all  --  10.0.0.0/24          anywhere             to:172.24.4.2

Chain neutron-postrouting-bottom (1 references)
target     prot opt source               destination        
neutron-l3-agent-snat  all  --  anywhere             anywhere         

5)
List all chains and rules of Mangle table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -t mangle --list

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        

Chain INPUT (policy ACCEPT)
target     prot opt source               destination        

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

6)
List all chains and rules of Raw table in a network namespace


#sudo ip netns exec qrouter-e7189379-ccd9-44f6-804f-820173f30e26 iptables -t raw --list

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination