]> review.fuel-infra Code Review - openstack-build/neutron-build.git/commitdiff
Update codebase for HACKING compliance.
authorMaru Newby <mnewby@internap.com>
Fri, 13 Apr 2012 19:53:56 +0000 (12:53 -0700)
committerMaru Newby <mnewby@internap.com>
Tue, 1 May 2012 18:46:24 +0000 (11:46 -0700)
 * This is a massive patch that aims to clean up the codebase
   and bring it into compliance with HACKING.rst and PEP8 in one
   fell swoop.
 * Cleaned up use of gettext.
 * Updated log usage for consistency.
 * The tests run successfully against all plugins except
   cisco and nicira (due to dependency issues with these plugins).
 * Addresses bug 981208

Change-Id: I4d8c7ab138d8f7bb906d18dc34f88f8bd0581c19

136 files changed:
quantum/__init__.py
quantum/api/__init__.py
quantum/api/api_common.py
quantum/api/attachments.py
quantum/api/faults.py
quantum/api/networks.py
quantum/api/ports.py
quantum/common/config.py
quantum/common/exceptions.py
quantum/common/flags.py
quantum/common/test_lib.py
quantum/common/utils.py
quantum/db/api.py
quantum/db/models.py
quantum/extensions/_credential_view.py
quantum/extensions/_novatenant_view.py
quantum/extensions/_portstats_view.py
quantum/extensions/_pprofiles.py
quantum/extensions/_qos_view.py
quantum/extensions/credential.py
quantum/extensions/extensions.py
quantum/extensions/multiport.py
quantum/extensions/novatenant.py
quantum/extensions/portprofile.py
quantum/extensions/portstats.py
quantum/extensions/qos.py
quantum/manager.py
quantum/plugins/cisco/__init__.py
quantum/plugins/cisco/client/__init__.py
quantum/plugins/cisco/client/cli.py
quantum/plugins/cisco/common/__init__.py
quantum/plugins/cisco/common/cisco_configparser.py
quantum/plugins/cisco/common/cisco_constants.py
quantum/plugins/cisco/common/cisco_credentials.py
quantum/plugins/cisco/common/cisco_exceptions.py
quantum/plugins/cisco/common/cisco_faults.py
quantum/plugins/cisco/common/cisco_utils.py
quantum/plugins/cisco/l2device_inventory_base.py
quantum/plugins/cisco/l2device_plugin_base.py
quantum/plugins/cisco/l2network_model_base.py
quantum/plugins/cisco/l2network_plugin.py
quantum/plugins/cisco/l2network_plugin_configuration.py
quantum/plugins/cisco/l2network_segmentation_base.py
quantum/plugins/cisco/models/__init__.py
quantum/plugins/cisco/models/l2network_multi_blade.py
quantum/plugins/cisco/models/l2network_single_blade.py
quantum/plugins/cisco/nexus/cisco_nexus_configuration.py
quantum/plugins/cisco/nexus/cisco_nexus_network_driver.py
quantum/plugins/cisco/nexus/cisco_nexus_plugin.py
quantum/plugins/cisco/nexus/cisco_nexus_snippets.py
quantum/plugins/cisco/nova/quantum_port_aware_scheduler.py
quantum/plugins/cisco/nova/vifdirect.py
quantum/plugins/cisco/run_tests.py
quantum/plugins/cisco/segmentation/__init__.py
quantum/plugins/cisco/segmentation/l2network_vlan_mgr.py
quantum/plugins/cisco/services/service_insertion.py
quantum/plugins/cisco/services/services_constants.py
quantum/plugins/cisco/services/services_logistics.py
quantum/plugins/cisco/tests/unit/test_cisco_extension.py
quantum/plugins/cisco/tests/unit/test_database.py
quantum/plugins/cisco/tests/unit/test_l2networkApi.py
quantum/plugins/cisco/tests/unit/test_l2network_multi_blade.py
quantum/plugins/cisco/tests/unit/test_nexus_plugin.py
quantum/plugins/cisco/tests/unit/test_ucs_driver.py
quantum/plugins/cisco/tests/unit/test_ucs_inventory.py
quantum/plugins/cisco/tests/unit/test_ucs_plugin.py
quantum/plugins/cisco/tests/unit/test_vlan_mgr.py
quantum/plugins/cisco/ucs/__init__.py
quantum/plugins/cisco/ucs/cisco_getvif.py
quantum/plugins/cisco/ucs/cisco_ucs_configuration.py
quantum/plugins/cisco/ucs/cisco_ucs_inventory.py
quantum/plugins/cisco/ucs/cisco_ucs_inventory_configuration.py
quantum/plugins/cisco/ucs/cisco_ucs_network_driver.py
quantum/plugins/cisco/ucs/cisco_ucs_plugin.py
quantum/plugins/linuxbridge/LinuxBridgePlugin.py
quantum/plugins/linuxbridge/agent/linuxbridge_quantum_agent.py
quantum/plugins/linuxbridge/common/__init__.py
quantum/plugins/linuxbridge/common/configparser.py
quantum/plugins/linuxbridge/common/constants.py
quantum/plugins/linuxbridge/common/exceptions.py
quantum/plugins/linuxbridge/common/utils.py
quantum/plugins/linuxbridge/db/l2network_db.py
quantum/plugins/linuxbridge/db/l2network_models.py
quantum/plugins/linuxbridge/plugin_configuration.py
quantum/plugins/linuxbridge/run_tests.py
quantum/plugins/linuxbridge/tests/unit/_test_linuxbridgeAgent.py
quantum/plugins/linuxbridge/tests/unit/test_database.py
quantum/plugins/nicira/nicira_nvp_plugin/NvpApiClient.py
quantum/plugins/nicira/nicira_nvp_plugin/QuantumPlugin.py
quantum/plugins/nicira/nicira_nvp_plugin/api_client/client_eventlet.py
quantum/plugins/nicira/nicira_nvp_plugin/api_client/common.py
quantum/plugins/nicira/nicira_nvp_plugin/api_client/request.py
quantum/plugins/nicira/nicira_nvp_plugin/api_client/request_eventlet.py
quantum/plugins/nicira/nicira_nvp_plugin/cli.py
quantum/plugins/nicira/nicira_nvp_plugin/nvplib.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/__init__.py [new file with mode: 0644]
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_check.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_config.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_network.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_nvp_api_common.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_nvp_api_request.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_nvp_api_request_eventlet.py
quantum/plugins/nicira/nicira_nvp_plugin/tests/test_port.py
quantum/plugins/openvswitch/README
quantum/plugins/openvswitch/agent/ovs_quantum_agent.py
quantum/plugins/openvswitch/ovs_db.py
quantum/plugins/openvswitch/ovs_models.py
quantum/plugins/openvswitch/ovs_quantum_plugin.py
quantum/plugins/openvswitch/run_tests.py
quantum/plugins/openvswitch/tests/unit/test_tunnel.py
quantum/plugins/openvswitch/tests/unit/test_vlan_map.py
quantum/plugins/ryu/agent/ryu_quantum_agent.py
quantum/plugins/ryu/nova/linux_net.py
quantum/plugins/ryu/nova/vif.py
quantum/plugins/ryu/ovs_quantum_plugin_base.py
quantum/plugins/ryu/run_tests.py
quantum/plugins/ryu/ryu_quantum_plugin.py
quantum/plugins/ryu/tests/unit/test_plugin_base.py
quantum/plugins/ryu/tests/unit/test_ryu_driver.py
quantum/plugins/ryu/tests/unit/utils.py
quantum/plugins/sample/SamplePlugin.py
quantum/quantum_plugin_base.py
quantum/rootwrap/filters.py
quantum/server/__init__.py
quantum/service.py
quantum/tests/unit/__init__.py
quantum/tests/unit/_test_api.py
quantum/tests/unit/extension_stubs.py
quantum/tests/unit/extensions/foxinsocks.py
quantum/tests/unit/runtime_flags.py
quantum/tests/unit/test_api.py
quantum/tests/unit/test_database.py
quantum/tests/unit/test_extensions.py
quantum/tests/unit/test_flags.py
quantum/tests/unit/testlib_api.py
quantum/wsgi.py

index a577e67385f5c16836509621fa3e243216ccda18..63cb82cd8841dca4a573d9c525b4ddd877d9ad97 100644 (file)
@@ -14,3 +14,8 @@
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
+
+import gettext
+
+
+gettext.install('quantum', unicode=1)
index 6987526998809f68b2d0ba29fe999c3d714f0a3c..b64f14f347ca681d64983d97801e2f3719a16d5d 100644 (file)
@@ -60,6 +60,9 @@ class APIRouter(wsgi.Router):
         plugin = manager.QuantumManager.get_plugin(options)
 
         uri_prefix = '/tenants/{tenant_id}/'
+        attachment_path = (
+            '%snetworks/{network_id}/ports/{id}/attachment{.format}' %
+            uri_prefix)
         mapper.resource('network', 'networks',
                         controller=networks.create_resource(plugin, version),
                         collection={'detail': 'GET'},
@@ -69,25 +72,22 @@ class APIRouter(wsgi.Router):
                         controller=ports.create_resource(plugin, version),
                         collection={'detail': 'GET'},
                         member={'detail': 'GET'},
-                        parent_resource=dict(member_name='network',
-                                             collection_name=uri_prefix +\
-                                                 'networks'))
+                        parent_resource=dict(
+                            member_name='network',
+                            collection_name='%snetworks' % uri_prefix))
         attachments_ctrl = attachments.create_resource(plugin, version)
         mapper.connect("get_resource",
-                       uri_prefix + 'networks/{network_id}/' \
-                                    'ports/{id}/attachment{.format}',
+                       attachment_path,
                        controller=attachments_ctrl,
                        action="get_resource",
                        conditions=dict(method=['GET']))
         mapper.connect("attach_resource",
-                       uri_prefix + 'networks/{network_id}/' \
-                                    'ports/{id}/attachment{.format}',
+                       attachment_path,
                        controller=attachments_ctrl,
                        action="attach_resource",
                        conditions=dict(method=['PUT']))
         mapper.connect("detach_resource",
-                       uri_prefix + 'networks/{network_id}/' \
-                                    'ports/{id}/attachment{.format}',
+                       attachment_path,
                        controller=attachments_ctrl,
                        action="detach_resource",
                        conditions=dict(method=['DELETE']))
index 07bfb89ebcefb29ad820c6c066cf021ac3c7fbff..6c70010ac01002f9b4dc71ed7d21bff45fd14695 100644 (file)
@@ -22,6 +22,7 @@ from webob import exc
 from quantum import wsgi
 from quantum.api import faults
 
+
 XML_NS_V10 = 'http://openstack.org/quantum/api/v1.0'
 XML_NS_V11 = 'http://openstack.org/quantum/api/v1.1'
 LOG = logging.getLogger('quantum.api.api_common')
index db41ab720d40d596ac0091f2db43d79825694d4c..be41a80f598ac9035a12a4d8e9851f593d3876db 100644 (file)
@@ -25,28 +25,33 @@ LOG = logging.getLogger('quantum.api.ports')
 
 def create_resource(plugin, version):
     controller_dict = {
-                        '1.0': [ControllerV10(plugin),
-                               ControllerV10._serialization_metadata,
-                               common.XML_NS_V10],
-                        '1.1': [ControllerV11(plugin),
-                                ControllerV11._serialization_metadata,
-                                common.XML_NS_V11]}
+        '1.0': [ControllerV10(plugin),
+                ControllerV10._serialization_metadata,
+                common.XML_NS_V10],
+        '1.1': [ControllerV11(plugin),
+                ControllerV11._serialization_metadata,
+                common.XML_NS_V11],
+        }
     return common.create_resource(version, controller_dict)
 
 
 class Controller(common.QuantumController):
     """ Port API controller for Quantum API """
 
-    _attachment_ops_param_list = [{
-        'param-name': 'id',
-        'required': True}, ]
+    _attachment_ops_param_list = [
+        {
+            'param-name': 'id',
+            'required': True,
+            },
+        ]
 
     _serialization_metadata = {
         "application/xml": {
             "attributes": {
-                "attachment": ["id"], }
-        },
-    }
+                "attachment": ["id"],
+                },
+            },
+        }
 
     def __init__(self, plugin):
         self._resource_name = 'attachment'
@@ -55,8 +60,7 @@ class Controller(common.QuantumController):
     @common.APIFaultWrapper([exception.NetworkNotFound,
                              exception.PortNotFound])
     def get_resource(self, request, tenant_id, network_id, id):
-        att_data = self._plugin.get_port_details(
-                        tenant_id, network_id, id)
+        att_data = self._plugin.get_port_details(tenant_id, network_id, id)
         builder = attachments_view.get_view_builder(request)
         result = builder.build(att_data)['attachment']
         return dict(attachment=result)
@@ -74,8 +78,7 @@ class Controller(common.QuantumController):
     @common.APIFaultWrapper([exception.NetworkNotFound,
                              exception.PortNotFound])
     def detach_resource(self, request, tenant_id, network_id, id):
-        self._plugin.unplug_interface(tenant_id,
-                                      network_id, id)
+        self._plugin.unplug_interface(tenant_id, network_id, id)
 
 
 class ControllerV10(Controller):
index c759a69da1b82e3c422132368f1fd0f0b8ff5f54..3ad04e5f41415e82ac675dbf858779fb2d4108fd 100644 (file)
@@ -20,6 +20,7 @@ import webob.exc
 
 from quantum.common import exceptions
 
+
 _NETNOTFOUND_EXPL = 'Unable to find a network with the specified identifier.'
 _NETINUSE_EXPL = 'Unable to remove the network: attachments still plugged.'
 _PORTNOTFOUND_EXPL = 'Unable to find a port with the specified identifier.'
@@ -39,13 +40,15 @@ def fault_body_function_v10(wrapped_exc):
     :rtype: tuple
     """
     code = wrapped_exc.status_int
-    fault_name = hasattr(wrapped_exc, 'title') and \
-                 wrapped_exc.title or "quantumServiceFault"
+    fault_name = (hasattr(wrapped_exc, 'title') and
+                  wrapped_exc.title or "quantumServiceFault")
     fault_data = {
         fault_name: {
             'code': code,
             'message': wrapped_exc.explanation,
-            'detail': str(wrapped_exc.detail)}}
+            'detail': str(wrapped_exc.detail),
+            },
+        }
     metadata = {'attributes': {fault_name: ['code']}}
     return fault_data, metadata
 
@@ -59,15 +62,17 @@ def fault_body_function_v11(wrapped_exc):
     :returns: response body contents and serialization metadata
     :rtype: tuple
     """
-    fault_name = hasattr(wrapped_exc, 'type') and \
-                 wrapped_exc.type or "QuantumServiceFault"
+    fault_name = (hasattr(wrapped_exc, 'type') and
+                  wrapped_exc.type or "QuantumServiceFault")
     # Ensure first letter is capital
     fault_name = fault_name[0].upper() + fault_name[1:]
     fault_data = {
         'QuantumError': {
             'type': fault_name,
             'message': wrapped_exc.explanation,
-            'detail': str(wrapped_exc.detail)}}
+            'detail': str(wrapped_exc.detail),
+            },
+        }
     # Metadata not required for v11
     return fault_data, None
 
index 29263807bfdb8b9b6899fdbfc2bd080b2294462c..2a5dc4f946e7aa50472888722e03924b8146ec4a 100644 (file)
@@ -19,30 +19,32 @@ from webob import exc
 
 from quantum.api import api_common as common
 from quantum.api import faults
-from quantum.api.views import networks as networks_view
 from quantum.api.views import filters
+from quantum.api.views import networks as networks_view
 from quantum.common import exceptions as exception
 
+
 LOG = logging.getLogger('quantum.api.networks')
 
 
 def create_resource(plugin, version):
     controller_dict = {
-                        '1.0': [ControllerV10(plugin),
-                               ControllerV10._serialization_metadata,
-                               common.XML_NS_V10],
-                        '1.1': [ControllerV11(plugin),
-                                ControllerV11._serialization_metadata,
-                                common.XML_NS_V11]}
+        '1.0': [ControllerV10(plugin),
+                ControllerV10._serialization_metadata,
+                common.XML_NS_V10],
+        '1.1': [ControllerV11(plugin),
+                ControllerV11._serialization_metadata,
+                common.XML_NS_V11],
+        }
     return common.create_resource(version, controller_dict)
 
 
 class Controller(common.QuantumController):
     """ Network API controller for Quantum API """
 
-    _network_ops_param_list = [{
-        'param-name': 'name',
-        'required': True}, ]
+    _network_ops_param_list = [
+        {'param-name': 'name', 'required': True},
+        ]
 
     def __init__(self, plugin):
         self._resource_name = 'network'
@@ -52,17 +54,17 @@ class Controller(common.QuantumController):
               net_details=True, port_details=False):
         # We expect get_network_details to return information
         # concerning logical ports as well.
-        network = self._plugin.get_network_details(
-                            tenant_id, network_id)
+        network = self._plugin.get_network_details(tenant_id, network_id)
         # Doing this in the API is inefficient
         # TODO(salvatore-orlando): This should be fixed with Bug #834012
         # Don't pass filter options
         ports_data = None
         if port_details:
             port_list = self._plugin.get_all_ports(tenant_id, network_id)
-            ports_data = [self._plugin.get_port_details(
-                                   tenant_id, network_id, port['port-id'])
-                      for port in port_list]
+            ports_data = [
+                self._plugin.get_port_details(tenant_id, network_id,
+                                              port['port-id'])
+                for port in port_list]
         builder = networks_view.get_view_builder(request, self.version)
         result = builder.build(network, net_details,
                                ports_data, port_details)['network']
@@ -128,10 +130,9 @@ class Controller(common.QuantumController):
         # request_params but that would mean all the plugins would need to
         # change.
         body = self._prepare_request_body(body, self._network_ops_param_list)
-        network = self._plugin.\
-                   create_network(tenant_id,
-                                  body['network']['name'],
-                                  **body)
+        network = self._plugin.create_network(tenant_id,
+                                              body['network']['name'],
+                                              **body)
         builder = networks_view.get_view_builder(request, self.version)
         result = builder.build(network)['network']
         return dict(network=result)
@@ -153,13 +154,16 @@ class ControllerV10(Controller):
     """Network resources controller for Quantum v1.0 API"""
 
     _serialization_metadata = {
-            "attributes": {
-                "network": ["id", "name"],
-                "port": ["id", "state"],
-                "attachment": ["id"]},
-            "plurals": {"networks": "network",
-                        "ports": "port"}
-    }
+        "attributes": {
+            "network": ["id", "name"],
+            "port": ["id", "state"],
+            "attachment": ["id"],
+            },
+        "plurals": {
+            "networks": "network",
+            "ports": "port",
+            },
+        }
 
     def __init__(self, plugin):
         self.version = "1.0"
@@ -176,13 +180,16 @@ class ControllerV11(Controller):
     """
 
     _serialization_metadata = {
-            "attributes": {
-                "network": ["id", "name", "op-status"],
-                "port": ["id", "state", "op-status"],
-                "attachment": ["id"]},
-            "plurals": {"networks": "network",
-                        "ports": "port"}
-    }
+        "attributes": {
+            "network": ["id", "name", "op-status"],
+            "port": ["id", "state", "op-status"],
+            "attachment": ["id"],
+            },
+        "plurals": {
+            "networks": "network",
+            "ports": "port",
+            },
+        }
 
     def __init__(self, plugin):
         self.version = "1.1"
index 09ee212df53d1d34e231732568b586546f623716..b3b28d53c9dd3740d9cd14807edcff96da9a1cba 100644 (file)
@@ -26,22 +26,22 @@ LOG = logging.getLogger('quantum.api.ports')
 
 def create_resource(plugin, version):
     controller_dict = {
-                        '1.0': [ControllerV10(plugin),
-                               ControllerV10._serialization_metadata,
-                               common.XML_NS_V10],
-                        '1.1': [ControllerV11(plugin),
-                                ControllerV11._serialization_metadata,
-                                common.XML_NS_V11]}
+        '1.0': [ControllerV10(plugin),
+                ControllerV10._serialization_metadata,
+                common.XML_NS_V10],
+        '1.1': [ControllerV11(plugin),
+                ControllerV11._serialization_metadata,
+                common.XML_NS_V11],
+        }
     return common.create_resource(version, controller_dict)
 
 
 class Controller(common.QuantumController):
     """ Port API controller for Quantum API """
 
-    _port_ops_param_list = [{
-        'param-name': 'state',
-        'default-value': 'DOWN',
-        'required': False}, ]
+    _port_ops_param_list = [
+        {'param-name': 'state', 'default-value': 'DOWN', 'required': False},
+        ]
 
     def __init__(self, plugin):
         self._resource_name = 'port'
@@ -69,10 +69,10 @@ class Controller(common.QuantumController):
         # This can be inefficient.
         # TODO(salvatore-orlando): the fix for bug #834012 should deal with it
         if port_details:
-            port_list_detail = \
-                [self._plugin.get_port_details(
-                            tenant_id, network_id, port['port-id'])
-                  for port in port_list]
+            port_list_detail = [
+                self._plugin.get_port_details(tenant_id, network_id,
+                                              port['port-id'])
+                for port in port_list]
             port_list = port_list_detail
 
         # Perform manual filtering if not supported by plugin
@@ -92,8 +92,7 @@ class Controller(common.QuantumController):
     def _item(self, request, tenant_id, network_id, port_id,
               att_details=False):
         """ Returns a specific port. """
-        port = self._plugin.get_port_details(
-                        tenant_id, network_id, port_id)
+        port = self._plugin.get_port_details(tenant_id, network_id, port_id)
         builder = ports_view.get_view_builder(request, self.version)
         result = builder.build(port, port_details=True,
                                att_details=att_details)['port']
@@ -160,11 +159,14 @@ class ControllerV10(Controller):
     """Port resources controller for Quantum v1.0 API"""
 
     _serialization_metadata = {
-            "attributes": {
-                "port": ["id", "state"],
-                "attachment": ["id"]},
-            "plurals": {"ports": "port"}
-    }
+        "attributes": {
+            "port": ["id", "state"],
+            "attachment": ["id"],
+            },
+        "plurals": {
+            "ports": "port",
+            },
+        }
 
     def __init__(self, plugin):
         self.version = "1.0"
@@ -175,11 +177,14 @@ class ControllerV11(Controller):
     """Port resources controller for Quantum v1.1 API"""
 
     _serialization_metadata = {
-            "attributes": {
-                "port": ["id", "state", "op-status"],
-                "attachment": ["id"]},
-            "plurals": {"ports": "port"}
-    }
+        "attributes": {
+            "port": ["id", "state", "op-status"],
+            "attachment": ["id"],
+            },
+        "plurals": {
+            "ports": "port",
+            },
+        }
 
     def __init__(self, plugin):
         self.version = "1.1"
index 67c831d35b060a66316d09f76c839b07b607ed62..858a7a979976585c02e4f7486da5f18ce1bdff81 100644 (file)
@@ -31,8 +31,9 @@ import socket
 
 from paste import deploy
 
-from quantum.common import flags
 from quantum.common import exceptions as exception
+from quantum.common import flags
+
 
 DEFAULT_LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"
 DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
@@ -142,10 +143,10 @@ def setup_logging(options, conf):
 
     # If either the CLI option or the conf value
     # is True, we set to True
-    debug = options.get('debug') or \
-            get_option(conf, 'debug', type='bool', default=False)
-    verbose = options.get('verbose') or \
-            get_option(conf, 'verbose', type='bool', default=False)
+    debug = (options.get('debug') or
+             get_option(conf, 'debug', type='bool', default=False))
+    verbose = (options.get('verbose') or
+               get_option(conf, 'verbose', type='bool', default=False))
     root_logger = logging.root
     if debug:
         root_logger.setLevel(logging.DEBUG)
@@ -227,7 +228,7 @@ def find_config_file(options, args, config_file='quantum.conf'):
     # Handle standard directory search for the config file
     config_file_dirs = [fix_path(os.path.join(os.getcwd(), 'etc')),
                         fix_path(os.path.join('~', '.quantum-venv', 'etc',
-                                 'quantum')),
+                                              'quantum')),
                         fix_path('~'),
                         os.path.join(FLAGS.state_path, 'etc'),
                         os.path.join(FLAGS.state_path, 'etc', 'quantum'),
@@ -239,13 +240,14 @@ def find_config_file(options, args, config_file='quantum.conf'):
                         '/etc']
 
     if 'plugin' in options:
-        config_file_dirs = [os.path.join(x, 'quantum', 'plugins',
-                                             options['plugin'])
-                            for x in config_file_dirs]
+        config_file_dirs = [
+            os.path.join(x, 'quantum', 'plugins', options['plugin'])
+            for x in config_file_dirs
+            ]
 
     if os.path.exists(os.path.join(root, 'plugins')):
         plugins = [fix_path(os.path.join(root, 'plugins', p, 'etc'))
-                  for p in os.listdir(os.path.join(root, 'plugins'))]
+                   for p in os.listdir(os.path.join(root, 'plugins'))]
         plugins = [p for p in plugins if os.path.isdir(p)]
         config_file_dirs.extend(plugins)
 
index bf59802bb4d1bcad9540804c50a640d1f36d1cc2..5a0dc9909766a280b945732d8cac7861f16702b7 100644 (file)
@@ -56,7 +56,7 @@ class NetworkNotFound(NotFound):
 
 
 class PortNotFound(NotFound):
-    message = _("Port %(port_id)s could not be found " \
+    message = _("Port %(port_id)s could not be found "
                 "on network %(net_id)s")
 
 
@@ -65,19 +65,19 @@ class StateInvalid(QuantumException):
 
 
 class NetworkInUse(QuantumException):
-    message = _("Unable to complete operation on network %(net_id)s. " \
+    message = _("Unable to complete operation on network %(net_id)s. "
                 "There is one or more attachments plugged into its ports.")
 
 
 class PortInUse(QuantumException):
-    message = _("Unable to complete operation on port %(port_id)s " \
-                "for network %(net_id)s. The attachment '%(att_id)s" \
+    message = _("Unable to complete operation on port %(port_id)s "
+                "for network %(net_id)s. The attachment '%(att_id)s"
                 "is plugged into the logical port.")
 
 
 class AlreadyAttached(QuantumException):
-    message = _("Unable to plug the attachment %(att_id)s into port " \
-                "%(port_id)s for network %(net_id)s. The attachment is " \
+    message = _("Unable to plug the attachment %(att_id)s into port "
+                "%(port_id)s for network %(net_id)s. The attachment is "
                 "already plugged into port %(att_port_id)s")
 
 
index 16badd33293390ef68f9bd5567326c0bd1f5d0c7..d9816cdd16c1cea2c9f80ef563ae2aa4a5c54ba7 100644 (file)
@@ -238,7 +238,7 @@ def DECLARE(name, module_string, flag_values=FLAGS):
         __import__(module_string, globals(), locals())
     if name not in flag_values:
         raise gflags.UnrecognizedFlag(
-                "%s not defined by %s" % (name, module_string))
+            "%s not defined by %s" % (name, module_string))
 
 
 # __GLOBAL FLAGS ONLY__
index 03578817d6a9cef930af7074bb3d612b92885c90..4e4fab730f2196adbaec420738fb34a795e29b1c 100644 (file)
 #    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 #    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
-import gettext
+import logging
 import os
-import unittest
 import sys
-import logging
+import unittest
 
-from nose import result
-from nose import core
 from nose import config
+from nose import core
+from nose import result
 
 
 class _AnsiColorizer(object):
index afa1e7470dab4eb877449dd47e8148aa2d853ae2..9fd1739d1054838333ca2c05219d110163b66458 100644 (file)
 
 """Utilities and helper functions."""
 
+
+import base64
 import ConfigParser
 import datetime
+import functools
 import inspect
+import json
 import logging
 import os
 import random
-import subprocess
-import socket
-import sys
-import base64
-import functools
-import json
 import re
+import socket
 import string
 import struct
+import subprocess
+import sys
 import time
 import types
 
-from quantum.common import flags
 from quantum.common import exceptions as exception
 from quantum.common.exceptions import ProcessExecutionError
+from quantum.common import flags
 
 
 def import_class(import_str):
@@ -96,6 +97,7 @@ def dumps(value):
 def loads(s):
     return json.loads(s)
 
+
 TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
 FLAGS = flags.FLAGS
 
@@ -173,7 +175,6 @@ def abspath(s):
 
 # TODO(sirp): when/if utils is extracted to common library, we should remove
 # the argument's default.
-#def default_flagfile(filename='nova.conf'):
 def default_flagfile(filename='quantum.conf'):
     for arg in sys.argv:
         if arg.find('flagfile') != -1:
@@ -184,8 +185,7 @@ def default_flagfile(filename='quantum.conf'):
             script_dir = os.path.dirname(inspect.stack()[-1][1])
             filename = os.path.abspath(os.path.join(script_dir, filename))
         if os.path.exists(filename):
-            sys.argv = \
-                sys.argv[:1] + ['--flagfile=%s' % filename] + sys.argv[1:]
+            sys.argv.insert(1, '--flagfile=%s' % filename)
 
 
 def debug(arg):
@@ -231,9 +231,9 @@ def parse_isotime(timestr):
 
 
 def get_plugin_from_config(file="config.ini"):
-        Config = ConfigParser.ConfigParser()
-        Config.read(file)
-        return Config.get("PLUGIN", "provider")
+    Config = ConfigParser.ConfigParser()
+    Config.read(file)
+    return Config.get("PLUGIN", "provider")
 
 
 class LazyPluggable(object):
@@ -251,7 +251,7 @@ class LazyPluggable(object):
                 raise exception.Error('Invalid backend: %s' % backend_name)
 
             backend = self.__backends[backend_name]
-            if type(backend) == type(tuple()):
+            if isinstance(backend, tuple):
                 name = backend[0]
                 fromlist = backend[1]
             else:
index 455453816d00e8f445d6ca9217a4b81180ef9688..cf47d8a48c50109f45dd87876901be900ba51a16 100644 (file)
@@ -18,6 +18,7 @@
 # @author: Dan Wendlandt, Nicira Networks, Inc.
 
 import logging
+
 import sqlalchemy as sql
 from sqlalchemy import create_engine
 from sqlalchemy.exc import DisconnectionError
@@ -127,17 +128,17 @@ def network_all_tenant_list():
 
 def network_list(tenant_id):
     session = get_session()
-    return session.query(models.Network).\
-      filter_by(tenant_id=tenant_id).\
-      all()
+    return (session.query(models.Network).
+            filter_by(tenant_id=tenant_id).
+            all())
 
 
 def network_get(net_id):
     session = get_session()
     try:
-        return  session.query(models.Network).\
-            filter_by(uuid=net_id).\
-            one()
+        return (session.query(models.Network).
+                filter_by(uuid=net_id).
+                one())
     except exc.NoResultFound, e:
         raise q_exc.NetworkNotFound(net_id=net_id)
 
@@ -155,13 +156,13 @@ def network_update(net_id, tenant_id, **kwargs):
 def network_destroy(net_id):
     session = get_session()
     try:
-        net = session.query(models.Network).\
-          filter_by(uuid=net_id).\
-          one()
+        net = (session.query(models.Network).
+               filter_by(uuid=net_id).
+               one())
 
-        ports = session.query(models.Port).\
-            filter_by(network_id=net_id).\
-            all()
+        ports = (session.query(models.Port).
+                 filter_by(network_id=net_id).
+                 all())
         for p in ports:
             session.delete(p)
 
@@ -175,10 +176,10 @@ def network_destroy(net_id):
 def validate_network_ownership(tenant_id, net_id):
     session = get_session()
     try:
-        return  session.query(models.Network).\
-            filter_by(uuid=net_id).\
-            filter_by(tenant_id=tenant_id).\
-            one()
+        return (session.query(models.Network).
+                filter_by(uuid=net_id).
+                filter_by(tenant_id=tenant_id).
+                one())
     except exc.NoResultFound, e:
         raise q_exc.NetworkNotFound(net_id=net_id)
 
@@ -204,9 +205,9 @@ def port_list(net_id):
     # confirm network exists
     network_get(net_id)
     session = get_session()
-    return session.query(models.Port).\
-      filter_by(network_id=net_id).\
-      all()
+    return (session.query(models.Port).
+            filter_by(network_id=net_id).
+            all())
 
 
 def port_get(port_id, net_id, session=None):
@@ -215,10 +216,10 @@ def port_get(port_id, net_id, session=None):
     if not session:
         session = get_session()
     try:
-        return session.query(models.Port).\
-          filter_by(uuid=port_id).\
-          filter_by(network_id=net_id).\
-          one()
+        return (session.query(models.Port).
+                filter_by(uuid=port_id).
+                filter_by(network_id=net_id).
+                one())
     except exc.NoResultFound:
         raise q_exc.PortNotFound(net_id=net_id, port_id=port_id)
 
@@ -228,7 +229,7 @@ def port_update(port_id, net_id, **kwargs):
     network_get(net_id)
     port = port_get(port_id, net_id)
     session = get_session()
-    for key in kwargs.keys():
+    for key in kwargs:
         if key == "state":
             if kwargs[key] not in ('ACTIVE', 'DOWN'):
                 raise q_exc.StateInvalid(port_state=kwargs[key])
@@ -249,16 +250,16 @@ def port_set_attachment(port_id, net_id, new_interface_id):
         # We are setting, not clearing, the attachment-id
         if port['interface_id']:
             raise q_exc.PortInUse(net_id=net_id, port_id=port_id,
-                                att_id=port['interface_id'])
+                                  att_id=port['interface_id'])
 
         try:
-            port = session.query(models.Port).\
-            filter_by(interface_id=new_interface_id).\
-            one()
+            port = (session.query(models.Port).
+                    filter_by(interface_id=new_interface_id).
+                    one())
             raise q_exc.AlreadyAttached(net_id=net_id,
-                                    port_id=port_id,
-                                    att_id=new_interface_id,
-                                    att_port_id=port['uuid'])
+                                        port_id=port_id,
+                                        att_id=new_interface_id,
+                                        att_port_id=port['uuid'])
         except exc.NoResultFound:
             # this is what should happen
             pass
@@ -285,13 +286,13 @@ def port_destroy(port_id, net_id):
 
     session = get_session()
     try:
-        port = session.query(models.Port).\
-          filter_by(uuid=port_id).\
-          filter_by(network_id=net_id).\
-          one()
+        port = (session.query(models.Port).
+                filter_by(uuid=port_id).
+                filter_by(network_id=net_id).
+                one())
         if port['interface_id']:
             raise q_exc.PortInUse(net_id=net_id, port_id=port_id,
-                                att_id=port['interface_id'])
+                                  att_id=port['interface_id'])
         session.delete(port)
         session.flush()
         return port
index 1039cbe2199bfe14bdaf25d332e09b15260ad94f..e26e20c2d85b35392d2571337cf30f2541b8068f 100644 (file)
@@ -26,6 +26,7 @@ from sqlalchemy.orm import relation, object_mapper
 
 from quantum.api import api_common as common
 
+
 BASE = declarative_base()
 
 
@@ -59,7 +60,7 @@ class QuantumBase(object):
         Includes attributes from joins."""
         local = dict(self)
         joined = dict([(k, v) for k, v in self.__dict__.iteritems()
-                      if not k[0] == '_'])
+                       if not k[0] == '_'])
         local.update(joined)
         return local.iteritems()
 
@@ -76,8 +77,7 @@ class Port(BASE, QuantumBase):
     state = Column(String(8))
     op_status = Column(String(16))
 
-    def __init__(self, network_id,
-                 op_status=common.OperationalStatus.UNKNOWN):
+    def __init__(self, network_id, op_status=common.OperationalStatus.UNKNOWN):
         self.uuid = str(uuid.uuid4())
         self.network_id = network_id
         self.interface_id = None
index 0175ecd84f6e9ff987227197eba03cc163aefebe..3a5e7f222211ea1f0fcb25266bc4ab8c8fd2f0f8 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,7 +16,6 @@
 #
 # @author: Ying Liu, Cisco Systems, Inc.
 #
-"""
 
 
 def get_view_builder(req):
@@ -52,5 +50,5 @@ class ViewBuilder(object):
     def _build_detail(self, credential_data):
         """Return a detailed description of credential."""
         return dict(credential=dict(id=credential_data['credential_id'],
-                                name=credential_data['user_name'],
-                                password=credential_data['password']))
+                                    name=credential_data['user_name'],
+                                    password=credential_data['password']))
index 64a27872a42790123c06e3e3a3f126a2a3ca6bbc..d02a418ccaf90a8732de62659b6e2179700cf3d2 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,7 +16,7 @@
 #
 # @author: Ying Liu, Cisco Systems, Inc.
 #
-"""
+
 from quantum.plugins.cisco.common import cisco_constants as const
 
 
index 700d42f2ed4cc53689a28be38463e8c0b0e7c161..d67b9147faee565f22a4d731d583189c0e7d1c75 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Nicira Networks, Inc.  All rights reserved.
@@ -17,7 +16,6 @@
 #
 # @author: Brad Hall, Nicira Networks, Inc
 #
-"""
 
 
 def get_view_builder(req):
index 5fb088fc991de2642dc4cef6b4231b2c430fc4bf..3be2e243342e42244d570a46f9516ff54f73bb36 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,6 @@
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
 
 
 def get_view_builder(req):
@@ -52,11 +49,15 @@ class ViewBuilder(object):
     def _build_detail(self, portprofile_data):
         """Return a detailed info of a portprofile."""
         if (portprofile_data['assignment'] is None):
-            return dict(portprofile=dict(id=portprofile_data['profile_id'],
-                                name=portprofile_data['profile_name'],
-                                qos_name=portprofile_data['qos_name']))
+            return dict(portprofile=dict(
+                id=portprofile_data['profile_id'],
+                name=portprofile_data['profile_name'],
+                qos_name=portprofile_data['qos_name'],
+                ))
         else:
-            return dict(portprofile=dict(id=portprofile_data['profile_id'],
-                                name=portprofile_data['profile_name'],
-                                qos_name=portprofile_data['qos_name'],
-                                assignment=portprofile_data['assignment']))
+            return dict(portprofile=dict(
+                id=portprofile_data['profile_id'],
+                name=portprofile_data['profile_name'],
+                qos_name=portprofile_data['qos_name'],
+                assignment=portprofile_data['assignment'],
+                ))
index 24469e4bc8c8711fb89a6fb9d8a42fa61955daa0..354fa413d9865578510e8e11be451096d578fba7 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,7 +16,6 @@
 #
 # @author: Ying Liu, Cisco Systems, Inc.
 #
-"""
 
 
 def get_view_builder(req):
@@ -52,5 +50,5 @@ class ViewBuilder(object):
     def _build_detail(self, qos_data):
         """Return a detailed description of qos."""
         return dict(qos=dict(id=qos_data['qos_id'],
-                                name=qos_data['qos_name'],
-                                description=qos_data['qos_desc']))
+                             name=qos_data['qos_name'],
+                             description=qos_data['qos_desc']))
index 586760663a946fef98a59d646f4944413a8705d1..4816d30d8fac57447994b63483d38264cb98a3f8 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
+
 import logging
 
 from webob import exc
-from quantum import wsgi
-from quantum.extensions import _credential_view as credential_view
+
 from quantum.api import api_common as common
+from quantum.extensions import _credential_view as credential_view
 from quantum.extensions import extensions
 from quantum.manager import QuantumManager
 from quantum.plugins.cisco.common import cisco_exceptions as exception
 from quantum.plugins.cisco.common import cisco_faults as faults
+from quantum import wsgi
+
 
 LOG = logging.getLogger('quantum.api.credentials')
 
@@ -76,13 +76,11 @@ class CredentialController(common.QuantumController, wsgi.Controller):
     """ credential API controller
         based on QuantumController """
 
-    _credential_ops_param_list = [{
-        'param-name': 'credential_name',
-        'required': True}, {
-        'param-name': 'user_name',
-        'required': True}, {
-        'param-name': 'password',
-        'required': True}]
+    _credential_ops_param_list = [
+        {'param-name': 'credential_name', 'required': True},
+        {'param-name': 'user_name', 'required': True},
+        {'param-name': 'password', 'required': True},
+        ]
 
     _serialization_metadata = {
         "application/xml": {
@@ -112,8 +110,7 @@ class CredentialController(common.QuantumController, wsgi.Controller):
     def show(self, request, tenant_id, id):
         """ Returns credential details for the given credential id """
         try:
-            credential = self._plugin.get_credential_details(
-                            tenant_id, id)
+            credential = self._plugin.get_credential_details(tenant_id, id)
             builder = credential_view.get_view_builder(request)
             #build response with details
             result = builder.build(credential, True)
@@ -125,18 +122,17 @@ class CredentialController(common.QuantumController, wsgi.Controller):
         """ Creates a new credential for a given tenant """
         try:
             body = self._deserialize(request.body, request.get_content_type())
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._credential_ops_param_list)
+            req_body = self._prepare_request_body(
+                body, self._credential_ops_param_list)
             req_params = req_body[self._resource_name]
 
         except exc.HTTPError as exp:
             return faults.Fault(exp)
-        credential = self._plugin.\
-                       create_credential(tenant_id,
-                                          req_params['credential_name'],
-                                          req_params['user_name'],
-                                          req_params['password'])
+        credential = self._plugin.create_credential(
+            tenant_id,
+            req_params['credential_name'],
+            req_params['user_name'],
+            req_params['password'])
         builder = credential_view.get_view_builder(request)
         result = builder.build(credential)
         return dict(credentials=result)
@@ -145,16 +141,14 @@ class CredentialController(common.QuantumController, wsgi.Controller):
         """ Updates the name for the credential with the given id """
         try:
             body = self._deserialize(request.body, request.get_content_type())
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._credential_ops_param_list)
+            req_body = self._prepare_request_body(
+                body, self._credential_ops_param_list)
             req_params = req_body[self._resource_name]
         except exc.HTTPError as exp:
             return faults.Fault(exp)
         try:
-            credential = self._plugin.\
-            rename_credential(tenant_id,
-                        id, req_params['credential_name'])
+            credential = self._plugin.rename_credential(
+                tenant_id, id, req_params['credential_name'])
 
             builder = credential_view.get_view_builder(request)
             result = builder.build(credential, True)
index 1cd8e31b2012cc1b13c411f28f4aa91056cc119b..91cf9a66f7e485a0898c13fcba445de6ba6d1b47 100644 (file)
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
+
+from abc import ABCMeta
 import imp
 import logging
 import os
+
 import routes
 import webob.dec
 import webob.exc
 
-from gettext import gettext as _
-from abc import ABCMeta
 from quantum.common import exceptions
 import quantum.extensions
 from quantum.manager import QuantumManager
 from quantum import wsgi
 
+
 LOG = logging.getLogger('quantum.extensions.extensions')
 
 
@@ -281,14 +283,14 @@ class ExtensionMiddleware(wsgi.Middleware):
             if not action.collection in action_controllers.keys():
                 controller = ActionExtensionController(application)
                 mapper.connect("/%s/:(id)/action.:(format)" %
-                                action.collection,
-                                action='action',
-                                controller=controller,
-                                conditions=dict(method=['POST']))
+                               action.collection,
+                               action='action',
+                               controller=controller,
+                               conditions=dict(method=['POST']))
                 mapper.connect("/%s/:(id)/action" % action.collection,
-                                action='action',
-                                controller=controller,
-                                conditions=dict(method=['POST']))
+                               action='action',
+                               controller=controller,
+                               conditions=dict(method=['POST']))
                 action_controllers[action.collection] = controller
 
         return action_controllers
@@ -300,14 +302,14 @@ class ExtensionMiddleware(wsgi.Middleware):
             if not req_ext.key in request_ext_controllers.keys():
                 controller = RequestExtensionController(application)
                 mapper.connect(req_ext.url_route + '.:(format)',
-                                action='process',
-                                controller=controller,
-                                conditions=req_ext.conditions)
+                               action='process',
+                               controller=controller,
+                               conditions=req_ext.conditions)
 
                 mapper.connect(req_ext.url_route,
-                                action='process',
-                                controller=controller,
-                                conditions=req_ext.conditions)
+                               action='process',
+                               controller=controller,
+                               conditions=req_ext.conditions)
                 request_ext_controllers[req_ext.key] = controller
 
         return request_ext_controllers
@@ -361,7 +363,7 @@ class ExtensionManager(object):
         """Returns a list of ResourceExtension objects."""
         resources = []
         resources.append(ResourceExtension('extensions',
-                                            ExtensionController(self)))
+                                           ExtensionController(self)))
         for alias, ext in self.extensions.iteritems():
             try:
                 resources.extend(ext.get_resources())
@@ -496,7 +498,7 @@ class PluginAwareExtensionManager(ExtensionManager):
         if not plugin_has_interface:
             LOG.warn("plugin %s does not implement extension's"
                      "plugin interface %s" % (self.plugin,
-                                             extension.get_alias()))
+                                              extension.get_alias()))
         return plugin_has_interface
 
 
index 44d1d9cb0f37734d576e1d0737d09cad9b3751ba..039d5465b24af1da56a035a8f71d4c4e46df6615 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
+
 import logging
 
 from webob import exc
-from quantum import wsgi
+
 from quantum.api import api_common as common
 from quantum.api.views import ports as port_view
 from quantum.extensions import extensions
 from quantum.manager import QuantumManager
 from quantum.plugins.cisco.common import cisco_exceptions as exception
 from quantum.plugins.cisco.common import cisco_faults as faults
+from quantum import wsgi
+
 
 LOG = logging.getLogger('quantum.api.multiports')
 
@@ -76,13 +76,11 @@ class MultiportController(common.QuantumController, wsgi.Controller):
     """ multiport API controller
         based on QuantumController """
 
-    _multiport_ops_param_list = [{
-        'param-name': 'net_id_list',
-        'required': True}, {
-        'param-name': 'status',
-        'required': True}, {
-        'param-name': 'ports_desc',
-        'required': True}]
+    _multiport_ops_param_list = [
+        {'param-name': 'net_id_list', 'required': True},
+        {'param-name': 'status', 'required': True},
+        {'param-name': 'ports_desc', 'required': True},
+        ]
 
     _serialization_metadata = {
         "application/xml": {
@@ -102,19 +100,16 @@ class MultiportController(common.QuantumController, wsgi.Controller):
         """ Creates a new multiport for a given tenant """
         try:
             body = self._deserialize(request.body, request.get_content_type())
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._multiport_ops_param_list)
+            req_body = self._prepare_request_body(
+                body, self._multiport_ops_param_list)
             req_params = req_body[self._resource_name]
 
         except exc.HTTPError as exp:
             return faults.Fault(exp)
-        multiports = self._plugin.\
-                       create_multiport(tenant_id,
-                                          req_params['net_id_list'],
-                                          req_params['status'],
-                                          req_params['ports_desc'])
+        multiports = self._plugin.create_multiport(tenant_id,
+                                                   req_params['net_id_list'],
+                                                   req_params['status'],
+                                                   req_params['ports_desc'])
         builder = port_view.get_view_builder(request, self.version)
-        result = [builder.build(port)['port']
-                      for port in multiports]
+        result = [builder.build(port)['port'] for port in multiports]
         return dict(ports=result)
index fb544d19bbe48c92cf981ae7597bb5eb39802e4d..84ad52c58fcd49d4ef36d477256df5380ec3bb86 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
+
 from webob import exc
-from quantum import wsgi
-from quantum.extensions import _novatenant_view as novatenant_view
+
 from quantum.api import api_common as common
 from quantum.common import exceptions as qexception
 from quantum.extensions import extensions
+from quantum.extensions import _novatenant_view as novatenant_view
 from quantum.manager import QuantumManager
 from quantum.plugins.cisco.common import cisco_faults as faults
+from quantum import wsgi
 
 
 class Novatenant(object):
@@ -76,15 +75,14 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
     """ Novatenant API controller
         based on QuantumController """
 
-    _Novatenant_ops_param_list = [{
-        'param-name': 'novatenant_name',
-        'required': True}]
+    _Novatenant_ops_param_list = [
+        {'param-name': 'novatenant_name', 'required': True},
+        ]
 
-    _schedule_host_ops_param_list = [{
-        'param-name': 'instance_id',
-        'required': True}, {
-        'param-name': 'instance_desc',
-        'required': True}]
+    _schedule_host_ops_param_list = [
+        {'param-name': 'instance_id', 'required': True},
+        {'param-name': 'instance_desc', 'required': True},
+        ]
 
     _serialization_metadata = {
         "application/xml": {
@@ -122,9 +120,8 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
 
         try:
             body = self._deserialize(request.body, content_type)
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._schedule_host_ops_param_list)
+            req_body = self._prepare_request_body(
+                body, self._schedule_host_ops_param_list)
             req_params = req_body[self._resource_name]
 
         except exc.HTTPError as exp:
@@ -132,8 +129,9 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
         instance_id = req_params['instance_id']
         instance_desc = req_params['instance_desc']
         try:
-            host = self._plugin.\
-            schedule_host(tenant_id, instance_id, instance_desc)
+            host = self._plugin.schedule_host(tenant_id,
+                                              instance_id,
+                                              instance_desc)
             builder = novatenant_view.get_view_builder(request)
             result = builder.build_host(host)
             return result
@@ -144,9 +142,8 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
         content_type = request.best_match_content_type()
         try:
             body = self._deserialize(request.body, content_type)
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._schedule_host_ops_param_list)
+            req_body = self._prepare_request_body(
+                body, self._schedule_host_ops_param_list)
             req_params = req_body[self._resource_name]
 
         except exc.HTTPError as exp:
@@ -154,8 +151,9 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
         instance_id = req_params['instance_id']
         instance_desc = req_params['instance_desc']
         try:
-            vif = self._plugin. \
-            associate_port(tenant_id, instance_id, instance_desc)
+            vif = self._plugin.associate_port(tenant_id,
+                                              instance_id,
+                                              instance_desc)
             builder = novatenant_view.get_view_builder(request)
             result = builder.build_vif(vif)
             return result
@@ -166,9 +164,8 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
         content_type = request.best_match_content_type()
         try:
             body = self._deserialize(request.body, content_type)
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._schedule_host_ops_param_list)
+            req_body = self._prepare_request_body(
+                body, self._schedule_host_ops_param_list)
             req_params = req_body[self._resource_name]
 
         except exc.HTTPError as exp:
@@ -178,8 +175,9 @@ class NovatenantsController(common.QuantumController, wsgi.Controller):
         instance_desc = req_params['instance_desc']
 
         try:
-            vif = self._plugin. \
-            detach_port(tenant_id, instance_id, instance_desc)
+            vif = self._plugin.detach_port(tenant_id,
+                                           instance_id,
+                                           instance_desc)
             builder = novatenant_view.get_view_builder(request)
             result = builder.build_result(True)
             return result
index ea3e2d9d6581bd6e03e9ac8c812f4488e640e70e..05ea91fb2aca43dca62fc43b6636adb954cdc991 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
 
 from webob import exc
-from quantum import wsgi
-from quantum.extensions import _pprofiles as pprofiles_view
+
 from quantum.api import api_common as common
 from quantum.common import exceptions as qexception
+from quantum.extensions import _pprofiles as pprofiles_view
 from quantum.extensions import extensions
 from quantum.manager import QuantumManager
 from quantum.plugins.cisco.common import cisco_exceptions as exception
 from quantum.plugins.cisco.common import cisco_faults as faults
+from quantum import wsgi
 
 
 class Portprofile(object):
index 59a706d34521d56b63d1310152a57cd4de867950..164687542d6114985f23b0be5600b4485dffd769 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Nicira Networks, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Brad Hall, Nicira Networks, Inc
-#
-"""
 
 import logging
 
-from quantum import wsgi
-from quantum.extensions import _portstats_view as portstats_view
 from quantum.api import faults
 from quantum.common import exceptions as qexception
 from quantum.common import extensions
+from quantum.extensions import _portstats_view as portstats_view
 from quantum.manager import QuantumManager
+from quantum import wsgi
 
 
 LOG = logging.getLogger("quantum.api.portstats")
@@ -61,8 +58,8 @@ class Portstats(object):
         """ Returns all defined resources """
         controller = StatsController(QuantumManager.get_plugin())
         parent_resource = dict(member_name="port",
-                               collection_name="extensions/ovs/tenants/" + \
-                               ":(tenant_id)/networks/:(network_id)/ports")
+                               collection_name="extensions/ovs/tenants/"
+                               ":(tenant_id)/ networks/:(network_id)/ports")
         return [extensions.ResourceExtension('stats', controller,
                                              parent=parent_resource)]
 
@@ -84,12 +81,10 @@ class StatsController(wsgi.Controller):
     def _show(self, request, tenant_id, network_id, port_id):
         """Returns port statistics for a given port"""
         if not hasattr(self._plugin, "get_port_stats"):
-            return \
-                faults.QuantumHTTPError(
-                    qexception.NotImplementedError("get_port_stats"))
+            return faults.QuantumHTTPError(
+                qexception.NotImplementedError("get_port_stats"))
 
-        stats = self._plugin.get_port_stats(tenant_id, network_id,
-                                            port_id)
+        stats = self._plugin.get_port_stats(tenant_id, network_id, port_id)
         builder = portstats_view.get_view_builder(request)
         result = builder.build(stats, True)
         return dict(stats=result)
index aad064cf0b62092b84ad42cd5fc99610d33a61c2..79606c94967265119c4e958e903fffaeb744f7d7 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
+
 import logging
 
-from quantum import wsgi
 from webob import exc
-from quantum.extensions import _qos_view as qos_view
+
 from quantum.api import api_common as common
+from quantum.extensions import _qos_view as qos_view
 from quantum.extensions import extensions
 from quantum.manager import QuantumManager
 from quantum.plugins.cisco.common import cisco_exceptions as exception
 from quantum.plugins.cisco.common import cisco_faults as faults
+from quantum import wsgi
 
 
 LOG = logging.getLogger('quantum.api.qoss')
@@ -78,11 +77,11 @@ class QosController(common.QuantumController, wsgi.Controller):
     """ qos API controller
         based on QuantumController """
 
-    _qos_ops_param_list = [{
-        'param-name': 'qos_name',
-        'required': True}, {
-        'param-name': 'qos_desc',
-        'required': True}]
+    _qos_ops_param_list = [
+        {'param-name': 'qos_name', 'required': True},
+        {'param-name': 'qos_desc', 'required': True},
+        ]
+
     _serialization_metadata = {
         "application/xml": {
             "attributes": {
@@ -103,16 +102,14 @@ class QosController(common.QuantumController, wsgi.Controller):
         """ Returns a list of qoss. """
         qoss = self._plugin.get_all_qoss(tenant_id)
         builder = qos_view.get_view_builder(request)
-        result = [builder.build(qos, is_detail)['qos']
-                  for qos in qoss]
+        result = [builder.build(qos, is_detail)['qos'] for qos in qoss]
         return dict(qoss=result)
 
     # pylint: disable-msg=E1101
     def show(self, request, tenant_id, id):
         """ Returns qos details for the given qos id """
         try:
-            qos = self._plugin.get_qos_details(
-                            tenant_id, id)
+            qos = self._plugin.get_qos_details(tenant_id, id)
             builder = qos_view.get_view_builder(request)
             #build response with details
             result = builder.build(qos, True)
@@ -125,16 +122,14 @@ class QosController(common.QuantumController, wsgi.Controller):
         #look for qos name in request
         try:
             body = self._deserialize(request.body, request.get_content_type())
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._qos_ops_param_list)
+            req_body = self._prepare_request_body(body,
+                                                  self._qos_ops_param_list)
             req_params = req_body[self._resource_name]
         except exc.HTTPError as exp:
             return faults.Fault(exp)
-        qos = self._plugin.\
-                       create_qos(tenant_id,
-                                          req_params['qos_name'],
-                                          req_params['qos_desc'])
+        qos = self._plugin.create_qos(tenant_id,
+                                      req_params['qos_name'],
+                                      req_params['qos_desc'])
         builder = qos_view.get_view_builder(request)
         result = builder.build(qos)
         return dict(qoss=result)
@@ -143,16 +138,14 @@ class QosController(common.QuantumController, wsgi.Controller):
         """ Updates the name for the qos with the given id """
         try:
             body = self._deserialize(request.body, request.get_content_type())
-            req_body = \
-                self._prepare_request_body(body,
-                                           self._qos_ops_param_list)
+            req_body = self._prepare_request_body(body,
+                                                  self._qos_ops_param_list)
             req_params = req_body[self._resource_name]
         except exc.HTTPError as exp:
             return faults.Fault(exp)
         try:
-            qos = self._plugin.\
-            rename_qos(tenant_id,
-                        id, req_params['qos_name'])
+            qos = self._plugin.rename_qos(tenant_id, id,
+                                          req_params['qos_name'])
 
             builder = qos_view.get_view_builder(request)
             result = builder.build(qos, True)
index eb3ffba84d7f8b9f21e29ad691852074d3e6c4fc..938e1ce6e07bb73119faba6621deb767fc254691 100644 (file)
 #    under the License.
 # @author: Somik Behera, Nicira Networks, Inc.
 
-
 """
 Quantum's Manager class is responsible for parsing a config file and
 instantiating the correct plugin that concretely implement quantum_plugin_base
 class.
 The caller should make sure that QuantumManager is a singleton.
 """
-import gettext
+
 import logging
 import os
 
-gettext.install('quantum', unicode=1)
-
 from quantum.common import utils
 from quantum.common.config import find_config_file
 from quantum.common.exceptions import ClassNotFound
-from quantum_plugin_base import QuantumPluginBase
+from quantum.quantum_plugin_base import QuantumPluginBase
+
 
 LOG = logging.getLogger('quantum.manager')
+
+
 CONFIG_FILE = "plugins.ini"
-LOG = logging.getLogger('quantum.manager')
 
 
 def find_config(basepath):
@@ -61,23 +60,23 @@ class QuantumManager(object):
         self.configuration_file = find_config_file(options, config_file,
                                                    CONFIG_FILE)
         if not 'plugin_provider' in options:
-            options['plugin_provider'] = \
-                utils.get_plugin_from_config(self.configuration_file)
+            options['plugin_provider'] = utils.get_plugin_from_config(
+                self.configuration_file)
         LOG.debug("Plugin location:%s", options['plugin_provider'])
 
         # If the plugin can't be found let them know gracefully
         try:
             plugin_klass = utils.import_class(options['plugin_provider'])
         except ClassNotFound:
-            raise Exception("Plugin not found.  You can install a " \
-                            "plugin with: pip install <plugin-name>\n" \
+            raise Exception("Plugin not found.  You can install a "
+                            "plugin with: pip install <plugin-name>\n"
                             "Example: pip install quantum-sample-plugin")
 
         if not issubclass(plugin_klass, QuantumPluginBase):
-            raise Exception("Configured Quantum plug-in " \
+            raise Exception("Configured Quantum plug-in "
                             "didn't pass compatibility test")
         else:
-            LOG.debug("Successfully imported Quantum plug-in." \
+            LOG.debug("Successfully imported Quantum plug-in."
                       "All compatibility tests passed")
         self.plugin = plugin_klass()
 
index 09b3fab896818e475990cc06e881e6781483f01e..db695fb0afb5d6a63f051006fba6aae6297a7414 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,4 +16,3 @@
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
index 09b3fab896818e475990cc06e881e6781483f01e..833357b735faf310ecf9ae934c41a0619555dd5f 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,5 +15,3 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
index ab22e8c8d2af241ac895df604ee65d8e751df37b..7477eacfb60a0a323da0ed597a4f33668de096c4 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 # Cisco adaptation for extensions
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
 
-import gettext
 import logging
 import logging.handlers
+from optparse import OptionParser
 import os
 import sys
 import subprocess
 
-from optparse import OptionParser
-
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantumclient import Client
 import quantumclient.cli as qcli
 
 
-gettext.install('quantum', unicode=1)
+LOG = logging.getLogger('quantum')
 
 
-LOG = logging.getLogger('quantum')
 FORMAT = 'json'
 ACTION_PREFIX_EXT = '/v1.0'
 ACTION_PREFIX_CSCO = ACTION_PREFIX_EXT + \
@@ -58,8 +52,8 @@ def help():
     """Help for CLI"""
     print "\nCisco Extension Commands:"
     for key in COMMANDS.keys():
-        print "    %s %s" % (key,
-          " ".join(["<%s>" % y for y in COMMANDS[key]["args"]]))
+        print "    %s %s" % (
+            key, " ".join(["<%s>" % y for y in COMMANDS[key]["args"]]))
 
 
 def build_args(cmd, cmdargs, arglist):
@@ -72,15 +66,15 @@ def build_args(cmd, cmdargs, arglist):
             del arglist[0]
     except:
         LOG.error("Not enough arguments for \"%s\" (expected: %d, got: %d)" % (
-          cmd, len(cmdargs), len(orig_arglist)))
-        print "Usage:\n    %s %s" % (cmd,
-          " ".join(["<%s>" % y for y in COMMANDS[cmd]["args"]]))
+            cmd, len(cmdargs), len(orig_arglist)))
+        print "Usage:\n    %s %s" % (
+            cmd, " ".join(["<%s>" % y for y in COMMANDS[cmd]["args"]]))
         sys.exit()
     if len(arglist) > 0:
         LOG.error("Too many arguments for \"%s\" (expected: %d, got: %d)" % (
-          cmd, len(cmdargs), len(orig_arglist)))
-        print "Usage:\n    %s %s" % (cmd,
-          " ".join(["<%s>" % y for y in COMMANDS[cmd]["args"]]))
+            cmd, len(cmdargs), len(orig_arglist)))
+        print "Usage:\n    %s %s" % (
+            cmd, " ".join(["<%s>" % y for y in COMMANDS[cmd]["args"]]))
         sys.exit()
     return args
 
@@ -98,12 +92,15 @@ def schedule_host(tenant_id, instance_id, user_id=None):
     """Gets the host name from the Quantum service"""
     project_id = tenant_id
 
-    instance_data_dict = \
-            {'novatenant': \
-             {'instance_id': instance_id,
-              'instance_desc': \
-              {'user_id': user_id,
-               'project_id': project_id}}}
+    instance_data_dict = {
+        'novatenant': {
+            'instance_id': instance_id,
+            'instance_desc': {
+                'user_id': user_id,
+                'project_id': project_id,
+                },
+            },
+        }
 
     request_url = "/novatenants/" + project_id + "/schedule_host"
     client = Client(HOST, PORT, USE_SSL, format='json', tenant=TENANT_ID,
@@ -112,8 +109,8 @@ def schedule_host(tenant_id, instance_id, user_id=None):
 
     hostname = data["host_list"]["host_1"]
     if not hostname:
-        print("Scheduler was unable to locate a host" + \
-              " for this request. Is the appropriate" + \
+        print("Scheduler was unable to locate a host"
+              " for this request. Is the appropriate"
               " service running?")
 
     print("Quantum service returned host: %s" % hostname)
@@ -122,7 +119,7 @@ def schedule_host(tenant_id, instance_id, user_id=None):
 def create_multiport(tenant_id, net_id_list, *args):
     """Creates ports on a single host"""
     net_list = net_id_list.split(",")
-    ports_info = {'multiport': \
+    ports_info = {'multiport':
                   {'status': 'ACTIVE',
                    'net_id_list': net_list,
                    'ports_desc': {'key': 'value'}}}
@@ -136,16 +133,20 @@ def create_multiport(tenant_id, net_id_list, *args):
 
 
 COMMANDS = {
-  "create_multiport": {
-    "func": create_multiport,
-    "args": ["tenant-id",
-             "net-id-list (comma separated list of netword IDs)"]},
-  "list_extensions": {
-    "func": list_extensions,
-    "args": []},
-  "schedule_host": {
-    "func": schedule_host,
-    "args": ["tenant-id", "instance-id"]}, }
+    "create_multiport": {
+        "func": create_multiport,
+        "args": ["tenant-id",
+                 "net-id-list (comma separated list of netword IDs)"],
+        },
+    "list_extensions": {
+        "func": list_extensions,
+        "args": [],
+        },
+    "schedule_host": {
+        "func": schedule_host,
+        "args": ["tenant-id", "instance-id"],
+        },
+    }
 
 
 def main():
@@ -153,17 +154,20 @@ def main():
     usagestr = "Usage: %prog [OPTIONS] <command> [args]"
     PARSER = OptionParser(usage=usagestr)
     PARSER.add_option("-H", "--host", dest="host",
-      type="string", default="127.0.0.1", help="ip address of api host")
+                      type="string", default="127.0.0.1",
+                      help="ip address of api host")
     PARSER.add_option("-p", "--port", dest="port",
-      type="int", default=9696, help="api poort")
+                      type="int", default=9696, help="api poort")
     PARSER.add_option("-s", "--ssl", dest="ssl",
-      action="store_true", default=False, help="use ssl")
+                      action="store_true", default=False, help="use ssl")
     PARSER.add_option("-v", "--verbose", dest="verbose",
-      action="store_true", default=False, help="turn on verbose logging")
+                      action="store_true", default=False,
+                      help="turn on verbose logging")
     PARSER.add_option("-f", "--logfile", dest="logfile",
-      type="string", default="syslog", help="log file path")
-    PARSER.add_option('--version', default=DEFAULT_QUANTUM_VERSION,
-      help='Accepts 1.1 and 1.0, defaults to env[QUANTUM_VERSION].')
+                      type="string", default="syslog", help="log file path")
+    PARSER.add_option(
+        '--version', default=DEFAULT_QUANTUM_VERSION,
+        help='Accepts 1.1 and 1.0, defaults to env[QUANTUM_VERSION].')
     options, args = PARSER.parse_args()
 
     if options.verbose:
index 09b3fab896818e475990cc06e881e6781483f01e..833357b735faf310ecf9ae934c41a0619555dd5f 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,5 +15,3 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
index a96513787f7952d8428b188ab7b8df0813207cc7..2d8de9ce5f00c62493ade7b9dd96c25bf77e3db2 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 from configobj import ConfigObj
+
 from quantum.plugins.cisco.common import cisco_constants as const
 
 
index 18b31a5a1c228dd0fe789ad83bc137591bbb14cc..696dc17ebc0cff1be34a71a55e11a01ce804c8fe 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,7 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
+
 
 PLUGINS = 'PLUGINS'
 INVENTORY = 'INVENTORY'
index 9d5e587864e594628139df3c12da9a1509f981e0..71c09ce0e4aa4681312df241bcf68298fad31dce 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,6 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 import os
 import logging as LOG
@@ -28,11 +25,12 @@ from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_exceptions as cexc
 from quantum.plugins.cisco.db import l2network_db as cdb
 
+
 LOG.basicConfig(level=LOG.WARN)
 LOG.getLogger(const.LOGGER_COMPONENT_NAME)
 
 CREDENTIALS_FILE = find_config_file({'plugin': 'cisco'}, None,
-                                     "credentials.ini")
+                                    "credentials.ini")
 TENANT = const.NETWORK_ADMIN
 
 cp = confp.CiscoConfigParser(CREDENTIALS_FILE)
index cc775cf46520712726ab85fc08e08fe83fbffd3d..f5a717274b0f2aa4638f6f0898a1c986576f4915 100644 (file)
 """
 Exceptions used by the Cisco plugin
 """
+
 from quantum.common import exceptions
 
 
 class NoMoreNics(exceptions.QuantumException):
     """No more dynamic nics are available in the system"""
-    message = _("Unable to complete operation. No more dynamic nics are " \
+    message = _("Unable to complete operation. No more dynamic nics are "
                  "available in the system.")
 
 
 class PortProfileLimit(exceptions.QuantumException):
     """Port profile limit has been hit"""
-    message = _("Unable to complete operation on port %(port_id)s " \
-                "for network %(net_id)s. The system has reached the maximum" \
+    message = _("Unable to complete operation on port %(port_id)s "
+                "for network %(net_id)s. The system has reached the maximum"
                 "limit of allowed port profiles.")
 
 
 class UCSMPortProfileLimit(exceptions.QuantumException):
     """UCSM Port profile limit has been hit"""
-    message = _("Unable to complete operation on port %(port_id)s " \
-                "for network %(net_id)s. The system has reached the maximum" \
+    message = _("Unable to complete operation on port %(port_id)s "
+                "for network %(net_id)s. The system has reached the maximum"
                 "limit of allowed UCSM port profiles.")
 
 
 class NetworksLimit(exceptions.QuantumException):
     """Total number of network objects limit has been hit"""
-    message = _("Unable to create new network. Number of networks" \
+    message = _("Unable to create new network. Number of networks"
                 "for the system has exceeded the limit")
 
 
 class PortProfileNotFound(exceptions.QuantumException):
     """Port profile cannot be found"""
-    message = _("Port profile %(portprofile_id)s could not be found " \
+    message = _("Port profile %(portprofile_id)s could not be found "
                 "for tenant %(tenant_id)s")
 
 
 class MultiportNotFound(exceptions.QuantumException):
     """Multiport cannot be found"""
-    message = _("Multiports %(port_id)s could not be found " \
+    message = _("Multiports %(port_id)s could not be found "
                 "for tenant %(tenant_id)s")
 
 
 class PortProfileInvalidDelete(exceptions.QuantumException):
     """Port profile cannot be deleted since its being used"""
-    message = _("Port profile %(profile_id)s could not be deleted " \
+    message = _("Port profile %(profile_id)s could not be deleted "
                 "for tenant %(tenant_id)s since port associations exist")
 
 
 class NetworkVlanBindingAlreadyExists(exceptions.QuantumException):
     """Binding cannot be created, since it already exists"""
-    message = _("NetworkVlanBinding for %(vlan_id)s and network " \
+    message = _("NetworkVlanBinding for %(vlan_id)s and network "
                 "%(network_id)s already exists")
 
 
 class PortProfileAlreadyExists(exceptions.QuantumException):
     """Port profile cannot be created since it already exisits"""
-    message = _("PortProfile %(pp_name) for %(tenant_id)s " \
+    message = _("PortProfile %(pp_name) for %(tenant_id)s "
                 "already exists")
 
 
 class PortProfileBindingAlreadyExists(exceptions.QuantumException):
     """Binding cannot be created, since it already exists"""
-    message = _("PortProfileBinding for port profile %(pp_id)s to " \
+    message = _("PortProfileBinding for port profile %(pp_id)s to "
                  "port %(port_id) already exists")
 
 
@@ -97,37 +98,37 @@ class VlanIDNotAvailable(exceptions.QuantumException):
 
 class QosNotFound(exceptions.QuantumException):
     """QoS level with this ID cannot be found"""
-    message = _("QoS level %(qos_id)s could not be found " \
+    message = _("QoS level %(qos_id)s could not be found "
                 "for tenant %(tenant_id)s")
 
 
 class QoSLevelInvalidDelete(exceptions.QuantumException):
     """QoS is associated with a port profile, hence cannot be deleted"""
-    message = _("QoS level %(qos_id)s could not be deleted " \
+    message = _("QoS level %(qos_id)s could not be deleted "
                 "for tenant %(tenant_id)s since association exists")
 
 
 class QosNameAlreadyExists(exceptions.QuantumException):
     """QoS Name already exists"""
-    message = _("QoS level with name %(qos_name)s already exists " \
+    message = _("QoS level with name %(qos_name)s already exists "
                 "for tenant %(tenant_id)s")
 
 
 class CredentialNotFound(exceptions.QuantumException):
     """Credential with this ID cannot be found"""
-    message = _("Credential %(credential_id)s could not be found " \
+    message = _("Credential %(credential_id)s could not be found "
                 "for tenant %(tenant_id)s")
 
 
 class CredentialNameNotFound(exceptions.QuantumException):
     """Credential Name could not be found"""
-    message = _("Credential %(credential_name)s could not be found " \
+    message = _("Credential %(credential_name)s could not be found "
                 "for tenant %(tenant_id)s")
 
 
 class CredentialAlreadyExists(exceptions.QuantumException):
     """Credential ID already exists"""
-    message = _("Credential %(credential_id)s already exists " \
+    message = _("Credential %(credential_id)s already exists "
                 "for tenant %(tenant_id)s")
 
 
@@ -177,23 +178,8 @@ class PortVnicNotFound(exceptions.QuantumException):
 
 
 class InvalidAttach(exceptions.QuantumException):
-    message = _("Unable to plug the attachment %(att_id)s into port " \
-                "%(port_id)s for network %(net_id)s. Association of " \
-                "attachment ID with port ID happens implicitly when " \
-                "VM is instantiated; attach operation can be " \
+    message = _("Unable to plug the attachment %(att_id)s into port "
+                "%(port_id)s for network %(net_id)s. Association of "
+                "attachment ID with port ID happens implicitly when "
+                "VM is instantiated; attach operation can be "
                 "performed subsequently.")
-
-
-try:
-    _("test")
-except NameError:
-
-    def _(a_string):
-        """
-        Default implementation of the gettext string
-        translation function: no translation
-        """
-        return a_string
-except TypeError:
-    # during doctesting, _ might mean something else
-    pass
index b97b4330deebf0dbcb7eae5f76031f8e6278002c..f5e94408104cf191bf797fee899d8841c25df840 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,7 @@
 #    under the License.
 #
 # @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
+
 import webob.dec
 
 from quantum import wsgi
@@ -73,7 +71,7 @@ class PortprofileNotFound(webob.exc.HTTPClientError):
     code = 450
     title = 'Portprofile Not Found'
     explanation = ('Unable to find a Portprofile with'
-                   ' the specified identifier.')
+                   ' the specified identifier.')
 
 
 class PortNotFound(webob.exc.HTTPClientError):
@@ -102,7 +100,7 @@ class CredentialNotFound(webob.exc.HTTPClientError):
     code = 451
     title = 'Credential Not Found'
     explanation = ('Unable to find a Credential with'
-                   ' the specified identifier.')
+                   ' the specified identifier.')
 
 
 class QosNotFound(webob.exc.HTTPClientError):
@@ -117,7 +115,7 @@ class QosNotFound(webob.exc.HTTPClientError):
     code = 452
     title = 'QoS Not Found'
     explanation = ('Unable to find a QoS with'
-                   ' the specified identifier.')
+                   ' the specified identifier.')
 
 
 class NovatenantNotFound(webob.exc.HTTPClientError):
@@ -132,7 +130,7 @@ class NovatenantNotFound(webob.exc.HTTPClientError):
     code = 453
     title = 'Nova tenant Not Found'
     explanation = ('Unable to find a Novatenant with'
-                   ' the specified identifier.')
+                   ' the specified identifier.')
 
 
 class MultiportNotFound(webob.exc.HTTPClientError):
@@ -147,7 +145,7 @@ class MultiportNotFound(webob.exc.HTTPClientError):
     code = 454
     title = 'Multiport Not Found'
     explanation = ('Unable to find Multiport with'
-                   ' the specified identifier.')
+                   ' the specified identifier.')
 
 
 class RequestedStateInvalid(webob.exc.HTTPClientError):
index ba6b07e3b1876292fc170e30781f0bb3b500ebda..32a73a91a581bc13a303d8d3f284fcbb8348ba5e 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 import hashlib
 import logging
-import MySQLdb
 import traceback
 
+import MySQLdb
+
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
 
+
 LOG = logging.getLogger(__name__)
 
 
index f2a3c9d9239ba40f9f1fa3ec664554cbeb44e501..f0c2ec5814da5345511a7cfeb2346b0de7b3f13f 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
-import inspect
 from abc import ABCMeta, abstractmethod
+import inspect
 
 
 class L2NetworkDeviceInventoryBase(object):
index defd7d2e99832df774d75787b099f0f059bd86a1..46ef83ebe1b93e50ada0ad5966f4ce23d95eddca 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
-import inspect
 from abc import ABCMeta, abstractmethod
+import inspect
 
 
 class L2DevicePluginBase(object):
index 7d03a3cd9760efafc9a051e47530b68f0e62bef6..2322eab086918564f04ede6caccbabecb83b68f6 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
-import inspect
 from abc import ABCMeta, abstractmethod
+import inspect
 
 
 class L2NetworkModelBase(object):
index 5e4e39198d6121ea19b67139265b3ef333c2f94f..0a7e115a27782565f78c1a8c0fc678abb60ac29c 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,6 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 import inspect
 import logging
@@ -26,7 +23,6 @@ import re
 from quantum.common import exceptions as exc
 from quantum.common import utils
 from quantum.quantum_plugin_base import QuantumPluginBase
-
 from quantum.plugins.cisco import l2network_plugin_configuration as conf
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_credentials as cred
@@ -35,6 +31,7 @@ from quantum.plugins.cisco.common import cisco_utils as cutil
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
 
+
 LOG = logging.getLogger(__name__)
 
 
@@ -83,8 +80,8 @@ class L2Network(QuantumPluginBase):
         vlan_id = self._get_vlan_for_tenant(tenant_id, net_name)
         vlan_name = self._get_vlan_name(new_net_id, str(vlan_id))
         self._invoke_device_plugins(self._func_name(), [tenant_id, net_name,
-                                                     new_net_id, vlan_name,
-                                                     vlan_id])
+                                                        new_net_id, vlan_name,
+                                                        vlan_id])
         cdb.add_vlan_binding(vlan_id, vlan_name, new_net_id)
         new_net_dict = {const.NET_ID: new_net_id,
                         const.NET_NAME: net_name,
@@ -137,8 +134,8 @@ class L2Network(QuantumPluginBase):
             ports_on_net.append(new_port)
 
         new_network = cutil.make_net_dict(network[const.UUID],
-                                              network[const.NETWORKNAME],
-                                              ports_on_net)
+                                          network[const.NETWORKNAME],
+                                          ports_on_net)
 
         return new_network
 
@@ -151,7 +148,7 @@ class L2Network(QuantumPluginBase):
         db.validate_network_ownership(tenant_id, net_id)
         network = db.network_update(net_id, tenant_id, **kwargs)
         self._invoke_device_plugins(self._func_name(), [tenant_id, net_id,
-                                                     kwargs])
+                                                        kwargs])
         net_dict = cutil.make_net_dict(network[const.UUID],
                                        network[const.NETWORKNAME],
                                        [])
@@ -187,8 +184,8 @@ class L2Network(QuantumPluginBase):
         port = db.port_create(net_id, port_state)
         unique_port_id_string = port[const.UUID]
         self._invoke_device_plugins(self._func_name(), [tenant_id, net_id,
-                                                     port_state,
-                                                     unique_port_id_string])
+                                                        port_state,
+                                                        unique_port_id_string])
         new_port_dict = cutil.make_port_dict(port[const.UUID],
                                              port[const.PORTSTATE],
                                              port[const.NETWORKID],
@@ -226,7 +223,7 @@ class L2Network(QuantumPluginBase):
         db.validate_port_ownership(tenant_id, net_id, port_id)
         network = db.network_get(net_id)
         self._invoke_device_plugins(self._func_name(), [tenant_id, net_id,
-                                        port_id, kwargs])
+                                                        port_id, kwargs])
         self._validate_port_state(kwargs["state"])
         db.port_update(port_id, net_id, **kwargs)
 
@@ -243,7 +240,7 @@ class L2Network(QuantumPluginBase):
         db.validate_port_ownership(tenant_id, net_id, port_id)
         network = db.network_get(net_id)
         self._invoke_device_plugins(self._func_name(), [tenant_id, net_id,
-                                                     port_id])
+                                                        port_id])
         port = db.port_get(net_id, port_id)
         new_port_dict = cutil.make_port_dict(port[const.UUID],
                                              port[const.PORTSTATE],
@@ -264,7 +261,7 @@ class L2Network(QuantumPluginBase):
         attachment_id = port[const.INTERFACEID]
         if attachment_id is None:
             raise cexc.InvalidAttach(port_id=port_id, net_id=net_id,
-                                    att_id=remote_interface_id)
+                                     att_id=remote_interface_id)
         attachment_id = attachment_id[:const.UUID_LENGTH]
         remote_interface_id = remote_interface_id[:const.UUID_LENGTH]
         if remote_interface_id != attachment_id:
@@ -295,7 +292,7 @@ class L2Network(QuantumPluginBase):
             raise exc.InvalidDetach(port_id=port_id, net_id=net_id,
                                     att_id=remote_interface_id)
         self._invoke_device_plugins(self._func_name(), [tenant_id, net_id,
-                                                     port_id])
+                                                        port_id])
         attachment_id = attachment_id[:const.UUID_LENGTH]
         attachment_id = attachment_id + const.UNPLUGGED
         db.port_unset_attachment(net_id, port_id)
@@ -337,7 +334,7 @@ class L2Network(QuantumPluginBase):
         """Create port profile"""
         LOG.debug("create_portprofile() called\n")
         portprofile = cdb.add_portprofile(tenant_id, profile_name,
-                                 const.NO_VLAN_ID, qos)
+                                          const.NO_VLAN_ID, qos)
         new_pp = cutil.make_portprofile_dict(tenant_id,
                                              portprofile[const.UUID],
                                              portprofile[const.PPNAME],
@@ -491,9 +488,10 @@ class L2Network(QuantumPluginBase):
     def schedule_host(self, tenant_id, instance_id, instance_desc):
         """Provides the hostname on which a dynamic vnic is reserved"""
         LOG.debug("schedule_host() called\n")
-        host_list = self._invoke_device_plugins(self._func_name(), [tenant_id,
-                                                               instance_id,
-                                                               instance_desc])
+        host_list = self._invoke_device_plugins(self._func_name(),
+                                                [tenant_id,
+                                                 instance_id,
+                                                 instance_desc])
         return host_list
 
     def associate_port(self, tenant_id, instance_id, instance_desc):
index 5d4f19e62115b659ed154eb88c539638e2e7a85e..f6a107f8e45dfddc0623454e5ac5d5b9ac7be1e1 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 # @author: Rohit Agarwalla, Cisco Systems, Inc.
-"""
 
 import os
+
 from quantum.common.config import find_config_file
 from quantum.plugins.cisco.common import cisco_configparser as confp
 
+
 CONF_FILE = find_config_file({'plugin': 'cisco'}, None, "l2network_plugin.ini")
 CONF_PARSER_OBJ = confp.CiscoConfigParser(CONF_FILE)
 
-"""
-Reading the conf for the l2network_plugin
-"""
+
+# Read the conf for the l2network_plugin
 SECTION_CONF = CONF_PARSER_OBJ['VLANS']
 VLAN_NAME_PREFIX = SECTION_CONF['vlan_name_prefix']
 VLAN_START = SECTION_CONF['vlan_start']
@@ -54,18 +53,16 @@ MANAGER_CLASS = SECTION_CONF['manager_class']
 
 CONF_PARSER_OBJ = confp.CiscoConfigParser(CONF_FILE)
 
-"""
-Reading the config for the device plugins
-"""
+
+# Read the config for the device plugins
 PLUGINS = CONF_PARSER_OBJ.walk(CONF_PARSER_OBJ.dummy)
 
 CONF_FILE = find_config_file({'plugin': 'cisco'}, None, "db_conn.ini")
 
 CONF_PARSER_OBJ = confp.CiscoConfigParser(CONF_FILE)
 
-"""
-Reading DB config for the Quantum DB
-"""
+
+# Read DB config for the Quantum DB
 SECTION_CONF = CONF_PARSER_OBJ['DATABASE']
 DB_NAME = SECTION_CONF['name']
 DB_USER = SECTION_CONF['user']
index 081d50fdfb5070d112eb20f595dfc13eb459b907..7cc349712ca078934b271f3edf330c32f2162df3 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
-import inspect
 from abc import ABCMeta, abstractmethod
+import inspect
 
 
 class L2NetworkSegmentationMgrBase(object):
index 09b3fab896818e475990cc06e881e6781483f01e..833357b735faf310ecf9ae934c41a0619555dd5f 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,5 +15,3 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
index ce2e5d8088e0dbc9efeae9b4dd4590ba2887124a..219d75c9ab8d8dfbad11c036a9f19ded3d7c9fa7 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,6 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 from copy import deepcopy
 import inspect
@@ -31,6 +28,7 @@ from quantum.plugins.cisco import l2network_plugin_configuration as conf
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_exceptions as cexc
 
+
 LOG = logging.getLogger(__name__)
 
 
@@ -49,13 +47,13 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
         for key in conf.PLUGINS[const.PLUGINS].keys():
             self._plugins[key] = utils.import_object(
                 conf.PLUGINS[const.PLUGINS][key])
-            LOG.debug("Loaded device plugin %s\n" % \
-                    conf.PLUGINS[const.PLUGINS][key])
+            LOG.debug("Loaded device plugin %s\n" %
+                      conf.PLUGINS[const.PLUGINS][key])
             if key in conf.PLUGINS[const.INVENTORY].keys():
                 self._inventory[key] = utils.import_object(
                     conf.PLUGINS[const.INVENTORY][key])
-                LOG.debug("Loaded device inventory %s\n" % \
-                        conf.PLUGINS[const.INVENTORY][key])
+                LOG.debug("Loaded device inventory %s\n" %
+                          conf.PLUGINS[const.INVENTORY][key])
 
     def _func_name(self, offset=0):
         """Get the name of the calling function"""
@@ -65,8 +63,8 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
         """Invoke only device plugin for all the devices in the system"""
         if not plugin_key in self._plugins.keys():
             LOG.info("No %s Plugin loaded" % plugin_key)
-            LOG.info("%s: %s with args %s ignored" \
-                     (plugin_key, function_name, args))
+            LOG.info("%s: %s with args %s ignored" %
+                     (plugin_key, function_name, args))
             return
         device_params = self._invoke_inventory(plugin_key, function_name,
                                                args)
@@ -74,7 +72,7 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
         if not device_ips:
             # Return in a list
             return [self._invoke_plugin(plugin_key, function_name, args,
-                                device_params)]
+                                        device_params)]
         else:
             # Return a list of return values from each device
             output = []
@@ -82,15 +80,15 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
                 new_device_params = deepcopy(device_params)
                 new_device_params[const.DEVICE_IP] = device_ip
                 output.append(self._invoke_plugin(plugin_key, function_name,
-                                args, new_device_params))
+                                                  args, new_device_params))
             return output
 
     def _invoke_inventory(self, plugin_key, function_name, args):
         """Invoke only the inventory implementation"""
         if not plugin_key in self._inventory.keys():
             LOG.warn("No %s inventory loaded" % plugin_key)
-            LOG.warn("%s: %s with args %s ignored" \
-                     (plugin_key, function_name, args))
+            LOG.warn("%s: %s with args %s ignored" %
+                     (plugin_key, function_name, args))
             return {const.DEVICE_IP: []}
         else:
             return getattr(self._inventory[plugin_key], function_name)(args)
@@ -101,8 +99,7 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
 
         # If there are more args than needed, add them to kwargs
         args_copy = deepcopy(args)
-        if args.__len__() + 1 > \
-           inspect.getargspec(func).args.__len__():
+        if (args.__len__() + 1) > inspect.getargspec(func).args.__len__():
             kwargs.update(args_copy.pop())
 
         return func(*args_copy, **kwargs)
@@ -115,9 +112,9 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
         """Support for the Quantum core API call"""
         output = []
         ucs_output = self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                       self._func_name(), args)
+                                                    self._func_name(), args)
         nexus_output = self._invoke_plugin_per_device(const.NEXUS_PLUGIN,
-                                       self._func_name(), args)
+                                                      self._func_name(), args)
         output.extend(ucs_output or [])
         output.extend(nexus_output or [])
         return output
@@ -126,9 +123,9 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
         """Support for the Quantum core API call"""
         output = []
         ucs_output = self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                       self._func_name(), args)
+                                                    self._func_name(), args)
         nexus_output = self._invoke_plugin_per_device(const.NEXUS_PLUGIN,
-                                       self._func_name(), args)
+                                                      self._func_name(), args)
         output.extend(ucs_output or [])
         output.extend(nexus_output or [])
         return output
@@ -141,9 +138,9 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
         """Support for the Quantum core API call"""
         output = []
         ucs_output = self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                       self._func_name(), args)
+                                                    self._func_name(), args)
         nexus_output = self._invoke_plugin_per_device(const.NEXUS_PLUGIN,
-                                       self._func_name(), args)
+                                                      self._func_name(), args)
         output.extend(ucs_output or [])
         output.extend(nexus_output or [])
         return output
@@ -155,12 +152,12 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
     def create_port(self, args):
         """Support for the Quantum core API call"""
         return self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                       self._func_name(), args)
+                                              self._func_name(), args)
 
     def delete_port(self, args):
         """Support for the Quantum core API call"""
         return self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                        self._func_name(), args)
+                                              self._func_name(), args)
 
     def update_port(self, args):
         """Not implemented for this model"""
@@ -173,12 +170,12 @@ class L2NetworkMultiBlade(L2NetworkModelBase):
     def plug_interface(self, args):
         """Support for the Quantum core API call"""
         return self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                        self._func_name(), args)
+                                              self._func_name(), args)
 
     def unplug_interface(self, args):
         """Support for the Quantum core API call"""
         return self._invoke_plugin_per_device(const.UCS_PLUGIN,
-                                        self._func_name(), args)
+                                              self._func_name(), args)
 
     def schedule_host(self, args):
         """Provides the hostname on which a dynamic vnic is reserved"""
index 93958561584098a9051a5b52ed3c80f417ae327c..d6567d3b4993554340836837112f32c6204f1928 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,6 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 from copy import deepcopy
 import inspect
@@ -31,6 +28,7 @@ from quantum.plugins.cisco import l2network_plugin_configuration as conf
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_exceptions as cexc
 
+
 LOG = logging.getLogger(__name__)
 
 
@@ -46,13 +44,13 @@ class L2NetworkSingleBlade(L2NetworkModelBase):
         for key in conf.PLUGINS[const.PLUGINS].keys():
             self._plugins[key] = utils.import_object(
                 conf.PLUGINS[const.PLUGINS][key])
-            LOG.debug("Loaded device plugin %s\n" % \
-                    conf.PLUGINS[const.PLUGINS][key])
+            LOG.debug("Loaded device plugin %s\n" %
+                      conf.PLUGINS[const.PLUGINS][key])
             if key in conf.PLUGINS[const.INVENTORY].keys():
                 self._inventory[key] = utils.import_object(
                     conf.PLUGINS[const.INVENTORY][key])
-                LOG.debug("Loaded device inventory %s\n" % \
-                        conf.PLUGINS[const.INVENTORY][key])
+                LOG.debug("Loaded device inventory %s\n" %
+                          conf.PLUGINS[const.INVENTORY][key])
 
     def _func_name(self, offset=0):
         """Get the name of the calling function"""
@@ -62,8 +60,8 @@ class L2NetworkSingleBlade(L2NetworkModelBase):
         """Invoke only device plugin for all the devices in the system"""
         if not plugin_key in self._plugins.keys():
             LOG.info("No %s Plugin loaded" % plugin_key)
-            LOG.info("%s: %s with args %s ignored" \
-                     (plugin_key, function_name, args))
+            LOG.info("%s: %s with args %s ignored" %
+                     (plugin_key, function_name, args))
             return
         device_params = self._invoke_inventory(plugin_key, function_name,
                                                args)
@@ -82,8 +80,8 @@ class L2NetworkSingleBlade(L2NetworkModelBase):
         """Invoke only the inventory implementation"""
         if not plugin_key in self._inventory.keys():
             LOG.warn("No %s inventory loaded" % plugin_key)
-            LOG.warn("%s: %s with args %s ignored" \
-                     (plugin_key, function_name, args))
+            LOG.warn("%s: %s with args %s ignored" %
+                     (plugin_key, function_name, args))
             return {const.DEVICE_IP: []}
         else:
             return getattr(self._inventory[plugin_key], function_name)(args)
index 9fd5d5de470e38bdade81b325b5dcbf32347294c..58b183ae88765dbf9d2164cd1aeb72fa5c77059d 100644 (file)
@@ -27,6 +27,7 @@ import os
 from quantum.common.config import find_config_file
 from quantum.plugins.cisco.common import cisco_configparser as confp
 
+
 CP = confp.CiscoConfigParser(find_config_file({'plugin': 'cisco'}, None,
                              "nexus.ini"))
 
index e2cb38b3aa0c12864a76175837f1a85dd4c903e0..a90441e3ddea32fc775d4c709c3620ae817b27a1 100644 (file)
@@ -23,11 +23,12 @@ Implements a Nexus-OS NETCONF over SSHv2 API Client
 
 import logging
 
+from ncclient import manager
+
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.db import l2network_db as cdb
 from quantum.plugins.cisco.nexus import cisco_nexus_snippets as snipp
 
-from ncclient import manager
 
 LOG = logging.getLogger(__name__)
 
@@ -45,7 +46,7 @@ class CiscoNEXUSDriver():
         Makes the SSH connection to the Nexus Switch
         """
         man = manager.connect(host=nexus_host, port=nexus_ssh_port,
-                                username=nexus_user, password=nexus_password)
+                              username=nexus_user, password=nexus_password)
         return man
 
     def create_xml_snippet(self, cutomized_config):
index e0d9775c3dec665cfb4a023ba0963cffa1d186cc..36e1394a860e0fe615fd2b63761640e12fd56c10 100644 (file)
@@ -32,6 +32,7 @@ from quantum.plugins.cisco.db import nexus_db as nxos_db
 from quantum.plugins.cisco.l2device_plugin_base import L2DevicePluginBase
 from quantum.plugins.cisco.nexus import cisco_nexus_configuration as conf
 
+
 LOG = logging.getLogger(__name__)
 
 
@@ -70,10 +71,11 @@ class NexusPlugin(L2DevicePluginBase):
         for this VLAN
         """
         LOG.debug("NexusPlugin:create_network() called\n")
-        self._client.create_vlan(vlan_name, str(vlan_id), self._nexus_ip,
-                self._nexus_username, self._nexus_password,
-                self._nexus_first_port, self._nexus_second_port,
-                self._nexus_ssh_port)
+        self._client.create_vlan(
+            vlan_name, str(vlan_id), self._nexus_ip,
+            self._nexus_username, self._nexus_password,
+            self._nexus_first_port, self._nexus_second_port,
+            self._nexus_ssh_port)
         nxos_db.add_nexusport_binding(self._nexus_first_port, str(vlan_id))
         nxos_db.add_nexusport_binding(self._nexus_second_port, str(vlan_id))
 
@@ -97,7 +99,8 @@ class NexusPlugin(L2DevicePluginBase):
         nxos_db.remove_nexusport_binding(vlan_id)
         net = self._get_network(tenant_id, net_id)
         if net:
-            self._client.delete_vlan(str(vlan_id), self._nexus_ip,
+            self._client.delete_vlan(
+                str(vlan_id), self._nexus_ip,
                 self._nexus_username, self._nexus_password,
                 self._nexus_first_port, self._nexus_second_port,
                 self._nexus_ssh_port)
index 18b1f7cd8f77f26c10948706e7a969604e2ed84c..72f7f37110795b89157c064d2f21ff45faaa0fa3 100644 (file)
@@ -24,6 +24,7 @@ import logging
 
 from quantum.plugins.cisco.common import cisco_constants as const
 
+
 LOG = logging.getLogger(__name__)
 
 
index 53543b2da2a2650e48a07736e3632b709e6e7bc5..3cb4440ed87e961ddf6603b90eab53b0aa1c3f4b 100644 (file)
@@ -26,13 +26,14 @@ from nova import exception as excp
 from nova import flags
 from nova import log as logging
 from nova.openstack.common import cfg
-from nova.scheduler import driver
 from nova.scheduler import chance
-from quantum.client import Client
+from nova.scheduler import driver
+from quantumclient import Client
 
 
 LOG = logging.getLogger(__name__)
 
+
 quantum_opts = [
     cfg.StrOpt('quantum_connection_host',
                default='127.0.0.1',
@@ -45,6 +46,7 @@ quantum_opts = [
                help='Default tenant id when creating quantum networks'),
     ]
 
+
 FLAGS = flags.FLAGS
 FLAGS.register_opts(quantum_opts)
 
@@ -88,17 +90,14 @@ class QuantumPortAwareScheduler(chance.ChanceScheduler):
         """Gets the host name from the Quantum service"""
         LOG.debug("Cisco Quantum Port-aware Scheduler is scheduling...")
         instance_id = request_spec['instance_properties']['uuid']
-        user_id = \
-                request_spec['instance_properties']['user_id']
-        project_id = \
-                request_spec['instance_properties']['project_id']
-
-        instance_data_dict = \
-                {'novatenant': \
-                 {'instance_id': instance_id,
-                  'instance_desc': \
-                  {'user_id': user_id,
-                   'project_id': project_id}}}
+        user_id = request_spec['instance_properties']['user_id']
+        project_id = request_spec['instance_properties']['project_id']
+
+        instance_data_dict = {'novatenant':
+                              {'instance_id': instance_id,
+                               'instance_desc':
+                               {'user_id': user_id,
+                                'project_id': project_id}}}
 
         client = Client(HOST, PORT, USE_SSL, format='json', version=VERSION,
                         uri_prefix=URI_PREFIX_CSCO, tenant=TENANT_ID,
@@ -109,8 +108,8 @@ class QuantumPortAwareScheduler(chance.ChanceScheduler):
         hostname = data["host_list"]["host_1"]
         if not hostname:
             raise excp.NoValidHost(_("Scheduler was unable to locate a host"
-                                       " for this request. Is the appropriate"
-                                       " service running?"))
+                                     " for this request. Is the appropriate"
+                                     " service running?"))
 
         LOG.debug(_("Quantum service returned host: %s") % hostname)
         return hostname
index 1554f9c3ee1c06d981bc0c87228b8b9efd9a2ce8..67a4148e60d96914e02ac8de75b918835d2dbc3d 100644 (file)
@@ -24,7 +24,7 @@ from nova import flags
 from nova import log as logging
 from nova.openstack.common import cfg
 from nova.virt.vif import VIFDriver
-from quantum.client import Client
+from quantumclient import Client
 
 
 LOG = logging.getLogger(__name__)
index b16843053dc8217fbb75fce901a1ff50b65f36fb..84e1313a6524a279a9fdfcb39c0a96dff8391d59 100644 (file)
@@ -26,9 +26,12 @@ export PLUGIN_DIR=quantum/plugins/cisco
 
 import os
 import sys
+
 from nose import config
+
 sys.path.append(os.getcwd())
 sys.path.append(os.path.dirname(__file__))
+
 from quantum.common.test_lib import run_tests, test_config
 import quantum.tests.unit
 
index 09b3fab896818e475990cc06e881e6781483f01e..db695fb0afb5d6a63f051006fba6aae6297a7414 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,4 +16,3 @@
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
index c60a1afd95debaf810ff9b3f9e9e223a72830b81..2e06fcab8a112857bb2fea1d71e5e0e6abd084e0 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
 
 import logging
 
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.db import l2network_db as cdb
-from quantum.plugins.cisco.l2network_segmentation_base \
-        import L2NetworkSegmentationMgrBase
+from quantum.plugins.cisco.l2network_segmentation_base import (
+    L2NetworkSegmentationMgrBase,
+    )
+
 
 LOG = logging.getLogger(__name__)
 
index a393cd16639d50149bcc0a3544a3c262bb4f1bc3..02aec9ffc2c70df97c3a8269e061939cb5593f65 100644 (file)
@@ -26,30 +26,29 @@ Currently has four functionalities:
 4. disconnect_vm <vm_instance_id>
 """
 
-
 import logging
 import logging.handlers
+from optparse import OptionParser
 import os
-import subprocess
 import re
+import subprocess
 import sys
 
-from optparse import OptionParser
-from quantum.client import Client
+from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as l2db
 from quantum.plugins.cisco.db import services_db as sdb
-from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.services import services_constants as servconts
 from quantum.plugins.cisco.services import services_logistics as servlogcs
+from quantumclient import Client
 
 
 LOG = logging.getLogger(__name__)
 
 
 def insert_inpath_service(tenant_id, service_image_id,
-             management_net_name, northbound_net_name,
-             southbound_net_name, *args):
+                          management_net_name, northbound_net_name,
+                          southbound_net_name, *args):
     """Inserting a network service between two networks"""
     print ("Creating Network for Services and Servers")
     service_logic = servlogcs.ServicesLogistics()
@@ -62,8 +61,8 @@ def insert_inpath_service(tenant_id, service_image_id,
         data = {servconts.NETWORK: {servconts.NAME: net}}
         net_list[net] = client.create_network(data)
         net_list[net][servconts.PORTS] = []
-        LOG.debug("Network %s Created with ID: %s " % (net, \
-                        net_list[net][servconts.NETWORK][servconts.ID]))
+        LOG.debug("Network %s Created with ID: %s " % (
+            net, net_list[net][servconts.NETWORK][servconts.ID]))
     print "Completed"
     print ("Creating Ports on Services and Server Networks")
     LOG.debug("Operation 'create_port' executed.")
@@ -82,8 +81,8 @@ def insert_inpath_service(tenant_id, service_image_id,
         for net in networks_name_list:
             port_id = data[servconts.PORTS][net_idx][servconts.ID]
             net_list[net][servconts.PORTS].append(port_id)
-            LOG.debug("Port UUID: %s on network: %s" % \
-                       (data[servconts.PORTS][net_idx][servconts.ID], net))
+            LOG.debug("Port UUID: %s on network: %s" %
+                      (data[servconts.PORTS][net_idx][servconts.ID], net))
             net_idx = net_idx + 1
     print "Completed"
     try:
@@ -110,9 +109,9 @@ def insert_inpath_service(tenant_id, service_image_id,
             port_id = net_list[net][servconts.PORTS][idx]
             attachment = client.show_port_attachment(network_id, port_id)
             attachment = attachment[servconts.ATTACHMENT][servconts.ID][:36]
-            LOG.debug("Plugging virtual interface: %s of VM %s \
-                            into port: %s on network: %s" %
-                            (attachment, service_vm_name, port_id, net))
+            LOG.debug(("Plugging virtual interface: %s of VM %s"
+                       "into port: %s on network: %s") %
+                      (attachment, service_vm_name, port_id, net))
             attach_data = {servconts.ATTACHMENT: {servconts.ID: '%s' %
                                                   attachment}}
             client.attach_resource(network_id, port_id, attach_data)
@@ -222,9 +221,9 @@ def connect_vm(tenant_id, vm_image_id, service_instance_id, *args):
     south_net = service_nets.sbnet_id
     attachment = client.show_port_attachment(south_net, new_port_id)
     attachment = attachment[servconts.ATTACHMENT][servconts.ID][:36]
-    LOG.debug("Plugging virtual interface: %s of VM %s \
-                into port: %s on network: %s" %
-                (attachment, vm_name, new_port_id, service_nets.sbnet_id))
+    LOG.debug(("Plugging virtual interface: %s of VM %s "
+               "into port: %s on network: %s") %
+              (attachment, vm_name, new_port_id, service_nets.sbnet_id))
     attach_data = {servconts.ATTACHMENT: {servconts.ID: '%s' % attachment}}
     client.attach_resource(service_nets.sbnet_id, new_port_id, attach_data)
     print ("Connect VM Ended")
@@ -232,13 +231,13 @@ def connect_vm(tenant_id, vm_image_id, service_instance_id, *args):
 
 def create_multiport(tenant_id, networks_list, *args):
     """Creates ports on a single host"""
-    ports_info = {'multiport': \
+    ports_info = {'multiport':
                   {'status': 'ACTIVE',
                    'net_id_list': networks_list,
                    'ports_desc': {'key': 'value'}}}
     request_url = "/multiport"
     client = Client(HOST, PORT, USE_SSL, format='json', tenant=tenant_id,
-                action_prefix=servconts.ACTION_PREFIX_CSCO)
+                    action_prefix=servconts.ACTION_PREFIX_CSCO)
     data = client.do_request('POST', request_url, body=ports_info)
     return data
 
@@ -252,36 +251,39 @@ def build_args(cmd, cmdargs, arglist):
             args.append(arglist[0])
             del arglist[0]
     except:
-        LOG.debug("Not enough arguments for \"%s\" (expected: %d, got: %d)"
-                  (cmd, len(cmdargs), len(orig_arglist)))
-        print "Service Insertion Usage:\n    %s %s" % (cmd,
-          " ".join(["<%s>" % y for y in SERVICE_COMMANDS[cmd]["args"]]))
+        LOG.debug("Not enough arguments for \"%s\" (expected: %d, got: %d)" %
+                  (cmd, len(cmdargs), len(orig_arglist)))
+        print "Service Insertion Usage:\n    %s %s" % (
+            cmd, " ".join(["<%s>" % y for y in SERVICE_COMMANDS[cmd]["args"]]))
         sys.exit()
     if len(arglist) > 0:
         LOG.debug("Too many arguments for \"%s\" (expected: %d, got: %d)" \
                   % (cmd, len(cmdargs), len(orig_arglist)))
-        print "Service Insertion Usage:\n    %s %s" % (cmd,
-          " ".join(["<%s>" % y for y in SERVICE_COMMANDS[cmd]["args"]]))
+        print "Service Insertion Usage:\n    %s %s" % (
+            cmd, " ".join(["<%s>" % y for y in SERVICE_COMMANDS[cmd]["args"]]))
         sys.exit()
     return args
 
 
 SERVICE_COMMANDS = {
-  "insert_inpath_service": {
-    "func": insert_inpath_service,
-    "args": ["tenant_id", "service_image_id",
-             "management_net_name", "northbound_net_name",
-             "southbound_net_name"]},
-  "delete_service": {
-    "func": delete_service,
-    "args": ["tenant_id", "service_instance_id"]},
-  "connect_vm": {
-    "func": connect_vm,
-    "args": ["tenant_id", "vm_image_id",
-             "service_instance_id"]},
-  "disconnect_vm": {
-    "func": disconnect_vm,
-    "args": ["vm_instance_id"]}}
+    "insert_inpath_service": {
+        "func": insert_inpath_service,
+        "args": ["tenant_id", "service_image_id", "management_net_name",
+                 "northbound_net_name", "southbound_net_name"],
+        },
+    "delete_service": {
+        "func": delete_service,
+        "args": ["tenant_id", "service_instance_id"],
+        },
+    "connect_vm": {
+        "func": connect_vm,
+        "args": ["tenant_id", "vm_image_id", "service_instance_id"],
+        },
+    "disconnect_vm": {
+        "func": disconnect_vm,
+        "args": ["vm_instance_id"],
+        },
+    }
 
 
 if __name__ == "__main__":
@@ -289,15 +291,17 @@ if __name__ == "__main__":
     usagestr = "Usage: %prog [OPTIONS] <command> [args]"
     PARSER = OptionParser(usage=usagestr)
     PARSER.add_option("-H", "--host", dest="host",
-      type="string", default="127.0.0.1", help="ip address of api host")
+                      type="string", default="127.0.0.1",
+                      help="ip address of api host")
     PARSER.add_option("-p", "--port", dest="port",
-      type="int", default=9696, help="api port")
+                      type="int", default=9696, help="api port")
     PARSER.add_option("-s", "--ssl", dest="ssl",
-      action="store_true", default=False, help="use ssl")
+                      action="store_true", default=False, help="use ssl")
     PARSER.add_option("-v", "--verbose", dest="verbose",
-      action="store_true", default=False, help="turn on verbose logging")
+                      action="store_true", default=False,
+                      help="turn on verbose logging")
     PARSER.add_option("-f", "--logfile", dest="logfile",
-      type="string", default="syslog", help="log file path")
+                      type="string", default="syslog", help="log file path")
     options, args = PARSER.parse_args()
     if options.verbose:
         LOG.setLevel(logging.DEBUG)
index 0ee80129c3af3a9f69f17098cce611228713a249..71098c4e960990e366729debc0a79ac1866d1860 100644 (file)
@@ -22,8 +22,7 @@ Services Constants for the Services insertion Library
 
 FORMAT = 'json'
 ACTION_PREFIX_EXT = '/v1.0'
-ACTION_PREFIX_CSCO = ACTION_PREFIX_EXT + \
-        '/extensions/csco/tenants/{tenant_id}'
+ACTION_PREFIX_CSCO = ACTION_PREFIX_EXT + '/extensions/csco/tenants/{tenant_id}'
 NETWORK = 'network'
 ID = 'id'
 PORTS = 'ports'
index 4b630e0b1989be9b0682929cf75e77c68fe42f0c..a83976b9b2d6705c5141104414837ccbed6cb5dc 100644 (file)
@@ -26,10 +26,11 @@ import time
 
 from quantum.common import utils
 from quantum.plugins.cisco import l2network_plugin_configuration as conf
-from quantum.plugins.cisco.db import services_db as sdb
 from quantum.plugins.cisco.common import cisco_constants as const
+from quantum.plugins.cisco.db import services_db as sdb
 from quantum.plugins.cisco.services import services_constants as servconts
 
+
 LOG = logging.getLogger(__name__)
 
 
@@ -53,7 +54,7 @@ class ServicesLogistics():
             while not flag and counter <= 5:
                 counter = counter + 1
                 time.sleep(2.5)
-                process = subprocess.Popen(service_args, \
+                process = subprocess.Popen(service_args,
                                            stdout=subprocess.PIPE)
                 result = process.stdout.readlines()
                 if not result:
@@ -74,8 +75,8 @@ class ServicesLogistics():
             while not flag and counter <= 10:
                 counter = counter + 1
                 time.sleep(2.5)
-                process = subprocess.Popen(service_args, \
-                                    stdout=subprocess.PIPE)
+                process = subprocess.Popen(service_args,
+                                           stdout=subprocess.PIPE)
                 result = process.stdout.readlines()
                 if result:
                     tokens = re.search("running", str(result[1]))
@@ -105,8 +106,8 @@ class ServicesLogistics():
         """
         _plugins = {}
         for key in conf.PLUGINS[const.PLUGINS].keys():
-            _plugins[key] = \
-                utils.import_object(conf.PLUGINS[const.PLUGINS][key])
+            _plugins[key] = (
+                utils.import_object(conf.PLUGINS[const.PLUGINS][key]))
         if not plugin_key in _plugins.keys():
             LOG.debug("No %s Plugin loaded" % plugin_key)
             return False
index aaf0e28d9da65ed4d233b4b8152abb20bc3fac0e..9c447cdac0fff8037e3f0c3afae232c82979b5b8 100644 (file)
 # @authors: Shweta Padubidri, Cisco Systems, Inc.
 #           Peter Strunk , Cisco Systems, Inc.
 #           Shubhangi Satras , Cisco Systems, Inc.
-import unittest
-import logging
-import webob
+
 import json
+import logging
 import os.path
+import unittest
+
 import routes
+import webob
 from webtest import TestApp
-from quantum.extensions import credential
-from quantum.extensions import portprofile
-from quantum.extensions import novatenant
-from quantum.extensions import qos
-from quantum.extensions import multiport
-from quantum.plugins.cisco.db import api as db
-from quantum import wsgi
-from quantum.common import config
-from quantum.extensions import extensions
+
 from quantum import api as server
-from quantum.plugins.cisco.l2network_plugin import L2Network
-from quantum.tests.unit.extension_stubs import StubBaseAppController
-from quantum.extensions.extensions import (PluginAwareExtensionManager,
-                                           ExtensionMiddleware)
+from quantum.common import config
+from quantum.extensions import (
+    credential,
+    extensions,
+    multiport,
+    novatenant,
+    portprofile,
+    qos,
+    )
+from quantum.extensions.extensions import (
+    ExtensionMiddleware,
+    PluginAwareExtensionManager,
+    )
 from quantum.manager import QuantumManager
+from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco import l2network_plugin
+from quantum.plugins.cisco.l2network_plugin import L2Network
+from quantum.tests.unit.extension_stubs import StubBaseAppController
+from quantum import wsgi
+
+
+LOG = logging.getLogger('quantum.plugins.cisco.tests.test_cisco_extensions')
+
 
 TEST_CONF_FILE = config.find_config_file({'plugin': 'cisco'}, None,
                                          'quantum.conf.ciscoext')
 EXTENSIONS_PATH = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
                                os.pardir, os.pardir, "extensions")
 
-LOG = logging.getLogger('quantum.plugins.cisco.tests.test_cisco_extensions')
-
 
 class ExtensionsTestApp(wsgi.Router):
 
@@ -71,23 +80,26 @@ class PortprofileExtensionTest(unittest.TestCase):
         member_actions = {'associate_portprofile': "PUT",
                           'disassociate_portprofile': "PUT"}
         controller = portprofile.PortprofilesController(
-                               QuantumManager.get_plugin())
+            QuantumManager.get_plugin())
         res_ext = extensions.ResourceExtension('portprofiles', controller,
-                                             parent=parent_resource,
-                                             member_actions=member_actions)
+                                               parent=parent_resource,
+                                               member_actions=member_actions)
         self.test_app = setup_extensions_test_app(
-                                          SimpleExtensionManager(res_ext))
+            SimpleExtensionManager(res_ext))
         self.contenttype = 'application/json'
         self.profile_path = '/extensions/csco/tenants/tt/portprofiles'
         self.portprofile_path = '/extensions/csco/tenants/tt/portprofiles/'
-        self.test_port_profile = {'portprofile':
-                            {'portprofile_name': 'cisco_test_portprofile',
-                             'qos_name': 'test-qos1'}}
+        self.test_port_profile = {
+            'portprofile': {
+                'portprofile_name': 'cisco_test_portprofile',
+                'qos_name': 'test-qos1',
+                },
+            }
         self.tenant_id = "test_tenant"
         self.network_name = "test_network"
         options = {}
-        options['plugin_provider'] = 'quantum.plugins.cisco.l2network_plugin'\
-                                     '.L2Network'
+        options['plugin_provider'] = ('quantum.plugins.cisco.l2network_plugin'
+                                      '.L2Network')
         self.api = server.APIRouterV10(options)
         self._l2network_plugin = l2network_plugin.L2Network()
 
@@ -98,14 +110,17 @@ class PortprofileExtensionTest(unittest.TestCase):
         LOG.debug("test_list_portprofile - START")
         req_body1 = json.dumps(self.test_port_profile)
         create_response1 = self.test_app.post(
-                           self.profile_path, req_body1,
-                           content_type=self.contenttype)
-        req_body2 = json.dumps({'portprofile':
-                               {'portprofile_name': 'cisco_test_portprofile2',
-                                'qos_name': 'test-qos2'}})
+            self.profile_path, req_body1,
+            content_type=self.contenttype)
+        req_body2 = json.dumps({
+            'portprofile': {
+                'portprofile_name': 'cisco_test_portprofile2',
+                'qos_name': 'test-qos2',
+                },
+            })
         create_response2 = self.test_app.post(
-                                self.profile_path, req_body2,
-                                content_type=self.contenttype)
+            self.profile_path, req_body2,
+            content_type=self.contenttype)
 
         index_response = self.test_app.get(self.profile_path)
         index_resp_body = wsgi.Serializer().deserialize(index_response.body,
@@ -114,19 +129,21 @@ class PortprofileExtensionTest(unittest.TestCase):
 
         resp_body1 = wsgi.Serializer().deserialize(create_response1.body,
                                                    self.contenttype)
-        portprofile_path1_temp = self.portprofile_path +\
-                              resp_body1['portprofiles']['portprofile']['id']
+        portprofile_path1_temp = (
+            self.portprofile_path +
+            resp_body1['portprofiles']['portprofile']['id'])
         portprofile_path1 = str(portprofile_path1_temp)
         resp_body2 = wsgi.Serializer().deserialize(create_response2.body,
                                                    self.contenttype)
         list_all_portprofiles = [resp_body1['portprofiles']['portprofile'],
                                  resp_body2['portprofiles']['portprofile']]
         self.assertTrue(index_resp_body['portprofiles'][0] in
-                                                 list_all_portprofiles)
+                        list_all_portprofiles)
         self.assertTrue(index_resp_body['portprofiles'][1] in
-                                                 list_all_portprofiles)
-        portprofile_path2_temp = self.portprofile_path +\
-                              resp_body2['portprofiles']['portprofile']['id']
+                        list_all_portprofiles)
+        portprofile_path2_temp = (
+            self.portprofile_path +
+            resp_body2['portprofiles']['portprofile']['id'])
         portprofile_path2 = str(portprofile_path2_temp)
 
         # Clean Up - Delete the Port Profiles
@@ -147,8 +164,9 @@ class PortprofileExtensionTest(unittest.TestCase):
         # Clean Up - Delete the Port Profile
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        portprofile_path_temp = self.portprofile_path +\
-                              resp_body['portprofiles']['portprofile']['id']
+        portprofile_path_temp = (
+            self.portprofile_path +
+            resp_body['portprofiles']['portprofile']['id'])
         portprofile_path = str(portprofile_path_temp)
         self.tear_down_profile(portprofile_path)
         LOG.debug("test_create_portprofile - END")
@@ -174,18 +192,18 @@ class PortprofileExtensionTest(unittest.TestCase):
                                             content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        show_path_temp = self.portprofile_path +\
-                            resp_body['portprofiles']['portprofile']['id']
+        show_path_temp = (self.portprofile_path +
+                          resp_body['portprofiles']['portprofile']['id'])
         show_port_path = str(show_path_temp)
         show_response = self.test_app.get(show_port_path)
         show_resp_dict = wsgi.Serializer().deserialize(show_response.body,
-                                                      self.contenttype)
+                                                       self.contenttype)
         self.assertEqual(
-                     show_resp_dict['portprofiles']['portprofile']['qos_name'],
-                     self.test_port_profile['portprofile']['qos_name'])
+            show_resp_dict['portprofiles']['portprofile']['qos_name'],
+            self.test_port_profile['portprofile']['qos_name'])
         self.assertEqual(
-                     show_resp_dict['portprofiles']['portprofile']['name'],
-                     self.test_port_profile['portprofile']['portprofile_name'])
+            show_resp_dict['portprofiles']['portprofile']['name'],
+            self.test_port_profile['portprofile']['portprofile_name'])
         self.assertEqual(200, show_response.status_int)
 
         # Clean Up - Delete the Port Profile
@@ -210,27 +228,30 @@ class PortprofileExtensionTest(unittest.TestCase):
         LOG.debug("test_update_portprofile - START")
         req_body = json.dumps(self.test_port_profile)
         index_response = self.test_app.post(
-                         self.profile_path, req_body,
-                         content_type=self.contenttype)
+            self.profile_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        rename_port_profile = {'portprofile':
-                              {'portprofile_name': 'cisco_rename_portprofile',
-                              'qos_name': 'test-qos1'}}
+        rename_port_profile = {
+            'portprofile': {
+                'portprofile_name': 'cisco_rename_portprofile',
+                'qos_name': 'test-qos1',
+                },
+            }
         rename_req_body = json.dumps(rename_port_profile)
-        rename_path_temp = self.portprofile_path +\
-                                resp_body['portprofiles']['portprofile']['id']
+        rename_path_temp = (self.portprofile_path +
+                            resp_body['portprofiles']['portprofile']['id'])
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, rename_req_body,
                                             content_type=self.contenttype)
         rename_resp_dict = wsgi.Serializer().deserialize(rename_response.body,
                                                          self.contenttype)
         self.assertEqual(
-                rename_resp_dict['portprofiles']['portprofile']['qos_name'],
-                self.test_port_profile['portprofile']['qos_name'])
+            rename_resp_dict['portprofiles']['portprofile']['qos_name'],
+            self.test_port_profile['portprofile']['qos_name'])
         self.assertEqual(
-                rename_resp_dict['portprofiles']['portprofile']['name'],
-                rename_port_profile['portprofile']['portprofile_name'])
+            rename_resp_dict['portprofiles']['portprofile']['name'],
+            rename_port_profile['portprofile']['portprofile_name'])
         self.assertEqual(200, rename_response.status_int)
 
         # Clean Up - Delete the Port Profile
@@ -244,12 +265,12 @@ class PortprofileExtensionTest(unittest.TestCase):
         LOG.debug("test_update_portprofileBADRequest - START")
         req_body = json.dumps(self.test_port_profile)
         index_response = self.test_app.post(
-                         self.profile_path, req_body,
-                         content_type=self.contenttype)
+            self.profile_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        rename_path_temp = self.portprofile_path +\
-                                resp_body['portprofiles']['portprofile']['id']
+        rename_path_temp = (self.portprofile_path +
+                            resp_body['portprofiles']['portprofile']['id'])
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, 'BAD_REQUEST',
                                             status='*')
@@ -264,9 +285,12 @@ class PortprofileExtensionTest(unittest.TestCase):
         """ Test update Portprofile does not exist"""
 
         LOG.debug("test_update_portprofileiDNE - START")
-        rename_port_profile = {'portprofile':
-                              {'portprofile_name': 'cisco_rename_portprofile',
-                              'qos_name': 'test-qos1'}}
+        rename_port_profile = {
+            'portprofile': {
+                'portprofile_name': 'cisco_rename_portprofile',
+                'qos_name': 'test-qos1',
+                },
+            }
         rename_req_body = json.dumps(rename_port_profile)
         update_path_temp = self.portprofile_path + portprofile_id
         update_path = str(update_path_temp)
@@ -283,12 +307,12 @@ class PortprofileExtensionTest(unittest.TestCase):
         LOG.debug("test_delete_portprofile - START")
         req_body = json.dumps(self.test_port_profile)
         index_response = self.test_app.post(
-                              self.profile_path, req_body,
-                              content_type=self.contenttype)
+            self.profile_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        delete_path_temp = self.portprofile_path +\
-                                resp_body['portprofiles']['portprofile']['id']
+        delete_path_temp = (self.portprofile_path +
+                            resp_body['portprofiles']['portprofile']['id'])
         delete_path = str(delete_path_temp)
         delete_response = self.test_app.delete(delete_path)
 
@@ -359,8 +383,8 @@ class PortprofileExtensionTest(unittest.TestCase):
     def _delete_port(self, network_id, port_id):
         """ Delete port """
         LOG.debug("Deleting port for network %s - START", network_id)
-        port_path = "/tenants/tt/networks/%(network_id)s/ports/"\
-                                "%(port_id)s" % locals()
+        port_path = ("/tenants/tt/networks/%(network_id)s/ports/%(port_id)s" %
+                     locals())
         port_req = self.create_request(port_path, None,
                                        self.contenttype, 'DELETE')
         port_req.get_response(self.api)
@@ -371,7 +395,7 @@ class PortprofileExtensionTest(unittest.TestCase):
         LOG.debug("Deleting network %s - START", network_id)
         network_path = "/tenants/tt/networks/%s" % network_id
         network_req = self.create_request(network_path, None,
-                                       self.contenttype, 'DELETE')
+                                          self.contenttype, 'DELETE')
         network_req.get_response(self.api)
         LOG.debug("Deleting network - END")
 
@@ -384,32 +408,38 @@ class PortprofileExtensionTest(unittest.TestCase):
         port_id = self._create_port(net_id, "ACTIVE")
         req_body = json.dumps(self.test_port_profile)
         index_response = self.test_app.post(
-                              self.profile_path, req_body,
-                              content_type=self.contenttype)
+            self.profile_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        test_port_assign_data = {'portprofile': {'network-id': net_id,
-                                         'port-id': port_id}}
+        test_port_assign_data = {
+            'portprofile': {
+                'network-id': net_id,
+                'port-id': port_id,
+                },
+            }
         req_assign_body = json.dumps(test_port_assign_data)
-        associate_path_temp = self.portprofile_path +\
-                         resp_body['portprofiles']['portprofile']['id'] +\
-                         "/associate_portprofile"
+        associate_path_temp = (
+            self.portprofile_path +
+            resp_body['portprofiles']['portprofile']['id'] +
+            "/associate_portprofile")
         associate_path = str(associate_path_temp)
         associate_response = self.test_app.put(
-                                  associate_path, req_assign_body,
-                                  content_type=self.contenttype)
+            associate_path, req_assign_body,
+            content_type=self.contenttype)
         self.assertEqual(200, associate_response.status_int)
 
         # Clean Up - Disassociate and Delete the Port Profile
-        disassociate_path_temp = self.portprofile_path +\
-                            resp_body['portprofiles']['portprofile']['id'] +\
-                            "/disassociate_portprofile"
+        disassociate_path_temp = (
+            self.portprofile_path +
+            resp_body['portprofiles']['portprofile']['id'] +
+            "/disassociate_portprofile")
         disassociate_path = str(disassociate_path_temp)
-        delete_path_temp = self.portprofile_path +\
-                                resp_body['portprofiles']['portprofile']['id']
+        delete_path_temp = (self.portprofile_path +
+                            resp_body['portprofiles']['portprofile']['id'])
         delete_path = str(delete_path_temp)
         self.tear_down_associate_profile(delete_path, disassociate_path,
-                                      req_assign_body)
+                                         req_assign_body)
         self.tear_down_port_network(net_id, port_id)
         LOG.debug("test_associate_portprofile - END")
 
@@ -418,14 +448,19 @@ class PortprofileExtensionTest(unittest.TestCase):
         """ Test associate portprofile does not exist"""
 
         LOG.debug("test_associate_portprofileDNE - START")
-        test_port_assign_data = {'portprofile': {'network-id': '001',
-                                         'port-id': '1'}}
+        test_port_assign_data = {
+            'portprofile': {
+                'network-id': '001',
+                'port-id': '1',
+                },
+            }
         req_assign_body = json.dumps(test_port_assign_data)
-        associate_path = self.portprofile_path + portprofile_id +\
-                         "/associate_portprofile"
+        associate_path = (self.portprofile_path +
+                          portprofile_id +
+                          "/associate_portprofile")
         associate_response = self.test_app.put(
-                              associate_path, req_assign_body,
-                              content_type=self.contenttype, status='*')
+            associate_path, req_assign_body,
+            content_type=self.contenttype, status='*')
         self.assertEqual(450, associate_response.status_int)
         LOG.debug("test_associate_portprofileDNE - END")
 
@@ -439,33 +474,38 @@ class PortprofileExtensionTest(unittest.TestCase):
 
         req_body = json.dumps(self.test_port_profile)
         index_response = self.test_app.post(
-                              self.profile_path, req_body,
-                              content_type=self.contenttype)
+            self.profile_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
 
-        test_port_assign_data = {'portprofile': {'network-id': net_id,
-                                         'port-id': port_id}}
+        test_port_assign_data = {
+            'portprofile': {
+                'network-id': net_id,
+                'port-id': port_id,
+                },
+            }
         req_assign_body = json.dumps(test_port_assign_data)
-        associate_path_temp = self.portprofile_path +\
-                              resp_body['portprofiles']['portprofile']['id'] +\
-                              "/associate_portprofile"
+        associate_path_temp = (self.portprofile_path +
+                               resp_body['portprofiles']['portprofile']['id'] +
+                               "/associate_portprofile")
         associate_path = str(associate_path_temp)
         self.test_app.put(associate_path, req_assign_body,
-                                               content_type=self.contenttype)
-        disassociate_path_temp = self.portprofile_path +\
-                            resp_body['portprofiles']['portprofile']['id'] +\
-                            "/disassociate_portprofile"
+                          content_type=self.contenttype)
+        disassociate_path_temp = (
+            self.portprofile_path +
+            resp_body['portprofiles']['portprofile']['id'] +
+            "/disassociate_portprofile")
 
         disassociate_path = str(disassociate_path_temp)
         disassociate_response = self.test_app.put(
-                                     disassociate_path, req_assign_body,
-                                     content_type=self.contenttype)
+            disassociate_path, req_assign_body,
+            content_type=self.contenttype)
         self.assertEqual(200, disassociate_response.status_int)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        delete_path_temp = self.portprofile_path +\
-                                resp_body['portprofiles']['portprofile']['id']
+        delete_path_temp = (self.portprofile_path +
+                            resp_body['portprofiles']['portprofile']['id'])
         delete_path = str(delete_path_temp)
         self.tear_down_profile(delete_path)
         self.tear_down_port_network(net_id, port_id)
@@ -484,12 +524,12 @@ class PortprofileExtensionTest(unittest.TestCase):
         self.test_app.delete(delete_profile_path)
 
     def tear_down_associate_profile(self, delete_profile_path,
-                                 dissociate_profile_path, req_body):
+                                    dissociate_profile_path, req_body):
 
         """ Tear down associate profile"""
 
         self.test_app.put(dissociate_profile_path, req_body,
-                           content_type=self.contenttype)
+                          content_type=self.contenttype)
         self.tear_down_profile(delete_profile_path)
 
     def tearDown(self):
@@ -510,20 +550,33 @@ class NovatenantExtensionTest(unittest.TestCase):
         member_actions = {'schedule_host': "PUT",
                           'associate_port': "PUT"}
         controller = novatenant.NovatenantsController(
-                               QuantumManager.get_plugin())
+            QuantumManager.get_plugin())
         res_ext = extensions.ResourceExtension('novatenants', controller,
-                                             parent=parent_resource,
-                                             member_actions=member_actions)
+                                               parent=parent_resource,
+                                               member_actions=member_actions)
         self.test_app = setup_extensions_test_app(
-                                          SimpleExtensionManager(res_ext))
+            SimpleExtensionManager(res_ext))
         self.contenttype = 'application/json'
         self.novatenants_path = '/extensions/csco/tenants/tt/novatenants/'
-        self.test_associate_port_data = {'novatenant': {'instance_id': 1,
-                                       'instance_desc': {'project_id': 'demo',
-                                     'user_id': 'root', 'vif_id': '23432423'}}}
-        self.test_associate_data = {'novatenant': {'instance_id': 1,
-                                   'instance_desc': {'project_id': 'demo',
-                                   'user_id': 'root'}}}
+        self.test_associate_port_data = {
+            'novatenant': {
+                'instance_id': 1,
+                'instance_desc': {
+                    'project_id': 'demo',
+                    'user_id': 'root',
+                    'vif_id': '23432423',
+                    },
+                },
+            }
+        self.test_associate_data = {
+            'novatenant': {
+                'instance_id': 1,
+                'instance_desc': {
+                    'project_id': 'demo',
+                    'user_id': 'root',
+                    },
+                },
+            }
         self._l2network_plugin = l2network_plugin.L2Network()
 
     def test_schedule_host(self):
@@ -532,8 +585,8 @@ class NovatenantExtensionTest(unittest.TestCase):
         req_body = json.dumps(self.test_associate_data)
         host_path = self.novatenants_path + "001/schedule_host"
         host_response = self.test_app.put(
-                                  host_path, req_body,
-                                  content_type=self.contenttype)
+            host_path, req_body,
+            content_type=self.contenttype)
         self.assertEqual(200, host_response.status_int)
         LOG.debug("test_schedule_host - END")
 
@@ -542,8 +595,8 @@ class NovatenantExtensionTest(unittest.TestCase):
         LOG.debug("test_schedule_hostBADRequest - START")
         host_path = self.novatenants_path + "001/schedule_host"
         host_response = self.test_app.put(
-                                 host_path, 'BAD_REQUEST',
-                                content_type=self.contenttype, status='*')
+            host_path, 'BAD_REQUEST',
+            content_type=self.contenttype, status='*')
         self.assertEqual(400, host_response.status_int)
         LOG.debug("test_schedule_hostBADRequest - END")
 
@@ -553,8 +606,8 @@ class NovatenantExtensionTest(unittest.TestCase):
         req_body = json.dumps(self.test_associate_port_data)
         associate_port_path = self.novatenants_path + "001/associate_port"
         associate_port_response = self.test_app.put(
-                                  associate_port_path, req_body,
-                                  content_type=self.contenttype)
+            associate_port_path, req_body,
+            content_type=self.contenttype)
         self.assertEqual(200, associate_port_response.status_int)
         LOG.debug("test_associate_port - END")
 
@@ -574,15 +627,22 @@ class QosExtensionTest(unittest.TestCase):
                                collection_name="extensions/csco/tenants")
         controller = qos.QosController(QuantumManager.get_plugin())
         res_ext = extensions.ResourceExtension('qos', controller,
-                                             parent=parent_resource)
+                                               parent=parent_resource)
 
         self.test_app = setup_extensions_test_app(
-                SimpleExtensionManager(res_ext))
+            SimpleExtensionManager(res_ext))
         self.contenttype = 'application/json'
         self.qos_path = '/extensions/csco/tenants/tt/qos'
         self.qos_second_path = '/extensions/csco/tenants/tt/qos/'
-        self.test_qos_data = {'qos': {'qos_name': 'cisco_test_qos',
-                               'qos_desc': {'PPS': 50, 'TTL': 5}}}
+        self.test_qos_data = {
+            'qos': {
+                'qos_name': 'cisco_test_qos',
+                'qos_desc': {
+                    'PPS': 50,
+                    'TTL': 5,
+                    },
+                },
+            }
         self._l2network_plugin = l2network_plugin.L2Network()
 
     def test_create_qos(self):
@@ -592,15 +652,14 @@ class QosExtensionTest(unittest.TestCase):
         LOG.debug("test_create_qos - START")
         req_body = json.dumps(self.test_qos_data)
         index_response = self.test_app.post(self.qos_path,
-                                       req_body,
-                                       content_type=self.contenttype)
+                                            req_body,
+                                            content_type=self.contenttype)
         self.assertEqual(200, index_response.status_int)
 
         # Clean Up - Delete the qos
         resp_body = wsgi.Serializer().deserialize(index_response.body,
-                                                   self.contenttype)
-        qos_path_temp = self.qos_second_path +\
-                resp_body['qoss']['qos']['id']
+                                                  self.contenttype)
+        qos_path_temp = self.qos_second_path + resp_body['qoss']['qos']['id']
         qos_path = str(qos_path_temp)
         self.tearDownQos(qos_path)
         LOG.debug("test_create_qos - END")
@@ -625,8 +684,15 @@ class QosExtensionTest(unittest.TestCase):
         req_body1 = json.dumps(self.test_qos_data)
         create_resp1 = self.test_app.post(self.qos_path, req_body1,
                                           content_type=self.contenttype)
-        req_body2 = json.dumps({'qos': {'qos_name': 'cisco_test_qos2',
-                               'qos_desc': {'PPS': 50, 'TTL': 5}}})
+        req_body2 = json.dumps({
+            'qos': {
+                'qos_name': 'cisco_test_qos2',
+                'qos_desc': {
+                    'PPS': 50,
+                    'TTL': 5,
+                    },
+                },
+            })
         create_resp2 = self.test_app.post(self.qos_path, req_body2,
                                           content_type=self.contenttype)
         index_response = self.test_app.get(self.qos_path)
@@ -637,16 +703,14 @@ class QosExtensionTest(unittest.TestCase):
         # Clean Up - Delete the qos's
         resp_body1 = wsgi.Serializer().deserialize(create_resp1.body,
                                                    self.contenttype)
-        qos_path1_temp = self.qos_second_path +\
-                resp_body1['qoss']['qos']['id']
+        qos_path1_temp = self.qos_second_path + resp_body1['qoss']['qos']['id']
         qos_path1 = str(qos_path1_temp)
         resp_body2 = wsgi.Serializer().deserialize(create_resp2.body,
                                                    self.contenttype)
         list_all_qos = [resp_body1['qoss']['qos'], resp_body2['qoss']['qos']]
         self.assertTrue(index_resp_body['qoss'][0] in list_all_qos)
         self.assertTrue(index_resp_body['qoss'][1] in list_all_qos)
-        qos_path2_temp = self.qos_second_path +\
-                resp_body2['qoss']['qos']['id']
+        qos_path2_temp = self.qos_second_path + resp_body2['qoss']['qos']['id']
         qos_path2 = str(qos_path2_temp)
         self.tearDownQos(qos_path1)
         self.tearDownQos(qos_path2)
@@ -662,15 +726,13 @@ class QosExtensionTest(unittest.TestCase):
                                             content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        show_path_temp = self.qos_second_path +\
-                resp_body['qoss']['qos']['id']
+        show_path_temp = self.qos_second_path + resp_body['qoss']['qos']['id']
         show_qos_path = str(show_path_temp)
         show_response = self.test_app.get(show_qos_path)
         show_resp_dict = wsgi.Serializer().deserialize(show_response.body,
-                                                      self.contenttype)
-        self.assertEqual(
-                     show_resp_dict['qoss']['qos']['name'],
-                     self.test_qos_data['qos']['qos_name'])
+                                                       self.contenttype)
+        self.assertEqual(show_resp_dict['qoss']['qos']['name'],
+                         self.test_qos_data['qos']['qos_name'])
 
         self.assertEqual(200, show_response.status_int)
 
@@ -699,16 +761,23 @@ class QosExtensionTest(unittest.TestCase):
                                             content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        rename_req_body = json.dumps({'qos': {'qos_name': 'cisco_rename_qos',
-                 'qos_desc': {'PPS': 50, 'TTL': 5}}})
-        rename_path_temp = self.qos_second_path +\
-                resp_body['qoss']['qos']['id']
+        rename_req_body = json.dumps({
+            'qos': {
+                'qos_name': 'cisco_rename_qos',
+                'qos_desc': {
+                    'PPS': 50,
+                    'TTL': 5,
+                    },
+                },
+            })
+        rename_path_temp = (self.qos_second_path +
+                            resp_body['qoss']['qos']['id'])
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, rename_req_body,
                                             content_type=self.contenttype)
         self.assertEqual(200, rename_response.status_int)
         rename_resp_dict = wsgi.Serializer().deserialize(rename_response.body,
-                                                      self.contenttype)
+                                                         self.contenttype)
         self.assertEqual(
                      rename_resp_dict['qoss']['qos']['name'],
                      'cisco_rename_qos')
@@ -720,8 +789,15 @@ class QosExtensionTest(unittest.TestCase):
         """ Test update qos does not exist """
 
         LOG.debug("test_update_qosDNE - START")
-        rename_req_body = json.dumps({'qos': {'qos_name': 'cisco_rename_qos',
-                 'qos_desc': {'PPS': 50, 'TTL': 5}}})
+        rename_req_body = json.dumps({
+            'qos': {
+                'qos_name': 'cisco_rename_qos',
+                'qos_desc': {
+                    'PPS': 50,
+                    'TTL': 5,
+                    },
+                },
+            })
         rename_path_temp = self.qos_second_path + qos_id
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, rename_req_body,
@@ -740,8 +816,8 @@ class QosExtensionTest(unittest.TestCase):
                                             content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        rename_path_temp = self.qos_second_path +\
-                resp_body['qoss']['qos']['id']
+        rename_path_temp = (self.qos_second_path +
+                            resp_body['qoss']['qos']['id'])
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, 'BAD_REQUEST',
                                             status="*")
@@ -756,14 +832,21 @@ class QosExtensionTest(unittest.TestCase):
         """ Test delte qos """
 
         LOG.debug("test_delete_qos - START")
-        req_body = json.dumps({'qos': {'qos_name': 'cisco_test_qos',
-                               'qos_desc': {'PPS': 50, 'TTL': 5}}})
+        req_body = json.dumps({
+            'qos': {
+                'qos_name': 'cisco_test_qos',
+                'qos_desc': {
+                    'PPS': 50,
+                    'TTL': 5,
+                    },
+                },
+            })
         index_response = self.test_app.post(self.qos_path, req_body,
                                             content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                   self.contenttype)
-        delete_path_temp = self.qos_second_path +\
-                resp_body['qoss']['qos']['id']
+        delete_path_temp = (self.qos_second_path +
+                            resp_body['qoss']['qos']['id'])
         delete_path = str(delete_path_temp)
         delete_response = self.test_app.delete(delete_path)
         self.assertEqual(200, delete_response.status_int)
@@ -801,16 +884,19 @@ class CredentialExtensionTest(unittest.TestCase):
         controller = credential.CredentialController(
                      QuantumManager.get_plugin())
         res_ext = extensions.ResourceExtension('credentials', controller,
-                                             parent=parent_resource)
+                                               parent=parent_resource)
         self.test_app = setup_extensions_test_app(
                         SimpleExtensionManager(res_ext))
         self.contenttype = 'application/json'
         self.credential_path = '/extensions/csco/tenants/tt/credentials'
         self.cred_second_path = '/extensions/csco/tenants/tt/credentials/'
-        self.test_credential_data = {'credential':
-                                    {'credential_name': 'cred8',
-                                    'user_name': 'newUser2',
-                                    'password': 'newPasswd1'}}
+        self.test_credential_data = {
+            'credential': {
+                'credential_name': 'cred8',
+                'user_name': 'newUser2',
+                'password': 'newPasswd1',
+                },
+            }
         self._l2network_plugin = l2network_plugin.L2Network()
 
     def test_list_credentials(self):
@@ -821,36 +907,38 @@ class CredentialExtensionTest(unittest.TestCase):
         LOG.debug("test_list_credentials - START")
         req_body1 = json.dumps(self.test_credential_data)
         create_response1 = self.test_app.post(
-                           self.credential_path, req_body1,
-                           content_type=self.contenttype)
-        req_body2 = json.dumps({'credential':
-                                {'credential_name': 'cred9',
-                                'user_name': 'newUser2',
-                                'password': 'newPasswd2'}})
+            self.credential_path, req_body1,
+            content_type=self.contenttype)
+        req_body2 = json.dumps({
+            'credential': {
+                'credential_name': 'cred9',
+                'user_name': 'newUser2',
+                'password': 'newPasswd2',
+                },
+            })
         create_response2 = self.test_app.post(
-                           self.credential_path, req_body2,
-                           content_type=self.contenttype)
-        index_response = self.test_app.get(
-                         self.credential_path)
+            self.credential_path, req_body2,
+            content_type=self.contenttype)
+        index_response = self.test_app.get(self.credential_path)
         index_resp_body = wsgi.Serializer().deserialize(index_response.body,
                                                         self.contenttype)
         self.assertEqual(200, index_response.status_int)
         #CLean Up - Deletion of the Credentials
-        resp_body1 = wsgi.Serializer().deserialize(
-                     create_response1.body, self.contenttype)
-        delete_path1_temp = self.cred_second_path +\
-                            resp_body1['credentials']['credential']['id']
+        resp_body1 = wsgi.Serializer().deserialize(create_response1.body,
+                                                   self.contenttype)
+        delete_path1_temp = (self.cred_second_path +
+                             resp_body1['credentials']['credential']['id'])
         delete_path1 = str(delete_path1_temp)
-        resp_body2 = wsgi.Serializer().deserialize(
-                     create_response2.body, self.contenttype)
+        resp_body2 = wsgi.Serializer().deserialize(create_response2.body,
+                                                   self.contenttype)
         list_all_credential = [resp_body1['credentials']['credential'],
                                resp_body2['credentials']['credential']]
-        self.assertTrue(index_resp_body['credentials'][0] in
-                                               list_all_credential)
-        self.assertTrue(index_resp_body['credentials'][1] in
-                                               list_all_credential)
-        delete_path2_temp = self.cred_second_path +\
-                            resp_body2['credentials']['credential']['id']
+        self.assertTrue(
+            index_resp_body['credentials'][0] in list_all_credential)
+        self.assertTrue(
+            index_resp_body['credentials'][1] in list_all_credential)
+        delete_path2_temp = (self.cred_second_path +
+                             resp_body2['credentials']['credential']['id'])
         delete_path2 = str(delete_path2_temp)
         self.tearDownCredential(delete_path1)
         self.tearDownCredential(delete_path2)
@@ -863,14 +951,14 @@ class CredentialExtensionTest(unittest.TestCase):
         LOG.debug("test_create_credential - START")
         req_body = json.dumps(self.test_credential_data)
         index_response = self.test_app.post(
-                         self.credential_path, req_body,
-                         content_type=self.contenttype)
+            self.credential_path, req_body,
+            content_type=self.contenttype)
         self.assertEqual(200, index_response.status_int)
         #CLean Up - Deletion of the Credentials
         resp_body = wsgi.Serializer().deserialize(
-                    index_response.body, self.contenttype)
-        delete_path_temp = self.cred_second_path +\
-                           resp_body['credentials']['credential']['id']
+            index_response.body, self.contenttype)
+        delete_path_temp = (self.cred_second_path +
+                            resp_body['credentials']['credential']['id'])
         delete_path = str(delete_path_temp)
         self.tearDownCredential(delete_path)
         LOG.debug("test_create_credential - END")
@@ -881,8 +969,8 @@ class CredentialExtensionTest(unittest.TestCase):
 
         LOG.debug("test_create_credentialBADRequest - START")
         index_response = self.test_app.post(
-                              self.credential_path, 'BAD_REQUEST',
-                              content_type=self.contenttype, status='*')
+            self.credential_path, 'BAD_REQUEST',
+            content_type=self.contenttype, status='*')
         self.assertEqual(400, index_response.status_int)
         LOG.debug("test_create_credentialBADRequest - END")
 
@@ -893,22 +981,21 @@ class CredentialExtensionTest(unittest.TestCase):
         LOG.debug("test_show_credential - START")
         req_body = json.dumps(self.test_credential_data)
         index_response = self.test_app.post(
-                         self.credential_path, req_body,
-                         content_type=self.contenttype)
-        resp_body = wsgi.Serializer().deserialize(
-                    index_response.body, self.contenttype)
-        show_path_temp = self.cred_second_path +\
-                         resp_body['credentials']['credential']['id']
+            self.credential_path, req_body,
+            content_type=self.contenttype)
+        resp_body = wsgi.Serializer().deserialize(index_response.body,
+                                                  self.contenttype)
+        show_path_temp = (self.cred_second_path +
+                          resp_body['credentials']['credential']['id'])
         show_cred_path = str(show_path_temp)
         show_response = self.test_app.get(show_cred_path)
         show_resp_dict = wsgi.Serializer().deserialize(show_response.body,
-                                                      self.contenttype)
-        self.assertEqual(
-                     show_resp_dict['credentials']['credential']['name'],
-                     self.test_credential_data['credential']['user_name'])
+                                                       self.contenttype)
+        self.assertEqual(show_resp_dict['credentials']['credential']['name'],
+                         self.test_credential_data['credential']['user_name'])
         self.assertEqual(
-                     show_resp_dict['credentials']['credential']['password'],
-                     self.test_credential_data['credential']['password'])
+            show_resp_dict['credentials']['credential']['password'],
+            self.test_credential_data['credential']['password'])
         self.assertEqual(200, show_response.status_int)
         LOG.debug("test_show_credential - END")
 
@@ -931,27 +1018,29 @@ class CredentialExtensionTest(unittest.TestCase):
         req_body = json.dumps(self.test_credential_data)
 
         index_response = self.test_app.post(
-                        self.credential_path, req_body,
-                        content_type=self.contenttype)
+            self.credential_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(
-                    index_response.body, self.contenttype)
-        rename_req_body = json.dumps({'credential':
-                                      {'credential_name': 'cred3',
-                                          'user_name': 'RenamedUser',
-                                          'password': 'Renamedpassword'}})
-        rename_path_temp = self.cred_second_path +\
-                           resp_body['credentials']['credential']['id']
+            index_response.body, self.contenttype)
+        rename_req_body = json.dumps({
+            'credential': {
+                'credential_name': 'cred3',
+                'user_name': 'RenamedUser',
+                'password': 'Renamedpassword',
+                },
+            })
+        rename_path_temp = (self.cred_second_path +
+                            resp_body['credentials']['credential']['id'])
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, rename_req_body,
                                             content_type=self.contenttype)
         rename_resp_dict = wsgi.Serializer().deserialize(rename_response.body,
-                                                      self.contenttype)
-        self.assertEqual(
-                     rename_resp_dict['credentials']['credential']['name'],
-                     'cred3')
+                                                         self.contenttype)
+        self.assertEqual(rename_resp_dict['credentials']['credential']['name'],
+                         'cred3')
         self.assertEqual(
-                     rename_resp_dict['credentials']['credential']['password'],
-                     self.test_credential_data['credential']['password'])
+            rename_resp_dict['credentials']['credential']['password'],
+            self.test_credential_data['credential']['password'])
         self.assertEqual(200, rename_response.status_int)
         # Clean Up - Delete the Credentials
         self.tearDownCredential(rename_path)
@@ -964,12 +1053,12 @@ class CredentialExtensionTest(unittest.TestCase):
         LOG.debug("test_update_credBADReq - START")
         req_body = json.dumps(self.test_credential_data)
         index_response = self.test_app.post(
-                        self.credential_path, req_body,
-                        content_type=self.contenttype)
+            self.credential_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(
-                    index_response.body, self.contenttype)
-        rename_path_temp = self.cred_second_path +\
-                           resp_body['credentials']['credential']['id']
+            index_response.body, self.contenttype)
+        rename_path_temp = (self.cred_second_path +
+                            resp_body['credentials']['credential']['id'])
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, 'BAD_REQUEST',
                                             status='*')
@@ -981,10 +1070,13 @@ class CredentialExtensionTest(unittest.TestCase):
         """ Test update credential does not exist"""
 
         LOG.debug("test_update_credentialDNE - START")
-        rename_req_body = json.dumps({'credential':
-                                      {'credential_name': 'cred3',
-                                          'user_name': 'RenamedUser',
-                                          'password': 'Renamedpassword'}})
+        rename_req_body = json.dumps({
+            'credential': {
+                'credential_name': 'cred3',
+                'user_name': 'RenamedUser',
+                'password': 'Renamedpassword',
+                },
+            })
         rename_path_temp = self.cred_second_path + credential_id
         rename_path = str(rename_path_temp)
         rename_response = self.test_app.put(rename_path, rename_req_body,
@@ -1000,12 +1092,12 @@ class CredentialExtensionTest(unittest.TestCase):
         LOG.debug("test_delete_credential - START")
         req_body = json.dumps(self.test_credential_data)
         index_response = self.test_app.post(
-                         self.credential_path, req_body,
-                         content_type=self.contenttype)
+            self.credential_path, req_body,
+            content_type=self.contenttype)
         resp_body = wsgi.Serializer().deserialize(
-                    index_response.body, self.contenttype)
-        delete_path_temp = self.cred_second_path +\
-                           resp_body['credentials']['credential']['id']
+            index_response.body, self.contenttype)
+        delete_path_temp = (self.cred_second_path +
+                            resp_body['credentials']['credential']['id'])
         delete_path = str(delete_path_temp)
         delete_response = self.test_app.delete(delete_path)
         self.assertEqual(200, delete_response.status_int)
@@ -1038,23 +1130,26 @@ class MultiPortExtensionTest(unittest.TestCase):
         parent_resource = dict(member_name="tenant",
                                collection_name="extensions/csco/tenants")
         controller = multiport.MultiportController(
-                               QuantumManager.get_plugin())
+            QuantumManager.get_plugin())
         res_ext = extensions.ResourceExtension('multiport', controller,
-                                             parent=parent_resource)
+                                               parent=parent_resource)
         self.test_app = setup_extensions_test_app(
-                                          SimpleExtensionManager(res_ext))
+            SimpleExtensionManager(res_ext))
         self.contenttype = 'application/json'
         self.multiport_path = '/extensions/csco/tenants/tt/multiport'
         self.multiport_path2 = '/extensions/csco/tenants/tt/multiport/'
-        self.test_multi_port = {'multiport':
-                            {'net_id_list': '1',
-                             'status': 'test-qos1',
-                             'ports_desc': 'Port Descr'}}
+        self.test_multi_port = {
+            'multiport': {
+                'net_id_list': '1',
+                'status': 'test-qos1',
+                'ports_desc': 'Port Descr',
+                },
+            }
         self.tenant_id = "test_tenant"
         self.network_name = "test_network"
         options = {}
-        options['plugin_provider'] = 'quantum.plugins.cisco.l2network_plugin'\
-                                     '.L2Network'
+        options['plugin_provider'] = (
+            'quantum.plugins.cisco.l2network_plugin.L2Network')
         self.api = server.APIRouterV10(options)
         self._l2network_plugin = l2network_plugin.L2Network()
 
@@ -1096,7 +1191,7 @@ class MultiPortExtensionTest(unittest.TestCase):
         LOG.debug("Deleting network %s - START", network_id)
         network_path = "/tenants/tt/networks/%s" % network_id
         network_req = self.create_request(network_path, None,
-                                       self.contenttype, 'DELETE')
+                                          self.contenttype, 'DELETE')
         network_req.get_response(self.api)
         LOG.debug("Deleting network - END")
 
@@ -1108,10 +1203,15 @@ class MultiPortExtensionTest(unittest.TestCase):
 
         net_id = self._create_network('net1')
         net_id2 = self._create_network('net2')
-        test_multi_port = {'multiport':
-                            {'net_id_list': [net_id, net_id2],
-                             'status': 'ACTIVE',
-                             'ports_desc': {'key': 'value'}}}
+        test_multi_port = {
+            'multiport': {
+                'net_id_list': [net_id, net_id2],
+                'status': 'ACTIVE',
+                'ports_desc': {
+                    'key': 'value',
+                    },
+                },
+            }
         req_body = json.dumps(test_multi_port)
         index_response = self.test_app.post(self.multiport_path, req_body,
                                             content_type=self.contenttype)
index 345348bd028cad1b2535796f4b2a9d48bc1af07f..0b752f81f11840c3afc09cb1cf1fee16d96f4a4d 100644 (file)
 test_database.py is an independent test suite
 that tests the database api method calls
 """
+
 import logging as LOG
 import unittest
 
 from quantum.plugins.cisco.common import cisco_constants as const
-
 import quantum.plugins.cisco.db.api as db
 import quantum.plugins.cisco.db.l2network_db as l2network_db
 import quantum.plugins.cisco.db.nexus_db as nexus_db
@@ -72,13 +72,14 @@ class UcsDB(object):
             LOG.error("Failed to get port binding: %s" % str(exc))
         return port_binding
 
-    def create_port_binding(self, port_id, blade_intf_dn, portprofile_name, \
+    def create_port_binding(self, port_id, blade_intf_dn, portprofile_name,
                             vlan_name, vlan_id, qos):
         """create port binding"""
         port_bind_dict = {}
         try:
-            res = ucs_db.add_portbinding(port_id, blade_intf_dn, \
-                                  portprofile_name, vlan_name, vlan_id, qos)
+            res = ucs_db.add_portbinding(port_id, blade_intf_dn,
+                                         portprofile_name, vlan_name,
+                                         vlan_id, qos)
             LOG.debug("Created port binding: %s" % res.port_id)
             port_bind_dict["port-id"] = res.port_id
             port_bind_dict["blade-intf-dn"] = str(res.blade_intf_dn)
@@ -101,12 +102,13 @@ class UcsDB(object):
         except Exception, exc:
             raise Exception("Failed to delete port profile: %s" % str(exc))
 
-    def update_port_binding(self, port_id, blade_intf_dn, \
-                         portprofile_name, vlan_name, vlan_id, qos):
+    def update_port_binding(self, port_id, blade_intf_dn,
+                            portprofile_name, vlan_name, vlan_id, qos):
         """update port binding"""
         try:
-            res = ucs_db.update_portbinding(port_id, blade_intf_dn, \
-                               portprofile_name, vlan_name, vlan_id, qos)
+            res = ucs_db.update_portbinding(port_id, blade_intf_dn,
+                                            portprofile_name, vlan_name,
+                                            vlan_id, qos)
             LOG.debug("Updating port binding: %s" % res.port_id)
             port_bind_dict = {}
             port_bind_dict["port-id"] = res.port_id
@@ -223,7 +225,7 @@ class ServicesDB(object):
         """create service binding"""
         bind_dict = {}
         try:
-            res = services_db.add_services_binding(service_id, mngnet_id, \
+            res = services_db.add_services_binding(service_id, mngnet_id,
                                                    nbnet_id, sbnet_id)
             LOG.debug("Created service binding : %s" % res.service_id)
             bind_dict["service_id"] = str(res.service_id)
@@ -253,7 +255,7 @@ class L2networkDB(object):
         try:
             for vlan_bind in l2network_db.get_all_vlan_bindings():
                 LOG.debug("Getting vlan bindings for vlan: %s" %
-                            vlan_bind.vlan_id)
+                          vlan_bind.vlan_id)
                 vlan_dict = {}
                 vlan_dict["vlan-id"] = str(vlan_bind.vlan_id)
                 vlan_dict["vlan-name"] = vlan_bind.vlan_name
@@ -268,8 +270,8 @@ class L2networkDB(object):
         vlan = []
         try:
             for vlan_bind in l2network_db.get_vlan_binding(network_id):
-                LOG.debug("Getting vlan binding for vlan: %s"
-                           % vlan_bind.vlan_id)
+                LOG.debug("Getting vlan binding for vlan: %s" %
+                          vlan_bind.vlan_id)
                 vlan_dict = {}
                 vlan_dict["vlan-id"] = str(vlan_bind.vlan_id)
                 vlan_dict["vlan-name"] = vlan_bind.vlan_name
@@ -395,7 +397,7 @@ class L2networkDB(object):
         try:
             for pp_bind in l2network_db.get_all_pp_bindings():
                 LOG.debug("Getting port profile binding: %s" %
-                                               pp_bind.portprofile_id)
+                          pp_bind.portprofile_id)
                 ppbinding_dict = {}
                 ppbinding_dict["portprofile-id"] = str(pp_bind.portprofile_id)
                 ppbinding_dict["port-id"] = str(pp_bind.port_id)
@@ -412,7 +414,7 @@ class L2networkDB(object):
         try:
             for pp_bind in l2network_db.get_pp_binding(tenant_id, pp_id):
                 LOG.debug("Getting port profile binding: %s" %
-                                                 pp_bind.portprofile_id)
+                          pp_bind.portprofile_id)
                 ppbinding_dict = {}
                 ppbinding_dict["portprofile-id"] = str(pp_bind.portprofile_id)
                 ppbinding_dict["port-id"] = str(pp_bind.port_id)
@@ -428,7 +430,7 @@ class L2networkDB(object):
         ppbinding_dict = {}
         try:
             res = l2network_db.add_pp_binding(tenant_id, port_id, pp_id,
-                                                                default)
+                                              default)
             LOG.debug("Created port profile binding: %s" % res.portprofile_id)
             ppbinding_dict["portprofile-id"] = str(res.portprofile_id)
             ppbinding_dict["port-id"] = str(res.port_id)
@@ -453,8 +455,8 @@ class L2networkDB(object):
                           port_id, default):
         """Update portprofile binding"""
         try:
-            res = l2network_db.update_pp_binding(tenant_id, pp_id,
-                                            newtenant_id, port_id, default)
+            res = l2network_db.update_pp_binding(
+                tenant_id, pp_id, newtenant_id, port_id, default)
             LOG.debug("Updating port profile binding: %s" % res.portprofile_id)
             ppbinding_dict = {}
             ppbinding_dict["portprofile-id"] = str(res.portprofile_id)
@@ -653,8 +655,8 @@ class UcsDBTest(unittest.TestCase):
         """create port binding"""
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
-        port_bind1 = self.dbtest.create_port_binding(port1["port-id"],
-                                "vnic1", "pp1", "vlan1", 10, "qos1")
+        port_bind1 = self.dbtest.create_port_binding(
+            port1["port-id"], "vnic1", "pp1", "vlan1", 10, "qos1")
         self.assertTrue(port_bind1["port-id"] == port1["port-id"])
         self.teardown_portbinding()
         self.teardown_network_port()
@@ -664,10 +666,10 @@ class UcsDBTest(unittest.TestCase):
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
         port2 = self.quantum.create_port(net1["net-id"])
-        port_bind1 = self.dbtest.create_port_binding(port1["port-id"],
-                                "vnic1", "pp1", "vlan1", 10, "qos1")
-        port_bind2 = self.dbtest.create_port_binding(port2["port-id"],
-                                "vnic2", "pp2", "vlan2", 20, "qos2")
+        port_bind1 = self.dbtest.create_port_binding(
+            port1["port-id"], "vnic1", "pp1", "vlan1", 10, "qos1")
+        port_bind2 = self.dbtest.create_port_binding(
+            port2["port-id"], "vnic2", "pp2", "vlan2", 20, "qos2")
         port_bindings = self.dbtest.get_all_port_bindings()
         count = 0
         for pbind in port_bindings:
@@ -681,8 +683,8 @@ class UcsDBTest(unittest.TestCase):
         """delete port binding"""
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
-        port_bind1 = self.dbtest.create_port_binding(port1["port-id"],
-                                "vnic1", "pp1", "vlan1", 10, "qos1")
+        port_bind1 = self.dbtest.create_port_binding(
+            port1["port-id"], "vnic1", "pp1", "vlan1", 10, "qos1")
         self.dbtest.delete_port_binding(port1["port-id"])
         port_bindings = self.dbtest.get_all_port_bindings()
         count = 0
@@ -697,10 +699,10 @@ class UcsDBTest(unittest.TestCase):
         """update port binding"""
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
-        port_bind1 = self.dbtest.create_port_binding(port1["port-id"],
-                                "vnic1", "pp1", "vlan1", 10, "qos1")
-        port_bind1 = self.dbtest.update_port_binding(port1["port-id"],
-                        "vnic1", "newpp1", "newvlan1", 11, "newqos1")
+        port_bind1 = self.dbtest.create_port_binding(
+            port1["port-id"], "vnic1", "pp1", "vlan1", 10, "qos1")
+        port_bind1 = self.dbtest.update_port_binding(
+            port1["port-id"], "vnic1", "newpp1", "newvlan1", 11, "newqos1")
         port_bindings = self.dbtest.get_all_port_bindings()
         count = 0
         for pbind in port_bindings:
@@ -776,8 +778,8 @@ class NexusDBTest(unittest.TestCase):
     def testd_update_nexusportbinding(self):
         """update nexus port binding"""
         binding1 = self.dbtest.create_nexusportbinding("port1", 10)
-        binding1 = self.dbtest.update_nexusport_binding(binding1["port-id"], \
-                                                             20)
+        binding1 = self.dbtest.update_nexusport_binding(binding1["port-id"],
+                                                        20)
         bindings = self.dbtest.get_all_nexusportbindings()
         count = 0
         for bind in bindings:
@@ -809,15 +811,15 @@ class ServicesDBTest(unittest.TestCase):
 
     def testa_create_servicebinding(self):
         """create service binding"""
-        service_id = self.dbtest.create_servicebinding("i-00001", \
-                                    "mng_net", "northb_net", "northb_net")
+        service_id = self.dbtest.create_servicebinding(
+            "i-00001", "mng_net", "northb_net", "northb_net")
         self.assertTrue(service_id["service_id"] == "i-00001")
         self.tearDown_servicebinding()
 
     def testb_get_servicesbindings(self):
         """get all services binding"""
-        service_id = self.dbtest.create_servicebinding("i-00001", \
-                                    "mng_net", "northb_net", "northb_net")
+        service_id = self.dbtest.create_servicebinding(
+            "i-00001", "mng_net", "northb_net", "northb_net")
         bindings = self.dbtest.get_servicebindings("i-00001")
         count = 0
         if bindings:
@@ -827,10 +829,10 @@ class ServicesDBTest(unittest.TestCase):
 
     def testb_getall_servicesbindings(self):
         """get all services binding"""
-        service_id = self.dbtest.create_servicebinding("i-00001", \
-                                    "mng_net", "northb_net", "northb_net")
-        service_id = self.dbtest.create_servicebinding("i-00002", \
-                                    "mng_net", "northb_net", "northb_net")
+        service_id = self.dbtest.create_servicebinding(
+            "i-00001", "mng_net", "northb_net", "northb_net")
+        service_id = self.dbtest.create_servicebinding(
+            "i-00002", "mng_net", "northb_net", "northb_net")
         bindings = self.dbtest.get_all_servicesbindings()
         count = 0
         for bind in bindings:
@@ -841,8 +843,8 @@ class ServicesDBTest(unittest.TestCase):
 
     def testc_delete_servicesbinding(self):
         """delete services binding"""
-        binding_serv = self.dbtest.create_servicebinding("i-00001", \
-                                    "mng_net", "northb_net", "northb_net")
+        binding_serv = self.dbtest.create_servicebinding(
+            "i-00001", "mng_net", "northb_net", "northb_net")
         self.dbtest.delete_servicebinding("i-00001")
         bindings = self.dbtest.get_all_servicesbindings()
         count = 0
@@ -967,8 +969,8 @@ class L2networkDBTest(unittest.TestCase):
         """test update portprofile"""
         pp1 = self.dbtest.create_portprofile("t1", "portprofile1", 10, "qos1")
         self.assertTrue(pp1["portprofile-name"] == "portprofile1")
-        pp1 = self.dbtest.update_portprofile("t1", pp1["portprofile-id"], \
-                                          "newportprofile1", 20, "qos2")
+        pp1 = self.dbtest.update_portprofile("t1", pp1["portprofile-id"],
+                                             "newportprofile1", 20, "qos2")
         pps = self.dbtest.get_all_portprofiles()
         count = 0
         for pprofile in pps:
@@ -982,8 +984,8 @@ class L2networkDBTest(unittest.TestCase):
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
         pp1 = self.dbtest.create_portprofile("t1", "portprofile1", 10, "qos1")
-        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"], \
-                                              pp1["portprofile-id"], "0")
+        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"],
+                                                    pp1["portprofile-id"], "0")
         self.assertTrue(pp_binding1["tenant-id"] == "t1")
         self.teardown_portprofilebinding()
         self.teardown_port()
@@ -997,11 +999,11 @@ class L2networkDBTest(unittest.TestCase):
         port2 = self.quantum.create_port(net1["net-id"])
         pp1 = self.dbtest.create_portprofile("t1", "portprofile1", 10, "qos1")
         pp2 = self.dbtest.create_portprofile("t1", "portprofile2", 20, "qos2")
-        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"], \
-                                               pp1["portprofile-id"], "0")
+        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"],
+                                                    pp1["portprofile-id"], "0")
         self.assertTrue(pp_binding1["tenant-id"] == "t1")
-        pp_binding2 = self.dbtest.create_pp_binding("t1", port2["port-id"], \
-                                               pp2["portprofile-id"], "0")
+        pp_binding2 = self.dbtest.create_pp_binding("t1", port2["port-id"],
+                                                    pp2["portprofile-id"], "0")
         self.assertTrue(pp_binding2["tenant-id"] == "t1")
         pp_bindings = self.dbtest.get_all_pp_bindings()
         count = 0
@@ -1019,10 +1021,10 @@ class L2networkDBTest(unittest.TestCase):
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
         pp1 = self.dbtest.create_portprofile("t1", "portprofile1", 10, "qos1")
-        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"], \
-                                                pp1["portprofile-id"], "0")
+        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"],
+                                                    pp1["portprofile-id"], "0")
         self.assertTrue(pp_binding1["tenant-id"] == "t1")
-        self.dbtest.delete_pp_binding("t1", port1["port-id"], \
+        self.dbtest.delete_pp_binding("t1", port1["port-id"],
                                       pp_binding1["portprofile-id"])
         pp_bindings = self.dbtest.get_all_pp_bindings()
         count = 0
@@ -1040,11 +1042,11 @@ class L2networkDBTest(unittest.TestCase):
         net1 = self.quantum.create_network("t1", "netid1")
         port1 = self.quantum.create_port(net1["net-id"])
         pp1 = self.dbtest.create_portprofile("t1", "portprofile1", 10, "qos1")
-        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"], \
-                                                pp1["portprofile-id"], "0")
+        pp_binding1 = self.dbtest.create_pp_binding("t1", port1["port-id"],
+                                                    pp1["portprofile-id"], "0")
         self.assertTrue(pp_binding1["tenant-id"] == "t1")
-        pp_binding1 = self.dbtest.update_pp_binding("t1", \
-                      pp1["portprofile-id"], "newt1", port1["port-id"], "1")
+        pp_binding1 = self.dbtest.update_pp_binding(
+            "t1", pp1["portprofile-id"], "newt1", port1["port-id"], "1")
         pp_bindings = self.dbtest.get_all_pp_bindings()
         count = 0
         for pp_bind in pp_bindings:
@@ -1246,26 +1248,3 @@ class QuantumDBTest(unittest.TestCase):
             for port in ports:
                 self.dbtest.delete_port(port["net-id"], port["port-id"])
             self.dbtest.delete_network(netid)
-
-"""
-if __name__ == "__main__":
-    usagestr = "Usage: %prog [OPTIONS] <command> [args]"
-    parser = OptionParser(usage=usagestr)
-    parser.add_option("-v", "--verbose", dest="verbose",
-      action="store_true", default=False, help="turn on verbose logging")
-
-    options, args = parser.parse_args()
-
-    if options.verbose:
-        LOG.basicConfig(level=LOG.DEBUG)
-    else:
-        LOG.basicConfig(level=LOG.WARN)
-
-    l2network_db.initialize()
-
-    # Run the tests
-    suite = unittest.TestLoader().loadTestsFromTestCase(QuantumDBTest)
-    unittest.TextTestRunner(verbosity=2).run(suite)
-    suite = unittest.TestLoader().loadTestsFromTestCase(L2networkDBTest)
-    unittest.TextTestRunner(verbosity=2).run(suite)
-"""
index 078116d6e9910e9d2e7dee2a826e33a1dbd92698..cf53b1ce98e4780a8ced285b54266f91aab64b7c 100644 (file)
@@ -19,6 +19,7 @@
 
 import logging
 import unittest
+
 from quantum.common import exceptions as exc
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_exceptions as cexc
@@ -27,6 +28,7 @@ from quantum.plugins.cisco import l2network_plugin_configuration as conf
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
 
+
 LOG = logging.getLogger('quantum.tests.test_core_api_func')
 
 
@@ -48,7 +50,7 @@ class CoreAPITestFunc(unittest.TestCase):
         else:
             network_name = self.network_name
         new_net_dict = self._l2network_plugin.create_network(
-                               tenant_id, network_name)
+            tenant_id, network_name)
         net = db.network_get(new_net_dict[const.NET_ID])
         self.assertEqual(net[const.NETWORKNAME], network_name)
         self.assertEqual(new_net_dict[const.NET_NAME], network_name)
@@ -65,13 +67,13 @@ class CoreAPITestFunc(unittest.TestCase):
         else:
             tenant_id = self.tenant_id
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         delete_net_dict = self._l2network_plugin.delete_network(
-                                tenant_id, new_net_dict[const.NET_ID])
+            tenant_id, new_net_dict[const.NET_ID])
         self.assertRaises(exc.NetworkNotFound, db.network_get,
                           new_net_dict[const.NET_ID])
-        self.assertEqual(
-                new_net_dict[const.NET_ID], delete_net_dict[const.NET_ID])
+        self.assertEqual(new_net_dict[const.NET_ID],
+                         delete_net_dict[const.NET_ID])
         LOG.debug("test_delete_network - END")
 
     def test_delete_networkDNE(self, net_tenant_id=None, net_id='0005'):
@@ -99,9 +101,9 @@ class CoreAPITestFunc(unittest.TestCase):
         LOG.debug("test_delete_networkInUse - START")
 
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                tenant_id, new_net_dict[const.NET_ID], self.state)
+            tenant_id, new_net_dict[const.NET_ID], self.state)
         instance_desc = {'project_id': tenant_id,
                          'user_id': nova_user_id}
         host_list = self._l2network_plugin.schedule_host(instance_tenant_id,
@@ -111,15 +113,15 @@ class CoreAPITestFunc(unittest.TestCase):
                              'user_id': nova_user_id,
                              'vif_id': vif_id}
         vif_description = self._l2network_plugin.associate_port(
-                                 instance_tenant_id, instance_id,
-                                 instance_vif_desc)
+            instance_tenant_id, instance_id,
+            instance_vif_desc)
 
         self.assertRaises(exc.NetworkInUse,
                           self._l2network_plugin.delete_network, tenant_id,
                           new_net_dict[const.NET_ID])
         self.tearDownNetworkPortInterface(
-                 tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
-                 new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
+            tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
+            new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
         LOG.debug("test_delete_networkInUse - END")
 
     def test_show_network(self, net_tenant_id=None):
@@ -133,13 +135,13 @@ class CoreAPITestFunc(unittest.TestCase):
         else:
             tenant_id = self.tenant_id
         new_net_dict = self._l2network_plugin.create_network(
-                        tenant_id, self.network_name)
+            tenant_id, self.network_name)
         result_net_dict = self._l2network_plugin.get_network_details(
-                                tenant_id, new_net_dict[const.NET_ID])
+            tenant_id, new_net_dict[const.NET_ID])
         net = db.network_get(new_net_dict[const.NET_ID])
         self.assertEqual(net[const.UUID], new_net_dict[const.NET_ID])
-        self.assertEqual(
-                new_net_dict[const.NET_ID], result_net_dict[const.NET_ID])
+        self.assertEqual(new_net_dict[const.NET_ID],
+                         result_net_dict[const.NET_ID])
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
         LOG.debug("test_show_network - END")
 
@@ -170,10 +172,10 @@ class CoreAPITestFunc(unittest.TestCase):
         else:
             tenant_id = self.tenant_id
         new_net_dict = self._l2network_plugin.create_network(
-                        tenant_id, self.network_name)
+            tenant_id, self.network_name)
         rename_net_dict = self._l2network_plugin.update_network(
-                            tenant_id, new_net_dict[const.NET_ID],
-                            name=new_name)
+            tenant_id, new_net_dict[const.NET_ID],
+            name=new_name)
         net = db.network_get(new_net_dict[const.NET_ID])
         self.assertEqual(net[const.NETWORKNAME], new_name)
         self.assertEqual(new_name, rename_net_dict[const.NET_NAME])
@@ -203,9 +205,9 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_list_networks - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         new_net_dict2 = self._l2network_plugin.create_network(
-                                tenant_id, 'test_net2')
+            tenant_id, 'test_net2')
         net_list = self._l2network_plugin.get_all_networks(tenant_id)
         net_temp_list = [new_net_dict, new_net_dict2]
         networks_list = db.network_list(tenant_id)
@@ -231,15 +233,15 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_list_ports - START")
         new_net_dict = self._l2network_plugin.create_network(
-                        tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         port_dict2 = self._l2network_plugin.create_port(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         port_list = self._l2network_plugin.get_all_ports(
-                        tenant_id, new_net_dict[const.NET_ID])
+            tenant_id, new_net_dict[const.NET_ID])
         port_temp_list = [port_dict, port_dict2]
         network = db.network_get(new_net_dict[const.NET_ID])
         ports_list = network[const.NETWORKPORTS]
@@ -270,9 +272,9 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_create_port - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                tenant_id, new_net_dict[const.NET_ID], state)
+            tenant_id, new_net_dict[const.NET_ID], state)
         port = db.port_get(new_net_dict[const.NET_ID],
                            port_dict[const.PORT_ID])
         self.assertEqual(port_dict[const.PORT_STATE], state)
@@ -308,13 +310,13 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_delete_port - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                            tenant_id, new_net_dict[const.NET_ID],
-                            state)
+            tenant_id, new_net_dict[const.NET_ID],
+            state)
         delete_port_dict = self._l2network_plugin.delete_port(
-                                tenant_id, new_net_dict[const.NET_ID],
-                                port_dict[const.PORT_ID])
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID])
         self.assertRaises(exc.PortNotFound, db.port_get,
                           new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
@@ -330,7 +332,7 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_delete_port_networkDNE - START")
         self.assertRaises(exc.NetworkNotFound,
-                              self._l2network_plugin.delete_port, tenant_id,
+                          self._l2network_plugin.delete_port, tenant_id,
                           net_id, port_id)
         LOG.debug("test_delete_port_networkDNE - END")
 
@@ -341,26 +343,28 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_delete_portDNE - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         self.assertRaises(exc.PortNotFound, self._l2network_plugin.delete_port,
                           tenant_id, new_net_dict[const.NET_ID], port_id)
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
         LOG.debug("test_delete_portDNE - END")
 
-    def test_delete_portInUse(
-                    self, tenant_id='test_tenant', instance_tenant_id='nova',
-                    nova_user_id='novaadmin', instance_id=10,
-                    vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
+    def test_delete_portInUse(self,
+                              tenant_id='test_tenant',
+                              instance_tenant_id='nova',
+                              nova_user_id='novaadmin',
+                              instance_id=10,
+                              vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
         """
         Tests deletion of Ports when port is in Use.
         """
 
         LOG.debug("test_delete_portInUse - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                        tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                                tenant_id, new_net_dict[const.NET_ID],
-                                self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         instance_desc = {'project_id': tenant_id,
                          'user_id': nova_user_id}
         host_list = self._l2network_plugin.schedule_host(instance_tenant_id,
@@ -370,14 +374,14 @@ class CoreAPITestFunc(unittest.TestCase):
                              'user_id': nova_user_id,
                              'vif_id': vif_id}
         vif_description = self._l2network_plugin.associate_port(
-                                 instance_tenant_id, instance_id,
-                                 instance_vif_desc)
+            instance_tenant_id, instance_id,
+            instance_vif_desc)
         self.assertRaises(exc.PortInUse,
                           self._l2network_plugin.delete_port, tenant_id,
                           new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
         self.tearDownNetworkPortInterface(
-                 tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
-                 new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
+            tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
+            new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
         LOG.debug("test_delete_portInUse - END")
 
     def test_update_port(self, tenant_id='test_tenant',
@@ -388,13 +392,13 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_update_port - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                        tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         update_port_dict = self._l2network_plugin.update_port(
-                              tenant_id, new_net_dict[const.NET_ID],
-                              port_dict[const.PORT_ID], state=state)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], state=state)
         new_port = db.port_get(new_net_dict[const.NET_ID],
                                port_dict[const.PORT_ID])
         self.assertEqual(new_port[const.PORTSTATE], state)
@@ -422,7 +426,7 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_update_portDNE - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         self.assertRaises(
             exc.PortNotFound, self._l2network_plugin.update_port, tenant_id,
             new_net_dict[const.NET_ID], port_id, state=const.PORT_UP)
@@ -436,13 +440,13 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_show_port - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         get_port_dict = self._l2network_plugin.get_port_details(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        port_dict[const.PORT_ID])
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID])
         port = db.port_get(new_net_dict[const.NET_ID],
                            port_dict[const.PORT_ID])
         self.assertEqual(port[const.PORTSTATE], self.state)
@@ -470,17 +474,19 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_show_portDNE - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         self.assertRaises(exc.PortNotFound,
                           self._l2network_plugin.get_port_details, tenant_id,
                           new_net_dict[const.NET_ID], port_id)
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
         LOG.debug("test_show_portDNE - END")
 
-    def test_plug_interface(
-                    self, tenant_id='test_tenant', instance_tenant_id='nova',
-                    nova_user_id='novaadmin', instance_id=10,
-                    vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
+    def test_plug_interface(self,
+                            tenant_id='test_tenant',
+                            instance_tenant_id='nova',
+                            nova_user_id='novaadmin',
+                            instance_id=10,
+                            vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
         """
         Tests attachment of interface to the port
         """
@@ -499,24 +505,26 @@ class CoreAPITestFunc(unittest.TestCase):
                              'user_id': nova_user_id,
                              'vif_id': vif_id}
         vif_description = self._l2network_plugin.associate_port(
-                                 instance_tenant_id, instance_id,
-                                 instance_vif_desc)
+            instance_tenant_id, instance_id,
+            instance_vif_desc)
 
         self._l2network_plugin.plug_interface(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        port_dict[const.PORT_ID], vif_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], vif_id)
         port = db.port_get(new_net_dict[const.NET_ID],
                            port_dict[const.PORT_ID])
         self.assertEqual(port[const.INTERFACEID], vif_id)
         self.tearDownNetworkPortInterface(
-                 tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
-                 new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
+            tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
+            new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
 
         LOG.debug("test_plug_interface - END")
 
-    def test_plug_interface_networkDNE(
-                        self, tenant_id='test_tenant', net_id='0005',
-                        port_id='p0005', remote_interface='new_interface'):
+    def test_plug_interface_networkDNE(self,
+                                       tenant_id='test_tenant',
+                                       net_id='0005',
+                                       port_id='p0005',
+                                       remote_interface='new_interface'):
         """
         Tests attachment of interface network does not exist
         """
@@ -535,8 +543,8 @@ class CoreAPITestFunc(unittest.TestCase):
         """
 
         LOG.debug("test_plug_interface_portDNE - START")
-        new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+        new_net_dict = self._l2network_plugin.create_network(tenant_id,
+                                                             self.network_name)
         self.assertRaises(
             exc.PortNotFound, self._l2network_plugin.plug_interface, tenant_id,
             new_net_dict[const.NET_ID], port_id, remote_interface)
@@ -544,11 +552,10 @@ class CoreAPITestFunc(unittest.TestCase):
         LOG.debug("test_plug_interface_portDNE - END")
 
     def test_plug_interface_portInUse(
-                  self, tenant_id='test_tenant', instance_tenant_id='nova',
-                  nova_user_id='novaadmin', instance_id=10,
-                  vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
-                  remote_interface='new_interface'):
-
+        self, tenant_id='test_tenant', instance_tenant_id='nova',
+        nova_user_id='novaadmin', instance_id=10,
+        vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
+        remote_interface='new_interface'):
         """
         Tests attachment of new interface to the port when there is an
         existing attachment
@@ -556,9 +563,9 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_plug_interface_portInUse - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                        tenant_id, new_net_dict[const.NET_ID], self.state)
+            tenant_id, new_net_dict[const.NET_ID], self.state)
         instance_desc = {'project_id': tenant_id,
                          'user_id': nova_user_id}
         host_list = self._l2network_plugin.schedule_host(instance_tenant_id,
@@ -568,34 +575,33 @@ class CoreAPITestFunc(unittest.TestCase):
                              'user_id': nova_user_id,
                              'vif_id': vif_id}
         vif_description = self._l2network_plugin.associate_port(
-                                 instance_tenant_id, instance_id,
-                                 instance_vif_desc)
+            instance_tenant_id, instance_id,
+            instance_vif_desc)
 
         self.assertRaises(exc.PortInUse,
-                              self._l2network_plugin.plug_interface, tenant_id,
-                              new_net_dict[const.NET_ID],
-                              port_dict[const.PORT_ID], remote_interface)
+                          self._l2network_plugin.plug_interface, tenant_id,
+                          new_net_dict[const.NET_ID],
+                          port_dict[const.PORT_ID], remote_interface)
         self.tearDownNetworkPortInterface(
-                 tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
-                 new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
+            tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
+            new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
 
         LOG.debug("test_plug_interface_portInUse - END")
 
     def test_unplug_interface(
-                    self, tenant_id='test_tenant', instance_tenant_id='nova',
-                    nova_user_id='novaadmin', instance_id=10,
-                    vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
-
+        self, tenant_id='test_tenant', instance_tenant_id='nova',
+        nova_user_id='novaadmin', instance_id=10,
+        vif_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
         """
         Tests detaachment of an interface to a port
         """
 
         LOG.debug("test_unplug_interface - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                                tenant_id, new_net_dict[const.NET_ID],
-                                self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         instance_desc = {'project_id': tenant_id,
                          'user_id': nova_user_id}
         host_list = self._l2network_plugin.schedule_host(instance_tenant_id,
@@ -605,22 +611,22 @@ class CoreAPITestFunc(unittest.TestCase):
                              'user_id': nova_user_id,
                              'vif_id': vif_id}
         vif_description = self._l2network_plugin.associate_port(
-                                 instance_tenant_id, instance_id,
-                                 instance_vif_desc)
+            instance_tenant_id, instance_id,
+            instance_vif_desc)
 
         self._l2network_plugin.plug_interface(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        port_dict[const.PORT_ID], vif_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], vif_id)
         self._l2network_plugin.unplug_interface(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        port_dict[const.PORT_ID])
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID])
         port = db.port_get(new_net_dict[const.NET_ID],
                            port_dict[const.PORT_ID])
         vif_id_unplugged = vif_id + '(detached)'
         self.assertEqual(port[const.INTERFACEID], vif_id_unplugged)
         self.tearDownNetworkPortInterface(
-                 tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
-                 new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
+            tenant_id, instance_tenant_id, instance_id, instance_vif_desc,
+            new_net_dict[const.NET_ID], port_dict[const.PORT_ID])
 
         LOG.debug("test_unplug_interface - END")
 
@@ -633,7 +639,7 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_unplug_interface_networkDNE - START")
         self.assertRaises(exc.NetworkNotFound,
-                             self._l2network_plugin.unplug_interface,
+                          self._l2network_plugin.unplug_interface,
                           tenant_id, net_id, port_id)
         LOG.debug("test_unplug_interface_networkDNE - END")
 
@@ -646,10 +652,10 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_unplug_interface_portDNE - START")
         new_net_dict = self._l2network_plugin.create_network(tenant_id,
-                                                        self.network_name)
+                                                             self.network_name)
         self.assertRaises(exc.PortNotFound,
-                self._l2network_plugin.unplug_interface, tenant_id,
-                new_net_dict[const.NET_ID], port_id)
+                          self._l2network_plugin.unplug_interface, tenant_id,
+                          new_net_dict[const.NET_ID], port_id)
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
         LOG.debug("test_unplug_interface_portDNE - END")
 
@@ -660,7 +666,7 @@ class CoreAPITestFunc(unittest.TestCase):
         """
 
         LOG.debug("test_create_portprofile - tenant id: %s - START",
-                                                net_tenant_id)
+                  net_tenant_id)
         if net_tenant_id:
             tenant_id = net_tenant_id
         else:
@@ -674,14 +680,14 @@ class CoreAPITestFunc(unittest.TestCase):
         else:
             qos = self.qos
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                                tenant_id, profile_name, qos)
+            tenant_id, profile_name, qos)
         port_profile_id = port_profile_dict['profile_id']
         port_profile = cdb.get_portprofile(tenant_id, port_profile_id)
         self.assertEqual(port_profile[const.PPNAME], profile_name)
         self.assertEqual(port_profile[const.PPQOS], qos)
         self.tearDownPortProfile(tenant_id, port_profile_id)
         LOG.debug("test_create_portprofile - tenant id: %s - END",
-                                                net_tenant_id)
+                  net_tenant_id)
 
     def test_delete_portprofile(self, net_tenant_id=None):
         """
@@ -689,18 +695,18 @@ class CoreAPITestFunc(unittest.TestCase):
         """
 
         LOG.debug("test_delete_portprofile - tenant id: %s - START",
-                                                net_tenant_id)
+                  net_tenant_id)
         if net_tenant_id:
             tenant_id = net_tenant_id
         else:
             tenant_id = self.tenant_id
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                                tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_id = port_profile_dict['profile_id']
         self._l2network_plugin.delete_portprofile(tenant_id, port_profile_id)
         self.assertRaises(Exception, cdb.get_portprofile, port_profile_id)
         LOG.debug("test_delete_portprofile - tenant id: %s - END",
-                                                     net_tenant_id)
+                  net_tenant_id)
 
     def test_delete_portprofileDNE(self, tenant_id='test_tenant',
                                    profile_id='pr0005'):
@@ -722,22 +728,22 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_delete_portprofileAssociated - START")
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                                tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_id = port_profile_dict['profile_id']
         new_net_dict = self._l2network_plugin.create_network(
                         tenant_id, 'test_network')
         port_dict = self._l2network_plugin.create_port(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        const.PORT_UP)
+            tenant_id, new_net_dict[const.NET_ID],
+            const.PORT_UP)
         self._l2network_plugin.associate_portprofile(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        port_dict[const.PORT_ID], port_profile_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], port_profile_id)
         self.assertRaises(cexc.PortProfileInvalidDelete,
                           self._l2network_plugin.delete_portprofile,
                           tenant_id, port_profile_id)
         self.tearDownAssociatePortProfile(
-                         tenant_id, new_net_dict[const.NET_ID],
-                         port_dict[const.PORT_ID], port_profile_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], port_profile_id)
         self.tearDownNetworkPort(tenant_id, new_net_dict[const.NET_ID],
                                  port_dict[const.PORT_ID])
         LOG.debug("test_delete_portprofileAssociated - END")
@@ -751,13 +757,13 @@ class CoreAPITestFunc(unittest.TestCase):
         profile_name2 = tenant_id + '_port_profile2'
         qos2 = tenant_id + 'qos2'
         port_profile_dict1 = self._l2network_plugin.create_portprofile(
-                                tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_dict2 = self._l2network_plugin.create_portprofile(
-                                tenant_id, profile_name2, qos2)
+            tenant_id, profile_name2, qos2)
         port_profile_id1 = port_profile_dict1['profile_id']
         port_profile_id2 = port_profile_dict2['profile_id']
         list_all_portprofiles = self._l2network_plugin.get_all_portprofiles(
-                                                                tenant_id)
+            tenant_id)
         port_profile_list = [port_profile_dict1, port_profile_dict2]
         pplist = cdb.get_all_portprofiles()
         new_pplist = []
@@ -785,17 +791,17 @@ class CoreAPITestFunc(unittest.TestCase):
         else:
             tenant_id = self.tenant_id
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                        tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_id = port_profile_dict['profile_id']
         result_port_profile = self._l2network_plugin.get_portprofile_details(
-                                        tenant_id, port_profile_id)
+            tenant_id, port_profile_id)
         port_profile = cdb.get_portprofile(tenant_id, port_profile_id)
         self.assertEqual(port_profile[const.PPQOS], self.qos)
         self.assertEqual(port_profile[const.PPNAME], self.profile_name)
         self.assertEqual(result_port_profile[const.PROFILE_QOS],
-                                                        self.qos)
+                         self.qos)
         self.assertEqual(result_port_profile[const.PROFILE_NAME],
-                                                self.profile_name)
+                         self.profile_name)
         self.tearDownPortProfile(tenant_id, port_profile_id)
         LOG.debug("test_show_portprofile - tenant id: %s - END", net_tenant_id)
 
@@ -808,7 +814,7 @@ class CoreAPITestFunc(unittest.TestCase):
         LOG.debug("test_show_portprofileDNE - START")
         self.assertRaises(Exception,
                           self._l2network_plugin.get_portprofile_details,
-                             tenant_id, profile_id)
+                          tenant_id, profile_id)
         LOG.debug("test_show_portprofileDNE - END")
 
     def test_rename_portprofile(self, tenant_id='test_tenant',
@@ -819,14 +825,14 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_rename_portprofile - START")
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                                tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_id = port_profile_dict['profile_id']
         result_port_profile_dict = self._l2network_plugin.rename_portprofile(
-                                tenant_id, port_profile_id, new_profile_name)
+            tenant_id, port_profile_id, new_profile_name)
         port_profile = cdb.get_portprofile(tenant_id, port_profile_id)
         self.assertEqual(port_profile[const.PPNAME], new_profile_name)
         self.assertEqual(result_port_profile_dict[const.PROFILE_NAME],
-                                                        new_profile_name)
+                         new_profile_name)
         self.tearDownPortProfile(tenant_id, port_profile_id)
         LOG.debug("test_show_portprofile - tenant id: %s - END")
 
@@ -850,25 +856,24 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_associate_portprofile - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                                tenant_id, new_net_dict[const.NET_ID],
-                                self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                        tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_id = port_profile_dict['profile_id']
         self._l2network_plugin.associate_portprofile(
-                        tenant_id, new_net_dict[const.NET_ID],
-                        port_dict[const.PORT_ID], port_profile_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], port_profile_id)
         port_profile_associate = cdb.get_pp_binding(tenant_id, port_profile_id)
         self.assertEqual(port_profile_associate[const.PORTID],
                          port_dict[const.PORT_ID])
         self.tearDownAssociatePortProfile(
-                     tenant_id, new_net_dict[const.NET_ID],
-                     port_dict[const.PORT_ID], port_profile_id)
-        self.tearDownNetworkPort(
-                          tenant_id, new_net_dict[const.NET_ID],
-                          port_dict[const.PORT_ID])
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], port_profile_id)
+        self.tearDownNetworkPort(tenant_id, new_net_dict[const.NET_ID],
+                                 port_dict[const.PORT_ID])
         LOG.debug("test_associate_portprofile - END")
 
     def test_associate_portprofileDNE(self, tenant_id='test_tenant',
@@ -892,25 +897,25 @@ class CoreAPITestFunc(unittest.TestCase):
 
         LOG.debug("test_disassociate_portprofile - START")
         new_net_dict = self._l2network_plugin.create_network(
-                                tenant_id, self.network_name)
+            tenant_id, self.network_name)
         port_dict = self._l2network_plugin.create_port(
-                                tenant_id, new_net_dict[const.NET_ID],
-                                self.state)
+            tenant_id, new_net_dict[const.NET_ID],
+            self.state)
         port_profile_dict = self._l2network_plugin.create_portprofile(
-                                tenant_id, self.profile_name, self.qos)
+            tenant_id, self.profile_name, self.qos)
         port_profile_id = port_profile_dict['profile_id']
         self._l2network_plugin.associate_portprofile(
-                          tenant_id, new_net_dict[const.NET_ID],
-                          port_dict[const.PORT_ID], port_profile_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], port_profile_id)
         self._l2network_plugin.disassociate_portprofile(
-                          tenant_id, new_net_dict[const.NET_ID],
-                          port_dict[const.PORT_ID], port_profile_id)
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID], port_profile_id)
         port_profile_associate = cdb.get_pp_binding(tenant_id, port_profile_id)
         self.assertEqual(port_profile_associate, [])
         self.tearDownPortProfile(tenant_id, port_profile_id)
         self.tearDownNetworkPort(
-                          tenant_id, new_net_dict[const.NET_ID],
-                          port_dict[const.PORT_ID])
+            tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORT_ID])
         LOG.debug("test_disassociate_portprofile - END")
 
     def test_disassociate_portprofileDNE(self, tenant_id='test_tenant',
@@ -1032,7 +1037,7 @@ class CoreAPITestFunc(unittest.TestCase):
         Tear down associate port profile
         """
         self._l2network_plugin.disassociate_portprofile(
-                        tenant_id, net_id, port_id, port_profile_id)
+            tenant_id, net_id, port_id, port_profile_id)
         self.tearDownPortProfile(tenant_id, port_profile_id)
 
     def _make_net_dict(self, net_id, net_name, ports):
@@ -1049,12 +1054,14 @@ class CoreAPITestFunc(unittest.TestCase):
     def _make_portprofile_dict(self, tenant_id, profile_id, profile_name,
                                qos):
         profile_associations = self._make_portprofile_assc_list(
-                                          tenant_id, profile_id)
-        res = {const.PROFILE_ID: str(profile_id),
-               const.PROFILE_NAME: profile_name,
-               const.PROFILE_ASSOCIATIONS: profile_associations,
-               const.PROFILE_VLAN_ID: None,
-               const.PROFILE_QOS: qos}
+            tenant_id, profile_id)
+        res = {
+            const.PROFILE_ID: str(profile_id),
+            const.PROFILE_NAME: profile_name,
+            const.PROFILE_ASSOCIATIONS: profile_associations,
+            const.PROFILE_VLAN_ID: None,
+            const.PROFILE_QOS: qos,
+            }
         return res
 
     def _make_portprofile_assc_list(self, tenant_id, profile_id):
index e42bc20dbe226b801bcae59e5ffdd52bd556362c..e69d4bf3e9cf785a61355212ff89896242fc617e 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 # @author: Peter Strunk, Cisco Systems, Inc.
 # @author: Atul Gaikad, Cisco Systems, Inc.
 # @author: Tyler Smith, Cisco Systems, Inc.
-#
-"""
 
+import logging
 import unittest
-import logging as LOG
 
 from quantum.common import exceptions as exc
 from quantum.common import utils
-from quantum.plugins.cisco import l2network_plugin_configuration as conf
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_credentials as creds
-from quantum.plugins.cisco.models import l2network_multi_blade
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
+from quantum.plugins.cisco import l2network_plugin_configuration as conf
+from quantum.plugins.cisco.models import l2network_multi_blade
+
 
-LOG.basicConfig(level=LOG.WARN)
-LOG.getLogger(__name__)
+logging.basicConfig(level=logging.WARN)
+LOG = logging.getLogger(__name__)
 
 
 # Set some data to use in tests
@@ -72,10 +70,10 @@ class TestMultiBlade(unittest.TestCase):
         self.port_id = 0
 
         # Create the multiblade object
-        self._l2network_multiblade = l2network_multi_blade. \
-                     L2NetworkMultiBlade()
-        self.plugin_key = "quantum.plugins.cisco.ucs.cisco_ucs_plugin" + \
-                            ".UCSVICPlugin"
+        self._l2network_multiblade = (
+            l2network_multi_blade.L2NetworkMultiBlade())
+        self.plugin_key = (
+            "quantum.plugins.cisco.ucs.cisco_ucs_plugin.UCSVICPlugin")
 
         # Get UCS inventory to make sure all UCSs are affected by tests
         for key in conf.PLUGINS[const.PLUGINS].keys():
@@ -83,15 +81,14 @@ class TestMultiBlade(unittest.TestCase):
                 self._inventory[key] = utils.import_object(
                     conf.PLUGINS[const.INVENTORY][key])
 
-        self.ucs_count = self._inventory['ucs_plugin'].\
-                             _inventory.__len__()
+        self.ucs_count = self._inventory['ucs_plugin']._inventory.__len__()
 
     def tearDown(self):
         """Tear down our tests"""
         try:
             port = db.port_get(self.net_id, self.port_id)
             self._l2network_multiblade.delete_port([tenant_id, self.net_id,
-                                                self.port_id])
+                                                    self.port_id])
         except exc.NetworkNotFound:
             # We won't always have a port to remove
             pass
@@ -113,11 +110,13 @@ class TestMultiBlade(unittest.TestCase):
 
         # Create the network in the test DB, then with the model
         self.net_id = db.network_create(tenant_id, net_name)[const.UUID]
-        networks = self._l2network_multiblade.create_network([tenant_id,
-                                                   net_name,
-                                                   self.net_id,
-                                                   vlan_name(self.net_id),
-                                                   vlan_id])
+        networks = self._l2network_multiblade.create_network([
+            tenant_id,
+            net_name,
+            self.net_id,
+            vlan_name(self.net_id),
+            vlan_id,
+            ])
         cdb.add_vlan_binding(vlan_id, vlan_name(self.net_id), self.net_id)
 
         for network in networks:
@@ -140,7 +139,7 @@ class TestMultiBlade(unittest.TestCase):
         cdb.add_vlan_binding(vlan_id, vlan_name(self.net_id), self.net_id)
 
         networks = self._l2network_multiblade.delete_network([tenant_id,
-                                                   self.net_id])
+                                                              self.net_id])
         cdb.remove_vlan_binding(self.net_id)
         db.network_destroy(self.net_id)
         for network in networks:
@@ -174,9 +173,11 @@ class TestMultiBlade(unittest.TestCase):
 
         net_details = db.network_update(self.net_id, tenant_id,
                                         name=new_net_name)
-        networks = self._l2network_multiblade.update_network([tenant_id,
-                                                   self.net_id,
-                                                   {'name': new_net_name}])
+        networks = self._l2network_multiblade.update_network([
+            tenant_id,
+            self.net_id,
+            {'name': new_net_name},
+            ])
 
         for network in networks:
             self.assertEqual(network[const.NET_ID], self.net_id)
@@ -212,9 +213,9 @@ class TestMultiBlade(unittest.TestCase):
 
         self.port_id = db.port_create(self.net_id, port_state)[const.UUID]
         port = self._l2network_multiblade.create_port([tenant_id,
-                                                self.net_id,
-                                                port_state,
-                                                self.port_id])
+                                                       self.net_id,
+                                                       port_state,
+                                                       self.port_id])
 
         self.assertEqual(self.port_id, port[0][const.PORTID])
         LOG.debug("test_create_port - END")
@@ -236,8 +237,8 @@ class TestMultiBlade(unittest.TestCase):
                                                 port_state, self.port_id])
 
         port = self._l2network_multiblade.delete_port([tenant_id,
-                                                self.net_id,
-                                                self.port_id])
+                                                       self.net_id,
+                                                       self.port_id])
 
         self.assertEqual(self.port_id, port[0][const.PORTID])
 
@@ -285,8 +286,8 @@ class TestMultiBlade(unittest.TestCase):
                                                 self.net_id,
                                                 port_state, self.port_id])
 
-        interface = self._l2network_multiblade.plug_interface([tenant_id,
-                              self.net_id, self.port_id, interface_id])
+        interface = self._l2network_multiblade.plug_interface(
+            [tenant_id, self.net_id, self.port_id, interface_id])
         port = db.port_set_attachment(self.net_id, self.port_id, interface_id)
 
         self.assertEqual(self.port_id, interface[0][const.PORTID])
@@ -349,10 +350,11 @@ class TestMultiBlade(unittest.TestCase):
                                                 port_state, self.port_id])
 
         self._l2network_multiblade.plug_interface([tenant_id, self.net_id,
-                                                  self.port_id, interface_id])
+                                                   self.port_id, interface_id])
         db.port_set_attachment(self.net_id, self.port_id, interface_id)
         interface = self._l2network_multiblade.unplug_interface([tenant_id,
-                                            self.net_id, self.port_id])
+                                                                 self.net_id,
+                                                                 self.port_id])
 
         self.assertEqual(self.port_id, interface[0][const.PORTID])
         LOG.debug("test_unplug_interface - END")
index ce9a480d7cb0fc099ee616c0269a538f615ed910..4d3a8c47081483e43ee1b53f963d979d5205d5e3 100644 (file)
 #    under the License.
 #
 # @author: Shweta Padubidri, Peter Strunk, Cisco Systems, Inc.
-#
+
 import logging
 import unittest
+
 from quantum.common import exceptions as exc
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_credentials as creds
-from quantum.plugins.cisco.db import l2network_db as cdb
 from quantum.plugins.cisco.db import api as db
-from quantum.plugins.cisco.common import cisco_credentials as cred
+from quantum.plugins.cisco.db import l2network_db as cdb
 from quantum.plugins.cisco.nexus import cisco_nexus_plugin
 
+
 LOG = logging.getLogger('quantum.tests.test_nexus')
 
 
@@ -42,7 +43,7 @@ class TestNexusPlugin(unittest.TestCase):
         self.port_id = "9"
         db.configure_db({'sql_connection': 'sqlite:///:memory:'})
         cdb.initialize()
-        cred.Store.initialize()
+        creds.Store.initialize()
         self._cisco_nexus_plugin = cisco_nexus_plugin.NexusPlugin()
 
     def test_create_network(self, net_tenant_id=None, network_name=None,
@@ -72,8 +73,8 @@ class TestNexusPlugin(unittest.TestCase):
         network_created = self.create_network(tenant_id, net_name)
         cdb.add_vlan_binding(vlan_id, vlan_name, network_created["net-id"])
         new_net_dict = self._cisco_nexus_plugin.create_network(
-                            tenant_id, net_name, network_created["net-id"],
-                            vlan_name, vlan_id)
+            tenant_id, net_name, network_created["net-id"],
+            vlan_name, vlan_id)
         self.assertEqual(new_net_dict[const.NET_ID],
                          network_created["net-id"])
         self.assertEqual(new_net_dict[const.NET_NAME], self.net_name)
@@ -102,10 +103,10 @@ class TestNexusPlugin(unittest.TestCase):
         cdb.add_vlan_binding(self.vlan_id, self.vlan_name,
                              network_created["net-id"])
         new_net_dict = self._cisco_nexus_plugin.create_network(
-                           tenant_id, self.net_name, network_created["net-id"],
-                           self.vlan_name, self.vlan_id)
+            tenant_id, self.net_name, network_created["net-id"],
+            self.vlan_name, self.vlan_id)
         deleted_net_dict = self._cisco_nexus_plugin.delete_network(
-                        tenant_id, new_net_dict[const.NET_ID])
+            tenant_id, new_net_dict[const.NET_ID])
         self.assertEqual(deleted_net_dict[const.NET_ID],
                          network_created["net-id"])
         LOG.debug("test_delete_network - END")
@@ -148,10 +149,10 @@ class TestNexusPlugin(unittest.TestCase):
         cdb.add_vlan_binding(self.vlan_id, self.vlan_name,
                              network_created["net-id"])
         new_net_dict = self._cisco_nexus_plugin.create_network(
-                           tenant_id, self.net_name, network_created["net-id"],
-                           self.vlan_name, self.vlan_id)
+            tenant_id, self.net_name, network_created["net-id"],
+            self.vlan_name, self.vlan_id)
         check_net_dict = self._cisco_nexus_plugin.get_network_details(
-                                        tenant_id, network_created["net-id"])
+            tenant_id, network_created["net-id"])
         self.assertEqual(check_net_dict[const.NET_ID],
                          network_created["net-id"])
         self.assertEqual(check_net_dict[const.NET_NAME], self.net_name)
@@ -199,10 +200,10 @@ class TestNexusPlugin(unittest.TestCase):
         cdb.add_vlan_binding(self.vlan_id, self.vlan_name,
                              network_created["net-id"])
         new_net_dict = self._cisco_nexus_plugin.create_network(
-                           tenant_id, self.net_name, network_created["net-id"],
-                           self.vlan_name, self.vlan_id)
+            tenant_id, self.net_name, network_created["net-id"],
+            self.vlan_name, self.vlan_id)
         rename_net_dict = self._cisco_nexus_plugin.update_network(
-                        tenant_id, new_net_dict[const.NET_ID], name=new_name)
+            tenant_id, new_net_dict[const.NET_ID], name=new_name)
         self.assertEqual(rename_net_dict[const.NET_NAME], new_name)
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
         LOG.debug("test_update_network - END")
@@ -245,14 +246,14 @@ class TestNexusPlugin(unittest.TestCase):
         cdb.add_vlan_binding(self.vlan_id, self.vlan_name,
                              network_created["net-id"])
         new_net_dict1 = self._cisco_nexus_plugin.create_network(
-                           tenant_id, self.net_name, network_created["net-id"],
-                           self.vlan_name, self.vlan_id)
+            tenant_id, self.net_name, network_created["net-id"],
+            self.vlan_name, self.vlan_id)
         network_created2 = self.create_network(tenant_id, 'test_network2')
         cdb.add_vlan_binding(self.second_vlan_id, 'second_vlan',
                              network_created2["net-id"])
         new_net_dict2 = self._cisco_nexus_plugin.create_network(
-                         tenant_id, "New_Network2", network_created2["net-id"],
-                         "second_vlan", self.second_vlan_id)
+            tenant_id, "New_Network2", network_created2["net-id"],
+            "second_vlan", self.second_vlan_id)
         list_net_dict = self._cisco_nexus_plugin.get_all_networks(tenant_id)
         net_temp_list = [new_net_dict1, new_net_dict2]
         self.assertTrue(net_temp_list[0] in list_net_dict)
@@ -281,10 +282,10 @@ class TestNexusPlugin(unittest.TestCase):
         cdb.add_vlan_binding(self.vlan_id, self.vlan_name,
                              network_created["net-id"])
         new_net_dict = self._cisco_nexus_plugin.create_network(
-                          tenant_id, self.net_name, network_created["net-id"],
-                          self.vlan_name, self.vlan_id)
+            tenant_id, self.net_name, network_created["net-id"],
+            self.vlan_name, self.vlan_id)
         result_vlan_id = self._cisco_nexus_plugin._get_vlan_id_for_network(
-                        tenant_id, network_created["net-id"])
+            tenant_id, network_created["net-id"])
         self.assertEqual(result_vlan_id, self.vlan_id)
         self.tearDownNetwork(tenant_id, new_net_dict[const.NET_ID])
         LOG.debug("test_get_vlan_id_for_network - END")
index c7adcc57d960e1ee5811873a7c5f56a079f1ef22..e6673a6ffed0472e9223fd22a4555e4a2579ae88 100644 (file)
@@ -22,52 +22,54 @@ import unittest
 
 from quantum.plugins.cisco.ucs import cisco_ucs_network_driver
 
+
 LOG = logging.getLogger('quantum.tests.test_ucs_driver')
 
-CREATE_VLAN_OUTPUT = "<configConfMos cookie=\"cookie_placeholder\" "\
-"inHierarchical=\"true\"> <inConfigs><pair key=\"fabric/lan/net-New Vlan\"> "\
-"<fabricVlan defaultNet=\"no\" dn=\"fabric/lan/net-New Vlan\" id=\"200\" "\
-"name=\"New Vlan\" status=\"created\"></fabricVlan> </pair> </inConfigs> "\
-"</configConfMos>"
-
-CREATE_PROFILE_OUTPUT = "<configConfMos cookie=\"cookie_placeholder\" "\
-"inHierarchical=\"true\"> <inConfigs><pair key=\"fabric/lan/profiles/vnic-"\
-"New Profile\"> <vnicProfile descr=\"Profile created by Cisco OpenStack "\
-"Quantum Plugin\" dn=\"fabric/lan/profiles/vnic-New Profile\" maxPorts="\
-"\"64\" name=\"New Profile\" nwCtrlPolicyName=\"\" pinToGroupName=\"\" "\
-"qosPolicyName=\"\" status=\"created\"> <vnicEtherIf defaultNet=\"yes\" "\
-"name=\"New Vlan\" rn=\"if-New Vlan\" > </vnicEtherIf> </vnicProfile> "\
-"</pair> </inConfigs> </configConfMos>"
-
-CHANGE_VLAN_OUTPUT = "<configConfMos cookie=\"cookie_placeholder\" "\
-"inHierarchical=\"true\"> <inConfigs><pair key=\""\
-"fabric/lan/profiles/vnic-New Profile\"> <vnicProfile descr=\"Profile "\
-"created by Cisco OpenStack Quantum Plugin\" "\
-"dn=\"fabric/lan/profiles/vnic-New Profile\" maxPorts=\"64\" "\
-"name=\"New Profile\" nwCtrlPolicyName=\"\" pinToGroupName=\"\" "\
-"qosPolicyName=\"\" status=\"created,modified\"><vnicEtherIf "\
-"rn=\"if-Old Vlan\" status=\"deleted\"> </vnicEtherIf> "\
-"<vnicEtherIf defaultNet=\"yes\" name=\"New Vlan\" rn=\"if-New Vlan\" > "\
-"</vnicEtherIf> </vnicProfile> </pair></inConfigs> </configConfMos>"
-
-DELETE_VLAN_OUTPUT = "<configConfMos cookie=\"cookie_placeholder\" "\
-"inHierarchical=\"true\"> <inConfigs><pair key=\"fabric/lan/net-New Vlan\"> "\
-"<fabricVlan dn=\"fabric/lan/net-New Vlan\" status=\"deleted\"> "\
-"</fabricVlan> </pair> </inConfigs></configConfMos>"
-
-DELETE_PROFILE_OUTPUT = "<configConfMos cookie=\"cookie_placeholder\" "\
-"inHierarchical=\"false\"> <inConfigs><pair key=\""\
-"fabric/lan/profiles/vnic-New Profile\"> <vnicProfile "\
-"dn=\"fabric/lan/profiles/vnic-New Profile\" status=\"deleted\"> "\
-"</vnicProfile></pair> </inConfigs> </configConfMos>"
-
-ASSOCIATE_PROFILE_OUTPUT = "<configConfMos cookie=\"cookie_placeholder\" "\
-"inHierarchical=\"true\"> <inConfigs> <pair key="\
-"\"fabric/lan/profiles/vnic-New Profile/cl-New Profile Client\">"\
-" <vmVnicProfCl dcName=\".*\" descr=\"\" dn=\"fabric/lan/profiles/vnic-"\
-"New Profile/cl-New Profile Client\"name=\"New Profile Client\" "\
-"orgPath=\".*\" status=\"created\" swName=\"default$\"> </vmVnicProfCl>" \
-"</pair> </inConfigs> </configConfMos>"
+
+CREATE_VLAN_OUTPUT = ("<configConfMos cookie=\"cookie_placeholder\" "
+"inHierarchical=\"true\"> <inConfigs><pair key=\"fabric/lan/net-New Vlan\"> "
+"<fabricVlan defaultNet=\"no\" dn=\"fabric/lan/net-New Vlan\" id=\"200\" "
+"name=\"New Vlan\" status=\"created\"></fabricVlan> </pair> </inConfigs> "
+"</configConfMos>")
+
+CREATE_PROFILE_OUTPUT = ("<configConfMos cookie=\"cookie_placeholder\" "
+"inHierarchical=\"true\"> <inConfigs><pair key=\"fabric/lan/profiles/vnic-"
+"New Profile\"> <vnicProfile descr=\"Profile created by Cisco OpenStack "
+"Quantum Plugin\" dn=\"fabric/lan/profiles/vnic-New Profile\" maxPorts="
+"\"64\" name=\"New Profile\" nwCtrlPolicyName=\"\" pinToGroupName=\"\" "
+"qosPolicyName=\"\" status=\"created\"> <vnicEtherIf defaultNet=\"yes\" "
+"name=\"New Vlan\" rn=\"if-New Vlan\" > </vnicEtherIf> </vnicProfile> "
+"</pair> </inConfigs> </configConfMos>")
+
+CHANGE_VLAN_OUTPUT = ("<configConfMos cookie=\"cookie_placeholder\" "
+"inHierarchical=\"true\"> <inConfigs><pair key=\""
+"fabric/lan/profiles/vnic-New Profile\"> <vnicProfile descr=\"Profile "
+"created by Cisco OpenStack Quantum Plugin\" "
+"dn=\"fabric/lan/profiles/vnic-New Profile\" maxPorts=\"64\" "
+"name=\"New Profile\" nwCtrlPolicyName=\"\" pinToGroupName=\"\" "
+"qosPolicyName=\"\" status=\"created,modified\"><vnicEtherIf "
+"rn=\"if-Old Vlan\" status=\"deleted\"> </vnicEtherIf> "
+"<vnicEtherIf defaultNet=\"yes\" name=\"New Vlan\" rn=\"if-New Vlan\" > "
+"</vnicEtherIf> </vnicProfile> </pair></inConfigs> </configConfMos>")
+
+DELETE_VLAN_OUTPUT = ("<configConfMos cookie=\"cookie_placeholder\" "
+"inHierarchical=\"true\"> <inConfigs><pair key=\"fabric/lan/net-New Vlan\"> "
+"<fabricVlan dn=\"fabric/lan/net-New Vlan\" status=\"deleted\"> "
+"</fabricVlan> </pair> </inConfigs></configConfMos>")
+
+DELETE_PROFILE_OUTPUT = ("<configConfMos cookie=\"cookie_placeholder\" "
+"inHierarchical=\"false\"> <inConfigs><pair key=\""
+"fabric/lan/profiles/vnic-New Profile\"> <vnicProfile "
+"dn=\"fabric/lan/profiles/vnic-New Profile\" status=\"deleted\"> "
+"</vnicProfile></pair> </inConfigs> </configConfMos>")
+
+ASSOCIATE_PROFILE_OUTPUT = ("<configConfMos cookie=\"cookie_placeholder\" "
+"inHierarchical=\"true\"> <inConfigs> <pair key="
+"\"fabric/lan/profiles/vnic-New Profile/cl-New Profile Client\">"
+" <vmVnicProfCl dcName=\".*\" descr=\"\" dn=\"fabric/lan/profiles/vnic-"
+"New Profile/cl-New Profile Client\"name=\"New Profile Client\" "
+"orgPath=\".*\" status=\"created\" swName=\"default$\"> </vmVnicProfCl>"
+"</pair> </inConfigs> </configConfMos>")
 
 
 class TestUCSDriver(unittest.TestCase):
@@ -88,7 +90,7 @@ class TestUCSDriver(unittest.TestCase):
 
         LOG.debug("test_create_vlan")
         vlan_details = self.ucsm_driver._create_vlan_post_data(
-                                self.vlan_name, self.vlan_id)
+            self.vlan_name, self.vlan_id)
         self.assertEqual(vlan_details, expected_output)
         LOG.debug("test_create_vlan - END")
 
@@ -100,7 +102,7 @@ class TestUCSDriver(unittest.TestCase):
 
         LOG.debug("test_create_profile_post_data - START")
         profile_details = self.ucsm_driver._create_profile_post_data(
-                                self.profile_name, self.vlan_name)
+            self.profile_name, self.vlan_name)
         self.assertEqual(profile_details, expected_output)
         LOG.debug("test_create_profile_post - END")
 
@@ -112,7 +114,7 @@ class TestUCSDriver(unittest.TestCase):
 
         LOG.debug("test_create_profile_post_data - START")
         profile_details = self.ucsm_driver._change_vlaninprof_post_data(
-                        self.profile_name, self.old_vlan_name, self.vlan_name)
+            self.profile_name, self.old_vlan_name, self.vlan_name)
         self.assertEqual(profile_details, expected_output)
         LOG.debug("test_create_profile_post - END")
 
@@ -124,34 +126,34 @@ class TestUCSDriver(unittest.TestCase):
         LOG.debug("test_create_profile_post_data - START")
 
         self.ucsm_driver._create_vlan_post_data(
-                                self.vlan_name, self.vlan_id)
+            self.vlan_name, self.vlan_id)
         vlan_delete_details = self.ucsm_driver._delete_vlan_post_data(
-                                                self.vlan_name)
+            self.vlan_name)
         self.assertEqual(vlan_delete_details, expected_output)
         LOG.debug("test_create_profile_post - END")
 
-    def test_delete_profile_post_data(
-                        self, expected_output=DELETE_PROFILE_OUTPUT):
+    def test_delete_profile_post_data(self,
+                                      expected_output=DELETE_PROFILE_OUTPUT):
         """
         Tests deletion of profile post Data
         """
 
         LOG.debug("test_create_profile_post_data - START")
         self.ucsm_driver._create_profile_post_data(
-                                self.profile_name, self.vlan_name)
+            self.profile_name, self.vlan_name)
         profile_delete_details = self.ucsm_driver._delete_profile_post_data(
-                                        self.profile_name)
+            self.profile_name)
         self.assertEqual(profile_delete_details, expected_output)
         LOG.debug("test_create_profile_post - END")
 
     def test_create_profile_client_data(
-                        self, expected_output=ASSOCIATE_PROFILE_OUTPUT):
+        self, expected_output=ASSOCIATE_PROFILE_OUTPUT):
         """
         Tests creation of profile client post Data
         """
 
         LOG.debug("test_create_profile_client_data - START")
         profile_details = self.ucsm_driver._create_pclient_post_data(
-                                self.profile_name, self.profile_client_name)
+            self.profile_name, self.profile_client_name)
         self.assertEqual(profile_details, expected_output)
         LOG.debug("test_create_profile_post - END")
index 2298fdb3ba18e4e5a7c24ac8ef2987d9914b10c7..1183aa85ae1cfc9be87f0b343ffb42a5bb770f13 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #
 # @author: Shubhangi Satras, Cisco Systems, Inc.
 # @author: Tyler Smith, Cisco Systems, Inc.
-#
-"""
 
+import logging
 import unittest
-import logging as LOG
 
 from quantum.common import exceptions as exc
-from quantum.plugins.cisco.l2network_plugin import L2Network
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_credentials as creds
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
+from quantum.plugins.cisco.l2network_plugin import L2Network
 from quantum.plugins.cisco.ucs.cisco_ucs_inventory import UCSInventory
 
-LOG.basicConfig(level=LOG.WARN)
-LOG.getLogger(__name__)
+
+logging.basicConfig(level=LOG.WARN)
+LOG = logging.getLogger(__name__)
+
 
 # Set some data to use in tests
 tenant = 'shubh'
@@ -97,12 +96,12 @@ class TestUCSInventory(unittest.TestCase):
 
         # Clean up created network and port
         try:
-            self._l2network.unplug_interface(tenant,
-                net[const.NET_ID], port[const.PORT_ID])
+            self._l2network.unplug_interface(
+                tenant, net[const.NET_ID], port[const.PORT_ID])
         except:
             pass
         self._l2network.delete_port(tenant,
-            net[const.NET_ID], port[const.PORT_ID])
+                                    net[const.NET_ID], port[const.PORT_ID])
         self._l2network.delete_network(tenant, net[const.NET_ID])
         db.clear_db()
 
index 9e1b93c7b7e0ada2073a3889714e0c0d811f76af..5bcd74be8f40b9a4efa7e2e5426e8293c5dc4445 100644 (file)
 #
 # @author: Shubhangi Satras, Cisco Systems, Inc.
 #          Shweta Padubidri, Cisco Systems, Inc.
-#
+
+import logging
 import unittest
-import logging as LOG
+
 from quantum.common import exceptions as exc
 from quantum.plugins.cisco.common import cisco_constants as const
-from quantum.plugins.cisco.ucs import cisco_ucs_plugin
-from quantum.plugins.cisco.ucs import cisco_ucs_configuration  as conf
 from quantum.plugins.cisco.common import cisco_credentials as cred
-
+from quantum.plugins.cisco.common import cisco_exceptions as c_exc
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
-from quantum.plugins.cisco.common import cisco_exceptions as c_exc
-
+from quantum.plugins.cisco.ucs import cisco_ucs_configuration as conf
 from quantum.plugins.cisco.ucs import cisco_ucs_inventory as ucsinv
+from quantum.plugins.cisco.ucs import cisco_ucs_plugin
+
 
-LOG.basicConfig(level=LOG.WARN)
-LOG.getLogger("cisco_ucs_plugin")
+logging.basicConfig(level=LOG.WARN)
+LOG = logging.getLogger("cisco_ucs_plugin")
 
 
 class UCSVICTestPlugin(unittest.TestCase):
@@ -53,13 +53,13 @@ class UCSVICTestPlugin(unittest.TestCase):
         self.device_ip = conf.UCSM_IP_ADDRESS
         self._ucs_inventory = ucsinv.UCSInventory()
         self._ucs_inventory._load_inventory()
-        self.chassis_id_list = self._ucs_inventory._inventory[\
-                               self.device_ip].keys()
+        self.chassis_id_list = (
+            self._ucs_inventory._inventory[self.device_ip].keys())
         self.chassis_id = self.chassis_id_list[0]
-        self.blade_id_list = self._ucs_inventory._inventory[\
-                             self.device_ip][self.chassis_id]
-        self.blade_id = self._ucs_inventory._inventory[\
-                             self.device_ip][self.chassis_id][0]
+        self.blade_id_list = (
+            self._ucs_inventory._inventory[self.device_ip][self.chassis_id])
+        self.blade_id = (
+            self._ucs_inventory._inventory[self.device_ip][self.chassis_id][0])
 
     def test_create_network(self):
         """
@@ -70,9 +70,9 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         self.assertEqual(new_net_dict[const.NET_ID], new_network[const.UUID])
         self.assertEqual(new_net_dict[const.NET_NAME],
                          new_network[const.NETWORKNAME])
@@ -88,11 +88,11 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_net_dict = self._cisco_ucs_plugin.delete_network(
-           self.tenant_id, new_network[const.UUID], device_ip=self.device_ip)
+            self.tenant_id, new_network[const.UUID], device_ip=self.device_ip)
         self.assertEqual(new_net_dict[const.NET_ID], new_network[const.UUID])
 
     def test_get_network_details(self):
@@ -105,12 +105,12 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_net_dict = self._cisco_ucs_plugin.get_network_details(
-                   self.tenant_id, new_network[const.UUID],
-                   device_ip=self.device_ip)
+            self.tenant_id, new_network[const.UUID],
+            device_ip=self.device_ip)
         self.assertEqual(new_net_dict[const.NET_ID], new_network[const.UUID])
         self.assertEqual(new_net_dict[const.NET_NAME],
                          new_network[const.NETWORKNAME])
@@ -127,18 +127,18 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network1[const.UUID])
         new_net_dict1 = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network1[const.NETWORKNAME],
-                new_network1[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network1[const.NETWORKNAME],
+            new_network1[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_network2 = db.network_create(self.tenant_id, "test_network2")
         cdb.add_vlan_binding("6", "q-000006vlan", new_network2[const.UUID])
         new_net_dict2 = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network2[const.NETWORKNAME],
-                new_network2[const.UUID], "q-000006vlan", "6",
-                device_ip=self.device_ip)
+            self.tenant_id, new_network2[const.NETWORKNAME],
+            new_network2[const.UUID], "q-000006vlan", "6",
+            device_ip=self.device_ip)
 
         net_list = self._cisco_ucs_plugin.get_all_networks(
-                                self.tenant_id, device_ip=self.device_ip)
+            self.tenant_id, device_ip=self.device_ip)
         net_id_list = [new_net_dict1, new_net_dict2]
 
         self.assertTrue(net_list[0] in net_id_list)
@@ -156,29 +156,29 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_port1 = db.port_create(new_network[const.UUID], const.PORT_UP)
         port_dict1 = self._cisco_ucs_plugin.create_port(
-                            self.tenant_id, self.net_id, const.PORT_UP,
-                            new_port1[const.UUID], device_ip=self.device_ip,
-                            ucs_inventory=self._ucs_inventory,
-                            least_rsvd_blade_dict=self._ucs_inventory.\
-                            _get_least_reserved_blade())
+            self.tenant_id, self.net_id, const.PORT_UP,
+            new_port1[const.UUID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         new_port2 = db.port_create(new_network[const.UUID], const.PORT_UP)
         port_dict2 = self._cisco_ucs_plugin.create_port(
-                               self.tenant_id, self.net_id, const.PORT_UP,
-                               new_port2[const.UUID], device_ip=self.device_ip,
-                               ucs_inventory=self._ucs_inventory,
-                               least_rsvd_blade_dict=self._ucs_inventory.\
-                               _get_least_reserved_blade())
+            self.tenant_id, self.net_id, const.PORT_UP,
+            new_port2[const.UUID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         ports_on_net = self._cisco_ucs_plugin.get_all_ports(
-                           self.tenant_id, new_net_dict[const.NET_ID],
-                           device_ip=self.device_ip,
-                           ucs_inventory=self._ucs_inventory,
-                           least_rsvd_blade_dict=self._ucs_inventory.\
-                           _get_least_reserved_blade())
+            self.tenant_id, new_net_dict[const.NET_ID],
+            device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         port_list = [port_dict1, port_dict2]
         self.assertTrue(str(ports_on_net[1]) == str(port_list[1]) or
                         str(ports_on_net[1]) == str(port_list[0]))
@@ -186,19 +186,19 @@ class UCSVICTestPlugin(unittest.TestCase):
                         str(ports_on_net[0]) == str(port_list[0]))
 
         blade_intf_details = self._ucs_inventory._get_rsvd_blade_intf_by_port(
-                                      self.tenant_id, port_dict1[const.PORTID])
+            self.tenant_id, port_dict1[const.PORTID])
         self._cisco_ucs_plugin.delete_port(
-                     self.tenant_id, new_net_dict[const.NET_ID],
-                     port_dict1[const.PORTID], device_ip=self.device_ip,
-                     ucs_inventory=self._ucs_inventory,
-                     chassis_id=self.chassis_id, blade_id=self.blade_id,
-                     blade_intf_distinguished_name=blade_intf_details[\
-                     const.BLADE_INTF_DN],
-                     least_rsvd_blade_dict=self._ucs_inventory.\
-                     _get_least_reserved_blade())
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict1[const.PORTID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            chassis_id=self.chassis_id, blade_id=self.blade_id,
+            blade_intf_distinguished_name=blade_intf_details[
+                const.BLADE_INTF_DN],
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         self.tear_down_network_port(
-                 self.tenant_id, new_net_dict[const.NET_ID],
-                 port_dict2[const.PORTID])
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict2[const.PORTID])
 
     def test_create_port(self):
         """
@@ -210,23 +210,23 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_port = db.port_create(new_network[const.UUID], const.PORT_UP)
         port_dict = self._cisco_ucs_plugin.create_port(
-                            self.tenant_id, self.net_id, const.PORT_UP,
-                            new_port[const.UUID], device_ip=self.device_ip,
-                            ucs_inventory=self._ucs_inventory,
-                            least_rsvd_blade_dict=self._ucs_inventory.\
-                            _get_least_reserved_blade())
+            self.tenant_id, self.net_id, const.PORT_UP,
+            new_port[const.UUID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         self.assertEqual(port_dict[const.PORTID], new_port[const.UUID])
-        profile_name = self._cisco_ucs_plugin.\
-                           _get_profile_name(port_dict[const.PORTID])
+        profile_name = (
+            self._cisco_ucs_plugin._get_profile_name(port_dict[const.PORTID]))
         self.assertTrue(profile_name is not None)
         self.tear_down_network_port(
-                 self.tenant_id, new_net_dict[const.NET_ID],
-                 port_dict[const.PORTID])
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID])
 
     def test_delete_port(self):
         """
@@ -240,28 +240,28 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_port = db.port_create(new_network[const.UUID], const.PORT_UP)
         port_dict = self._cisco_ucs_plugin.create_port(
-                            self.tenant_id, self.net_id, const.PORT_UP,
-                            new_port[const.UUID], device_ip=self.device_ip,
-                            ucs_inventory=self._ucs_inventory,
-                            least_rsvd_blade_dict=self._ucs_inventory.\
-                            _get_least_reserved_blade())
+            self.tenant_id, self.net_id, const.PORT_UP,
+            new_port[const.UUID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
 
         blade_intf_details = self._ucs_inventory._get_rsvd_blade_intf_by_port(
-                                       self.tenant_id, port_dict[const.PORTID])
+            self.tenant_id, port_dict[const.PORTID])
         port_bind = self._cisco_ucs_plugin.delete_port(
-                         self.tenant_id, new_net_dict[const.NET_ID],
-                         port_dict[const.PORTID], device_ip=self.device_ip,
-                         ucs_inventory=self._ucs_inventory,
-                         chassis_id=self.chassis_id, blade_id=self.blade_id,
-                         blade_intf_distinguished_name=blade_intf_details[\
-                         const.BLADE_INTF_DN],
-                         least_rsvd_blade_dict=self._ucs_inventory.\
-                         _get_least_reserved_blade())
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            chassis_id=self.chassis_id, blade_id=self.blade_id,
+            blade_intf_distinguished_name=blade_intf_details[
+                const.BLADE_INTF_DN],
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
 
         self.assertEqual(port_bind[const.PORTID], new_port[const.UUID])
         self.tear_down_network(self.tenant_id, new_net_dict[const.NET_ID])
@@ -276,24 +276,24 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_port = db.port_create(new_network[const.UUID], port_state)
         port_dict = self._cisco_ucs_plugin.create_port(
-                            self.tenant_id, self.net_id, port_state,
-                            new_port[const.UUID], device_ip=self.device_ip,
-                            ucs_inventory=self._ucs_inventory,
-                            least_rsvd_blade_dict=self._ucs_inventory.\
-                            _get_least_reserved_blade())
+            self.tenant_id, self.net_id, port_state,
+            new_port[const.UUID], device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
 
         port_detail = self._cisco_ucs_plugin.get_port_details(
-                            self.tenant_id, new_net_dict[const.NET_ID],
-                            port_dict[const.PORTID], device_ip=self.device_ip)
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID], device_ip=self.device_ip)
         self.assertEqual(str(port_dict), str(port_detail))
         self.tear_down_network_port(
-                 self.tenant_id, new_net_dict[const.NET_ID],
-                 port_dict[const.PORTID])
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID])
 
     def test_get_port_details_state_up(self):
         """
@@ -318,11 +318,11 @@ class UCSVICTestPlugin(unittest.TestCase):
         new_port = db.port_create(new_network[const.UUID], const.PORT_UP)
         self._cisco_ucs_plugin._set_ucsm(self.device_ip)
         new_port_profile = self._cisco_ucs_plugin._create_port_profile(
-                                self.tenant_id, new_network[const.UUID],
-                                new_port[const.UUID], self.vlan_name,
-                                self.vlan_id)
-        profile_name = self._cisco_ucs_plugin.\
-                            _get_profile_name(new_port[const.UUID])
+            self.tenant_id, new_network[const.UUID],
+            new_port[const.UUID], self.vlan_name,
+            self.vlan_id)
+        profile_name = (
+            self._cisco_ucs_plugin._get_profile_name(new_port[const.UUID]))
         self.assertEqual(new_port_profile[const.PROFILE_NAME], profile_name)
         self.assertEqual(new_port_profile[const.PROFILE_VLAN_NAME],
                          self.vlan_name)
@@ -341,11 +341,11 @@ class UCSVICTestPlugin(unittest.TestCase):
         new_port = db.port_create(new_network[const.UUID], const.PORT_UP)
         self._cisco_ucs_plugin._set_ucsm(self.device_ip)
         self._cisco_ucs_plugin._create_port_profile(
-                                self.tenant_id, new_network[const.UUID],
-                                new_port[const.UUID], self.vlan_name,
-                                self.vlan_id)
-        profile_name = self._cisco_ucs_plugin.\
-                            _get_profile_name(new_port[const.UUID])
+            self.tenant_id, new_network[const.UUID],
+            new_port[const.UUID], self.vlan_name,
+            self.vlan_id)
+        profile_name = (
+            self._cisco_ucs_plugin._get_profile_name(new_port[const.UUID]))
 
         counter1 = self._cisco_ucs_plugin._port_profile_counter
         self._cisco_ucs_plugin._delete_port_profile(new_port[const.UUID],
@@ -364,28 +364,28 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_port = db.port_create(new_network[const.UUID], const.PORT_UP)
         port_dict = self._cisco_ucs_plugin.create_port(
-                            self.tenant_id, new_net_dict[const.NET_ID],
-                            const.PORT_UP, new_port[const.UUID],
-                            device_ip=self.device_ip,
-                            ucs_inventory=self._ucs_inventory,
-                            least_rsvd_blade_dict=self._ucs_inventory.\
-                            _get_least_reserved_blade())
+            self.tenant_id, new_net_dict[const.NET_ID],
+            const.PORT_UP, new_port[const.UUID],
+            device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         cdb.update_vlan_binding(new_network[const.UUID],
                                 str(new_vlanid), new_vlan_name)
         port_bind = self._cisco_ucs_plugin.plug_interface(
-                           self.tenant_id, new_net_dict[const.NET_ID],
-                           port_dict[const.PORTID], remote_interface_id,
-                           device_ip=self.device_ip)
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID], remote_interface_id,
+            device_ip=self.device_ip)
         self.assertEqual(port_bind[const.VLANNAME], new_vlan_name)
         self.assertEqual(port_bind[const.VLANID], new_vlanid)
         self.tear_down_network_port_interface(
-                                   self.tenant_id, new_net_dict[const.NET_ID],
-                                   new_port[const.UUID])
+            self.tenant_id, new_net_dict[const.NET_ID],
+            new_port[const.UUID])
 
     def test_unplug_interface(self, remote_interface_id=None,
                               new_vlanid=10, new_vlan_name='new_vlan'):
@@ -398,32 +398,32 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
         new_port = db.port_create(new_network[const.UUID], const.PORT_UP)
         port_dict = self._cisco_ucs_plugin.create_port(
-                            self.tenant_id, new_net_dict[const.NET_ID],
-                            const.PORT_UP, new_port[const.UUID],
-                            device_ip=self.device_ip,
-                            ucs_inventory=self._ucs_inventory,
-                            least_rsvd_blade_dict=self._ucs_inventory.\
-                            _get_least_reserved_blade())
+            self.tenant_id, new_net_dict[const.NET_ID],
+            const.PORT_UP, new_port[const.UUID],
+            device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         cdb.update_vlan_binding(new_network[const.UUID],
                                 str(new_vlanid), new_vlan_name)
         self._cisco_ucs_plugin.plug_interface(
-                           self.tenant_id, new_net_dict[const.NET_ID],
-                           port_dict[const.PORTID], remote_interface_id,
-                           device_ip=self.device_ip)
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID], remote_interface_id,
+            device_ip=self.device_ip)
 
         port_bind = self._cisco_ucs_plugin.unplug_interface(
-                           self.tenant_id, new_net_dict[const.NET_ID],
-                           port_dict[const.PORTID], device_ip=self.device_ip)
+            self.tenant_id, new_net_dict[const.NET_ID],
+            port_dict[const.PORTID], device_ip=self.device_ip)
         self.assertEqual(port_bind[const.VLANNAME], self.vlan_name)
         self.assertEqual(port_bind[const.VLANID], self.vlan_id)
         self.tear_down_network_port_interface(
-                                   self.tenant_id, new_net_dict[const.NET_ID],
-                                   new_port[const.UUID])
+            self.tenant_id, new_net_dict[const.NET_ID],
+            new_port[const.UUID])
 
     def test_get_vlan_name_for_network(self):
         """
@@ -434,7 +434,7 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         vlan_bind_name = self._cisco_ucs_plugin._get_vlan_name_for_network(
-                                    self.tenant_id, new_network[const.UUID])
+            self.tenant_id, new_network[const.UUID])
 
         self.assertEqual(vlan_bind_name, self.vlan_name)
 
@@ -447,7 +447,7 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         vlan_bind_id = self._cisco_ucs_plugin._get_vlan_id_for_network(
-                                    self.tenant_id, new_network[const.UUID])
+            self.tenant_id, new_network[const.UUID])
         self.assertEqual(str(vlan_bind_id), self.vlan_id)
 
     def test_show_network_not_found(self):
@@ -476,9 +476,9 @@ class UCSVICTestPlugin(unittest.TestCase):
         cdb.add_vlan_binding(str(self.vlan_id), self.vlan_name,
                              new_network[const.UUID])
         new_net_dict = self._cisco_ucs_plugin.create_network(
-                self.tenant_id, new_network[const.NETWORKNAME],
-                new_network[const.UUID], self.vlan_name, self.vlan_id,
-                device_ip=self.device_ip)
+            self.tenant_id, new_network[const.NETWORKNAME],
+            new_network[const.UUID], self.vlan_name, self.vlan_id,
+            device_ip=self.device_ip)
 
         self.assertRaises(c_exc.PortVnicNotFound,
                           self._cisco_ucs_plugin.delete_port,
@@ -487,8 +487,8 @@ class UCSVICTestPlugin(unittest.TestCase):
                           ucs_inventory=self._ucs_inventory,
                           chassis_id=self.chassis_id, blade_id=self.blade_id,
                           blade_intf_distinguished_name=None,
-                          least_rsvd_blade_dict=self._ucs_inventory.\
-                          _get_least_reserved_blade())
+                          least_rsvd_blade_dict=(
+                              self._ucs_inventory._get_least_reserved_blade()))
 
         self.tear_down_network(self.tenant_id, new_net_dict[const.NET_ID])
 
@@ -503,19 +503,18 @@ class UCSVICTestPlugin(unittest.TestCase):
 
     def tear_down_network_port(self, tenant_id, net_id, port_id):
         blade_intf_details = self._ucs_inventory._get_rsvd_blade_intf_by_port(
-                                                 tenant_id, port_id)
+            tenant_id, port_id)
         self._cisco_ucs_plugin.delete_port(
-                    tenant_id, net_id, port_id, device_ip=self.device_ip,
-                    ucs_inventory=self._ucs_inventory,
-                    chassis_id=self.chassis_id, blade_id=self.blade_id,
-                    blade_intf_distinguished_name=blade_intf_details[\
-                    const.BLADE_INTF_DN],
-                    least_rsvd_blade_dict=self._ucs_inventory.\
-                    _get_least_reserved_blade())
+            tenant_id, net_id, port_id, device_ip=self.device_ip,
+            ucs_inventory=self._ucs_inventory,
+            chassis_id=self.chassis_id, blade_id=self.blade_id,
+            blade_intf_distinguished_name=blade_intf_details[
+                const.BLADE_INTF_DN],
+            least_rsvd_blade_dict=(
+                self._ucs_inventory._get_least_reserved_blade()))
         self.tear_down_network(tenant_id, net_id)
 
     def tear_down_network_port_interface(self, tenant_id, net_id, port_id):
-        self._cisco_ucs_plugin.unplug_interface(
-                                   tenant_id, net_id, port_id,
-                                   device_ip=self.device_ip)
+        self._cisco_ucs_plugin.unplug_interface(tenant_id, net_id, port_id,
+                                                device_ip=self.device_ip)
         self.tear_down_network_port(tenant_id, net_id, port_id)
index 90e2641ce55a5fefe590cec5d71b960fdc02e038..461bee6719f198aff7166caebf10f31b8d6fd4ff 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Peter Strunk, Cisco Systems, Inc.
-#
-"""
 
+import logging
 import unittest
-import logging as LOG
 
 from quantum.common import exceptions as exc
-from quantum.plugins.cisco import l2network_plugin_configuration  as conf
 from quantum.plugins.cisco.common import cisco_exceptions as c_exc
 from quantum.plugins.cisco.common import cisco_credentials as creds
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
-from quantum.plugins.cisco.segmentation.l2network_vlan_mgr \
-                                import L2NetworkVLANMgr
+from quantum.plugins.cisco import l2network_plugin_configuration as conf
+from quantum.plugins.cisco.segmentation.l2network_vlan_mgr import (
+    L2NetworkVLANMgr,
+    )
+
 
-LOG.basicConfig(level=LOG.WARN)
-LOG.getLogger(__name__)
+logging.basicConfig(level=logging.WARN)
+LOG = logging.getLogger(__name__)
 
 
 class Test_L2Network_Vlan_Mgr(unittest.TestCase):
@@ -50,8 +49,8 @@ class Test_L2Network_Vlan_Mgr(unittest.TestCase):
         self.vlan_id = 300
         self.net_id = 100
         self.vlan_mgr = L2NetworkVLANMgr()
-        self.plugin_key = "quantum.plugins.cisco.ucs.cisco_ucs_plugin" +\
-                          ".UCSVICPlugin"
+        self.plugin_key = (
+            "quantum.plugins.cisco.ucs.cisco_ucs_plugin.UCSVICPlugin")
 
     def tearDown(self):
         db.clear_db()
@@ -60,7 +59,7 @@ class Test_L2Network_Vlan_Mgr(unittest.TestCase):
         LOG.debug("test_reserve_segmentation_id - START")
         db.network_create(self.tenant_id, self.net_name)
         vlan_id = self.vlan_mgr.reserve_segmentation_id(self.tenant_id,
-                                                             self.net_name)
+                                                        self.net_name)
         self.assertEqual(vlan_id, int(conf.VLAN_START))
         LOG.debug("test_reserve_segmentation_id - END")
 
@@ -77,10 +76,10 @@ class Test_L2Network_Vlan_Mgr(unittest.TestCase):
         LOG.debug("test_release_segmentation_id - START")
         db.network_create(self.tenant_id, self.net_name)
         vlan_id = self.vlan_mgr.reserve_segmentation_id(self.tenant_id,
-                                                             self.net_name)
+                                                        self.net_name)
         cdb.add_vlan_binding(vlan_id, self.vlan_name, self.net_id)
         release_return = self.vlan_mgr.release_segmentation_id(self.tenant_id,
-                                                                self.net_id)
+                                                               self.net_id)
         self.assertEqual(release_return, False)
         LOG.debug("test_release_segmentation_id - END")
 
index 09b3fab896818e475990cc06e881e6781483f01e..db695fb0afb5d6a63f051006fba6aae6297a7414 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,4 +16,3 @@
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
index 2b849641de50b89072f64f3871983da54588d0ff..d8dc195eb46d1b93ca7d8adc4b80e9fb412e9588 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,7 +16,6 @@
 #
 # @author: Rohit Agarwalla, Cisco Systems Inc.
 #
-"""
 
 import subprocess
 
@@ -25,29 +23,29 @@ import subprocess
 def get_next_dynic(argv=[]):
     """Get the next available dynamic nic on this host"""
     cmd = ["ifconfig", "-a"]
-    f_cmd_output = subprocess.Popen(cmd, stdout=subprocess.PIPE).\
-                   communicate()[0]
-    eths = [lines.split(' ')[0] for lines in f_cmd_output.splitlines() \
+    f_cmd_output = (
+        subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0])
+    eths = [lines.split(' ')[0] for lines in f_cmd_output.splitlines()
             if "eth" in lines]
     #print eths
     for eth in eths:
         cmd = ["ethtool", "-i", eth]
-        f_cmd_output = subprocess.Popen(cmd, stdout=subprocess.PIPE).\
-                       communicate()[0]
-        bdf = [lines.split(' ')[1] for lines in f_cmd_output.splitlines() \
+        f_cmd_output = (
+            subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0])
+        bdf = [lines.split(' ')[1] for lines in f_cmd_output.splitlines()
                if "bus-info" in lines]
         #print bdf
         cmd = ["lspci", "-n", "-s", bdf[0]]
-        f_cmd_output = subprocess.Popen(cmd, stdout=subprocess.PIPE).\
-                       communicate()[0]
-        deviceid = [(lines.split(':')[3]).split(' ')[0] \
+        f_cmd_output = (subprocess.Popen(cmd, stdout=subprocess.PIPE).
+                        communicate()[0])
+        deviceid = [(lines.split(':')[3]).split(' ')[0]
                     for lines in f_cmd_output.splitlines()]
         #print deviceid
         if deviceid[0] == "0044":
             cmd = ["/sbin/ip", "link", "show", eth]
-            f_cmd_output = subprocess.Popen(cmd, stdout=subprocess.PIPE).\
-                           communicate()[0]
-            used = [lines for lines in f_cmd_output.splitlines() \
+            f_cmd_output = (
+                subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0])
+            used = [lines for lines in f_cmd_output.splitlines()
                     if "UP" in lines]
             if not used:
                 break
index aa9236e3c4cbafcb24b1359ba643718b222d5b6c..a1a9d16a3d9affc1d403db72afd366ce36078f7f 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
 
 import os
+
 from quantum.common.config import find_config_file
 from quantum.plugins.cisco.common import cisco_configparser as confp
 
+
 CP = confp.CiscoConfigParser(find_config_file({'plugin': 'cisco'}, [],
-                             'ucs.ini'))
+                                              'ucs.ini'))
 
 SECTION = CP['UCSM']
 UCSM_IP_ADDRESS = SECTION['ip_address']
@@ -37,6 +37,6 @@ SECTION = CP['DRIVER']
 UCSM_DRIVER = SECTION['name']
 
 CP = confp.CiscoConfigParser(find_config_file({'plugin': 'cisco'}, [],
-                             'ucs_inventory.ini'))
+                                              'ucs_inventory.ini'))
 
 INVENTORY = CP.walk(CP.dummy)
index 2f530a0e09a241ba912ae315f672ba0a9b3d8183..a2d1694a0f1a2442d82f635caec4631072ed8e9b 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
-from copy import deepcopy
-import logging
-
-from quantum.common import exceptions as exc
-from quantum.plugins.cisco.l2device_inventory_base \
-        import L2NetworkDeviceInventoryBase
-from quantum.plugins.cisco.common import cisco_constants as const
-from quantum.plugins.cisco.common import cisco_credentials as cred
-from quantum.plugins.cisco.common import cisco_exceptions as cexc
-from quantum.plugins.cisco.common import cisco_utils as cutil
-from quantum.plugins.cisco.db import api as db
-from quantum.plugins.cisco.db import ucs_db as udb
-from quantum.plugins.cisco.ucs \
-        import cisco_ucs_inventory_configuration as conf
-from quantum.plugins.cisco.ucs import cisco_ucs_network_driver
-
-LOG = logging.getLogger(__name__)
 
 """
 The _inventory data strcuture contains a nested disctioary:
@@ -80,6 +60,27 @@ const.INSTANCE_ID
 const.VIF_ID
 """
 
+from copy import deepcopy
+import logging
+
+from quantum.common import exceptions as exc
+from quantum.plugins.cisco.l2device_inventory_base import (
+    L2NetworkDeviceInventoryBase,
+    )
+from quantum.plugins.cisco.common import cisco_constants as const
+from quantum.plugins.cisco.common import cisco_credentials as cred
+from quantum.plugins.cisco.common import cisco_exceptions as cexc
+from quantum.plugins.cisco.common import cisco_utils as cutil
+from quantum.plugins.cisco.db import api as db
+from quantum.plugins.cisco.db import ucs_db as udb
+from quantum.plugins.cisco.ucs import (
+    cisco_ucs_inventory_configuration as conf,
+    )
+from quantum.plugins.cisco.ucs import cisco_ucs_network_driver
+
+
+LOG = logging.getLogger(__name__)
+
 
 class UCSInventory(L2NetworkDeviceInventoryBase):
     """
@@ -110,10 +111,10 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                 inventory[ucsm][chassis].pop(const.CHASSIS_ID)
                 blade_list = []
                 for blade in inventory[ucsm][chassis].keys():
-                    blade_id = \
-                            inventory[ucsm][chassis][blade][const.BLADE_ID]
-                    host_name = \
-                            inventory[ucsm][chassis][blade][const.HOST_NAME]
+                    blade_id = (
+                        inventory[ucsm][chassis][blade][const.BLADE_ID])
+                    host_name = (
+                        inventory[ucsm][chassis][blade][const.HOST_NAME])
                     host_key = ucsm_ip + "-" + chassis_id + "-" + blade_id
                     self._host_names[host_key] = host_name
                     blade_list.append(blade_id)
@@ -178,18 +179,18 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
             if not const.VIF_ID in blade_intf_data[blade_intf].keys():
                 blade_intf_data[blade_intf][const.VIF_ID] = None
 
-            if (blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] == \
-                const.BLADE_INTF_STATE_UNALLOCATED  or \
-                blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] == \
-                const.BLADE_INTF_STATE_UNKNOWN) and \
-               blade_intf_data[blade_intf][const.BLADE_INTF_OPER_STATE] == \
-               const.BLADE_INTF_STATE_UNKNOWN:
-                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = \
-                        const.BLADE_INTF_UNRESERVED
+            if (blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] ==
+                    const.BLADE_INTF_STATE_UNALLOCATED or
+                    blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] ==
+                    const.BLADE_INTF_STATE_UNKNOWN) and (
+                    blade_intf_data[blade_intf][const.BLADE_INTF_OPER_STATE] ==
+                    const.BLADE_INTF_STATE_UNKNOWN):
+                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = (
+                    const.BLADE_INTF_UNRESERVED)
                 unreserved_counter += 1
             else:
-                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = \
-                        const.BLADE_INTF_RESERVED
+                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = (
+                    const.BLADE_INTF_RESERVED)
 
             port_binding = udb.get_portbinding_dn(dist_name)
             if port_binding:
@@ -198,21 +199,17 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                 # need to change it, and also load the state from the DB for
                 # other associations
                 intf_data = blade_intf_data[blade_intf]
-                if intf_data[const.BLADE_INTF_RESERVATION] == \
-                   const.BLADE_INTF_UNRESERVED:
+                if (intf_data[const.BLADE_INTF_RESERVATION] ==
+                    const.BLADE_INTF_UNRESERVED):
                     unreserved_counter -= 1
-                    intf_data[const.BLADE_INTF_RESERVATION] = \
-                            const.BLADE_INTF_RESERVED
-                intf_data[const.TENANTID] = \
-                        port_binding[const.TENANTID]
-                intf_data[const.PORTID] = \
-                        port_binding[const.PORTID]
-                intf_data[const.PROFILE_ID] = \
-                        port_binding[const.PORTPROFILENAME]
-                intf_data[const.INSTANCE_ID] = \
-                        port_binding[const.INSTANCE_ID]
-                intf_data[const.VIF_ID] = \
-                        port_binding[const.VIF_ID]
+                    intf_data[const.BLADE_INTF_RESERVATION] = (
+                        const.BLADE_INTF_RESERVED)
+                intf_data[const.TENANTID] = port_binding[const.TENANTID]
+                intf_data[const.PORTID] = port_binding[const.PORTID]
+                intf_data[const.PROFILE_ID] = (
+                    port_binding[const.PORTPROFILENAME])
+                intf_data[const.INSTANCE_ID] = port_binding[const.INSTANCE_ID]
+                intf_data[const.VIF_ID] = port_binding[const.VIF_ID]
         host_name = self._get_host_name(ucsm_ip, chassis_id, blade_id)
         blade_data = {const.BLADE_INTF_DATA: blade_intf_data,
                       const.BLADE_UNRESERVED_INTF_COUNT: unreserved_counter,
@@ -220,7 +217,7 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
         return blade_data
 
     def _get_blade_state(self, chassis_id, blade_id, ucsm_ip,
-                                 ucsm_username, ucsm_password):
+                         ucsm_username, ucsm_password):
         """Get the blade state"""
         blade_intf_data = self._client.get_blade_data(chassis_id, blade_id,
                                                       ucsm_ip, ucsm_username,
@@ -228,21 +225,21 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
         unreserved_counter = 0
 
         for blade_intf in blade_intf_data.keys():
-            if (blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] == \
-                const.BLADE_INTF_STATE_UNALLOCATED  or \
-                blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] == \
-                const.BLADE_INTF_STATE_UNKNOWN) and \
-               blade_intf_data[blade_intf][const.BLADE_INTF_OPER_STATE] == \
-               const.BLADE_INTF_STATE_UNKNOWN:
-                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = \
-                        const.BLADE_INTF_UNRESERVED
+            if (blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] ==
+                    const.BLADE_INTF_STATE_UNALLOCATED or
+                    blade_intf_data[blade_intf][const.BLADE_INTF_LINK_STATE] ==
+                    const.BLADE_INTF_STATE_UNKNOWN) and (
+                    blade_intf_data[blade_intf][const.BLADE_INTF_OPER_STATE] ==
+                    const.BLADE_INTF_STATE_UNKNOWN):
+                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = (
+                    const.BLADE_INTF_UNRESERVED)
                 unreserved_counter += 1
             else:
-                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = \
-                        const.BLADE_INTF_RESERVED
+                blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = (
+                    const.BLADE_INTF_RESERVED)
 
         blade_data = {const.BLADE_INTF_DATA: blade_intf_data,
-                     const.BLADE_UNRESERVED_INTF_COUNT: unreserved_counter}
+                      const.BLADE_UNRESERVED_INTF_COUNT: unreserved_counter}
         return blade_data
 
     def _get_all_ucsms(self):
@@ -278,9 +275,9 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                         tmp = deepcopy(blade_intf_data[blade_intf])
                         intf_data = blade_intf_data[blade_intf]
                         if (intf_data[const.BLADE_INTF_RESERVATION] ==
-                           const.BLADE_INTF_RESERVED and
-                           intf_data[const.TENANTID] == tenant_id and
-                           intf_data[const.INSTANCE_ID] is None):
+                                const.BLADE_INTF_RESERVED and
+                                intf_data[const.TENANTID] == tenant_id and
+                                intf_data[const.INSTANCE_ID] is None):
                             intf_data[const.INSTANCE_ID] = instance_id
                             host_name = self._get_host_name(ucsm_ip,
                                                             chassis_id,
@@ -307,40 +304,40 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                     blade_intf_data = blade_data[const.BLADE_INTF_DATA]
                     for blade_intf in blade_intf_data.keys():
                         intf_data = blade_intf_data[blade_intf]
-                        if intf_data[const.BLADE_INTF_RESERVATION] == \
-                           const.BLADE_INTF_RESERVED and \
-                           intf_data[const.TENANTID] == tenant_id and \
-                           intf_data[const.INSTANCE_ID] == instance_id:
+                        if (intf_data[const.BLADE_INTF_RESERVATION] ==
+                                const.BLADE_INTF_RESERVED and
+                                intf_data[const.TENANTID] == tenant_id and
+                                intf_data[const.INSTANCE_ID] == instance_id):
                             found_blade_intf_data = blade_intf_data
-                            LOG.debug("Found blade %s associated with this" \
-                                      " instance: %s" % \
-                                      (blade_id,
-                                       instance_id))
+                            LOG.debug(("Found blade %s associated with this"
+                                       " instance: %s") % (blade_id,
+                                                           instance_id))
                             break
 
         if found_blade_intf_data:
             blade_intf_data = found_blade_intf_data
             for blade_intf in blade_intf_data.keys():
                 intf_data = blade_intf_data[blade_intf]
-                if intf_data[const.BLADE_INTF_RESERVATION] == \
-                   const.BLADE_INTF_RESERVED and \
-                   intf_data[const.TENANTID] == tenant_id and \
-                   (not intf_data[const.VIF_ID]):
+                if (intf_data[const.BLADE_INTF_RESERVATION] ==
+                        const.BLADE_INTF_RESERVED and
+                        intf_data[const.TENANTID] == tenant_id and
+                        (not intf_data[const.VIF_ID])):
                     intf_data[const.VIF_ID] = vif_id
                     intf_data[const.INSTANCE_ID] = instance_id
                     port_binding = udb.get_portbinding_dn(blade_intf)
                     port_id = port_binding[const.PORTID]
                     udb.update_portbinding(port_id, instance_id=instance_id,
                                            vif_id=vif_id)
-                    db.port_set_attachment_by_id(port_id, vif_id +
-                                                 const.UNPLUGGED)
+                    db.port_set_attachment_by_id(port_id,
+                                                 vif_id + const.UNPLUGGED)
                     device_name = intf_data[const.BLADE_INTF_RHEL_DEVICE_NAME]
                     profile_name = port_binding[const.PORTPROFILENAME]
-                    dynamicnic_details = \
-                            {const.DEVICENAME: device_name,
-                             const.UCSPROFILE: profile_name}
-                    LOG.debug("Found reserved dynamic nic: %s" \
-                              "associated with port %s" %
+                    dynamicnic_details = {
+                        const.DEVICENAME: device_name,
+                        const.UCSPROFILE: profile_name,
+                        }
+                    LOG.debug(("Found reserved dynamic nic: %s"
+                               "associated with port %s") %
                               (intf_data, port_id))
                     LOG.debug("Returning dynamic nic details: %s" %
                               dynamicnic_details)
@@ -363,13 +360,13 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                     blade_intf_data = blade_data[const.BLADE_INTF_DATA]
                     for blade_intf in blade_intf_data.keys():
                         intf_data = blade_intf_data[blade_intf]
-                        if intf_data[const.BLADE_INTF_RESERVATION] == \
-                           const.BLADE_INTF_RESERVED and \
-                           intf_data[const.TENANTID] == tenant_id and \
-                           blade_intf_data[blade_intf][const.INSTANCE_ID] == \
-                           instance_id and \
-                           intf_data[const.VIF_ID][:const.UUID_LENGTH] == \
-                           vif_id:
+                        if (intf_data[const.BLADE_INTF_RESERVATION] ==
+                                const.BLADE_INTF_RESERVED and
+                                intf_data[const.TENANTID] == tenant_id and
+                                blade_intf_data[blade_intf][const.INSTANCE_ID]
+                                == instance_id and
+                                intf_data[const.VIF_ID][:const.UUID_LENGTH] ==
+                                vif_id):
                             intf_data[const.VIF_ID] = None
                             intf_data[const.INSTANCE_ID] = None
                             port_binding = udb.get_portbinding_dn(blade_intf)
@@ -377,15 +374,16 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                             udb.update_portbinding(port_id, instance_id=None,
                                                    vif_id=None)
                             db.port_unset_attachment_by_id(port_id)
-                            LOG.debug("Disassociated VIF-ID: %s " \
-                                      "from port: %s" \
-                                      "in UCS inventory state for blade: %s" %
-                                      (vif_id, port_id, intf_data))
+                            LOG.debug(
+                                ("Disassociated VIF-ID: %s "
+                                 "from port: %s"
+                                 "in UCS inventory state for blade: %s") %
+                                (vif_id, port_id, intf_data))
                             device_params = {const.DEVICE_IP: [ucsm_ip],
                                              const.PORTID: port_id}
                             return device_params
-        LOG.warn("Disassociating VIF-ID in UCS inventory failed. " \
-                 "Could not find a reserved dynamic nic for tenant: %s" %
+        LOG.warn(("Disassociating VIF-ID in UCS inventory failed. "
+                  "Could not find a reserved dynamic nic for tenant: %s") %
                  tenant_id)
         return None
 
@@ -401,14 +399,14 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                     blade_data = ucsm[chassis_id][blade_id]
                     blade_intf_data = blade_data[const.BLADE_INTF_DATA]
                     for blade_intf in blade_intf_data.keys():
-                        if not blade_intf_data[blade_intf][const.PORTID] or \
-                           not blade_intf_data[blade_intf][const.TENANTID]:
+                        if (not blade_intf_data[blade_intf][const.PORTID] or
+                            not blade_intf_data[blade_intf][const.TENANTID]):
                             continue
                         intf_data = blade_intf_data[blade_intf]
-                        if intf_data[const.BLADE_INTF_RESERVATION] == \
-                           const.BLADE_INTF_RESERVED and \
-                           intf_data[const.TENANTID] == tenant_id and \
-                           intf_data[const.PORTID] == port_id:
+                        if (intf_data[const.BLADE_INTF_RESERVATION] ==
+                                const.BLADE_INTF_RESERVED and
+                                intf_data[const.TENANTID] == tenant_id and
+                                intf_data[const.PORTID] == port_id):
                             interface_dn = intf_data[const.BLADE_INTF_DN]
                             blade_intf_info = {const.UCSM_IP: ucsm_ip,
                                                const.CHASSIS_ID: chassis_id,
@@ -433,26 +431,27 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
             for chassis_id in ucsm.keys():
                 for blade_id in ucsm[chassis_id]:
                     blade_data = ucsm[chassis_id][blade_id]
-                    if blade_data[const.BLADE_UNRESERVED_INTF_COUNT] > \
-                       unreserved_interface_count:
-                        unreserved_interface_count = \
-                                blade_data[const.BLADE_UNRESERVED_INTF_COUNT]
+                    if (blade_data[const.BLADE_UNRESERVED_INTF_COUNT] >
+                        unreserved_interface_count):
+                        unreserved_interface_count = (
+                            blade_data[const.BLADE_UNRESERVED_INTF_COUNT])
                         least_reserved_blade_ucsm = ucsm_ip
                         least_reserved_blade_chassis = chassis_id
                         least_reserved_blade_id = blade_id
                         least_reserved_blade_data = blade_data
 
         if unreserved_interface_count < intf_count:
-            LOG.warn("Not enough dynamic nics available on a single host." \
-                     " Requested: %s, Maximum available: %s" %
+            LOG.warn(("Not enough dynamic nics available on a single host."
+                      " Requested: %s, Maximum available: %s") %
                      (intf_count, unreserved_interface_count))
             return False
 
-        least_reserved_blade_dict = \
-                {const.LEAST_RSVD_BLADE_UCSM: least_reserved_blade_ucsm,
-                 const.LEAST_RSVD_BLADE_CHASSIS: least_reserved_blade_chassis,
-                 const.LEAST_RSVD_BLADE_ID: least_reserved_blade_id,
-                 const.LEAST_RSVD_BLADE_DATA: least_reserved_blade_data}
+        least_reserved_blade_dict = {
+            const.LEAST_RSVD_BLADE_UCSM: least_reserved_blade_ucsm,
+            const.LEAST_RSVD_BLADE_CHASSIS: least_reserved_blade_chassis,
+            const.LEAST_RSVD_BLADE_ID: least_reserved_blade_id,
+            const.LEAST_RSVD_BLADE_DATA: least_reserved_blade_data,
+            }
         LOG.debug("Found dynamic nic %s available for reservation",
                   least_reserved_blade_dict)
         return least_reserved_blade_dict
@@ -474,8 +473,6 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
         blade_data = self._get_blade_state(chassis_id, blade_id, ucsm_ip,
                                            ucsm_username, ucsm_password)
         blade_intf_data = blade_data[const.BLADE_INTF_DATA]
-        #import sys
-        #sys.exit(ucsm_ip)
         chassis_data = self._inventory_state[ucsm_ip][chassis_id]
         old_blade_intf_data = chassis_data[blade_id][const.BLADE_INTF_DATA]
 
@@ -485,34 +482,32 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
         """
         for blade_intf in blade_intf_data.keys():
             old_intf_data = old_blade_intf_data[blade_intf]
-            blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = \
-                    old_intf_data[const.BLADE_INTF_RESERVATION]
-            blade_intf_data[blade_intf][const.TENANTID] = \
-                    old_intf_data[const.TENANTID]
-            blade_intf_data[blade_intf][const.PORTID] = \
-                    old_intf_data[const.PORTID]
-            blade_intf_data[blade_intf][const.PROFILE_ID] = \
-                    old_intf_data[const.PROFILE_ID]
-            blade_intf_data[blade_intf][const.INSTANCE_ID] = \
-                    old_intf_data[const.INSTANCE_ID]
-            blade_intf_data[blade_intf][const.VIF_ID] = \
-                    old_intf_data[const.VIF_ID]
-
-        blade_data[const.BLADE_UNRESERVED_INTF_COUNT] = \
-                chassis_data[blade_id][const.BLADE_UNRESERVED_INTF_COUNT]
+            blade_intf_data[blade_intf][const.BLADE_INTF_RESERVATION] = (
+                old_intf_data[const.BLADE_INTF_RESERVATION])
+            blade_intf_data[blade_intf][const.TENANTID] = (
+                old_intf_data[const.TENANTID])
+            blade_intf_data[blade_intf][const.PORTID] = (
+                old_intf_data[const.PORTID])
+            blade_intf_data[blade_intf][const.PROFILE_ID] = (
+                old_intf_data[const.PROFILE_ID])
+            blade_intf_data[blade_intf][const.INSTANCE_ID] = (
+                old_intf_data[const.INSTANCE_ID])
+            blade_intf_data[blade_intf][const.VIF_ID] = (
+                old_intf_data[const.VIF_ID])
+
+        blade_data[const.BLADE_UNRESERVED_INTF_COUNT] = (
+            chassis_data[blade_id][const.BLADE_UNRESERVED_INTF_COUNT])
         """
         Now we will reserve an interface if its available
         """
         for blade_intf in blade_intf_data.keys():
             intf_data = blade_intf_data[blade_intf]
-            if intf_data[const.BLADE_INTF_RESERVATION] == \
-               const.BLADE_INTF_UNRESERVED:
-                intf_data[const.BLADE_INTF_RESERVATION] = \
-                        const.BLADE_INTF_RESERVED
+            if (intf_data[const.BLADE_INTF_RESERVATION] ==
+                    const.BLADE_INTF_UNRESERVED):
+                intf_data[const.BLADE_INTF_RESERVATION] = (
+                    const.BLADE_INTF_RESERVED)
                 intf_data[const.TENANTID] = tenant_id
                 intf_data[const.PORTID] = port_id
-                #intf_data[const.PROFILE_ID] = \
-                #        portprofile_name
                 intf_data[const.INSTANCE_ID] = None
                 dev_eth_name = intf_data[const.BLADE_INTF_RHEL_DEVICE_NAME]
                 """
@@ -520,11 +515,12 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
                 """
                 chassis_data[blade_id][const.BLADE_INTF_DATA] = blade_intf_data
                 chassis_data[blade_id][const.BLADE_UNRESERVED_INTF_COUNT] -= 1
-                host_name = self._get_host_name(ucsm_ip, chassis_id,
-                                                       blade_id)
-                reserved_nic_dict = {const.RESERVED_NIC_HOSTNAME: host_name,
-                                   const.RESERVED_NIC_NAME: dev_eth_name,
-                                   const.BLADE_INTF_DN: blade_intf}
+                host_name = self._get_host_name(ucsm_ip, chassis_id, blade_id)
+                reserved_nic_dict = {
+                    const.RESERVED_NIC_HOSTNAME: host_name,
+                    const.RESERVED_NIC_NAME: dev_eth_name,
+                    const.BLADE_INTF_DN: blade_intf,
+                    }
                 port_binding = udb.add_portbinding(port_id, blade_intf, None,
                                                    None, None, None)
                 udb.update_portbinding(port_id,
@@ -598,10 +594,11 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
         if not least_reserved_blade_dict:
             raise cexc.NoMoreNics()
         ucsm_ip = least_reserved_blade_dict[const.LEAST_RSVD_BLADE_UCSM]
-        device_params = {const.DEVICE_IP: [ucsm_ip],
-                         const.UCS_INVENTORY: self,
-                         const.LEAST_RSVD_BLADE_DICT:\
-                         least_reserved_blade_dict}
+        device_params = {
+            const.DEVICE_IP: [ucsm_ip],
+            const.UCS_INVENTORY: self,
+            const.LEAST_RSVD_BLADE_DICT: least_reserved_blade_dict,
+            }
         return device_params
 
     def delete_port(self, args):
@@ -618,12 +615,13 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
             LOG.warn("UCSInventory: Port not found: net_id: %s, port_id: %s" %
                      (net_id, port_id))
             return {const.DEVICE_IP: []}
-        device_params = \
-                {const.DEVICE_IP: [rsvd_info[const.UCSM_IP]],
-                 const.UCS_INVENTORY: self,
-                 const.CHASSIS_ID: rsvd_info[const.CHASSIS_ID],
-                 const.BLADE_ID: rsvd_info[const.BLADE_ID],
-                 const.BLADE_INTF_DN: rsvd_info[const.BLADE_INTF_DN]}
+        device_params = {
+            const.DEVICE_IP: [rsvd_info[const.UCSM_IP]],
+            const.UCS_INVENTORY: self,
+            const.CHASSIS_ID: rsvd_info[const.CHASSIS_ID],
+            const.BLADE_ID: rsvd_info[const.BLADE_ID],
+            const.BLADE_INTF_DN: rsvd_info[const.BLADE_INTF_DN],
+            }
         return device_params
 
     def update_port(self, args):
@@ -707,8 +705,10 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
         if not least_reserved_blade_dict:
             raise cexc.NoMoreNics()
         ucsm_ip = least_reserved_blade_dict[const.LEAST_RSVD_BLADE_UCSM]
-        device_params = {const.DEVICE_IP: [ucsm_ip],
-                         const.UCS_INVENTORY: self,
-                         const.LEAST_RSVD_BLADE_DICT:\
-                         least_reserved_blade_dict}
+        device_params = {
+            const.DEVICE_IP: [ucsm_ip],
+            const.UCS_INVENTORY: self,
+            const.LEAST_RSVD_BLADE_DICT:
+            least_reserved_blade_dict,
+            }
         return device_params
index 0f21fb863526d7160a72aff7c0130d6ce695b1a9..5b4298f9c3aa9eb77ddf78257ac9c2aec243f4ee 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
 
 import os
+
 from quantum.common.config import find_config_file
 from quantum.plugins.cisco.common import cisco_configparser as confp
 
+
 CONF_FILE = find_config_file({'plugin': 'cisco'}, None, "ucs_inventory.ini")
 CP = confp.CiscoConfigParser(CONF_FILE)
 
index 89775be96653f50093805c2c085d14f3be560ac8..e1bfdbb0c753ec72a0e601c963ed4d96dd51b944 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
@@ -17,7 +16,6 @@
 #
 # @author: Sumit Naiksatam, Cisco Systems Inc.
 #
-"""
 
 """
 Implements a UCSM XML API Client
@@ -27,12 +25,14 @@ import httplib
 import logging
 from xml.etree import ElementTree as et
 
-from quantum.plugins.cisco.common import cisco_exceptions as cexc
 from quantum.plugins.cisco.common import cisco_constants as const
+from quantum.plugins.cisco.common import cisco_exceptions as cexc
 from quantum.plugins.cisco.ucs import cisco_getvif as gvif
 
+
 LOG = logging.getLogger(__name__)
 
+
 COOKIE_VALUE = "cookie_placeholder"
 PROFILE_NAME = "profilename_placeholder"
 PROFILE_CLIENT = "profileclient_placeholder"
@@ -144,35 +144,25 @@ class CiscoUCSMDriver():
     def _post_data(self, ucsm_ip, ucsm_username, ucsm_password, data):
         """Send command to UCSM in http request"""
         conn = httplib.HTTPSConnection(ucsm_ip)
-        login_data = "<aaaLogin inName=\"" + ucsm_username + \
-        "\" inPassword=\"" + ucsm_password + "\" />"
+        login_data = ("<aaaLogin inName=\"" + ucsm_username +
+                      "\" inPassword=\"" + ucsm_password + "\" />")
         conn.request(METHOD, URL, login_data, HEADERS)
         response = conn.getresponse()
         response_data = response.read()
-        #LOG.debug(response.status)
-        #LOG.debug(response.reason)
-        #LOG.debug(response_data)
         # TODO (Sumit): If login is not successful, throw exception
         xml_tree = et.XML(response_data)
         cookie = xml_tree.attrib["outCookie"]
 
         data = data.replace(COOKIE_VALUE, cookie)
-        #LOG.debug("POST: %s" % data)
         conn.request(METHOD, URL, data, HEADERS)
         response = conn.getresponse()
         response_data = response.read()
-        #LOG.debug(response.status)
-        #LOG.debug(response.reason)
-        #LOG.debug("UCSM Response: %s" % response_data)
         post_data_response = response_data
 
         logout_data = "<aaaLogout inCookie=\"" + cookie + "\" />"
         conn.request(METHOD, URL, logout_data, HEADERS)
         response = conn.getresponse()
         response_data = response.read()
-        #LOG.debug(response.status)
-        #LOG.debug(response.reason)
-        #LOG.debug(response_data)
         return post_data_response
 
     def _create_vlan_post_data(self, vlan_name, vlan_id):
@@ -187,15 +177,14 @@ class CiscoUCSMDriver():
         data = data.replace(VLAN_NAME, vlan_name)
         return data
 
-    def _create_pclient_post_data(self, profile_name,
-                                         profile_client_name):
+    def _create_pclient_post_data(self, profile_name, profile_client_name):
         """Create command"""
         data = ASSOCIATE_PROFILE.replace(PROFILE_NAME, profile_name)
         data = data.replace(PROFILE_CLIENT, profile_client_name)
         return data
 
     def _change_vlaninprof_post_data(self, profile_name, old_vlan_name,
-                                          new_vlan_name):
+                                     new_vlan_name):
         """Create command"""
         data = CHANGE_VLAN_IN_PROFILE.replace(PROFILE_NAME, profile_name)
         data = data.replace(OLD_VLAN_NAME, old_vlan_name)
@@ -229,20 +218,23 @@ class CiscoUCSMDriver():
         data = self._get_blade_interfaces_post_data(chassis_number,
                                                     blade_number)
         response = self._post_data(ucsm_ip, ucsm_username, ucsm_password, data)
-        elements = \
-                et.XML(response).find("outConfigs").findall("adaptorHostEthIf")
+        elements = (
+            et.XML(response).find("outConfigs").findall("adaptorHostEthIf")
+            )
         blade_interfaces = {}
         for element in elements:
             dist_name = element.get("dn", default=None)
             if dist_name:
                 order = element.get("order", default=None)
-                blade_interface = {const.BLADE_INTF_DN: dist_name,
-                                  const.BLADE_INTF_ORDER: order,
-                                  const.BLADE_INTF_LINK_STATE: None,
-                                  const.BLADE_INTF_OPER_STATE: None,
-                                  const.BLADE_INTF_INST_TYPE: None,
-                                  const.BLADE_INTF_RHEL_DEVICE_NAME:
-                                  self._get_rhel_device_name(order)}
+                blade_interface = {
+                    const.BLADE_INTF_DN: dist_name,
+                    const.BLADE_INTF_ORDER: order,
+                    const.BLADE_INTF_LINK_STATE: None,
+                    const.BLADE_INTF_OPER_STATE: None,
+                    const.BLADE_INTF_INST_TYPE: None,
+                    const.BLADE_INTF_RHEL_DEVICE_NAME:
+                    self._get_rhel_device_name(order),
+                    }
                 blade_interfaces[dist_name] = blade_interface
 
         return blade_interfaces
@@ -250,18 +242,18 @@ class CiscoUCSMDriver():
     def _get_blade_interface_state(self, blade_intf, ucsm_ip,
                               ucsm_username, ucsm_password):
         """Create command"""
-        data = \
-        self._get_blade_intf_st_post_data(blade_intf[const.BLADE_INTF_DN])
+        data = (
+            self._get_blade_intf_st_post_data(blade_intf[const.BLADE_INTF_DN])
+            )
         response = self._post_data(ucsm_ip, ucsm_username, ucsm_password, data)
-        elements = \
-                et.XML(response).find("outConfigs").findall("dcxVIf")
+        elements = et.XML(response).find("outConfigs").findall("dcxVIf")
         for element in elements:
             blade_intf[const.BLADE_INTF_LINK_STATE] = element.get("linkState",
-                                                                 default=None)
+                                                                  default=None)
             blade_intf[const.BLADE_INTF_OPER_STATE] = element.get("operState",
-                                                                 default=None)
+                                                                  default=None)
             blade_intf[const.BLADE_INTF_INST_TYPE] = element.get("instType",
-                                                                default=None)
+                                                                 default=None)
 
     def _get_rhel_device_name(self, order):
         """Get the device name as on the RHEL host"""
@@ -279,8 +271,7 @@ class CiscoUCSMDriver():
         """Create request for UCSM"""
         data = self._create_profile_post_data(profile_name, vlan_name)
         self._post_data(ucsm_ip, ucsm_username, ucsm_password, data)
-        data = self._create_pclient_post_data(profile_name,
-                                                     profile_name[-16:])
+        data = self._create_pclient_post_data(profile_name, profile_name[-16:])
         self._post_data(ucsm_ip, ucsm_username, ucsm_password, data)
 
     def change_vlan_in_profile(self, profile_name, old_vlan_name,
@@ -288,21 +279,20 @@ class CiscoUCSMDriver():
                                ucsm_password):
         """Create request for UCSM"""
         data = self._change_vlaninprof_post_data(profile_name,
-                                                      old_vlan_name,
-                                                      new_vlan_name)
+                                                 old_vlan_name,
+                                                 new_vlan_name)
         self._post_data(ucsm_ip, ucsm_username, ucsm_password, data)
 
-    def get_blade_data(self, chassis_number, blade_number,
-                                         ucsm_ip, ucsm_username,
-                                         ucsm_password):
+    def get_blade_data(self, chassis_number, blade_number, ucsm_ip,
+                       ucsm_username, ucsm_password):
         """
         Returns only the dynamic interfaces on the blade
         """
         blade_interfaces = self._get_blade_interfaces(chassis_number,
-                                                       blade_number,
-                                                       ucsm_ip,
-                                                       ucsm_username,
-                                                       ucsm_password)
+                                                      blade_number,
+                                                      ucsm_ip,
+                                                      ucsm_username,
+                                                      ucsm_password)
         for blade_intf in blade_interfaces.keys():
             self._get_blade_interface_state(blade_interfaces[blade_intf],
                                             ucsm_ip, ucsm_username,
index 0bb7655dcc313325296f912b6355f73980087423..52594679339b93bbcce06816e36d657a25bb5358 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2011 Cisco Systems, Inc.  All rights reserved.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 #
-"""
 
 import logging
 
 from quantum.common import exceptions as exc
 from quantum.common import utils
-from quantum.plugins.cisco.common import cisco_exceptions as cexc
 from quantum.plugins.cisco.common import cisco_constants as const
 from quantum.plugins.cisco.common import cisco_credentials as cred
+from quantum.plugins.cisco.common import cisco_exceptions as cexc
 from quantum.plugins.cisco.common import cisco_utils as cutil
 from quantum.plugins.cisco.db import api as db
 from quantum.plugins.cisco.db import l2network_db as cdb
@@ -33,6 +31,7 @@ from quantum.plugins.cisco.db import ucs_db as udb
 from quantum.plugins.cisco.l2device_plugin_base import L2DevicePluginBase
 from quantum.plugins.cisco.ucs import cisco_ucs_configuration as conf
 
+
 LOG = logging.getLogger(__name__)
 
 
@@ -115,8 +114,8 @@ class UCSVICPlugin(L2DevicePluginBase):
             ports_on_net.append(new_port)
 
         new_network = cutil.make_net_dict(network[const.UUID],
-                                              network[const.NETWORKNAME],
-                                              ports_on_net)
+                                          network[const.NETWORKNAME],
+                                          ports_on_net)
 
         return new_network
 
@@ -166,16 +165,16 @@ class UCSVICPlugin(L2DevicePluginBase):
                                                      conf.DEFAULT_VLAN_NAME,
                                                      conf.DEFAULT_VLAN_ID)
         profile_name = new_port_profile[const.PROFILE_NAME]
-        rsvd_nic_dict = ucs_inventory.\
-                reserve_blade_interface(self._ucsm_ip, chassis_id,
-                                        blade_id, blade_data_dict,
-                                        tenant_id, port_id,
-                                        profile_name)
+        rsvd_nic_dict = ucs_inventory.reserve_blade_interface(
+            self._ucsm_ip, chassis_id,
+            blade_id, blade_data_dict,
+            tenant_id, port_id,
+            profile_name)
         port_binding = udb.update_portbinding(port_id,
-                                       portprofile_name=profile_name,
-                                       vlan_name=conf.DEFAULT_VLAN_NAME,
-                                       vlan_id=conf.DEFAULT_VLAN_ID,
-                                       qos=qos)
+                                              portprofile_name=profile_name,
+                                              vlan_name=conf.DEFAULT_VLAN_NAME,
+                                              vlan_id=conf.DEFAULT_VLAN_ID,
+                                              qos=qos)
         return port_binding
 
     def delete_port(self, tenant_id, net_id, port_id, **kwargs):
@@ -269,21 +268,22 @@ class UCSVICPlugin(L2DevicePluginBase):
         blade_data_dict = least_rsvd_blade_dict[const.LEAST_RSVD_BLADE_DATA]
         port_binding_list = []
         for port_id, net_id in zip(port_id_list, net_id_list):
-            new_port_profile = \
-                    self._create_port_profile(tenant_id, net_id, port_id,
-                                              conf.DEFAULT_VLAN_NAME,
-                                              conf.DEFAULT_VLAN_ID)
+            new_port_profile = self._create_port_profile(
+                tenant_id, net_id, port_id,
+                conf.DEFAULT_VLAN_NAME,
+                conf.DEFAULT_VLAN_ID)
             profile_name = new_port_profile[const.PROFILE_NAME]
-            rsvd_nic_dict = ucs_inventory.\
-                    reserve_blade_interface(self._ucsm_ip, chassis_id,
-                                            blade_id, blade_data_dict,
-                                            tenant_id, port_id,
-                                            profile_name)
-            port_binding = udb.update_portbinding(port_id,
-                                           portprofile_name=profile_name,
-                                           vlan_name=conf.DEFAULT_VLAN_NAME,
-                                           vlan_id=conf.DEFAULT_VLAN_ID,
-                                           qos=qos)
+            rsvd_nic_dict = ucs_inventory.reserve_blade_interface(
+                self._ucsm_ip, chassis_id,
+                blade_id, blade_data_dict,
+                tenant_id, port_id,
+                profile_name)
+            port_binding = udb.update_portbinding(
+                port_id,
+                portprofile_name=profile_name,
+                vlan_name=conf.DEFAULT_VLAN_NAME,
+                vlan_id=conf.DEFAULT_VLAN_ID,
+                qos=qos)
             port_binding_list.append(port_binding)
         return port_binding_list
 
@@ -298,8 +298,7 @@ class UCSVICPlugin(L2DevicePluginBase):
 
     def _get_profile_name(self, port_id):
         """Returns the port profile name based on the port UUID"""
-        profile_name = conf.PROFILE_NAME_PREFIX \
-                + cutil.get16ByteUUID(port_id)
+        profile_name = conf.PROFILE_NAME_PREFIX + cutil.get16ByteUUID(port_id)
         return profile_name
 
     def _get_vlan_name_for_network(self, tenant_id, network_id):
index 378fc52b17994a870ec858c5ec08633f57486042..97c75325d6a9049649d73002d01e80a1ba710e0b 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012, Cisco Systems, Inc.
 #    License for the specific language governing permissions and limitations
 #    under the License.
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-"""
 
 import logging
 
 from quantum.api.api_common import OperationalStatus
 from quantum.common import exceptions as exc
 from quantum.db import api as db
-from quantum.plugins.linuxbridge import plugin_configuration as conf
 from quantum.plugins.linuxbridge.common import constants as const
 from quantum.plugins.linuxbridge.common import utils as cutil
 from quantum.plugins.linuxbridge.db import l2network_db as cdb
+from quantum.plugins.linuxbridge import plugin_configuration as conf
 from quantum.quantum_plugin_base import QuantumPluginBase
 
 
@@ -111,10 +109,12 @@ class LinuxBridgePlugin(QuantumPluginBase):
         new_net_id = new_network[const.UUID]
         vlan_id = self._get_vlan_for_tenant(tenant_id)
         cdb.add_vlan_binding(vlan_id, new_net_id)
-        new_net_dict = {const.NET_ID: new_net_id,
-                        const.NET_NAME: net_name,
-                        const.NET_PORTS: [],
-                        const.NET_OP_STATUS: new_network[const.OPSTATUS]}
+        new_net_dict = {
+            const.NET_ID: new_net_id,
+            const.NET_NAME: net_name,
+            const.NET_PORTS: [],
+            const.NET_OP_STATUS: new_network[const.OPSTATUS],
+            }
         return new_net_dict
 
     def delete_network(self, tenant_id, net_id):
@@ -197,7 +197,7 @@ class LinuxBridgePlugin(QuantumPluginBase):
         LOG.debug("LinuxBridgePlugin.create_port() called")
         db.validate_network_ownership(tenant_id, net_id)
         port = db.port_create(net_id, port_state,
-                                op_status=OperationalStatus.DOWN)
+                              op_status=OperationalStatus.DOWN)
         unique_port_id_string = port[const.UUID]
         new_port_dict = cutil.make_port_dict(port)
         return new_port_dict
index 45cd2b62db9bb7abea5868291b705d1dc18904b1..863a8a546aecc139243f654a420b176b5067743b 100755 (executable)
 # Based on the structure of the OpenVSwitch agent in the
 # Quantum OpenVSwitch Plugin.
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-
-from optparse import OptionParser
-from subprocess import *
 
 import ConfigParser
-import logging as LOG
-import MySQLdb
+import logging
+from optparse import OptionParser
 import os
 import shlex
 import signal
 import sqlite3
+import subprocess
 import sys
 import time
 
+import MySQLdb
+
+
+LOG = logging.getLogger(__name__)
+
 
 BRIDGE_NAME_PREFIX = "brq"
 GATEWAY_INTERFACE_PREFIX = "gw-"
@@ -62,7 +64,7 @@ class LinuxBridge:
     def run_cmd(self, args):
         cmd = shlex.split(self.root_helper) + args
         LOG.debug("Running command: " + " ".join(cmd))
-        p = Popen(cmd, stdout=PIPE)
+        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
         retval = p.communicate()[0]
         if p.returncode == -(signal.SIGALRM):
             LOG.debug("Timeout running command: " + " ".join(cmd))
@@ -81,7 +83,7 @@ class LinuxBridge:
     def get_bridge_name(self, network_id):
         if not network_id:
             LOG.warning("Invalid Network ID, will lead to incorrect bridge" \
-                      "name")
+                        "name")
         bridge_name = self.br_name_prefix + network_id[0:11]
         return bridge_name
 
@@ -95,7 +97,7 @@ class LinuxBridge:
     def get_tap_device_name(self, interface_id):
         if not interface_id:
             LOG.warning("Invalid Interface ID, will lead to incorrect " \
-                      "tap device name")
+                        "tap device name")
         tap_device_name = TAP_INTERFACE_PREFIX + interface_id[0:11]
         return tap_device_name
 
@@ -109,9 +111,8 @@ class LinuxBridge:
 
     def get_interfaces_on_bridge(self, bridge_name):
         if self.device_exists(bridge_name):
-            bridge_interface_path = \
-                    BRIDGE_INTERFACES_FS.replace(BRIDGE_NAME_PLACEHOLDER,
-                                                 bridge_name)
+            bridge_interface_path = BRIDGE_INTERFACES_FS.replace(
+                BRIDGE_NAME_PLACEHOLDER, bridge_name)
             return os.listdir(bridge_interface_path)
 
     def get_all_tap_devices(self):
@@ -149,9 +150,8 @@ class LinuxBridge:
         if not device_name:
             return False
         else:
-            bridge_port_path = \
-                    BRIDGE_PORT_FS_FOR_DEVICE.replace(DEVICE_NAME_PLACEHOLDER,
-                                                      device_name)
+            bridge_port_path = BRIDGE_PORT_FS_FOR_DEVICE.replace(
+                DEVICE_NAME_PLACEHOLDER, device_name)
             return os.path.exists(bridge_port_path)
 
     def ensure_vlan_bridge(self, network_id, vlan_id):
@@ -183,7 +183,7 @@ class LinuxBridge:
         """
         if not self.device_exists(bridge_name):
             LOG.debug("Starting bridge %s for subinterface %s" % (bridge_name,
-                                                                interface))
+                                                                  interface))
             if self.run_cmd(['brctl', 'addbr', bridge_name]):
                 return
             if self.run_cmd(['brctl', 'setfd', bridge_name, str(0)]):
@@ -210,8 +210,7 @@ class LinuxBridge:
                       tap_device_name)
             return False
 
-        current_bridge_name = \
-                self.get_bridge_for_tap_device(tap_device_name)
+        current_bridge_name = self.get_bridge_for_tap_device(tap_device_name)
         bridge_name = self.get_bridge_name(network_id)
         if bridge_name == current_bridge_name:
             return False
@@ -237,12 +236,10 @@ class LinuxBridge:
             """
             return False
         if interface_id.startswith(GATEWAY_INTERFACE_PREFIX):
-            return self.add_tap_interface(network_id, vlan_id,
-                                              interface_id)
+            return self.add_tap_interface(network_id, vlan_id, interface_id)
         else:
             tap_device_name = self.get_tap_device_name(interface_id)
-            return self.add_tap_interface(network_id, vlan_id,
-                                          tap_device_name)
+            return self.add_tap_interface(network_id, vlan_id, tap_device_name)
 
     def delete_vlan_bridge(self, bridge_name):
         if self.device_exists(bridge_name):
@@ -266,15 +263,15 @@ class LinuxBridge:
         if self.device_exists(bridge_name):
             if not self.is_device_on_bridge(interface_name):
                 return True
-            LOG.debug("Removing device %s from bridge %s" % \
+            LOG.debug("Removing device %s from bridge %s" %
                       (interface_name, bridge_name))
             if self.run_cmd(['brctl', 'delif', bridge_name, interface_name]):
                 return False
-            LOG.debug("Done removing device %s from bridge %s" % \
+            LOG.debug("Done removing device %s from bridge %s" %
                       (interface_name, bridge_name))
             return True
         else:
-            LOG.debug("Cannot remove device %s, bridge %s does not exist" % \
+            LOG.debug("Cannot remove device %s, bridge %s does not exist" %
                       (interface_name, bridge_name))
             return False
 
@@ -327,16 +324,16 @@ class LinuxBridgeQuantumAgent:
         LOG.debug("plugged tap device names %s" % plugged_tap_device_names)
         for tap_device in self.linux_br.get_all_tap_devices():
             if tap_device not in plugged_tap_device_names:
-                current_bridge_name = \
-                        self.linux_br.get_bridge_for_tap_device(tap_device)
+                current_bridge_name = (
+                    self.linux_br.get_bridge_for_tap_device(tap_device))
                 if current_bridge_name:
                     self.linux_br.remove_interface(current_bridge_name,
                                                    tap_device)
 
         for gw_device in self.linux_br.get_all_gateway_devices():
             if gw_device not in plugged_gateway_device_names:
-                current_bridge_name = \
-                        self.linux_br.get_bridge_for_tap_device(gw_device)
+                current_bridge_name = (
+                    self.linux_br.get_bridge_for_tap_device(gw_device))
                 if current_bridge_name:
                     self.linux_br.remove_interface(current_bridge_name,
                                                    gw_device)
@@ -378,15 +375,13 @@ class LinuxBridgeQuantumAgent:
         for pb in port_bindings:
             ports_string = "%s %s" % (ports_string, pb)
             if pb['interface_id']:
-                vlan_id = \
-                        str(vlan_bindings[pb['network_id']]['vlan_id'])
+                vlan_id = str(vlan_bindings[pb['network_id']]['vlan_id'])
                 if self.process_port_binding(pb['uuid'],
                                              pb['network_id'],
                                              pb['interface_id'],
                                              vlan_id):
                     cursor = MySQLdb.cursors.DictCursor(conn)
-                    sql = PORT_OPSTATUS_UPDATESQL % (pb['uuid'],
-                                                     OP_STATUS_UP)
+                    sql = PORT_OPSTATUS_UPDATESQL % (pb['uuid'], OP_STATUS_UP)
                     cursor.execute(sql)
                     cursor.close()
                 plugged_interfaces.append(pb['interface_id'])
index f77db6ef689dc0a0f328836e8027dcbcf3efb259..5bb15232d0290be80e22fd1a237ea71429feeebd 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012 Cisco Systems, Inc.  All rights reserved.
@@ -16,5 +15,3 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
index 2b170a2fbff17c7d1af943fdac7af1469349d3ed..d818753598b31972acb8a9e798b3e9c82558bdb4 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,6 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 from configobj import ConfigObj
 
@@ -27,7 +24,7 @@ class ConfigParser(ConfigObj):
 
     def __init__(self, filename):
         super(ConfigParser, self).__init__(filename, raise_errors=True,
-                                                file_error=True)
+                                           file_error=True)
 
     def dummy(self, section, key):
         """Dummy function to return the same key, used in walk"""
index 0aff3ff45c8e152f50f4547e60f4b336c177a5bd..7e67247eef29f8df8d421e2875b6882732bbe85b 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012 Cisco Systems, Inc.  All rights reserved.
@@ -16,8 +15,7 @@
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
+
 
 PORT_STATE = 'port-state'
 PORT_UP = "ACTIVE"
index 40dafd3538c97edb259f419d8e2845f8f34b4db1..897db0ac879c7a723ec5b4395f8df8ebfad13d6e 100644 (file)
 """
 Exceptions used by the LinuxBridge plugin
 """
+
 from quantum.common import exceptions
 
 
 class NetworksLimit(exceptions.QuantumException):
     """Total number of network objects limit has been hit"""
-    message = _("Unable to create new network. Number of networks" \
+    message = _("Unable to create new network. Number of networks"
                 "for the system has exceeded the limit")
 
 
 class NetworkVlanBindingAlreadyExists(exceptions.QuantumException):
     """Binding cannot be created, since it already exists"""
-    message = _("NetworkVlanBinding for %(vlan_id)s and network " \
+    message = _("NetworkVlanBinding for %(vlan_id)s and network "
                 "%(network_id)s already exists")
 
 
 class NetworkVlanBindingNotFound(exceptions.QuantumException):
     """Binding could not be found"""
-    message = _("NetworkVlanBinding for network " \
+    message = _("NetworkVlanBinding for network "
                 "%(network_id)s does not exist")
 
 
@@ -53,20 +54,5 @@ class VlanIDNotAvailable(exceptions.QuantumException):
 
 class UnableToChangeVlanRange(exceptions.QuantumException):
     """No VLAN ID available"""
-    message = _("Current VLAN ID range %(range_start)s to %(range_end)s " \
+    message = _("Current VLAN ID range %(range_start)s to %(range_end)s "
                 "cannot be changed. Please check plugin conf file.")
-
-
-try:
-    _("test")
-except NameError:
-
-    def _(a_string):
-        """
-        Default implementation of the gettext string
-        translation function: no translation
-        """
-        return a_string
-except TypeError:
-    # during doctesting, _ might mean something else
-    pass
index 569eaa3315e1b9fcb0c22ba795c52199d24385a7..06a4651c2bb070d13db8b1ddc92060e743399d23 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012 Cisco Systems, Inc.  All rights reserved.
 #    under the License.
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
 
 import logging
 
 from quantum.api.api_common import OperationalStatus
 from quantum.plugins.linuxbridge.common import constants as const
 
+
 LOG = logging.getLogger(__name__)
 
 
 def make_net_dict(net_id, net_name, ports, op_status):
     """Helper funciton"""
-    res = {const.NET_ID: net_id, const.NET_NAME: net_name, const.NET_OP_STATUS:
-          op_status}
+    res = {
+        const.NET_ID: net_id,
+        const.NET_NAME: net_name,
+        const.NET_OP_STATUS: op_status,
+        }
     if ports:
         res[const.NET_PORTS] = ports
     return res
@@ -43,8 +44,10 @@ def make_port_dict(port):
     else:
         op_status = OperationalStatus.DOWN
 
-    return {const.PORT_ID: str(port[const.UUID]),
-            const.PORT_STATE: port[const.PORTSTATE],
-            const.PORT_OP_STATUS: op_status,
-            const.NET_ID: port[const.NETWORKID],
-            const.ATTACHMENT: port[const.INTERFACEID]}
+    return {
+        const.PORT_ID: str(port[const.UUID]),
+        const.PORT_STATE: port[const.PORTSTATE],
+        const.PORT_OP_STATUS: op_status,
+        const.NET_ID: port[const.NETWORKID],
+        const.ATTACHMENT: port[const.INTERFACEID],
+        }
index c6d64a4ba6e504b49a5c3edf4bfbf1f0e3ba584f..5b02419fa4cc874db0a2f9a9983329956781d8ce 100644 (file)
 #    under the License.
 # @author: Rohit Agarwalla, Cisco Systems, Inc.
 
+import logging
+
 from sqlalchemy import func
 from sqlalchemy.orm import exc
 
 from quantum.common import exceptions as q_exc
-from quantum.plugins.linuxbridge import plugin_configuration as conf
+import quantum.db.api as db
 from quantum.plugins.linuxbridge.common import exceptions as c_exc
 from quantum.plugins.linuxbridge.db import l2network_models
-
-import logging
-
-import quantum.db.api as db
+from quantum.plugins.linuxbridge import plugin_configuration as conf
 
 
 LOG = logging.getLogger(__name__)
@@ -63,12 +62,12 @@ def create_vlanids():
         has to be supported.
         Per Dan's suggestion we just throw a server exception for now.
         """
-        current_start = \
-                int(session.query(func.min(l2network_models.VlanID.vlan_id)).
-                    one()[0])
-        current_end = \
-                int(session.query(func.max(l2network_models.VlanID.vlan_id)).
-                    one()[0])
+        current_start = (
+            int(session.query(func.min(l2network_models.VlanID.vlan_id)).
+                one()[0]))
+        current_end = (
+            int(session.query(func.max(l2network_models.VlanID.vlan_id)).
+                one()[0]))
         if current_start != start or current_end != end:
             LOG.debug("Old VLAN range %s-%s" % (current_start, current_end))
             LOG.debug("New VLAN range %s-%s" % (start, end))
@@ -89,8 +88,8 @@ def get_all_vlanids():
     LOG.debug("get_all_vlanids() called")
     session = db.get_session()
     try:
-        vlanids = session.query(l2network_models.VlanID).\
-          all()
+        vlanids = (session.query(l2network_models.VlanID).
+                   all())
         return vlanids
     except exc.NoResultFound:
         return []
@@ -101,9 +100,9 @@ def is_vlanid_used(vlan_id):
     LOG.debug("is_vlanid_used() called")
     session = db.get_session()
     try:
-        vlanid = session.query(l2network_models.VlanID).\
-          filter_by(vlan_id=vlan_id).\
-          one()
+        vlanid = (session.query(l2network_models.VlanID).
+                  filter_by(vlan_id=vlan_id).
+                  one())
         return vlanid["vlan_used"]
     except exc.NoResultFound:
         raise c_exc.VlanIDNotFound(vlan_id=vlan_id)
@@ -114,9 +113,9 @@ def release_vlanid(vlan_id):
     LOG.debug("release_vlanid() called")
     session = db.get_session()
     try:
-        vlanid = session.query(l2network_models.VlanID).\
-         filter_by(vlan_id=vlan_id).\
-          one()
+        vlanid = (session.query(l2network_models.VlanID).
+                  filter_by(vlan_id=vlan_id).
+                  one())
         vlanid["vlan_used"] = False
         session.merge(vlanid)
         session.flush()
@@ -131,9 +130,9 @@ def delete_vlanid(vlan_id):
     LOG.debug("delete_vlanid() called")
     session = db.get_session()
     try:
-        vlanid = session.query(l2network_models.VlanID).\
-          filter_by(vlan_id=vlan_id).\
-          one()
+        vlanid = (session.query(l2network_models.VlanID).
+                  filter_by(vlan_id=vlan_id).
+                  one())
         session.delete(vlanid)
         session.flush()
         return vlanid
@@ -146,20 +145,20 @@ def reserve_vlanid():
     LOG.debug("reserve_vlanid() called")
     session = db.get_session()
     try:
-        rvlan = session.query(l2network_models.VlanID).\
-          first()
+        rvlan = (session.query(l2network_models.VlanID).
+                 first())
         if not rvlan:
             create_vlanids()
 
-        rvlan = session.query(l2network_models.VlanID).\
-         filter_by(vlan_used=False).\
-          first()
+        rvlan = (session.query(l2network_models.VlanID).
+                 filter_by(vlan_used=False).
+                 first())
         if not rvlan:
             raise c_exc.VlanIDNotAvailable()
 
-        rvlanid = session.query(l2network_models.VlanID).\
-         filter_by(vlan_id=rvlan["vlan_id"]).\
-          one()
+        rvlanid = (session.query(l2network_models.VlanID).
+                   filter_by(vlan_id=rvlan["vlan_id"]).
+                   one())
         rvlanid["vlan_used"] = True
         session.merge(rvlanid)
         session.flush()
@@ -173,9 +172,9 @@ def get_all_vlanids_used():
     LOG.debug("get_all_vlanids() called")
     session = db.get_session()
     try:
-        vlanids = session.query(l2network_models.VlanID).\
-        filter_by(vlan_used=True).\
-          all()
+        vlanids = (session.query(l2network_models.VlanID).
+                   filter_by(vlan_used=True).
+                   all())
         return vlanids
     except exc.NoResultFound:
         return []
@@ -186,8 +185,8 @@ def get_all_vlan_bindings():
     LOG.debug("get_all_vlan_bindings() called")
     session = db.get_session()
     try:
-        bindings = session.query(l2network_models.VlanBinding).\
-          all()
+        bindings = (session.query(l2network_models.VlanBinding).
+                    all())
         return bindings
     except exc.NoResultFound:
         return []
@@ -198,9 +197,9 @@ def get_vlan_binding(netid):
     LOG.debug("get_vlan_binding() called")
     session = db.get_session()
     try:
-        binding = session.query(l2network_models.VlanBinding).\
-          filter_by(network_id=netid).\
-          one()
+        binding = (session.query(l2network_models.VlanBinding).
+                   filter_by(network_id=netid).
+                   one())
         return binding
     except exc.NoResultFound:
         raise c_exc.NetworkVlanBindingNotFound(network_id=netid)
@@ -211,9 +210,9 @@ def add_vlan_binding(vlanid, netid):
     LOG.debug("add_vlan_binding() called")
     session = db.get_session()
     try:
-        binding = session.query(l2network_models.VlanBinding).\
-          filter_by(vlan_id=vlanid).\
-          one()
+        binding = (session.query(l2network_models.VlanBinding).
+                   filter_by(vlan_id=vlanid).
+                   one())
         raise c_exc.NetworkVlanBindingAlreadyExists(vlan_id=vlanid,
                                                     network_id=netid)
     except exc.NoResultFound:
@@ -228,9 +227,9 @@ def remove_vlan_binding(netid):
     LOG.debug("remove_vlan_binding() called")
     session = db.get_session()
     try:
-        binding = session.query(l2network_models.VlanBinding).\
-          filter_by(network_id=netid).\
-          one()
+        binding = (session.query(l2network_models.VlanBinding).
+                   filter_by(network_id=netid).
+                   one())
         session.delete(binding)
         session.flush()
         return binding
@@ -243,9 +242,9 @@ def update_vlan_binding(netid, newvlanid=None):
     LOG.debug("update_vlan_binding() called")
     session = db.get_session()
     try:
-        binding = session.query(l2network_models.VlanBinding).\
-          filter_by(network_id=netid).\
-          one()
+        binding = (session.query(l2network_models.VlanBinding).
+                   filter_by(network_id=netid).
+                   one())
         if newvlanid:
             binding["vlan_id"] = newvlanid
         session.merge(binding)
index b5613b322308535577401157b0fed62d53bc7bf5..caf9657cd1682c7322170ae4f9cb47b43855b5e0 100644 (file)
@@ -20,9 +20,9 @@ import uuid
 from sqlalchemy import Column, Integer, String, Boolean
 from sqlalchemy.orm import relation, object_mapper
 
+from quantum.db import models
 from quantum.db.models import BASE
 from quantum.db.models import QuantumBase
-from quantum.db import models
 
 
 class VlanID(BASE, QuantumBase):
@@ -37,8 +37,7 @@ class VlanID(BASE, QuantumBase):
         self.vlan_used = False
 
     def __repr__(self):
-        return "<VlanID(%d,%s)>" % \
-          (self.vlan_id, self.vlan_used)
+        return "<VlanID(%d,%s)>" % (self.vlan_id, self.vlan_used)
 
 
 class VlanBinding(BASE, QuantumBase):
@@ -53,5 +52,4 @@ class VlanBinding(BASE, QuantumBase):
         self.network_id = network_id
 
     def __repr__(self):
-        return "<VlanBinding(%d,%s,%s)>" % \
-          (self.vlan_id, self.network_id)
+        return "<VlanBinding(%d,%s,%s)>" % (self.vlan_id, self.network_id)
index cc6cdd66d64907ef90e4aa8df450af740523735a..a5bacb134b8ac10b78265fb6c9837389c0b44698 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012 Cisco Systems, Inc.  All rights reserved.
@@ -17,7 +16,6 @@
 #
 # @author: Sumit Naiksatam, Cisco Systems, Inc.
 # @author: Rohit Agarwalla, Cisco Systems, Inc.
-"""
 
 import os
 
index 805922670a690d2a38c4bd2697ae3960db12e5c1..9d8a263a6adf96342fb0f22c03bf300afb1c0329 100644 (file)
@@ -25,11 +25,10 @@ To run all tests::
     PLUGIN_DIR=quantum/plugins/linuxbridge ./run_tests.sh
 """
 
-import gettext
 import logging
 import os
-import unittest
 import sys
+import unittest
 
 from nose import config
 from nose import core
index 09d30bf8d7c22978a83497c0866d5584eff4e898..3fd7f5bb08ce08398b11469c584e5910937bec10 100644 (file)
 #    under the License.
 #
 # @author: Shweta Padubidri, Cisco Systems, Inc.
-#
 
 import ConfigParser
-import logging as LOG
-import unittest
-import sys
+import logging
 import os
 import shlex
 import signal
-from subprocess import *
+import subprocess
+import sys
+import unittest
 
-import quantum.plugins.linuxbridge.agent.linuxbridge_quantum_agent\
-                                                     as linux_agent
-from quantum.plugins.linuxbridge.common import constants as lconst
+import quantum.db.api as db
 from quantum.plugins.linuxbridge import LinuxBridgePlugin
+from quantum.plugins.linuxbridge.agent import (
+    linuxbridge_quantum_agent as linux_agent,
+    )
+from quantum.plugins.linuxbridge.common import constants as lconst
 from quantum.plugins.linuxbridge.db import l2network_db as cdb
-import quantum.db.api as db
 
 
-LOG.getLogger(__name__)
+LOG = logger.getLogger(__name__)
 
 
 class LinuxBridgeAgentTest(unittest.TestCase):
 
     def test_add_gateway_interface(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
-                  mac_address='fe:16:3e:51:60:dd'):
+        self, tenant_id="test_tenant", network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
+        mac_address='fe:16:3e:51:60:dd'):
 
         LOG.debug("test_tap_gateway_interface - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         self.create_bridge(bridge_name)
         device_name = self.gw_name_prefix + new_network[lconst.NET_ID][0:11]
@@ -61,15 +61,15 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         vlan_id = vlan_bind[lconst.VLANID]
 
         self._linuxbridge_quantum_agent.process_port_binding(
-                         new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
-                         device_name, str(vlan_id))
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                               get_interfaces_on_bridge(bridge_name)
+            new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
+            device_name, str(vlan_id))
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                          get_interfaces_on_bridge(bridge_name))
 
         self.assertTrue(device_name in list_interface)
         for interface in list_interface:
             self._linuxbridge_quantum_agent.linux_br.remove_interface(
-                                               bridge_name, interface)
+                bridge_name, interface)
             self.delete_device(interface)
         self.delete_bridge(bridge_name)
         self.tearDownUnplugInterface(tenant_id, new_network[lconst.NET_ID],
@@ -78,18 +78,18 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         LOG.debug("test_add_gateway_interface - END")
 
     def test_add_tap_interface(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
-                  mac_address='fe:16:3e:51:60:dd'):
+        self, tenant_id="test_tenant", network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
+        mac_address='fe:16:3e:51:60:dd'):
 
         LOG.debug("test_add_tap_interface - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         self.create_bridge(bridge_name)
         device_name = self.tap_name_prefix + interface_id[0:11]
@@ -99,15 +99,15 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         vlan_id = vlan_bind[lconst.VLANID]
 
         self._linuxbridge_quantum_agent.process_port_binding(
-                         new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
-                         interface_id, str(vlan_id))
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                                        get_interfaces_on_bridge(bridge_name)
+            new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
+            interface_id, str(vlan_id))
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                          get_interfaces_on_bridge(bridge_name))
 
         self.assertTrue(device_name in list_interface)
         for interface in list_interface:
             self._linuxbridge_quantum_agent.linux_br.remove_interface(
-                                               bridge_name, interface)
+                bridge_name, interface)
             self.delete_device(interface)
         self.delete_bridge(bridge_name)
         self.tearDownUnplugInterface(tenant_id, new_network[lconst.NET_ID],
@@ -121,13 +121,13 @@ class LinuxBridgeAgentTest(unittest.TestCase):
                   mac_address='fe:16:3e:51:60:dd'):
 
         LOG.debug("test_remove_interface - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         self.create_bridge(bridge_name)
         device_name = self.tap_name_prefix + interface_id[0:11]
@@ -137,19 +137,19 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         vlan_id = vlan_bind[lconst.VLANID]
 
         self._linuxbridge_quantum_agent.process_port_binding(
-                         new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
-                         interface_id, str(vlan_id))
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+            new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
+            interface_id, str(vlan_id))
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                          get_interfaces_on_bridge(bridge_name))
 
         self._linuxbridge_quantum_agent.linux_br.remove_interface(bridge_name,
-                                                            device_name)
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+                                                                  device_name)
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                          get_interfaces_on_bridge(bridge_name))
         self.assertFalse(device_name in list_interface)
         for interface in list_interface:
             self._linuxbridge_quantum_agent.linux_br.remove_interface(
-                                               bridge_name, interface)
+                bridge_name, interface)
             self.delete_device(interface)
         self.delete_device(device_name)
         self.delete_bridge(bridge_name)
@@ -159,34 +159,35 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         LOG.debug("test_remove_interface -END")
 
     def test_ensure_vlan_bridge(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
+        self, tenant_id="test_tenant",
+        network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
 
         LOG.debug("test_ensure_vlan_bridge - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         vlan_bind = cdb.get_vlan_binding(new_network[lconst.NET_ID])
         vlan_id = vlan_bind[lconst.VLANID]
         vlan_subinterface = self.physical_interface + '.' + str(vlan_id)
 
         self._linuxbridge_quantum_agent.linux_br.ensure_vlan_bridge(
-                         new_network[lconst.NET_ID], str(vlan_id))
-        list_quantum_bridges = self._linuxbridge_quantum_agent.linux_br.\
-                                    get_all_quantum_bridges()
+            new_network[lconst.NET_ID], str(vlan_id))
+        list_quantum_bridges = (self._linuxbridge_quantum_agent.linux_br.
+                               get_all_quantum_bridges())
         self.assertTrue(bridge_name in list_quantum_bridges)
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                          get_interfaces_on_bridge(bridge_name))
         self.assertTrue(vlan_subinterface in list_interface)
 
         for interface in list_interface:
             self._linuxbridge_quantum_agent.linux_br.remove_interface(
-                                               bridge_name, interface)
+                bridge_name, interface)
             self.delete_device(interface)
         self.delete_bridge(bridge_name)
         self.tearDownUnplugInterface(tenant_id, new_network[lconst.NET_ID],
@@ -195,26 +196,26 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         LOG.debug("test_ensure_vlan_bridge -END")
 
     def test_delete_vlan_bridge(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
+        self, tenant_id="test_tenant", network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
 
         LOG.debug("test_delete_vlan_bridge - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         vlan_bind = cdb.get_vlan_binding(new_network[lconst.NET_ID])
         vlan_id = vlan_bind[lconst.VLANID]
         vlan_subinterface = self.physical_interface + '.' + str(vlan_id)
 
         self._linuxbridge_quantum_agent.linux_br.ensure_vlan_bridge(
-                         new_network[lconst.NET_ID], str(vlan_id))
+            new_network[lconst.NET_ID], str(vlan_id))
         self._linuxbridge_quantum_agent.linux_br.delete_vlan_bridge(
-                                                 bridge_name)
+            bridge_name)
 
         self.assertEquals(self.device_exists(vlan_subinterface), False)
         self.assertEquals(self.device_exists(bridge_name), False)
@@ -224,26 +225,26 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         LOG.debug("test_delete_vlan_bridge - END")
 
     def test_process_deleted_networks(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
+        self, tenant_id="test_tenant", network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc'):
 
         LOG.debug("test_delete_vlan_bridge - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         vlan_bindings = {}
-        vlan_bindings[new_network[lconst.NET_ID]] =\
-                       cdb.get_vlan_binding(new_network[lconst.NET_ID])
+        vlan_bindings[new_network[lconst.NET_ID]] = (
+            cdb.get_vlan_binding(new_network[lconst.NET_ID]))
         vlan_id = vlan_bindings[new_network[lconst.NET_ID]][lconst.VLANID]
         vlan_subinterface = self.physical_interface + '.' + str(vlan_id)
 
         self._linuxbridge_quantum_agent.linux_br.ensure_vlan_bridge(
-                         new_network[lconst.NET_ID], str(vlan_id))
+            new_network[lconst.NET_ID], str(vlan_id))
         self.tearDownUnplugInterface(tenant_id, new_network[lconst.NET_ID],
                                      new_port[lconst.PORT_ID])
         vlan_bindings = {}
@@ -254,18 +255,18 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         LOG.debug("test_delete_vlan_bridge - END")
 
     def test_process_unplugged_tap_interface(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
-                  mac_address='fe:16:3e:51:60:dd'):
+        self, tenant_id="test_tenant", network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
+        mac_address='fe:16:3e:51:60:dd'):
 
         LOG.debug("test_process_unplugged_tap_interface - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         self.create_bridge(bridge_name)
         device_name = self.tap_name_prefix + interface_id[0:11]
@@ -275,43 +276,43 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         vlan_id = vlan_bind[lconst.VLANID]
 
         self._linuxbridge_quantum_agent.process_port_binding(
-                         new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
-                         interface_id, str(vlan_id))
+            new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
+            interface_id, str(vlan_id))
         list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+                         get_interfaces_on_bridge(bridge_name)
         self._linuxbridge_plugin.unplug_interface(tenant_id,
                                                   new_network[lconst.NET_ID],
                                                   new_port[lconst.PORT_ID])
         plugged_interface = []
         self._linuxbridge_quantum_agent.process_unplugged_interfaces(
-                                                          plugged_interface)
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+            plugged_interface)
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                         get_interfaces_on_bridge(bridge_name))
         self.assertFalse(device_name in list_interface)
         for interface in list_interface:
             self._linuxbridge_quantum_agent.linux_br.remove_interface(
-                                               bridge_name, interface)
+                bridge_name, interface)
             self.delete_device(interface)
         self.delete_device(device_name)
         self.delete_bridge(bridge_name)
         self.tearDownNetworkPort(tenant_id, new_network[lconst.NET_ID],
-                                     new_port[lconst.PORT_ID])
+                                 new_port[lconst.PORT_ID])
 
         LOG.debug("test_test_process_unplugged_tap_interface -END")
 
     def test_process_unplugged_gw_interface(
-                  self, tenant_id="test_tenant", network_name="test_network",
-                  interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
-                  mac_address='fe:16:3e:51:60:dd'):
+        self, tenant_id="test_tenant", network_name="test_network",
+        interface_id='fe701ddf-26a2-42ea-b9e6-7313d1c522cc',
+        mac_address='fe:16:3e:51:60:dd'):
 
         LOG.debug("test_process_unplugged_gw_interface - START")
-        new_network =\
-               self._linuxbridge_plugin.create_network(tenant_id, network_name)
+        new_network = (
+            self._linuxbridge_plugin.create_network(tenant_id, network_name))
         new_port = self._linuxbridge_plugin.create_port(
-                         tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
+            tenant_id, new_network[lconst.NET_ID], lconst.PORT_UP)
         self._linuxbridge_plugin.plug_interface(
-                         tenant_id, new_network[lconst.NET_ID],
-                         new_port[lconst.PORT_ID], interface_id)
+            tenant_id, new_network[lconst.NET_ID],
+            new_port[lconst.PORT_ID], interface_id)
         bridge_name = self.br_name_prefix + new_network[lconst.NET_ID][0:11]
         self.create_bridge(bridge_name)
         device_name = self.gw_name_prefix + new_network[lconst.NET_ID][0:11]
@@ -321,27 +322,27 @@ class LinuxBridgeAgentTest(unittest.TestCase):
         vlan_id = vlan_bind[lconst.VLANID]
 
         self._linuxbridge_quantum_agent.process_port_binding(
-                         new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
-                         interface_id, str(vlan_id))
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+            new_port[lconst.PORT_ID], new_network[lconst.NET_ID],
+            interface_id, str(vlan_id))
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                          get_interfaces_on_bridge(bridge_name))
         self._linuxbridge_plugin.unplug_interface(tenant_id,
                                                   new_network[lconst.NET_ID],
                                                   new_port[lconst.PORT_ID])
         plugged_interface = []
         self._linuxbridge_quantum_agent.process_unplugged_interfaces(
-                                                          plugged_interface)
-        list_interface = self._linuxbridge_quantum_agent.linux_br.\
-                              get_interfaces_on_bridge(bridge_name)
+            plugged_interface)
+        list_interface = (self._linuxbridge_quantum_agent.linux_br.
+                         get_interfaces_on_bridge(bridge_name))
         self.assertFalse(device_name in list_interface)
         for interface in list_interface:
             self._linuxbridge_quantum_agent.linux_br.remove_interface(
-                                               bridge_name, interface)
+                bridge_name, interface)
             self.delete_device(interface)
         self.delete_device(device_name)
         self.delete_bridge(bridge_name)
         self.tearDownNetworkPort(tenant_id, new_network[lconst.NET_ID],
-                                     new_port[lconst.PORT_ID])
+                                 new_port[lconst.PORT_ID])
 
         LOG.debug("test_test_process_unplugged_gw_interface -END")
 
@@ -402,15 +403,15 @@ class LinuxBridgeAgentTest(unittest.TestCase):
                                                     self.physical_interface,
                                                     self.root_helper)
         self._linuxbridge_quantum_agent = linux_agent.LinuxBridgeQuantumAgent(
-                                                    self.br_name_prefix,
-                                                    self.physical_interface,
-                                                    self.polling_interval,
-                                                    self.root_helper)
+            self.br_name_prefix,
+            self.physical_interface,
+            self.polling_interval,
+            self.root_helper)
 
     def run_cmd(self, args):
         cmd = shlex.split(self.root_helper) + args
         LOG.debug("Running command: " + " ".join(cmd))
-        p = Popen(cmd, stdout=PIPE)
+        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
         retval = p.communicate()[0]
         if p.returncode == -(signal.SIGALRM):
             LOG.debug("Timeout running command: " + " ".join(args))
index 3ce70af94e30c8f8461c8c37a3b0739c0db5fabe..e839e5396a5b03e3d9002a574e0c2342f2430c48 100644 (file)
@@ -1,4 +1,3 @@
-"""
 # vim: tabstop=4 shiftwidth=4 softtabstop=4
 #
 # Copyright 2012, Cisco Systems, Inc.
 #    License for the specific language governing permissions and limitations
 #    under the License.
 # @author: Rohit Agarwalla, Cisco Systems, Inc.
-"""
 
 """
 test_database.py is an independent test suite
 that tests the database api method calls
 """
-import logging as LOG
-import unittest
 
-from common import constants as const
+import logging
+import unittest
 
 import quantum.db.api as db
-import db.l2network_db as l2network_db
+from quantum.plugins.linuxbridge.common import constants as const
+import quantum.plugins.linuxbridge.db.l2network_db as l2network_db
 
 
-LOG.getLogger(__name__)
+LOG = logging.getLogger(__name__)
 
 
 class L2networkDB(object):
@@ -42,7 +40,7 @@ class L2networkDB(object):
         try:
             for vlan_bind in l2network_db.get_all_vlan_bindings():
                 LOG.debug("Getting vlan bindings for vlan: %s" %
-                            vlan_bind.vlan_id)
+                          vlan_bind.vlan_id)
                 vlan_dict = {}
                 vlan_dict["vlan-id"] = str(vlan_bind.vlan_id)
                 vlan_dict["net-id"] = str(vlan_bind.network_id)
@@ -56,8 +54,8 @@ class L2networkDB(object):
         vlan = []
         try:
             for vlan_bind in l2network_db.get_vlan_binding(network_id):
-                LOG.debug("Getting vlan binding for vlan: %s"
-                           % vlan_bind.vlan_id)
+                LOG.debug("Getting vlan binding for vlan: %s" %
+                          vlan_bind.vlan_id)
                 vlan_dict = {}
                 vlan_dict["vlan-id"] = str(vlan_bind.vlan_id)
                 vlan_dict["net-id"] = str(vlan_bind.network_id)
index dff3871c14e73273ae8a15352e59fa1f8555c6ed..86baf24b0a2575f91c55da4717d3982a82fdbda6 100644 (file)
@@ -1,4 +1,3 @@
-'''
 # Copyright 2012 Nicira Networks, Inc.
 #
 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
-
-@author: Somik Behera, Nicira Networks, Inc.
-'''
+#
+#@author: Somik Behera, Nicira Networks, Inc.
 
 import httplib  # basic HTTP library for HTTPS connections
 import logging
-from api_client.client_eventlet import NvpApiClientEventlet
-from api_client.request_eventlet import NvpGenericRequestEventlet
+
+
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client.client_eventlet \
+     import NvpApiClientEventlet
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client.request_eventlet \
+     import NvpGenericRequestEventlet
+
 
 LOG = logging.getLogger("NVPApiHelper")
 LOG.setLevel(logging.INFO)
@@ -124,8 +127,9 @@ class NVPApiHelper(NvpApiClientEventlet):
         # Continue processing for non-error condition.
         if (status != httplib.OK and status != httplib.CREATED
                 and status != httplib.NO_CONTENT):
-            LOG.error("%s to %s, unexpected response code: %d (content = '%s')"
-                     % (method, url, response.status, response.body))
+            LOG.error(
+                "%s to %s, unexpected response code: %d (content = '%s')" %
+                (method, url, response.status, response.body))
             return None
 
         return response.body
@@ -145,14 +149,16 @@ class NVPApiHelper(NvpApiClientEventlet):
     def zero(self):
         raise NvpApiException()
 
-    error_codes = {404: fourZeroFour,
-                   409: fourZeroNine,
-                   503: fiveZeroThree,
-                   403: fourZeroThree,
-                   301: zero,
-                   307: zero,
-                   400: zero,
-                   500: zero}
+    error_codes = {
+        404: fourZeroFour,
+        409: fourZeroNine,
+        503: fiveZeroThree,
+        403: fourZeroThree,
+        301: zero,
+        307: zero,
+        400: zero,
+        500: zero,
+        }
 
 
 class NvpApiException(Exception):
@@ -191,13 +197,13 @@ class Conflict(NvpApiException):
 
 
 class ServiceUnavailable(NvpApiException):
-    message = "Request could not completed because the associated " \
-        "resource could not be reached."
+    message = ("Request could not completed because the associated "
+               "resource could not be reached.")
 
 
 class Forbidden(NvpApiException):
-    message = "The request is forbidden from accessing the " \
-        "referenced resource."
+    message = ("The request is forbidden from accessing the "
+               "referenced resource.")
 
 
 class RequestTimeout(NvpApiException):
index 37cf8440ededeec6e06b558a36b6277fd0af2265..1cb53af339e7218247348c012fee8a274cb6ab0e 100644 (file)
 
 import ConfigParser
 import logging
-import nvplib
-import NvpApiClient
 import os
 import sys
 
-from api_client.client_eventlet import DEFAULT_CONCURRENT_CONNECTIONS
-from api_client.client_eventlet import DEFAULT_FAILOVER_TIME
-from api_client.request_eventlet import DEFAULT_REQUEST_TIMEOUT
-from api_client.request_eventlet import DEFAULT_HTTP_TIMEOUT
-from api_client.request_eventlet import DEFAULT_RETRIES
-from api_client.request_eventlet import DEFAULT_REDIRECTS
+import NvpApiClient
+import nvplib
 
 from quantum.common import exceptions as exception
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client.client_eventlet \
+     import (
+    DEFAULT_CONCURRENT_CONNECTIONS,
+    DEFAULT_FAILOVER_TIME,
+    )
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client.request_eventlet \
+     import (
+    DEFAULT_REQUEST_TIMEOUT,
+    DEFAULT_HTTP_TIMEOUT,
+    DEFAULT_RETRIES,
+    DEFAULT_REDIRECTS,
+    )
+
+
+LOG = logging.getLogger("QuantumPlugin")
+
 
 CONFIG_FILE = "nvp.ini"
 CONFIG_FILE_PATHS = []
@@ -38,7 +48,6 @@ if os.environ.get('QUANTUM_HOME', None):
 CONFIG_FILE_PATHS.append("/etc/quantum/plugins/nicira")
 CONFIG_KEYS = ["DEFAULT_TZ_UUID", "NVP_CONTROLLER_IP", "PORT", "USER",
                "PASSWORD"]
-LOG = logging.getLogger("QuantumPlugin")
 
 
 def initConfig(cfile=None):
@@ -50,8 +59,7 @@ def initConfig(cfile=None):
             cfile = find_config(os.path.abspath(os.path.dirname(__file__)))
 
     if cfile == None:
-        raise Exception("Configuration file \"%s\" doesn't exist" %
-                        (cfile))
+        raise Exception("Configuration file \"%s\" doesn't exist" % (cfile))
     LOG.info("Using configuration file: %s" % cfile)
     config.read(cfile)
     LOG.debug("Config: %s" % config)
@@ -71,7 +79,7 @@ def find_config(basepath):
 
 
 def parse_config(config):
-    '''Backwards compatible parsing.
+    """Backwards compatible parsing.
 
     :param config: ConfigParser object initilized with nvp.ini.
     :returns: A tuple consisting of a control cluster object and a
@@ -81,7 +89,7 @@ def parse_config(config):
         At some point, error handling needs to be significantly
         enhanced to provide user friendly error messages, clean program
         exists, rather than exceptions propagated to the user.
-    '''
+    """
     # Extract plugin config parameters.
     try:
         failover_time = config.get('NVP', 'failover_time')
@@ -95,16 +103,15 @@ def parse_config(config):
 
     plugin_config = {
         'failover_time': failover_time,
-        'concurrent_connections': concurrent_connections
-    }
+        'concurrent_connections': concurrent_connections,
+        }
     LOG.info('parse_config(): plugin_config == "%s"' % plugin_config)
 
     cluster = NVPCluster('cluster1')
 
     # Extract connection information.
     try:
-        defined_connections = config.get(
-            'NVP', 'NVP_CONTROLLER_CONNECTIONS')
+        defined_connections = config.get('NVP', 'NVP_CONTROLLER_CONNECTIONS')
 
         for conn_key in defined_connections.split():
             args = [config.get('NVP', 'DEFAULT_TZ_UUID')]
@@ -131,7 +138,7 @@ def parse_config(config):
 
 
 class NVPCluster(object):
-    '''Encapsulates controller connection and api_client.
+    """Encapsulates controller connection and api_client.
 
     Initialized within parse_config().
     Accessed within the NvpPlugin class.
@@ -142,7 +149,7 @@ class NVPCluster(object):
 
     There may be some redundancy here, but that has been done to provide
     future flexibility.
-    '''
+    """
     def __init__(self, name):
         self._name = name
         self.controllers = []
@@ -162,7 +169,7 @@ class NVPCluster(object):
                        request_timeout=DEFAULT_REQUEST_TIMEOUT,
                        http_timeout=DEFAULT_HTTP_TIMEOUT,
                        retries=DEFAULT_RETRIES, redirects=DEFAULT_REDIRECTS):
-        '''Add a new set of controller parameters.
+        """Add a new set of controller parameters.
 
         :param ip: IP address of controller.
         :param port: port controller is listening on.
@@ -174,14 +181,12 @@ class NVPCluster(object):
         :param redirects: maximum number of server redirect responses to
             follow.
         :param default_tz_uuid: default transport zone uuid.
-        '''
+        """
 
-        keys = [
-            'ip', 'port', 'user', 'password', 'default_tz_uuid']
+        keys = ['ip', 'port', 'user', 'password', 'default_tz_uuid']
         controller_dict = dict([(k, locals()[k]) for k in keys])
 
-        int_keys = [
-            'request_timeout', 'http_timeout', 'retries', 'redirects']
+        int_keys = ['request_timeout', 'http_timeout', 'retries', 'redirects']
         for k in int_keys:
             controller_dict[k] = int(locals()[k])
 
@@ -236,10 +241,10 @@ class NVPCluster(object):
 
 
 class NvpPlugin(object):
-    '''
+    """
     NvpPlugin is a Quantum plugin that provides L2 Virtual Network
     functionality using NVP.
-    '''
+    """
     supported_extension_aliases = ["portstats"]
 
     def __init__(self, configfile=None, loglevel=None, cli=False):
@@ -251,8 +256,7 @@ class NvpPlugin(object):
         config = initConfig(configfile)
         self.controller, self.plugin_config = parse_config(config)
         c = self.controller
-        api_providers = [
-            (x['ip'], x['port'], True) for x in c.controllers]
+        api_providers = [(x['ip'], x['port'], True) for x in c.controllers]
 
         c.api_client = NvpApiClient.NVPApiHelper(
             api_providers, c.user, c.password,
@@ -268,7 +272,7 @@ class NvpPlugin(object):
         self.api_client = self.controller.api_client
 
     def get_all_networks(self, tenant_id, **kwargs):
-        '''
+        """
         Returns a dictionary containing all <network_uuid, network_name> for
         the specified tenant.
 
@@ -286,15 +290,14 @@ class NvpPlugin(object):
                       }
                    ]
         :raises: None
-        '''
-        networks = nvplib.get_all_networks(self.controller, tenant_id,
-                                           [])
-        LOG.debug("get_all_networks() completed for tenant %s: %s" % (
-            tenant_id, networks))
+        """
+        networks = nvplib.get_all_networks(self.controller, tenant_id, [])
+        LOG.debug("get_all_networks() completed for tenant %s: %s" %
+                  (tenant_id, networks))
         return networks
 
     def create_network(self, tenant_id, net_name, **kwargs):
-        '''
+        """
         Creates a new Virtual Network, and assigns it a symbolic name.
         :returns: a sequence of mappings with the following signature:
                     {'net-id': uuid that uniquely identifies the
@@ -303,7 +306,7 @@ class NvpPlugin(object):
                                     with network referenced by net-id
                    }
         :raises:
-        '''
+        """
         kwargs["controller"] = self.controller
         return nvplib.create_network(tenant_id, net_name, **kwargs)
 
@@ -315,7 +318,7 @@ class NvpPlugin(object):
                                    controller=controller)
 
     def delete_network(self, tenant_id, netw_id):
-        '''
+        """
         Deletes the network with the specified network identifier
         belonging to the specified tenant.
 
@@ -325,7 +328,7 @@ class NvpPlugin(object):
                    }
         :raises: exception.NetworkInUse
         :raises: exception.NetworkNotFound
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         nvplib.delete_network(self.controller, netw_id)
@@ -334,7 +337,7 @@ class NvpPlugin(object):
         return {'net-id': netw_id}
 
     def get_network_details(self, tenant_id, netw_id):
-        '''
+        """
         Retrieves a list of all the remote vifs that
         are attached to the network.
 
@@ -348,14 +351,14 @@ class NvpPlugin(object):
                    }
         :raises: exception.NetworkNotFound
         :raises: exception.QuantumException
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         result = None
         remote_vifs = []
         switch = netw_id
         lports = nvplib.query_ports(self.controller, switch,
-          relations="LogicalPortAttachment")
+                                    relations="LogicalPortAttachment")
 
         for port in lports:
             relation = port["_relations"]
@@ -366,16 +369,18 @@ class NvpPlugin(object):
         if not result:
             result = nvplib.get_network(self.controller, switch)
 
-        d = {"net-id": netw_id,
-             "net-ifaces": remote_vifs,
-             "net-name": result["display_name"],
-             "net-op-status": "UP"}
-        LOG.debug("get_network_details() completed for tenant %s: %s" % (
-                  tenant_id, d))
+        d = {
+            "net-id": netw_id,
+            "net-ifaces": remote_vifs,
+            "net-name": result["display_name"],
+            "net-op-status": "UP",
+            }
+        LOG.debug("get_network_details() completed for tenant %s: %s" %
+                  (tenant_id, d))
         return d
 
     def update_network(self, tenant_id, netw_id, **kwargs):
-        '''
+        """
         Updates the properties of a particular Virtual Network.
 
         :returns: a sequence of mappings representing the new network
@@ -386,16 +391,19 @@ class NvpPlugin(object):
                                   associated with network referenced by net-id
                    }
         :raises: exception.NetworkNotFound
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         result = nvplib.update_network(self.controller, netw_id, **kwargs)
         LOG.debug("update_network() completed for tenant: %s" % tenant_id)
-        return {'net-id': netw_id, 'net-name': result["display_name"],
-                'net-op-status': "UP"}
+        return {
+            'net-id': netw_id,
+            'net-name': result["display_name"],
+            'net-op-status': "UP",
+            }
 
     def get_all_ports(self, tenant_id, netw_id, **kwargs):
-        '''
+        """
         Retrieves all port identifiers belonging to the
         specified Virtual Network.
 
@@ -409,7 +417,7 @@ class NvpPlugin(object):
                       }
                      ]
         :raises: exception.NetworkNotFound
-        '''
+        """
         ids = []
         filters = kwargs.get("filter_opts") or {}
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
@@ -430,9 +438,8 @@ class NvpPlugin(object):
         LOG.debug(ids)
         return ids
 
-    def create_port(self, tenant_id, netw_id, port_init_state=None,
-            **params):
-        '''
+    def create_port(self, tenant_id, netw_id, port_init_state=None, **params):
+        """
         Creates a port on the specified Virtual Network.
 
         :returns: a mapping sequence with the following signature:
@@ -441,7 +448,7 @@ class NvpPlugin(object):
                    }
         :raises: exception.NetworkNotFound
         :raises: exception.StateInvalid
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         params["controller"] = self.controller
@@ -449,13 +456,15 @@ class NvpPlugin(object):
             raise exception.NetworkNotFound(net_id=netw_id)
         result = nvplib.create_port(tenant_id, netw_id, port_init_state,
           **params)
-        d = {"port-id": result["uuid"],
-             "port-op-status": result["port-op-status"]}
+        d = {
+            "port-id": result["uuid"],
+            "port-op-status": result["port-op-status"],
+            }
         LOG.debug("create_port() completed for tenant %s: %s" % (tenant_id, d))
         return d
 
     def update_port(self, tenant_id, netw_id, portw_id, **params):
-        '''
+        """
         Updates the properties of a specific port on the
         specified Virtual Network.
 
@@ -466,21 +475,23 @@ class NvpPlugin(object):
                    }
         :raises: exception.StateInvalid
         :raises: exception.PortNotFound
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         LOG.debug("Update port request: %s" % (params))
         params["controller"] = self.controller
         result = nvplib.update_port(netw_id, portw_id, **params)
         LOG.debug("update_port() completed for tenant: %s" % tenant_id)
-        port = {'port-id': portw_id,
-                'port-state': result["admin_status_enabled"],
-                'port-op-status': result["port-op-status"]}
+        port = {
+            'port-id': portw_id,
+            'port-state': result["admin_status_enabled"],
+            'port-op-status': result["port-op-status"],
+            }
         LOG.debug("returning updated port %s: " % port)
         return port
 
     def delete_port(self, tenant_id, netw_id, portw_id):
-        '''
+        """
         Deletes a port on a specified Virtual Network,
         if the port contains a remote interface attachment,
         the remote interface is first un-plugged and then the port
@@ -493,7 +504,7 @@ class NvpPlugin(object):
         :raises: exception.PortInUse
         :raises: exception.PortNotFound
         :raises: exception.NetworkNotFound
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         nvplib.delete_port(self.controller, netw_id, portw_id)
@@ -501,7 +512,7 @@ class NvpPlugin(object):
         return {"port-id": portw_id}
 
     def get_port_details(self, tenant_id, netw_id, portw_id):
-        '''
+        """
         This method allows the user to retrieve a remote interface
         that is attached to this particular port.
 
@@ -515,7 +526,7 @@ class NvpPlugin(object):
                     }
         :raises: exception.PortNotFound
         :raises: exception.NetworkNotFound
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         port = nvplib.get_port(self.controller, netw_id, portw_id,
@@ -530,15 +541,17 @@ class NvpPlugin(object):
         if attach_type == "VifAttachment":
             vif_uuid = relation["LogicalPortAttachment"]["vif_uuid"]
 
-        d = {"port-id": portw_id, "attachment": vif_uuid,
-             "net-id": netw_id, "port-state": state,
-             "port-op-status": op_status}
+        d = {
+            "port-id": portw_id, "attachment": vif_uuid,
+            "net-id": netw_id, "port-state": state,
+            "port-op-status": op_status,
+            }
         LOG.debug("Port details for tenant %s: %s" % (tenant_id, d))
         return d
 
     def plug_interface(self, tenant_id, netw_id, portw_id,
                        remote_interface_id):
-        '''
+        """
         Attaches a remote interface to the specified port on the
         specified Virtual Network.
 
@@ -547,29 +560,29 @@ class NvpPlugin(object):
         :raises: exception.PortNotFound
         :raises: exception.AlreadyAttached
                     (? should the network automatically unplug/replug)
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         result = nvplib.plug_interface(self.controller, netw_id, portw_id,
           "VifAttachment", attachment=remote_interface_id)
-        LOG.debug("plug_interface() completed for %s: %s" % (
-            tenant_id, result))
+        LOG.debug("plug_interface() completed for %s: %s" %
+                  (tenant_id, result))
 
     def unplug_interface(self, tenant_id, netw_id, portw_id):
-        '''
+        """
         Detaches a remote interface from the specified port on the
         specified Virtual Network.
 
         :returns: None
         :raises: exception.NetworkNotFound
         :raises: exception.PortNotFound
-        '''
+        """
         if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
             raise exception.NetworkNotFound(net_id=netw_id)
         result = nvplib.unplug_interface(self.controller, netw_id, portw_id)
 
         LOG.debug("unplug_interface() completed for tenant %s: %s" %
-          (tenant_id, result))
+                  (tenant_id, result))
 
     def get_port_stats(self, tenant_id, network_id, port_id):
         """
index d9493d09f5824f9663a8583fed310e8ee7a7eabb..a3d7d65dea8bbed527eb3a703f1c048fe99fbdd9 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
-import client
-import eventlet
 import httplib
 import logging
-import request_eventlet
 import time
-from common import _conn_str
+
+import eventlet
+
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client.common import (
+    _conn_str,
+    )
+import quantum.plugins.nicira.nicira_nvp_plugin.api_client.client as client
+import quantum.plugins.nicira.nicira_nvp_plugin.api_client.request_eventlet
 
 
 logging.basicConfig(level=logging.INFO)
-lg = logging.getLogger('nvp_api_client')
+LOG = logging.getLogger('nvp_api_client')
+
 
 # Default parameters.
 DEFAULT_FAILOVER_TIME = 5
@@ -32,7 +36,7 @@ DEFAULT_CONNECT_TIMEOUT = 5
 
 
 class NvpApiClientEventlet(object):
-    '''Eventlet-based implementation of NvpApiClient ABC.'''
+    """Eventlet-based implementation of NvpApiClient ABC."""
 
     CONN_IDLE_TIMEOUT = 60 * 15
 
@@ -41,7 +45,7 @@ class NvpApiClientEventlet(object):
                  use_https=True,
                  connect_timeout=DEFAULT_CONNECT_TIMEOUT,
                  failover_time=DEFAULT_FAILOVER_TIME):
-        '''Constructor
+        """Constructor
 
         Args:
             api_providers: a list of tuples of the form: (host, port, is_ssl).
@@ -50,7 +54,7 @@ class NvpApiClientEventlet(object):
             concurrent_connections: total number of concurrent connections.
             use_https: whether or not to use https for requests.
             connect_timeout: connection timeout in seconds.
-        '''
+        """
         self._api_providers = set([tuple(p) for p in api_providers])
         self._user = user
         self._password = password
@@ -107,13 +111,13 @@ class NvpApiClientEventlet(object):
         return self._cookie
 
     def acquire_connection(self):
-        '''Check out an available HTTPConnection instance.
+        """Check out an available HTTPConnection instance.
 
         Blocks until a connection is available.
 
         Returns: An available HTTPConnection instance or None if no
                  api_providers are configured.
-        '''
+        """
         if not self._api_providers:
             return None
 
@@ -121,47 +125,47 @@ class NvpApiClientEventlet(object):
         # there has been a change in the controller used as the api_provider.
         now = time.time()
         if now < getattr(self, '_issue_conn_barrier', now):
-            lg.info("acquire_connection() waiting for timer to expire.")
+            LOG.info("acquire_connection() waiting for timer to expire.")
             time.sleep(self._issue_conn_barrier - now)
 
         if self._active_conn_pool.empty():
-            lg.debug("Waiting to acquire an API client connection")
+            LOG.debug("Waiting to acquire an API client connection")
 
         # get() call is blocking.
         conn = self._active_conn_pool.get()
         now = time.time()
         if getattr(conn, 'last_used', now) < now - self.CONN_IDLE_TIMEOUT:
-            lg.info("Connection %s idle for %0.2f seconds; reconnecting."
-                    % (_conn_str(conn), now - conn.last_used))
+            LOG.info("Connection %s idle for %0.2f seconds; reconnecting." %
+                     (_conn_str(conn), now - conn.last_used))
             conn = self._create_connection(*self._conn_params(conn))
 
             # Stash conn pool so conn knows where to go when it releases.
             conn.conn_pool = self._active_conn_pool
 
         conn.last_used = now
-        lg.debug("API client connection %s acquired" % _conn_str(conn))
+        LOG.debug("API client connection %s acquired" % _conn_str(conn))
         return conn
 
     def release_connection(self, http_conn, bad_state=False):
-        '''Mark HTTPConnection instance as available for check-out.
+        """Mark HTTPConnection instance as available for check-out.
 
         Args:
             http_conn: An HTTPConnection instance obtained from this
                 instance.
             bad_state: True if http_conn is known to be in a bad state
                 (e.g. connection fault.)
-        '''
+        """
         if self._conn_params(http_conn) not in self._api_providers:
-            lg.debug("Released connection '%s' is no longer an API provider "
-                     "for the cluster" % _conn_str(http_conn))
+            LOG.debug(("Released connection '%s' is no longer an API provider "
+                       "for the cluster") % _conn_str(http_conn))
             return
 
         # Retrieve "home" connection pool.
         conn_pool = http_conn.conn_pool
         if bad_state:
             # reconnect
-            lg.info("API connection fault, reconnecting to %s"
-                    % _conn_str(http_conn))
+            LOG.info("API connection fault, reconnecting to %s" %
+                     _conn_str(http_conn))
             http_conn = self._create_connection(*self._conn_params(http_conn))
             http_conn.conn_pool = conn_pool
             conn_pool.put(http_conn)
@@ -169,14 +173,14 @@ class NvpApiClientEventlet(object):
             if self._active_conn_pool == http_conn.conn_pool:
                 # Get next connection from the connection pool and make it
                 # active.
-                lg.info("API connection fault changing active_conn_pool.")
+                LOG.info("API connection fault changing active_conn_pool.")
                 self._conn_pool.put(self._active_conn_pool)
                 self._active_conn_pool = self._conn_pool.get()
                 self._issue_conn_barrier = time.time() + self._failover_time
         else:
             conn_pool.put(http_conn)
 
-        lg.debug("API client connection %s released" % _conn_str(http_conn))
+        LOG.debug("API client connection %s released" % _conn_str(http_conn))
 
     @property
     def need_login(self):
@@ -192,13 +196,15 @@ class NvpApiClientEventlet(object):
                 self.login()
                 self._doing_login_sem.release()
             else:
-                lg.debug("Waiting for auth to complete")
+                LOG.debug("Waiting for auth to complete")
                 self._doing_login_sem.acquire()
                 self._doing_login_sem.release()
         return self._cookie
 
     def login(self):
-        '''Issue login request and update authentication cookie.'''
+        """Issue login request and update authentication cookie."""
+        request_eventlet = (quantum.plugins.nicira.nicira_nvp_plugin.
+                            api_client.request_eventlet)
         g = request_eventlet.NvpLoginRequestEventlet(
             self, self._user, self._password)
         g.start()
@@ -206,13 +212,13 @@ class NvpApiClientEventlet(object):
 
         if ret:
             if isinstance(ret, Exception):
-                lg.error('NvpApiClient: login error "%s"' % ret)
+                LOG.error('NvpApiClient: login error "%s"' % ret)
                 raise ret
 
             self._cookie = None
             cookie = ret.getheader("Set-Cookie")
             if cookie:
-                lg.debug("Saving new authentication cookie '%s'" % cookie)
+                LOG.debug("Saving new authentication cookie '%s'" % cookie)
                 self._cookie = cookie
                 self._need_login = False
 
index 2ed8fb11f613d011ccc1c945bd65a6528d287882..33c6503d1ec67aee412bfdacae5ad830a73423cd 100644 (file)
@@ -12,8 +12,8 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
 import httplib
+
 import mock
 
 
index 51a27b3e1d00664aa431cbfcbf112575ed29dde6..a09468a2358becc91e49ff22a992ab3e0abd03ea 100644 (file)
@@ -12,7 +12,6 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
 from abc import ABCMeta
 from abc import abstractmethod
 from abc import abstractproperty
index 7d31c99ca67eff6e1a59c2e944e200ae31b47cc3..355d961e7e890386af92039b09a31aaf43d12541 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
-import client_eventlet
-import eventlet
 import httplib
-import urllib
-import urlparse
+import json
 import logging
-import request
 import time
-import json
-from common import _conn_str
+import urllib
+import urlparse
+
+import eventlet
 from eventlet import timeout
 
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client.common import (
+    _conn_str,
+    )
+import quantum.plugins.nicira.nicira_nvp_plugin.api_client.request as request
+import quantum.plugins.nicira.nicira_nvp_plugin.api_client.client_eventlet
+
 
 logging.basicConfig(level=logging.INFO)
-lg = logging.getLogger("nvp_api_request")
+LOG = logging.getLogger("nvp_api_request")
+
+
 USER_AGENT = "NVP gevent client/1.0"
 
 # Default parameters.
@@ -57,7 +62,7 @@ class NvpApiRequestEventlet:
         httplib.NOT_FOUND,
         httplib.CONFLICT,
         httplib.INTERNAL_SERVER_ERROR,
-        httplib.SERVICE_UNAVAILABLE
+        httplib.SERVICE_UNAVAILABLE,
     ]
 
     API_REQUEST_POOL = eventlet.GreenPool(API_REQUEST_POOL_SIZE)
@@ -102,7 +107,7 @@ class NvpApiRequestEventlet:
     def join(self):
         if self._green_thread is not None:
             return self._green_thread.wait()
-        lg.error('Joining on invalid green thread')
+        LOG.error('Joining on invalid green thread')
         return Exception('Joining an invalid green thread')
 
     def start(self):
@@ -124,7 +129,7 @@ class NvpApiRequestEventlet:
             with timeout.Timeout(self._request_timeout, False):
                 return self._handle_request()
 
-            lg.info('Request timeout handling request.')
+            LOG.info('Request timeout handling request.')
             self._request_error = Exception('Request timeout')
             return None
         else:
@@ -141,7 +146,7 @@ class NvpApiRequestEventlet:
             return error
 
         url = self._url
-        lg.info("Issuing request '%s'" % self._request_str(conn, url))
+        LOG.info("Issuing request '%s'" % self._request_str(conn, url))
         issued_time = time.time()
         is_conn_error = False
         try:
@@ -159,28 +164,29 @@ class NvpApiRequestEventlet:
                 try:
                     conn.request(self._method, url, self._body, self._headers)
                 except Exception, e:
-                    lg.info('_issue_request: conn.request() exception: %s' % e)
+                    LOG.info('_issue_request: conn.request() exception: %s' %
+                             e)
                     raise e
 
                 response = conn.getresponse()
                 response.body = response.read()
                 response.headers = response.getheaders()
-                lg.info("Request '%s' complete: %s (%0.2f seconds)"
+                LOG.info("Request '%s' complete: %s (%0.2f seconds)"
                         % (self._request_str(conn, url), response.status,
                           time.time() - issued_time))
                 if response.status not in [httplib.MOVED_PERMANENTLY,
                                            httplib.TEMPORARY_REDIRECT]:
                     break
                 elif redirects >= self._redirects:
-                    lg.warn("Maximum redirects exceeded, aborting request")
+                    LOG.warn("Maximum redirects exceeded, aborting request")
                     break
                 redirects += 1
                 conn, url = self._redirect_params(conn, response.headers)
                 if url is None:
                     response.status = httplib.INTERNAL_SERVER_ERROR
                     break
-                lg.info("Redirecting request to: %s" % \
-                        self._request_str(conn, url))
+                LOG.info("Redirecting request to: %s" %
+                         self._request_str(conn, url))
 
             # If we receive any of these responses, then our server did not
             # process our request and may be in an errored state. Raise an
@@ -188,8 +194,8 @@ class NvpApiRequestEventlet:
             # is_conn_error == True which puts the conn on the back of the
             # client's priority queue.
             if response.status >= 500:
-                lg.warn("API Request '%s %s' received: %s"
-                        % (self._method, self._url, response.status))
+                LOG.warn("API Request '%s %s' received: %s" %
+                         (self._method, self._url, response.status))
                 raise Exception('Server error return: %s' %
                                 response.status)
             return response
@@ -198,9 +204,9 @@ class NvpApiRequestEventlet:
                 msg = "Invalid server response"
             else:
                 msg = unicode(e)
-            lg.warn("Request '%s' failed: %s (%0.2f seconds)"
-                    % (self._request_str(conn, url), msg,
-                       time.time() - issued_time))
+            LOG.warn("Request '%s' failed: %s (%0.2f seconds)"
+                     % (self._request_str(conn, url), msg,
+                        time.time() - issued_time))
             self._request_error = e
             is_conn_error = True
             return e
@@ -214,7 +220,7 @@ class NvpApiRequestEventlet:
                 url = value
                 break
         if not url:
-            lg.warn("Received redirect status without location header field")
+            LOG.warn("Received redirect status without location header field")
             return (conn, None)
         # Accept location with the following format:
         # 1. /path, redirect to same node
@@ -230,15 +236,18 @@ class NvpApiRequestEventlet:
                     url = result.path
                 return (conn, url)      # case 1
             else:
-                lg.warn("Received invalid redirect location: %s" % url)
+                LOG.warn("Received invalid redirect location: %s" % url)
                 return (conn, None)     # case 3
         elif result.scheme not in ["http", "https"] or not result.hostname:
-            lg.warn("Received malformed redirect location: %s" % url)
+            LOG.warn("Received malformed redirect location: %s" % url)
             return (conn, None)         # case 3
         # case 2, redirect location includes a scheme
         # so setup a new connection and authenticate
         use_https = result.scheme == "https"
         api_providers = [(result.hostname, result.port, use_https)]
+        client_eventlet = (
+            quantum.plugins.nicira.nicira_nvp_plugin.api_client.client_eventlet
+            )
         api_client = client_eventlet.NvpApiClientEventlet(
             api_providers, self._api_client.user, self._api_client.password,
             use_https=use_https)
@@ -268,7 +277,7 @@ class NvpApiRequestEventlet:
 
             req = self.spawn(self._issue_request).wait()
             # automatically raises any exceptions returned.
-            lg.debug('req: %s' % type(req))
+            LOG.debug('req: %s' % type(req))
 
             if isinstance(req, httplib.HTTPResponse):
                 if (req.status == httplib.UNAUTHORIZED
@@ -278,15 +287,15 @@ class NvpApiRequestEventlet:
                         continue
                     # else fall through to return the error code
 
-                lg.debug("API Request '%s %s' complete: %s"
-                         % (self._method, self._url, req.status))
+                LOG.debug("API Request '%s %s' complete: %s" %
+                          (self._method, self._url, req.status))
                 self._request_error = None
                 response = req
             else:
-                lg.info('_handle_request: caught an error - %s' % req)
+                LOG.info('_handle_request: caught an error - %s' % req)
                 self._request_error = req
 
-        lg.debug('_handle_request: response - %s' % response)
+        LOG.debug('_handle_request: response - %s' % response)
         return response
 
 
@@ -332,7 +341,7 @@ class NvpGetApiProvidersRequestEventlet(NvpApiRequestEventlet):
                                 ret.append(_provider_from_listen_addr(addr))
                 return ret
         except Exception, e:
-            lg.warn("Failed to parse API provider: %s" % e)
+            LOG.warn("Failed to parse API provider: %s" % e)
             # intentionally fall through
         return None
 
index 9e548e02c300efd9597e9995cc3964d5160cabbc..b4647a5b98def339efd9f1ac19b3f5d7b3a696c7 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-from optparse import OptionParser
-
-import gettext
 import logging
+from optparse import OptionParser
 import os
 import sys
 
-gettext.install('nvp-plugin-cli', unicode=1)
+from quantum.plugins.nicira.nicira_nvp_plugin import nvplib
+from quantum.plugins.nicira.nicira_nvp_plugin.QuantumPlugin import (
+    NvpPlugin as QuantumManager,
+    )
 
-from QuantumPlugin import NvpPlugin as QuantumManager
-import nvplib
 
 logging.basicConfig(level=logging.INFO)
 LOG = logging.getLogger('nvp-plugin-cli')
index 74ba648f8e853478825eb8e3c0e420ce65605cd2..37899cf44d1a2aa19a892a8be84f6b559ad14444 100644 (file)
 #
 # @author: Brad Hall, Nicira Networks, Inc.
 
-from quantum.common import exceptions as exception
 import json
 import logging
-import NvpApiClient
+
+from quantum.common import exceptions as exception
+from quantum.plugins.nicira.nicira_nvp_plugin import NvpApiClient
+
 
 LOG = logging.getLogger("nvplib")
 LOG.setLevel(logging.INFO)
@@ -36,13 +38,14 @@ def check_default_transport_zone(c):
     msg = []
     # This will throw an exception on failure and that's ok since it will
     # just propogate to the cli.
-    resp = do_single_request("GET",
+    resp = do_single_request(
+        "GET",
         "/ws.v1/transport-zone?uuid=%s" % c.default_tz_uuid,
         controller=c)
     result = json.loads(resp)
     if int(result["result_count"]) == 0:
         msg.append("Unable to find zone \"%s\" for controller \"%s\"" %
-            (c.default_tz_uuid, c.name))
+                   (c.default_tz_uuid, c.name))
     if len(msg) > 0:
         raise Exception(' '.join(msg))
 
@@ -78,8 +81,8 @@ def create_lswitch(controller, lswitch_obj):
     # Warn if no tenant is specified
     found = "os_tid" in [x["scope"] for x in lswitch_obj["tags"]]
     if not found:
-        LOG.warn("No tenant-id tag specified in logical switch: %s" % (
-            lswitch_obj))
+        LOG.warn("No tenant-id tag specified in logical switch: %s" %
+                 lswitch_obj)
     uri = "/ws.v1/lswitch"
     try:
         resp_obj = do_single_request("POST", uri,
@@ -102,8 +105,8 @@ def update_network(controller, network, **kwargs):
     if "name" in kwargs:
         lswitch_obj["display_name"] = kwargs["name"]
     try:
-        resp_obj = do_single_request("PUT", uri,
-          json.dumps(lswitch_obj), controller=controller)
+        resp_obj = do_single_request(
+            "PUT", uri, json.dumps(lswitch_obj), controller=controller)
     except NvpApiClient.ResourceNotFound as e:
         LOG.error("Network not found, Error: %s" % str(e))
         raise exception.NetworkNotFound(net_id=network)
@@ -148,7 +151,7 @@ def query_networks(controller, tenant_id, fields="*", tags=None):
     lswitches = json.loads(resp_obj)["results"]
     nets = [{'net-id': lswitch["uuid"],
              'net-name': lswitch["display_name"]}
-             for lswitch in lswitches]
+            for lswitch in lswitches]
     return nets
 
 
@@ -175,13 +178,16 @@ def create_network(tenant_id, net_name, **kwargs):
     transport_zone = kwargs.get("transport_zone",
       controller.default_tz_uuid)
     transport_type = kwargs.get("transport_type", "gre")
-    lswitch_obj = {"display_name": net_name,
-                   "transport_zones": [
-                    {"zone_uuid": transport_zone,
-                     "transport_type": transport_type}
-                   ],
-                "tags": [{"tag": tenant_id, "scope": "os_tid"}]
-             }
+    lswitch_obj = {
+        "display_name": net_name,
+        "transport_zones": [
+            {
+                "zone_uuid": transport_zone,
+                "transport_type": transport_type,
+                },
+            ],
+        "tags": [{"tag": tenant_id, "scope": "os_tid"}],
+        }
 
     net = create_lswitch(controller, lswitch_obj)
     net['net-op-status'] = "UP"
@@ -216,8 +222,8 @@ def get_port_stats(controller, network_id, port_id):
 
 def check_port_state(state):
     if state not in ["ACTIVE", "DOWN"]:
-        LOG.error("Invalid port state (ACTIVE and " \
-                          "DOWN are valid states): %s" % state)
+        LOG.error("Invalid port state (ACTIVE and DOWN are valid states): %s" %
+                  state)
         raise exception.StateInvalid(port_state=state)
 
 
@@ -256,9 +262,10 @@ def delete_all_ports(controller, ls_uuid):
       controller=controller)
     res = json.loads(res)
     for r in res["results"]:
-        do_single_request("DELETE",
-          "/ws.v1/lswitch/%s/lport/%s" % (ls_uuid, r["uuid"]),
-          controller=controller)
+        do_single_request(
+            "DELETE",
+            "/ws.v1/lswitch/%s/lport/%s" % (ls_uuid, r["uuid"]),
+            controller=controller)
 
 
 def get_port(controller, network, port, relations=None):
@@ -292,7 +299,7 @@ def plug_interface(controller, network, port, type, attachment=None):
         raise exception.PortNotFound(port_id=port, net_id=network)
     except NvpApiClient.Conflict as e:
         LOG.error("Conflict while making attachment to port, " \
-                      "Error: %s" % str(e))
+                  "Error: %s" % str(e))
         raise exception.AlreadyAttached(att_id=attachment,
                                         port_id=port,
                                         net_id=network,
@@ -308,8 +315,8 @@ def unplug_interface(controller, network, port):
     uri = "/ws.v1/lswitch/" + network + "/lport/" + port + "/attachment"
     lport_obj = {"type": "NoAttachment"}
     try:
-        resp_obj = do_single_request("PUT",
-          uri, json.dumps(lport_obj), controller=controller)
+        resp_obj = do_single_request(
+            "PUT", uri, json.dumps(lport_obj), controller=controller)
     except NvpApiClient.ResourceNotFound as e:
         LOG.error("Port or Network not found, Error: %s" % str(e))
         raise exception.PortNotFound(port_id=port, net_id=network)
@@ -332,8 +339,8 @@ def update_port(network, port_id, **params):
 
     uri = "/ws.v1/lswitch/" + network + "/lport/" + port_id
     try:
-        resp_obj = do_single_request("PUT", uri,
-          json.dumps(lport_obj), controller=controller)
+        resp_obj = do_single_request(
+            "PUT", uri, json.dumps(lport_obj), controller=controller)
     except NvpApiClient.ResourceNotFound as e:
         LOG.error("Port or Network not found, Error: %s" % str(e))
         raise exception.PortNotFound(port_id=port_id, net_id=network)
@@ -361,8 +368,8 @@ def create_port(tenant, network, port_init_state, **params):
 
     path = "/ws.v1/lswitch/" + ls_uuid + "/lport"
     try:
-        resp_obj = do_single_request("POST", path,
-          json.dumps(lport_obj), controller=controller)
+        resp_obj = do_single_request(
+            "POST", path, json.dumps(lport_obj), controller=controller)
     except NvpApiClient.ResourceNotFound as e:
         LOG.error("Network not found, Error: %s" % str(e))
         raise exception.NetworkNotFound(net_id=network)
@@ -387,7 +394,8 @@ def get_port_status(controller, lswitch_id, port_id):
     except NvpApiClient.NvpApiException as e:
         raise exception.QuantumException()
     try:
-        r = do_single_request("GET",
+        r = do_single_request(
+            "GET",
             "/ws.v1/lswitch/%s/lport/%s/status" % (lswitch_id, port_id),
             controller=controller)
         r = json.loads(r)
diff --git a/quantum/plugins/nicira/nicira_nvp_plugin/tests/__init__.py b/quantum/plugins/nicira/nicira_nvp_plugin/tests/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
index 3bc0af9136652b9d56ae7d40eb262c5d2112dde7..d96a8d9bc635bc74b648276689691fb729741d79 100644 (file)
@@ -17,8 +17,9 @@
 import logging
 import unittest
 
-from nicira_nvp_plugin.QuantumPlugin import NvpPlugin
-from nicira_nvp_plugin import nvplib
+from quantum.plugins.nicira.nicira_nvp_plugin.QuantumPlugin import NvpPlugin
+from quantum.plugins.nicira.nicira_nvp_plugin import nvplib
+
 
 logging.basicConfig(level=logging.DEBUG)
 LOG = logging.getLogger("test_check")
index 2c0085c70caa1b84c121f8ab69e70ca05222b295..d8f732a6d415b3838892748578a2e627e4bb60bf 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
-import unittest
-import StringIO
 import ConfigParser
-from nicira_nvp_plugin.QuantumPlugin import parse_config
-from nicira_nvp_plugin.QuantumPlugin import NVPCluster
+import StringIO
+import unittest
+
+from quantum.plugins.nicira.nicira_nvp_plugin.QuantumPlugin import (
+    NVPCluster,
+    parse_config,
+    )
 
 
 class ConfigParserTest(unittest.TestCase):
@@ -46,7 +48,7 @@ class ConfigParserTest(unittest.TestCase):
         self.assertTrue(len(nvpc.controllers) == 3)
 
     def test_old_config_parser_old_style(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 DEFAULT_TZ_UUID = <default uuid>
@@ -54,7 +56,7 @@ NVP_CONTROLLER_IP = <controller ip>
 PORT = <port>
 USER = <user>
 PASSWORD = <pass>
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
@@ -78,13 +80,13 @@ PASSWORD = <pass>
             cluster1.controllers[0]['redirects'] == 2)
 
     def test_old_config_parser_new_style(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 DEFAULT_TZ_UUID = <default uuid>
 NVP_CONTROLLER_CONNECTIONS = CONNECTION1
 CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
@@ -108,7 +110,7 @@ CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
             cluster1.controllers[0]['redirects'] == 45)
 
     def test_old_config_parser_both_styles(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 NVP_CONTROLLER_IP = <controller ip>
@@ -118,7 +120,7 @@ PASSWORD = <pass>
 DEFAULT_TZ_UUID = <default uuid>
 NVP_CONTROLLER_CONNECTIONS = CONNECTION1
 CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
@@ -142,7 +144,7 @@ CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
             cluster1.controllers[0]['redirects'] == 45)
 
     def test_old_config_parser_both_styles(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 NVP_CONTROLLER_IP = <controller ip>
@@ -152,7 +154,7 @@ PASSWORD = <pass>
 DEFAULT_TZ_UUID = <default uuid>
 NVP_CONTROLLER_CONNECTIONS = CONNECTION1
 CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
@@ -176,7 +178,7 @@ CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
             cluster1.controllers[0]['redirects'] == 45)
 
     def test_failover_time(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 DEFAULT_TZ_UUID = <default uuid>
@@ -185,28 +187,28 @@ PORT = 443
 USER = admin
 PASSWORD = admin
 FAILOVER_TIME = 10
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
         self.assertTrue(plugin_config['failover_time'] == '10')
 
     def test_failover_time_new_style(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 DEFAULT_TZ_UUID = <default uuid>
 NVP_CONTROLLER_CONNECTIONS = CONNECTION1
 CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
 FAILOVER_TIME = 10
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
         self.assertTrue(plugin_config['failover_time'] == '10')
 
     def test_concurrent_connections_time(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 DEFAULT_TZ_UUID = <default uuid>
@@ -215,21 +217,21 @@ PORT = 443
 USER = admin
 PASSWORD = admin
 CONCURRENT_CONNECTIONS = 5
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
         self.assertTrue(plugin_config['concurrent_connections'] == '5')
 
     def test_concurrent_connections_time_new_style(self):
-        config = StringIO.StringIO('''
+        config = StringIO.StringIO("""
 [DEFAULT]
 [NVP]
 DEFAULT_TZ_UUID = <default uuid>
 NVP_CONTROLLER_CONNECTIONS = CONNECTION1
 CONNECTION1 = 10.0.0.1:4242:admin:admin:42:43:44:45
 CONCURRENT_CONNECTIONS = 5
-''')
+""")
         cp = ConfigParser.ConfigParser()
         cp.readfp(config)
         cluster1, plugin_config = parse_config(cp)
index 8eacdc248278c4d9137e18f03cbe57e0bab98565..9f2f459208268bb7a993067212d6dd169e6cd413 100644 (file)
@@ -19,10 +19,14 @@ import json
 import logging
 import os
 import unittest
+
 from quantum.common import exceptions as exception
-from nicira_nvp_plugin.QuantumPlugin import NvpPlugin
-from nicira_nvp_plugin import NvpApiClient
-from nicira_nvp_plugin import nvplib
+from quantum.plugins.nicira.nicira_nvp_plugin.QuantumPlugin import NvpPlugin
+from quantum.plugins.nicira.nicira_nvp_plugin import (
+    NvpApiClient,
+    nvplib,
+    )
+
 
 logging.basicConfig(level=logging.DEBUG)
 LOG = logging.getLogger("test_network")
@@ -72,11 +76,11 @@ class NvpTests(unittest.TestCase):
             "quantum-test-tenant", "quantum-Private-TenantA",
             self.BRIDGE_TZ_UUID, self.quantum.controller)
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         resp2 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantC")
+                                            "quantum-Private-TenantC")
         resp3 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantD")
+                                            "quantum-Private-TenantD")
         net_id = resp["net-id"]
 
         resp = self.quantum.create_port("quantum-test-tenant", net_id,
@@ -88,7 +92,7 @@ class NvpTests(unittest.TestCase):
         self.assertTrue(old_vic == "None")
 
         self.quantum.plug_interface("quantum-test-tenant", net_id, port_id1,
-            "nova-instance-test-%s" % os.getpid())
+                                    "nova-instance-test-%s" % os.getpid())
         resp = self.quantum.get_port_details("quantum-test-tenant", net_id,
                                              port_id1)
         new_vic = resp["attachment"]
@@ -103,7 +107,7 @@ class NvpTests(unittest.TestCase):
         self.assertTrue(old_vic2 == "None")
 
         self.quantum.plug_interface("quantum-test-tenant", net_id, port_id2,
-            "nova-instance-test2-%s" % os.getpid())
+                                    "nova-instance-test2-%s" % os.getpid())
         resp = self.quantum.get_port_details("quantum-test-tenant", net_id,
                                              port_id2)
         new_vic = resp["attachment"]
@@ -130,7 +134,7 @@ class NvpTests(unittest.TestCase):
         net_id = resp["net-id"]
         try:
             resp = self.quantum.update_network("quantum-test-tenant", net_id,
-                name="new-name")
+                                               name="new-name")
         except exception.NetworkNotFound:
             self.assertTrue(False)
 
@@ -152,7 +156,7 @@ class NvpTests(unittest.TestCase):
     def test_negative_update_network(self):
         try:
             self.quantum.update_network("quantum-test-tenant", "xxx-no-net-id",
-                name="new-name")
+                                        name="new-name")
         except exception.NetworkNotFound:
             self.assertTrue(True)
 
index d84e9efd54cb3a787fb5613cc8788558f68f0360..c358c3fc3179f86466775baf2f906b071c4a8a62 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
 import httplib
-import unittest
+import unittest2 as unittest
 
-import nicira_nvp_plugin.api_client.common as naco
+import quantum.plugins.nicira.nicira_nvp_plugin.api_client.common as naco
 
 
 class NvpApiCommonTest(unittest.TestCase):
index 56aad5c1f7f4252a2fbb815f9b8960fedf33bddb..3fe7ee2fbe0fc2c3c3d53d74b93d3c32c6e449f0 100644 (file)
 
 import logging
 import unittest
+
 from eventlet.green import urllib2
 
+
 logging.basicConfig(level=logging.DEBUG)
-lg = logging.getLogger("test_nvp_api_request")
+LOG = logging.getLogger("test_nvp_api_request")
+
 
 REQUEST_TIMEOUT = 1
 
index dc8cc797779ddd8d070bd6b4f7f470c117b28f25..07f6e94fdd4ec8304ff7ff73f690afa3aded8426 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-
-# System
 import httplib
 import logging
 import new
 import random
 import unittest
 
-# Third party
 import eventlet
 from eventlet.green import urllib2
 from mock import Mock
 from mock import patch
 
-# Local
-import nicira_nvp_plugin.api_client.client_eventlet as nace
-import nicira_nvp_plugin.api_client.request_eventlet as nare
+from quantum.plugins.nicira.nicira_nvp_plugin.api_client import (
+    client_eventlet as nace,
+    request_eventlet as nare,
+    )
+
 
 logging.basicConfig(level=logging.DEBUG)
-lg = logging.getLogger("test_nvp_api_request_eventlet")
+LOG = logging.getLogger("test_nvp_api_request_eventlet")
+
 
 REQUEST_TIMEOUT = 1
 
@@ -47,8 +47,7 @@ class NvpApiRequestEventletTest(unittest.TestCase):
         self.client = nace.NvpApiClientEventlet(
             [("127.0.0.1", 4401, True)], "admin", "admin")
         self.url = "/ws.v1/_debug"
-        self.req = nare.NvpApiRequestEventlet(
-            self.client, self.url)
+        self.req = nare.NvpApiRequestEventlet(self.client, self.url)
 
     def tearDown(self):
         self.client = None
@@ -61,7 +60,7 @@ class NvpApiRequestEventletTest(unittest.TestCase):
     def test_apirequest_spawn(self):
         def x(id):
             eventlet.greenthread.sleep(random.random())
-            lg.info('spawned: %d' % id)
+            LOG.info('spawned: %d' % id)
 
         for i in range(10):
             nare.NvpApiRequestEventlet._spawn(x, i)
@@ -108,8 +107,8 @@ class NvpApiRequestEventletTest(unittest.TestCase):
 
     def test_run_and_timeout(self):
         def my_handle_request(self):
-            lg.info('my_handle_request() self: %s' % self)
-            lg.info('my_handle_request() dir(self): %s' % dir(self))
+            LOG.info('my_handle_request() self: %s' % self)
+            LOG.info('my_handle_request() dir(self): %s' % dir(self))
             eventlet.greenthread.sleep(REQUEST_TIMEOUT * 2)
 
         self.req._request_timeout = REQUEST_TIMEOUT
@@ -156,7 +155,7 @@ class NvpApiRequestEventletTest(unittest.TestCase):
         self.client.acquire_connection.return_value = None
 
         self.req._issue_request()
-        lg.info('request_error: %s' % self.req._request_error)
+        LOG.info('request_error: %s' % self.req._request_error)
         self.assertTrue(isinstance(self.req._request_error, Exception))
         self.assertTrue(self.client.acquire_connection.called)
 
@@ -343,11 +342,11 @@ class NvpApiRequestEventletTest(unittest.TestCase):
     def test_api_providers_non_none_api_providers(self):
         r = nare.NvpGetApiProvidersRequestEventlet(self.client)
         r.value = Mock()
-        r.value.body = '''{
+        r.value.body = """{
           "results": [
             { "roles": [
               { "role": "api_provider",
-                "listen_addr": "pssl:1.1.1.1:1" }]}]}'''
+                "listen_addr": "pssl:1.1.1.1:1" }]}]}"""
         r.successful = Mock(return_value=True)
-        lg.info('%s' % r.api_providers())
+        LOG.info('%s' % r.api_providers())
         self.assertTrue(r.api_providers() is not None)
index e2569f0ac0ac75c82e7b5e011d5d98adeaa27c74..18f2cf1355c7a5f70ad9aed6bea0586110c83d98 100644 (file)
@@ -20,9 +20,12 @@ import os
 import unittest
 
 from quantum.common import exceptions as exception
-from nicira_nvp_plugin.QuantumPlugin import NvpPlugin
-from nicira_nvp_plugin import NvpApiClient
-from nicira_nvp_plugin import nvplib
+from quantum.plugins.nicira.nicira_nvp_plugin.QuantumPlugin import NvpPlugin
+from quantum.plugins.nicira.nicira_nvp_plugin import (
+    NvpApiClient,
+    nvplib,
+    )
+
 
 logging.basicConfig(level=logging.DEBUG)
 LOG = logging.getLogger("test_port")
@@ -49,17 +52,17 @@ class NvpTests(unittest.TestCase):
             nvplib.do_single_request("DELETE", "/ws.v1/transport-node/%s" % t,
                                      controller=self.quantum.controller)
         for c in self.cis_uuids:
-            nvplib.do_single_request("DELETE",
+            nvplib.do_single_request(
+                "DELETE",
                 "/ws.v1/cluster-interconnect-service/%s" % c,
                 controller=self.quantum.controller)
 
     def _create_tz(self, name):
         post_uri = "/ws.v1/transport-zone"
-        body = {"display_name": name,
-                "tags": [{"tag": "plugin-test"}]}
+        body = {"display_name": name, "tags": [{"tag": "plugin-test"}]}
         try:
-            resp_obj = self.quantum.api_client.request("POST",
-              post_uri, json.dumps(body))
+            resp_obj = self.quantum.api_client.request(
+                "POST", post_uri, json.dumps(body))
         except NvpApiClient.NvpApiException as e:
             LOG.error("Unknown API Error: %s" % str(e))
             raise exception.QuantumException()
@@ -135,17 +138,17 @@ class NvpTests(unittest.TestCase):
 
         params = {}
         params["NICIRA:allowed_address_pairs"] = [
-          {
-             "ip_address": "172.168.17.5",
-             "mac_address": "10:9a:dd:61:4e:89"
-            },
             {
-             "ip_address": "172.168.17.6",
-             "mac_address": "10:9a:dd:61:4e:88"
-            }
-        ]
+                "ip_address": "172.168.17.5",
+                "mac_address": "10:9a:dd:61:4e:89",
+                },
+            {
+                "ip_address": "172.168.17.6",
+                "mac_address": "10:9a:dd:61:4e:88",
+                },
+            ]
         resp = self.quantum.create_port("quantum-test-tenant", net_id,
-            "ACTIVE", **params)
+                                        "ACTIVE", **params)
         port_id = resp["port-id"]
         resp = self.quantum.delete_port("quantum-test-tenant", net_id, port_id)
         self.quantum.delete_network("quantum-test-tenant", net_id)
@@ -256,7 +259,7 @@ class NvpTests(unittest.TestCase):
     def test_negative_create_port1(self):
         try:
             self.quantum.create_port("quantum-test-tenant", "xxx-no-net-id",
-              "ACTIVE")
+                                     "ACTIVE")
         except exception.NetworkNotFound:
             self.assertTrue(True)
             return
@@ -265,10 +268,10 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_create_port2(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.create_port("quantum-test-tenant", resp1["net-id"],
-                "INVALID")
+                                     "INVALID")
         except exception.StateInvalid:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant", resp1["net-id"])
@@ -279,10 +282,10 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_update_port1(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.update_port("quantum-test-tenant", resp1["net-id"],
-                "port_id_fake", state="ACTIVE")
+                                     "port_id_fake", state="ACTIVE")
         except exception.PortNotFound:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant", resp1["net-id"])
@@ -292,10 +295,10 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_update_port2(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.update_port("quantum-test-tenant", resp1["net-id"],
-                "port_id_fake", state="INVALID")
+                                     "port_id_fake", state="INVALID")
         except exception.StateInvalid:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant", resp1["net-id"])
@@ -305,10 +308,10 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_update_port3(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.update_port("quantum-test-tenant", resp1["net-id"],
-                "port_id_fake", state="ACTIVE")
+                                     "port_id_fake", state="ACTIVE")
         except exception.PortNotFound:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant", resp1["net-id"])
@@ -319,10 +322,10 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_delete_port1(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.delete_port("quantum-test-tenant", resp1["net-id"],
-                "port_id_fake")
+                                     "port_id_fake")
         except exception.PortNotFound:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant", resp1["net-id"])
@@ -332,10 +335,10 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_delete_port2(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.delete_port("quantum-test-tenant", resp1["net-id"],
-                "port_id_fake")
+                                     "port_id_fake")
         except exception.PortNotFound:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant", resp1["net-id"])
@@ -346,11 +349,11 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_get_port_details(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.get_port_details("quantum-test-tenant",
                                           resp1["net-id"],
-                "port_id_fake")
+                                          "port_id_fake")
         except exception.PortNotFound:
             self.assertTrue(True)
             self.quantum.delete_network("quantum-test-tenant",
@@ -362,7 +365,7 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_plug_interface(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.plug_interface("quantum-test-tenant",
                                         resp1["net-id"],
@@ -377,7 +380,7 @@ class NvpTests(unittest.TestCase):
 
     def test_negative_unplug_interface(self):
         resp1 = self.quantum.create_network("quantum-test-tenant",
-            "quantum-Private-TenantB")
+                                            "quantum-Private-TenantB")
         try:
             self.quantum.unplug_interface("quantum-test-tenant",
                                           resp1["net-id"], "port_id_fake")
@@ -401,8 +404,9 @@ class NvpTests(unittest.TestCase):
 
     def test_get_port_status_invalid_port(self):
         resp = self.quantum.create_custom_network("quantum-test-tenant",
-            "quantum-Private-TenantA", self.BRIDGE_TZ_UUID,
-            self.quantum.controller)
+                                                  "quantum-Private-TenantA",
+                                                  self.BRIDGE_TZ_UUID,
+                                                  self.quantum.controller)
         net_id = resp["net-id"]
         self.networks.append(net_id)
 
@@ -416,8 +420,9 @@ class NvpTests(unittest.TestCase):
 
     def test_get_port_status_returns_the_right_stuff(self):
         resp = self.quantum.create_custom_network("quantum-test-tenant",
-            "quantum-Private-TenantA", self.BRIDGE_TZ_UUID,
-            self.quantum.controller)
+                                                  "quantum-Private-TenantA",
+                                                  self.BRIDGE_TZ_UUID,
+                                                  self.quantum.controller)
         net_id = resp["net-id"]
         self.networks.append(net_id)
         resp = self.quantum.create_port("quantum-test-tenant", net_id,
@@ -439,8 +444,9 @@ class NvpTests(unittest.TestCase):
 
     def test_get_port_stats_invalid_port(self):
         resp = self.quantum.create_custom_network("quantum-test-tenant",
-            "quantum-Private-TenantA", self.BRIDGE_TZ_UUID,
-            self.quantum.controller)
+                                                  "quantum-Private-TenantA",
+                                                  self.BRIDGE_TZ_UUID,
+                                                  self.quantum.controller)
         net_id = resp["net-id"]
         self.networks.append(net_id)
 
@@ -454,8 +460,9 @@ class NvpTests(unittest.TestCase):
 
     def test_get_port_stats_returns_the_right_stuff(self):
         resp = self.quantum.create_custom_network("quantum-test-tenant",
-            "quantum-Private-TenantA", self.BRIDGE_TZ_UUID,
-            self.quantum.controller)
+                                                  "quantum-Private-TenantA",
+                                                  self.BRIDGE_TZ_UUID,
+                                                  self.quantum.controller)
         net_id = resp["net-id"]
         self.networks.append(net_id)
         resp = self.quantum.create_port("quantum-test-tenant", net_id,
@@ -472,8 +479,9 @@ class NvpTests(unittest.TestCase):
 
     def test_port_filters_by_attachment(self):
         resp = self.quantum.create_custom_network("quantum-test-tenant",
-            "quantum-Private-TenantA", self.BRIDGE_TZ_UUID,
-            self.quantum.controller)
+                                                  "quantum-Private-TenantA",
+                                                  self.BRIDGE_TZ_UUID,
+                                                  self.quantum.controller)
         net_id = resp["net-id"]
         self.networks.append(net_id)
 
@@ -483,7 +491,7 @@ class NvpTests(unittest.TestCase):
         port_id1 = port_id
         self.ports.append((net_id, port_id))
         self.quantum.plug_interface("quantum-test-tenant", net_id, port_id,
-            "attachment1")
+                                    "attachment1")
 
         resp = self.quantum.create_port("quantum-test-tenant", net_id,
                                         "ACTIVE")
@@ -491,7 +499,7 @@ class NvpTests(unittest.TestCase):
         port_id2 = port_id
         self.ports.append((net_id, port_id))
         self.quantum.plug_interface("quantum-test-tenant", net_id, port_id,
-            "attachment2")
+                                    "attachment2")
 
         # Make sure we get all the ports that we created back
         ports = self.quantum.get_all_ports("quantum-test-tenant", net_id)
@@ -504,6 +512,7 @@ class NvpTests(unittest.TestCase):
         self.assertTrue(ports[0]["port-id"] == port_id2)
 
         # Make sure we don't get any back with an invalid filter
-        ports = self.quantum.get_all_ports("quantum-test-tenant", net_id,
+        ports = self.quantum.get_all_ports(
+            "quantum-test-tenant", net_id,
             filter_opts={"attachment": "invalidattachment"})
         self.assertTrue(len(ports) == 0)
index e268c5c833130a166ce848b95b7c66b27367408e..82efd05e94443abdc36a32ee7a9a444f8ad2c724 100644 (file)
@@ -1,5 +1,5 @@
-The Open vSwitch (OVS) Quantum plugin is a simple plugin to manage OVS features using a
-local agent running on each hypervisor.
+The Open vSwitch (OVS) Quantum plugin is a simple plugin to manage OVS
+features using a local agent running on each hypervisor.
 
 For details on how to configure and use the plugin, see:
 
index 837f1c5e36e76cb889efa220d51520837cc797f8..bb51b84d8f6a457bb03c283131849d7bdedb4c6d 100755 (executable)
 # @author: Dave Lapsley, Nicira Networks, Inc.
 
 import ConfigParser
-import logging as LOG
+import logging
+from optparse import OptionParser
 import shlex
+import signal
+import subprocess
 import sys
 import time
-import signal
 
-from optparse import OptionParser
 from sqlalchemy.ext.sqlsoup import SqlSoup
-from subprocess import *
+
+
+LOG = logging.getLogger(__name__)
 
 
 # Global constants.
@@ -52,9 +55,10 @@ class VifPort:
         self.switch = switch
 
     def __str__(self):
-        return "iface-id=" + self.vif_id + ", vif_mac=" + \
-          self.vif_mac + ", port_name=" + self.port_name + \
-          ", ofport=" + self.ofport + ", bridge name = " + self.switch.br_name
+        return ("iface-id=" + self.vif_id + ", vif_mac=" +
+                self.vif_mac + ", port_name=" + self.port_name +
+                ", ofport=" + self.ofport + ", bridge name = " +
+                self.switch.br_name)
 
 
 class OVSBridge:
@@ -65,7 +69,7 @@ class OVSBridge:
     def run_cmd(self, args):
         cmd = shlex.split(self.root_helper) + args
         LOG.debug("## running command: " + " ".join(cmd))
-        p = Popen(cmd, stdout=PIPE)
+        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
         retval = p.communicate()[0]
         if p.returncode == -(signal.SIGALRM):
             LOG.debug("## timeout running command: " + " ".join(cmd))
@@ -128,10 +132,10 @@ class OVSBridge:
         self.run_vsctl(["add-port", self.br_name, port_name])
         self.set_db_attribute("Interface", port_name, "type", "gre")
         self.set_db_attribute("Interface", port_name, "options:remote_ip",
-            remote_ip)
+                              remote_ip)
         self.set_db_attribute("Interface", port_name, "options:in_key", "flow")
         self.set_db_attribute("Interface", port_name, "options:out_key",
-            "flow")
+                              "flow")
         return self.get_port_ofport(port_name)
 
     def add_patch_port(self, local_name, remote_name):
@@ -166,12 +170,13 @@ class OVSBridge:
         return self.db_get_map("Interface", port_name, "statistics")
 
     def get_xapi_iface_id(self, xs_vif_uuid):
-        return self.run_cmd(
-                        ["xe",
-                        "vif-param-get",
-                        "param-name=other-config",
-                        "param-key=nicira-iface-id",
-                        "uuid=%s" % xs_vif_uuid]).strip()
+        return self.run_cmd([
+            "xe",
+            "vif-param-get",
+            "param-name=other-config",
+            "param-key=nicira-iface-id",
+            "uuid=%s" % xs_vif_uuid,
+            ]).strip()
 
     # returns a VIF object for each VIF port
     def get_vif_ports(self):
@@ -184,8 +189,8 @@ class OVSBridge:
                 p = VifPort(name, ofport, external_ids["iface-id"],
                             external_ids["attached-mac"], self)
                 edge_ports.append(p)
-            elif "xs-vif-uuid" in external_ids and \
-                 "attached-mac" in external_ids:
+            elif ("xs-vif-uuid" in external_ids and
+                  "attached-mac" in external_ids):
                 # if this is a xenserver and iface-id is not automatically
                 # synced to OVS from XAPI, we grab it from XAPI directly
                 iface_id = self.get_xapi_iface_id(external_ids["xs-vif-uuid"])
@@ -215,8 +220,8 @@ class OVSQuantumAgent(object):
         self.setup_integration_br(integ_br)
 
     def port_bound(self, port, vlan_id):
-        self.int_br.set_db_attribute("Port", port.port_name, "tag",
-                str(vlan_id))
+        self.int_br.set_db_attribute("Port", port.port_name,
+                                     "tag", str(vlan_id))
         self.int_br.delete_flows(match="in_port=%s" % port.ofport)
 
     def port_unbound(self, port, still_exists):
@@ -265,7 +270,8 @@ class OVSQuantumAgent(object):
                     self.int_br.set_db_attribute("Port", p.port_name, "tag",
                                                  DEAD_VLAN_TAG)
                     self.int_br.add_flow(priority=2,
-                           match="in_port=%s" % p.ofport, actions="drop")
+                                         match="in_port=%s" % p.ofport,
+                                         actions="drop")
 
                 old_b = old_local_bindings.get(p.vif_id, None)
                 new_b = new_local_bindings.get(p.vif_id, None)
@@ -285,8 +291,9 @@ class OVSQuantumAgent(object):
                         self.port_bound(p, vlan_id)
                         if p.vif_id in all_bindings:
                             all_bindings[p.vif_id].op_status = OP_STATUS_UP
-                        LOG.info("Adding binding to net-id = %s " \
-                             "for %s on vlan %s" % (new_b, str(p), vlan_id))
+                        LOG.info(("Adding binding to net-id = %s "
+                                  "for %s on vlan %s") %
+                                 (new_b, str(p), vlan_id))
 
             for vif_id in old_vif_ports:
                 if vif_id not in new_vif_ports:
@@ -356,13 +363,13 @@ class OVSQuantumTunnelAgent(object):
 
         # outbound
         self.tun_br.add_flow(priority=4, match="in_port=%s,dl_vlan=%s" %
-                            (self.patch_int_ofport, lvid),
+                             (self.patch_int_ofport, lvid),
                              actions="set_tunnel:%s,normal" % (lsw_id))
 
         # inbound
         self.tun_br.add_flow(priority=3, match="tun_id=%s" % lsw_id,
-                             actions="mod_vlan_vid:%s,output:%s" % (lvid,
-                             self.patch_int_ofport))
+                             actions="mod_vlan_vid:%s,output:%s" %
+                             (lvid, self.patch_int_ofport))
 
     def reclaim_local_vlan(self, net_uuid, lvm):
         '''Reclaim a local VLAN.
@@ -401,8 +408,8 @@ class OVSQuantumTunnelAgent(object):
         :param port: a VifPort object.
         :param net_uuid: the net_uuid this port is associated with.'''
         if net_uuid not in self.local_vlan_map:
-            LOG.info('port_unbound() net_uuid %s not in local_vlan_map'
-                     net_uuid)
+            LOG.info('port_unbound() net_uuid %s not in local_vlan_map' %
+                     net_uuid)
             return
         lvm = self.local_vlan_map[net_uuid]
 
@@ -460,8 +467,8 @@ class OVSQuantumTunnelAgent(object):
                 for i, remote_ip in enumerate(tunnel_ips):
                     self.tun_br.add_tunnel_port("gre-" + str(i), remote_ip)
         except Exception, e:
-            LOG.error("Error configuring tunnels: '%s' %s"
-                      (remote_ip_file, str(e)))
+            LOG.error("Error configuring tunnels: '%s' %s" %
+                      (remote_ip_file, str(e)))
             raise
 
         self.tun_br.remove_all_flows()
@@ -525,11 +532,11 @@ class OVSQuantumTunnelAgent(object):
             new_local_bindings_ids = all_bindings_vif_port_ids.intersection(
                 new_vif_ports_ids)
             new_local_bindings = dict([(p, all_bindings.get(p))
-                for p in new_vif_ports_ids])
-            new_bindings = set((p, old_local_bindings.get(p),
-                new_local_bindings.get(p)) for p in new_vif_ports_ids)
-            changed_bindings = set([b for b in new_bindings
-                if b[2] != b[1]])
+                                       for p in new_vif_ports_ids])
+            new_bindings = set(
+                (p, old_local_bindings.get(p),
+                 new_local_bindings.get(p)) for p in new_vif_ports_ids)
+            changed_bindings = set([b for b in new_bindings if b[2] != b[1]])
 
             LOG.debug('all_bindings: %s' % all_bindings)
             LOG.debug('lsw_id_bindings: %s' % lsw_id_bindings)
@@ -563,7 +570,7 @@ class OVSQuantumTunnelAgent(object):
                     new_net_uuid = new_port.network_id
                     if new_net_uuid not in lsw_id_bindings:
                         LOG.warn("No ls-id binding found for net-id '%s'" %
-                            new_net_uuid)
+                                 new_net_uuid)
                         continue
 
                     lsw_id = lsw_id_bindings[new_net_uuid]
@@ -574,8 +581,8 @@ class OVSQuantumTunnelAgent(object):
                                  str(self.local_vlan_map[new_net_uuid]))
                     except Exception, e:
                         LOG.info("Unable to bind Port " + str(p) +
-                            " on netid = " + new_net_uuid + " to "
-                            + str(self.local_vlan_map[new_net_uuid]))
+                                 " on netid = " + new_net_uuid + " to "
+                                 + str(self.local_vlan_map[new_net_uuid]))
 
             for vif_id in disappeared_vif_ports_ids:
                 LOG.info("Port Disappeared: " + vif_id)
@@ -615,8 +622,8 @@ def main():
     try:
         config.read(config_file)
     except Exception, e:
-        LOG.error("Unable to parse config file \"%s\": %s"
-                  (config_file, str(e)))
+        LOG.error("Unable to parse config file \"%s\": %s" %
+                  (config_file, str(e)))
         raise e
 
     # Determine which agent type to use.
@@ -639,8 +646,8 @@ def main():
         root_helper = config.get("AGENT", "root_helper")
 
     except Exception, e:
-        LOG.error("Error parsing common params in config_file: '%s': %s"
-                  (config_file, str(e)))
+        LOG.error("Error parsing common params in config_file: '%s': %s" %
+                  (config_file, str(e)))
         sys.exit(1)
 
     if enable_tunneling:
@@ -662,8 +669,8 @@ def main():
             if not len(local_ip):
                 raise Exception('Empty local-ip in configuration file.')
         except Exception, e:
-            LOG.error("Error parsing tunnel params in config_file: '%s': %s"
-                      (config_file, str(e)))
+            LOG.error("Error parsing tunnel params in config_file: '%s': %s" %
+                      (config_file, str(e)))
             sys.exit(1)
 
         plugin = OVSQuantumTunnelAgent(integ_br, tun_br, remote_ip_file,
index d02aafd068d174c4e9522ed2f379e54a65e20e9e..b3b294cf4e147bea1cddc194748414c0ad391342 100644 (file)
 # @author: Brad Hall, Nicira Networks, Inc.
 # @author: Dan Wendlandt, Nicira Networks, Inc.
 
-
 from sqlalchemy.orm import exc
 
 import quantum.db.api as db
 import quantum.db.models as models
-import ovs_models
+from quantum.plugins.openvswitch import ovs_models
 
 
 def get_vlans():
     session = db.get_session()
     try:
-        bindings = session.query(ovs_models.VlanBinding).\
-          all()
+        bindings = (session.query(ovs_models.VlanBinding).
+                    all())
     except exc.NoResultFound:
         return []
     res = []
@@ -49,9 +48,9 @@ def add_vlan_binding(vlanid, netid):
 def remove_vlan_binding(netid):
     session = db.get_session()
     try:
-        binding = session.query(ovs_models.VlanBinding).\
-          filter_by(network_id=netid).\
-          one()
+        binding = (session.query(ovs_models.VlanBinding).
+                   filter_by(network_id=netid).
+                   one())
         session.delete(binding)
     except exc.NoResultFound:
             pass
index 4c2eed0627ef5edccd03f00eb1b35d8e40e8869e..91edafd517ef08496005e77715808c66311cf244 100644 (file)
 # @author: Brad Hall, Nicira Networks, Inc.
 # @author: Dan Wendlandt, Nicira Networks, Inc.
 
-
 import uuid
 
 from sqlalchemy import Column, Integer, String, ForeignKey
 from sqlalchemy.ext.declarative import declarative_base
 from sqlalchemy.orm import relation
+
 from quantum.db.models import BASE
 
 
index aced08c30117c04c584faa50f4c4dc3e17c2b275..09012749bd6244efd5c51d395a865c437990b37b 100644 (file)
@@ -19,7 +19,7 @@
 # @author: Dave Lapsley, Nicira Networks, Inc.
 
 import ConfigParser
-import logging as LOG
+import logging
 from optparse import OptionParser
 import os
 import sys
@@ -27,17 +27,17 @@ import sys
 from quantum.api.api_common import OperationalStatus
 from quantum.common import exceptions as q_exc
 from quantum.common.config import find_config_file
+import quantum.db.api as db
+from quantum.plugins.openvswitch import ovs_db
 from quantum.quantum_plugin_base import QuantumPluginBase
 
-import quantum.db.api as db
-import ovs_db
 
-CONF_FILE = find_config_file(
-  {"plugin": "openvswitch"},
-  None, "ovs_quantum_plugin.ini")
+logging.basicConfig(level=logging.WARN)
+LOG = logging.getLogger("ovs_quantum_plugin")
+
 
-LOG.basicConfig(level=LOG.WARN)
-LOG.getLogger("ovs_quantum_plugin")
+CONF_FILE = find_config_file({"plugin": "openvswitch"},
+                             None, "ovs_quantum_plugin.ini")
 
 
 # Exception thrown if no more VLANs are available
@@ -81,8 +81,8 @@ class VlanMap(object):
             self.free_vlans.add(vlan)
             del self.vlans[vlan]
             del self.net_ids[network_id]
-            LOG.debug("Deallocated VLAN %s (used by network %s)"
-                      (vlan, network_id))
+            LOG.debug("Deallocated VLAN %s (used by network %s)" %
+                      (vlan, network_id))
         else:
             LOG.error("No vlan found with network \"%s\"", network_id)
 
@@ -96,10 +96,10 @@ class OVSQuantumPlugin(QuantumPluginBase):
                 configfile = CONF_FILE
             else:
                 configfile = find_config(os.path.abspath(
-                        os.path.dirname(__file__)))
+                    os.path.dirname(__file__)))
         if configfile is None:
             raise Exception("Configuration file \"%s\" doesn't exist" %
-              (configfile))
+                            (configfile))
         LOG.debug("Using configuration file: %s" % configfile)
         config.read(configfile)
         LOG.debug("Config: %s" % config)
@@ -113,8 +113,8 @@ class OVSQuantumPlugin(QuantumPluginBase):
         vlans = ovs_db.get_vlans()
         for x in vlans:
             vlan_id, network_id = x
-            LOG.debug("Adding already populated vlan %s -> %s"
-                      (vlan_id, network_id))
+            LOG.debug("Adding already populated vlan %s -> %s" %
+                      (vlan_id, network_id))
             self.vmap.already_used(vlan_id, network_id)
 
     def get_all_networks(self, tenant_id, **kwargs):
@@ -126,21 +126,22 @@ class OVSQuantumPlugin(QuantumPluginBase):
         return nets
 
     def _make_net_dict(self, net_id, net_name, ports, op_status):
-        res = {'net-id': net_id,
-                'net-name': net_name,
-                'net-op-status': op_status}
+        res = {
+            'net-id': net_id,
+            'net-name': net_name,
+            'net-op-status': op_status,
+            }
         if ports:
             res['net-ports'] = ports
         return res
 
     def create_network(self, tenant_id, net_name, **kwargs):
         net = db.network_create(tenant_id, net_name,
-                          op_status=OperationalStatus.UP)
+                                op_status=OperationalStatus.UP)
         LOG.debug("Created network: %s" % net)
         vlan_id = self.vmap.acquire(str(net.uuid))
         ovs_db.add_vlan_binding(vlan_id, str(net.uuid))
-        return self._make_net_dict(str(net.uuid), net.name, [],
-                                        net.op_status)
+        return self._make_net_dict(str(net.uuid), net.name, [], net.op_status)
 
     def delete_network(self, tenant_id, net_id):
         db.validate_network_ownership(tenant_id, net_id)
@@ -153,21 +154,20 @@ class OVSQuantumPlugin(QuantumPluginBase):
         net = db.network_destroy(net_id)
         ovs_db.remove_vlan_binding(net_id)
         self.vmap.release(net_id)
-        return self._make_net_dict(str(net.uuid), net.name, [],
-                                        net.op_status)
+        return self._make_net_dict(str(net.uuid), net.name, [], net.op_status)
 
     def get_network_details(self, tenant_id, net_id):
         db.validate_network_ownership(tenant_id, net_id)
         net = db.network_get(net_id)
         ports = self.get_all_ports(tenant_id, net_id)
         return self._make_net_dict(str(net.uuid), net.name,
-                                    ports, net.op_status)
+                                   ports, net.op_status)
 
     def update_network(self, tenant_id, net_id, **kwargs):
         db.validate_network_ownership(tenant_id, net_id)
         net = db.network_update(net_id, tenant_id, **kwargs)
         return self._make_net_dict(str(net.uuid), net.name,
-                                        None, net.op_status)
+                                   None, net.op_status)
 
     def _make_port_dict(self, port):
         if port.state == "ACTIVE":
@@ -175,11 +175,13 @@ class OVSQuantumPlugin(QuantumPluginBase):
         else:
             op_status = OperationalStatus.DOWN
 
-        return {'port-id': str(port.uuid),
-                'port-state': port.state,
-                'port-op-status': op_status,
-                'net-id': port.network_id,
-                'attachment': port.interface_id}
+        return {
+            'port-id': str(port.uuid),
+            'port-state': port.state,
+            'port-op-status': op_status,
+            'net-id': port.network_id,
+            'attachment': port.interface_id,
+            }
 
     def get_all_ports(self, tenant_id, net_id, **kwargs):
         ids = []
@@ -192,7 +194,7 @@ class OVSQuantumPlugin(QuantumPluginBase):
         LOG.debug("Creating port with network_id: %s" % net_id)
         db.validate_network_ownership(tenant_id, net_id)
         port = db.port_create(net_id, port_state,
-                                op_status=OperationalStatus.DOWN)
+                              op_status=OperationalStatus.DOWN)
         return self._make_port_dict(port)
 
     def delete_port(self, tenant_id, net_id, port_id):
index b01ba765d6fcd531c3822f8983e297cc4cc0e6d3..e65bf6624c41e2c2c13682632c54c0dbbd87577c 100755 (executable)
@@ -25,11 +25,10 @@ To run all tests::
     PLUGIN_DIR=quantum/plugins/openvswitch ./run_tests.sh
 """
 
-import gettext
 import logging
 import os
-import unittest
 import sys
+import unittest
 
 from nose import config
 from nose import core
@@ -37,11 +36,11 @@ from nose import core
 sys.path.append(os.getcwd())
 sys.path.append(os.path.dirname(__file__))
 
-
 from quantum.api.api_common import OperationalStatus
 from quantum.common.test_lib import run_tests, test_config
+from quantum.plugins.openvswitch.tests.unit.test_vlan_map import VlanMapTest
 import quantum.tests.unit
-from tests.unit.test_vlan_map import VlanMapTest
+
 
 if __name__ == '__main__':
     exit_status = False
index ee408f929bcca450b753ff68114efa68850f6095..c0bf2b35d146463b7522f117d2d08a8f64d3fbdb 100644 (file)
 # @author: Dave Lapsley, Nicira Networks, Inc.
 
 import logging
-import mox
 import os
 import unittest
-from agent import ovs_quantum_agent
+
+import mox
+
+from quantum.plugins.openvswitch.agent import ovs_quantum_agent
+
 
 LOG = logging.getLogger("quantum.plugins.openvswitch.tests.unit.test_tunnel")
 LOG.setLevel(logging.INFO)
 
+
 LOCAL_DIR = os.path.dirname(__file__)
 REMOTE_IP_FILE = LOCAL_DIR + '/remote-ip-file.txt'
 
@@ -135,7 +139,7 @@ class TunnelTest(unittest.TestCase):
 
     def testPortBound(self):
         self.mock_int_bridge.set_db_attribute('Port', VIF_PORT.port_name,
-                                               'tag', str(LVM.vlan))
+                                              'tag', str(LVM.vlan))
         self.mock_int_bridge.delete_flows(match='in_port=%s' % VIF_PORT.ofport)
 
         self.mox.ReplayAll()
@@ -161,8 +165,8 @@ class TunnelTest(unittest.TestCase):
         self.mox.VerifyAll()
 
     def testPortDead(self):
-        self.mock_int_bridge.set_db_attribute('Port', VIF_PORT.port_name,
-            'tag', ovs_quantum_agent.DEAD_VLAN_TAG)
+        self.mock_int_bridge.set_db_attribute(
+            'Port', VIF_PORT.port_name, 'tag', ovs_quantum_agent.DEAD_VLAN_TAG)
 
         match_string = 'in_port=%s' % VIF_PORT.ofport
         self.mock_int_bridge.add_flow(priority=2, match=match_string,
index 4e4b62406ddc8e751df592257345a0c7c66b68a8..dc54a73a2d6697f0a292f0965ed6e7c034f3d3c9 100644 (file)
 #    under the License.
 
 import unittest
-from ovs_quantum_plugin import VlanMap, NoFreeVLANException
+
+from quantum.plugins.openvswitch.ovs_quantum_plugin import (
+    NoFreeVLANException,
+    VlanMap,
+    )
 
 
 class VlanMapTest(unittest.TestCase):
index 4f96b88e04704dd5119a75b7c7fa5e69ea11acf9..8a33aecb17dbb6729162316f0c47f940e54a3602 100755 (executable)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 # @author: Isaku Yamahata
+
 import ConfigParser
 import logging as LOG
+from optparse import OptionParser
 import shlex
 import signal
+from subprocess import PIPE, Popen
 import sys
 import time
-from optparse import OptionParser
-from sqlalchemy.ext.sqlsoup import SqlSoup
-from subprocess import PIPE, Popen
 
 from ryu.app import rest_nw_id
 from ryu.app.client import OFPClient
+from sqlalchemy.ext.sqlsoup import SqlSoup
 
 
 OP_STATUS_UP = "UP"
@@ -115,11 +116,11 @@ class OVSBridge:
 
     def get_xapi_iface_id(self, xs_vif_uuid):
         return self.run_cmd(
-                        ["xe",
-                        "vif-param-get",
-                        "param-name=other-config",
-                        "param-key=nicira-iface-id",
-                        "uuid=%s" % xs_vif_uuid]).strip()
+            ["xe",
+             "vif-param-get",
+             "param-name=other-config",
+             "param-key=nicira-iface-id",
+             "uuid=%s" % xs_vif_uuid]).strip()
 
     def _vifport(self, name, external_ids):
         ofport = self.db_get_val("Interface", name, "ofport")
index b14f678576fb3837f201ce9ce31ee7d208f9727a..bb32abae2922ab7ce3ab2dd2f9de8d6a5c0b3cd8 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+from ryu.app.client import OFPClient
+
 from nova import flags
 from nova import log as logging
-from nova import utils
 from nova.network import linux_net
 from nova.openstack.common import cfg
-from ryu.app.client import OFPClient
+from nova import utils
+
 
 LOG = logging.getLogger(__name__)
 
@@ -56,8 +58,9 @@ class LinuxOVSRyuInterfaceDriver(linux_net.LinuxOVSInterfaceDriver):
         if linux_net.binary_name == 'nova-network':
             for tables in [linux_net.iptables_manager.ipv4,
                            linux_net.iptables_manager.ipv6]:
-                tables['filter'].add_rule('FORWARD',
-                        '--in-interface gw-+ --out-interface gw-+ -j DROP')
+                tables['filter'].add_rule(
+                    'FORWARD',
+                    '--in-interface gw-+ --out-interface gw-+ -j DROP')
             linux_net.iptables_manager.apply()
 
     def plug(self, network, mac_address, gateway=True):
index 2bd2f00963ccf05d0df49219658fd35a6c1bfdd8..d2a61ead1132923eb340505dc1d81c7b7cfc3103 100644 (file)
 
 import httplib
 
+from ryu.app.client import OFPClient
+
 from nova import flags
 from nova import log as logging
-from nova import utils
 from nova.openstack.common import cfg
+from nova import utils
 from nova.virt.libvirt import vif as libvirt_vif
-from ryu.app.client import OFPClient
 
 
 LOG = logging.getLogger(__name__)
@@ -63,8 +64,7 @@ class LibvirtOpenVswitchOFPRyuDriver(libvirt_vif.LibvirtOpenVswitchDriver):
         result = super(LibvirtOpenVswitchOFPRyuDriver, self).plug(
             instance, network, mapping)
         port_no = self._get_port_no(mapping)
-        self.ryu_client.create_port(network['id'],
-                                    self.datapath_id, port_no)
+        self.ryu_client.create_port(network['id'], self.datapath_id, port_no)
         return result
 
     def unplug(self, instance, network, mapping):
index ee83435cf06b2b70f5a0f73771c524deb69c7f08..91841928fabcf545a7d0e44f1643522414ecf038 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 # @author: Isaku Yamahata
+
 import ConfigParser
+from abc import ABCMeta, abstractmethod
 import logging as LOG
 import os
-from abc import ABCMeta, abstractmethod
 
-import quantum.db.api as db
 from quantum.api.api_common import OperationalStatus
 from quantum.common import exceptions as q_exc
+import quantum.db.api as db
 from quantum.manager import find_config
 from quantum.quantum_plugin_base import QuantumPluginBase
 
@@ -59,11 +60,11 @@ class OVSQuantumPluginBase(QuantumPluginBase):
             if conf_file and os.path.exists(conf_file):
                 configfile = conf_file
             else:
-                configfile = find_config(os.path.abspath(
-                        os.path.dirname(mod_file)))
+                configfile = (
+                    find_config(os.path.abspath(os.path.dirname(mod_file))))
         if configfile is None:
             raise Exception("Configuration file \"%s\" doesn't exist" %
-              (configfile))
+                            (configfile))
         LOG.debug("Using configuration file: %s", configfile)
         config.read(configfile)
         LOG.debug("Config: %s", config)
index c1e227e41898d5116c909c23405bd7a62f58911a..4b66c23e2c78eeefa28b0e675b2af098317c5010 100644 (file)
@@ -34,11 +34,10 @@ from nose import core
 sys.path.append(os.getcwd())
 sys.path.append(os.path.dirname(__file__))
 
-
-import quantum.tests.unit
 from quantum.api.api_common import OperationalStatus
 from quantum.common.test_lib import run_tests, test_config
 from quantum.plugins.ryu.tests.unit.utils import patch_fake_ryu_client
+import quantum.tests.unit
 
 
 if __name__ == '__main__':
index 49ceeaafd2bb725b202c6da0e924346072c1992a..a08fb591ee21338018316ba118f48d9ff5088931 100644 (file)
 #    under the License.
 # @author: Isaku Yamahata
 
-import quantum.db.api as db
-from quantum.common import exceptions as q_exc
+from ryu.app import client
+from ryu.app import rest_nw_id
+
 from quantum.common.config import find_config_file
+from quantum.common import exceptions as q_exc
+import quantum.db.api as db
 from quantum.plugins.ryu import ofp_service_type
 from quantum.plugins.ryu import ovs_quantum_plugin_base
 from quantum.plugins.ryu.db import api as db_api
 
 
-from ryu.app import client
-from ryu.app import rest_nw_id
-
-
 CONF_FILE = find_config_file({"plugin": "ryu"}, None, "ryu.ini")
 
 
index 3accc143b1781ce10a53dba77b13b0c4839e555e..1c81b027cf19af34fdd8dc269d4484121268e2f4 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-import mox
 import os
 
+import mox
+
 from quantum.plugins.ryu.tests.unit import fake_plugin
 from quantum.plugins.ryu.tests.unit import utils
 from quantum.plugins.ryu.tests.unit.basetest import BaseRyuTest
index 37dce46eae7c2039a281942e3d1b1b8d1f50e63d..ad113e74be1f8cea4baae885eaad0d5db3d8f2ba 100644 (file)
@@ -18,8 +18,8 @@
 import uuid
 
 import quantum.db.api as db
-from quantum.plugins.ryu.tests.unit import utils
 from quantum.plugins.ryu.tests.unit.basetest import BaseRyuTest
+from quantum.plugins.ryu.tests.unit import utils
 from quantum.plugins.ryu.tests.unit.utils import patch_fake_ryu_client
 
 
index e7bf4d72c50df4edd37044fdb2162f02bc2e5362..77b1f6cc60c7a50365e956a11cfee831cea049ce 100644 (file)
 #    under the License.
 
 import ConfigParser
+from StringIO import StringIO
 import imp
 import os
 import tempfile
-from StringIO import StringIO
 
 import mock
 
 from quantum.plugins.ryu.tests.unit import fake_rest_nw_id
 from quantum.plugins.ryu.tests.unit import fake_ryu_client
 
+
 FAKE_CONTROLLER_ADDR = '127.0.0.1:6633'
 FAKE_REST_ADDR = '127.0.0.1:8080'
 FAKE_RYU_INI_TEMPLATE = """
index d4fdc307d32e7d8ba0c67bc0abcfaeafce2cdd10..07d59cff04da9048690ed101ed4418796d169cb3 100644 (file)
@@ -22,6 +22,7 @@ from quantum.api.api_common import OperationalStatus
 from quantum.common import exceptions as exc
 from quantum.db import api as db
 
+
 LOG = logging.getLogger('quantum.plugins.sample.SamplePlugin')
 
 
@@ -247,8 +248,8 @@ class FakePlugin(object):
         """
         LOG.debug("FakePlugin.get_all_ports() called")
         db.validate_network_ownership(tenant_id, net_id)
-        filter_opts = kwargs.get('filter_opts', None)
-        if not filter_opts is None and len(filter_opts) > 0:
+        filter_opts = kwargs.get('filter_opts')
+        if filter_opts:
             LOG.debug("filtering options were passed to the plugin"
                       "but the Fake plugin does not support them")
         port_ids = []
@@ -279,8 +280,7 @@ class FakePlugin(object):
         self._get_network(tenant_id, net_id)
         port = db.port_create(net_id, port_state)
         # Put operational status UP
-        db.port_update(port.uuid, net_id,
-                       op_status=OperationalStatus.UP)
+        db.port_update(port.uuid, net_id, op_status=OperationalStatus.UP)
         port_item = {'port-id': str(port.uuid)}
         return port_item
 
@@ -293,8 +293,7 @@ class FakePlugin(object):
         self._get_network(tenant_id, net_id)
         self._get_port(tenant_id, net_id, port_id)
         port = db.port_update(port_id, net_id, **kwargs)
-        port_item = {'port-id': port_id,
-                     'port-state': port['state']}
+        port_item = {'port-id': port_id, 'port-state': port['state']}
         return port_item
 
     def delete_port(self, tenant_id, net_id, port_id):
index 3af3d0f84aa6b0ce780334a9a8b8877bf59ab5b6..b88b4476945ef7ceeccf53dc53c8def0a0fad973 100644 (file)
@@ -260,8 +260,8 @@ class QuantumPluginBase(object):
                         if inspect.isfunction(fn_obj):
                             abstract_fn_obj = cls.__dict__[method]
                             arg_count = fn_obj.func_code.co_argcount
-                            expected_arg_count = \
-                                abstract_fn_obj.func_code.co_argcount
+                            expected_arg_count = (
+                                abstract_fn_obj.func_code.co_argcount)
                             method_ok = arg_count == expected_arg_count
                 if method_ok:
                     continue
index 48076f462ecd75abaca79a15355082a1454db93b..127cb442ded5f2238a2bc0ac6f2f8aaf853f90d7 100644 (file)
@@ -30,9 +30,7 @@ class CommandFilter(object):
 
     def match(self, userargs):
         """Only check that the first argument (command) matches exec_path"""
-        if (os.path.basename(self.exec_path) == userargs[0]):
-            return True
-        return False
+        return os.path.basename(self.exec_path) == userargs[0]
 
     def get_command(self, userargs):
         """Returns command to execute (with sudo -u if run_as != root)."""
@@ -108,13 +106,12 @@ class KillFilter(CommandFilter):
             if signal not in self.args[0]:
                 # Requested signal not in accepted list
                 return False
-        else:
-            if len(args) != 2:
-                # Incorrect number of arguments
-                return False
-            if '' not in self.args[0]:
-                # No signal, but list doesn't include empty string
-                return False
+        elif len(args) != 2:
+            # Incorrect number of arguments
+            return False
+        elif '' not in self.args[0]:
+            # No signal, but list doesn't include empty string
+            return False
         try:
             command = os.readlink("/proc/%d/exe" % int(args[1]))
             if command not in self.args[1]:
index 7f19074c9c96fdbb3dcfca90d4fb72369fe41c11..93ef1cc9bdffb20981b8b855d0f7decf4c0a43b2 100755 (executable)
 # If ../quantum/__init__.py exists, add ../ to Python search path, so that
 # it will override what happens to be installed in /usr/(local/)lib/python...
 
-import gettext
 import optparse
 import os
 import sys
 
-gettext.install('quantum', unicode=1)
-
 from quantum import service
 from quantum.common import config
 
@@ -47,11 +44,12 @@ def main():
 
     try:
         quantum_service = service.serve_wsgi(service.QuantumApiService,
-                                     options=options,
-                                     args=args)
+                                             options=options,
+                                             args=args)
         quantum_service.wait()
     except RuntimeError, e:
         sys.exit("ERROR: %s" % e)
 
+
 if __name__ == "__main__":
     main()
index 18cc93b730749aa1029d800a2b4d04f00f4a2d8d..31204fb871c3d5991141e994123c0d4722c68452 100644 (file)
 #    under the License.
 
 import logging
+
 from quantum.common import config
-from quantum import wsgi
 from quantum.common import exceptions as exception
+from quantum import wsgi
 
 
 LOG = logging.getLogger('quantum.service')
@@ -53,11 +54,9 @@ class QuantumApiService(WsgiService):
     def create(cls, conf=None, options=None, args=None):
         app_name = "quantum"
         if not conf:
-            conf_file, conf = config.load_paste_config(
-                              app_name, options, args)
+            conf_file, conf = config.load_paste_config(app_name, options, args)
             if not conf:
-                message = (_('No paste configuration found for: %s'),
-                           app_name)
+                message = (_('No paste configuration found for: %s'), app_name)
                 raise exception.Error(message)
 
         # Setup logging early, supplying both the CLI options and the
@@ -67,12 +66,11 @@ class QuantumApiService(WsgiService):
         # Log the options used when starting if we're in debug mode...
 
         config.setup_logging(options, conf)
-        debug = options.get('debug') or \
-                config.get_option(conf, 'debug',
-                                  type='bool', default=False)
-        verbose = options.get('verbose') or \
-                config.get_option(conf, 'verbose',
-                                  type='bool', default=False)
+        debug = (options.get('debug') or
+                 config.get_option(conf, 'debug', type='bool', default=False))
+        verbose = (options.get('verbose') or
+                   config.get_option(conf, 'verbose', type='bool',
+                                     default=False))
         conf['debug'] = debug
         conf['verbose'] = verbose
         LOG.debug("*" * 80)
@@ -107,9 +105,8 @@ def _run_wsgi(app_name, paste_conf, paste_config_file):
                                       None)
     if not app:
         LOG.error(_('No known API applications configured in %s.'),
-                      paste_config_file)
+                  paste_config_file)
         return
     server = wsgi.Server("Quantum")
-    server.start(app,
-                 int(paste_conf['bind_port']), paste_conf['bind_host'])
+    server.start(app, int(paste_conf['bind_port']), paste_conf['bind_host'])
     return server
index feeb9d3e964d9d781ed3c5b98ed24eb7cf405ade..cc3a43a338cf5775daea321192aca0103d5e27ad 100644 (file)
 # The code below enables nosetests to work with i18n _() blocks
 
 import __builtin__
+import os
 import unittest
+
 setattr(__builtin__, '_', lambda x: x)
 
-import os
 from quantum.common import flags
 
+
 FLAGS = flags.FLAGS
 reldir = os.path.join(os.path.dirname(__file__), '..', '..', '..')
 absdir = os.path.abspath(reldir)
index 73a417dba165705ac94260ca9005f9bd2e636c17..0ef5fa3da38a9da8f21eaa8b145726217ce0008c 100644 (file)
 import logging
 import unittest
 
-import quantum.tests.unit.testlib_api as testlib
-
-from quantum.db import api as db
-from quantum.common import utils
 from quantum.common.test_lib import test_config
+from quantum.common import utils
+from quantum.db import api as db
+import quantum.tests.unit.testlib_api as testlib
 from quantum.wsgi import XMLDeserializer, JSONDeserializer
 
+
 LOG = logging.getLogger('quantum.tests.test_api')
+
+
 NETS = "networks"
 PORTS = "ports"
 ATTS = "attachments"
@@ -37,16 +39,16 @@ class AbstractAPITest(unittest.TestCase):
     """ Base class definiting some methods for API tests """
 
     def _deserialize_net_response(self, content_type, response):
-        network_data = self._net_deserializers[content_type].\
-                            deserialize(response.body)['body']
+        network_data = (self._net_deserializers[content_type].
+                        deserialize(response.body)['body'])
         # do not taint assertions with xml namespace
         if 'xmlns' in network_data['network']:
             del network_data['network']['xmlns']
         return network_data
 
     def _deserialize_port_response(self, content_type, response):
-        port_data = self._port_deserializers[content_type].\
-                         deserialize(response.body)['body']
+        port_data = (self._port_deserializers[content_type].
+                     deserialize(response.body)['body'])
         # do not taint assertions with xml namespace
         if 'xmlns' in port_data['port']:
             del port_data['port']['xmlns']
@@ -64,8 +66,8 @@ class AbstractAPITest(unittest.TestCase):
                                                   net_name, fmt,
                                                   custom_req_body)
         network_res = network_req.get_response(self.api)
-        expected_res_status = expected_res_status or \
-                              self._successful_create_code
+        expected_res_status = (expected_res_status or
+                               self._successful_create_code)
         self.assertEqual(network_res.status_int, expected_res_status)
         if expected_res_status in (200, 202):
             network_data = self._deserialize_net_response(content_type,
@@ -80,8 +82,8 @@ class AbstractAPITest(unittest.TestCase):
                                             port_state, fmt,
                                             custom_req_body)
         port_res = port_req.get_response(self.api)
-        expected_res_status = expected_res_status or \
-                              self._successful_create_code
+        expected_res_status = (expected_res_status or
+                               self._successful_create_code)
         self.assertEqual(port_res.status_int, expected_res_status)
         if expected_res_status in (200, 202):
             port_data = self._deserialize_port_response(content_type,
@@ -146,19 +148,17 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                         fmt)
         show_network_res = show_network_req.get_response(self.api)
         self.assertEqual(show_network_res.status_int, 200)
-        network_data = self._net_deserializers[content_type].\
-                            deserialize(show_network_res.body)['body']
+        network_data = (self._net_deserializers[content_type].
+                        deserialize(show_network_res.body)['body'])
         self.assertEqual(network_id, network_data['network']['id'])
         LOG.debug("_test_create_network - fmt:%s - END", fmt)
 
     def _test_create_network_badrequest(self, fmt):
-        LOG.debug("_test_create_network_badrequest - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_create_network_badrequest - fmt:%s - START", fmt)
         bad_body = {'network': {'bad-attribute': 'very-bad'}}
         self._create_network(fmt, custom_req_body=bad_body,
                              expected_res_status=400)
-        LOG.debug("_test_create_network_badrequest - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_create_network_badrequest - fmt:%s - END", fmt)
 
     def _test_list_networks(self, fmt):
         LOG.debug("_test_list_networks - fmt:%s - START", fmt)
@@ -169,8 +169,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                         fmt)
         list_network_res = list_network_req.get_response(self.api)
         self.assertEqual(list_network_res.status_int, 200)
-        network_data = self._net_deserializers[content_type].\
-                            deserialize(list_network_res.body)['body']
+        network_data = (self._net_deserializers[content_type].
+                        deserialize(list_network_res.body)['body'])
         # Check network count: should return 2
         self.assertEqual(len(network_data['networks']), 2)
         LOG.debug("_test_list_networks - fmt:%s - END", fmt)
@@ -184,8 +184,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                                fmt)
         list_network_res = list_network_req.get_response(self.api)
         self.assertEqual(list_network_res.status_int, 200)
-        network_data = self._net_deserializers[content_type].\
-                            deserialize(list_network_res.body)['body']
+        network_data = (self._net_deserializers[content_type].
+                        deserialize(list_network_res.body)['body'])
         # Check network count: should return 2
         self.assertEqual(len(network_data['networks']), 2)
         # Check contents - id & name for each network
@@ -259,22 +259,19 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_rename_network - fmt:%s - END", fmt)
 
     def _test_rename_network_badrequest(self, fmt):
-        LOG.debug("_test_rename_network_badrequest - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_rename_network_badrequest - fmt:%s - START", fmt)
         network_id = self._create_network(fmt)
         bad_body = {'network': {'bad-attribute': 'very-bad'}}
-        update_network_req = testlib.\
-                             update_network_request(self.tenant_id,
-                                                    network_id, fmt,
-                                                    custom_req_body=bad_body)
+        update_network_req = testlib.update_network_request(
+            self.tenant_id,
+            network_id, fmt,
+            custom_req_body=bad_body)
         update_network_res = update_network_req.get_response(self.api)
         self.assertEqual(update_network_res.status_int, 400)
-        LOG.debug("_test_rename_network_badrequest - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_rename_network_badrequest - fmt:%s - END", fmt)
 
     def _test_rename_network_not_found(self, fmt):
-        LOG.debug("_test_rename_network_not_found - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_rename_network_not_found - fmt:%s - START", fmt)
         new_name = 'new_network_name'
         update_network_req = testlib.update_network_request(self.tenant_id,
                                                             "A BAD ID",
@@ -283,15 +280,14 @@ class BaseAPIOperationsTest(AbstractAPITest):
         update_network_res = update_network_req.get_response(self.api)
         self.assertEqual(update_network_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_rename_network_not_found - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_rename_network_not_found - fmt:%s - END", fmt)
 
     def _test_delete_network(self, fmt):
         LOG.debug("_test_delete_network - fmt:%s - START", fmt)
         content_type = "application/%s" % fmt
         network_id = self._create_network(fmt)
-        LOG.debug("Deleting network %s"\
-                  " of tenant %s" % (network_id, self.tenant_id))
+        LOG.debug("Deleting network %s of tenant %s" %
+                  (network_id, self.tenant_id))
         delete_network_req = testlib.network_delete_request(self.tenant_id,
                                                             network_id,
                                                             fmt)
@@ -300,8 +296,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
         list_network_req = testlib.network_list_request(self.tenant_id,
                                                         fmt)
         list_network_res = list_network_req.get_response(self.api)
-        network_list_data = self._net_deserializers[content_type].\
-                                 deserialize(list_network_res.body)['body']
+        network_list_data = (self._net_deserializers[content_type].
+                             deserialize(list_network_res.body)['body'])
         network_count = len(network_list_data['networks'])
         self.assertEqual(network_count, 0)
         LOG.debug("_test_delete_network - fmt:%s - END", fmt)
@@ -311,8 +307,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
         port_state = "ACTIVE"
         attachment_id = "test_attachment"
         network_id = self._create_network(fmt)
-        LOG.debug("Deleting network %s"\
-                  " of tenant %s" % (network_id, self.tenant_id))
+        LOG.debug("Deleting network %s of tenant %s" %
+                  (network_id, self.tenant_id))
         port_id = self._create_port(network_id, port_state, fmt)
         #plug an attachment into the port
         LOG.debug("Putting attachment into port %s", port_id)
@@ -323,8 +319,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
         attachment_res = attachment_req.get_response(self.api)
         self.assertEquals(attachment_res.status_int, 204)
 
-        LOG.debug("Deleting network %s"\
-                  " of tenant %s" % (network_id, self.tenant_id))
+        LOG.debug("Deleting network %s of tenant %s" %
+                  (network_id, self.tenant_id))
         delete_network_req = testlib.network_delete_request(self.tenant_id,
                                                             network_id,
                                                             fmt)
@@ -334,23 +330,23 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_delete_network_in_use - fmt:%s - END", fmt)
 
     def _test_delete_network_with_unattached_port(self, fmt):
-        LOG.debug("_test_delete_network_with_unattached_port "\
-                    "- fmt:%s - START", fmt)
+        LOG.debug("_test_delete_network_with_unattached_port "
+                  "- fmt:%s - START", fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
-        LOG.debug("Deleting network %s"\
-                  " of tenant %s" % (network_id, self.tenant_id))
+        LOG.debug("Deleting network %s of tenant %s" %
+                  (network_id, self.tenant_id))
         self._create_port(network_id, port_state, fmt)
 
-        LOG.debug("Deleting network %s"\
-                  " of tenant %s" % (network_id, self.tenant_id))
+        LOG.debug("Deleting network %s of tenant %s" %
+                  (network_id, self.tenant_id))
         delete_network_req = testlib.network_delete_request(self.tenant_id,
                                                             network_id,
                                                             fmt)
         delete_network_res = delete_network_req.get_response(self.api)
         self.assertEqual(delete_network_res.status_int, 204)
-        LOG.debug("_test_delete_network_with_unattached_port "\
-                    "- fmt:%s - END", fmt)
+        LOG.debug("_test_delete_network_with_unattached_port - fmt:%s - END",
+                  fmt)
 
     def _test_list_ports(self, fmt):
         LOG.debug("_test_list_ports - fmt:%s - START", fmt)
@@ -360,11 +356,11 @@ class BaseAPIOperationsTest(AbstractAPITest):
         self._create_port(network_id, port_state, fmt)
         self._create_port(network_id, port_state, fmt)
         list_port_req = testlib.port_list_request(self.tenant_id,
-                                                   network_id, fmt)
+                                                  network_id, fmt)
         list_port_res = list_port_req.get_response(self.api)
         self.assertEqual(list_port_res.status_int, 200)
-        port_data = self._port_deserializers[content_type].\
-                         deserialize(list_port_res.body)['body']
+        port_data = (self._port_deserializers[content_type].
+                     deserialize(list_port_res.body)['body'])
         # Check port count: should return 2
         self.assertEqual(len(port_data['ports']), 2)
         LOG.debug("_test_list_ports - fmt:%s - END", fmt)
@@ -390,8 +386,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                          network_id, fmt)
         list_port_res = list_port_req.get_response(self.api)
         self.assertEqual(list_port_res.status_int, 200)
-        port_data = self._port_deserializers[content_type].\
-                         deserialize(list_port_res.body)['body']
+        port_data = (self._port_deserializers[content_type].
+                     deserialize(list_port_res.body)['body'])
         # Check port count: should return 2
         self.assertEqual(len(port_data['ports']), 2)
         # Check contents - id & name for each network
@@ -425,14 +421,14 @@ class BaseAPIOperationsTest(AbstractAPITest):
         port_id = self._create_port(network_id, port_state, fmt)
 
         # Part 1 - no attachment
-        show_port_req = testlib.show_port_detail_request(self.tenant_id,
-                                    network_id, port_id, fmt)
+        show_port_req = testlib.show_port_detail_request(
+            self.tenant_id, network_id, port_id, fmt)
         show_port_res = show_port_req.get_response(self.api)
         self.assertEqual(show_port_res.status_int, 200)
         port_data = self._deserialize_port_response(content_type,
                                                     show_port_res)
         self.assert_port(id=port_id, state=port_state,
-                        port_data=port_data['port'])
+                         port_data=port_data['port'])
 
         # Part 2 - plug attachment into port
         interface_id = "test_interface"
@@ -443,8 +439,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                             fmt)
         put_attachment_res = put_attachment_req.get_response(self.api)
         self.assertEqual(put_attachment_res.status_int, 204)
-        show_port_req = testlib.show_port_detail_request(self.tenant_id,
-                                    network_id, port_id, fmt)
+        show_port_req = testlib.show_port_detail_request(
+            self.tenant_id, network_id, port_id, fmt)
         show_port_res = show_port_req.get_response(self.api)
         self.assertEqual(show_port_res.status_int, 200)
         port_data = self._deserialize_port_response(content_type,
@@ -456,27 +452,25 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_show_port_detail - fmt:%s - END", fmt)
 
     def _test_show_port_networknotfound(self, fmt):
-        LOG.debug("_test_show_port_networknotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_show_port_networknotfound - fmt:%s - START", fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
         show_port_req = testlib.show_port_request(self.tenant_id,
-                                                        "A_BAD_ID", port_id,
-                                                        fmt)
+                                                  "A_BAD_ID", port_id,
+                                                  fmt)
         show_port_res = show_port_req.get_response(self.api)
         self.assertEqual(show_port_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_show_port_networknotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_show_port_networknotfound - fmt:%s - END", fmt)
 
     def _test_show_port_portnotfound(self, fmt):
         LOG.debug("_test_show_port_portnotfound - fmt:%s - START", fmt)
         network_id = self._create_network(fmt)
         show_port_req = testlib.show_port_request(self.tenant_id,
-                                                        network_id,
-                                                        "A_BAD_ID",
-                                                        fmt)
+                                                  network_id,
+                                                  "A_BAD_ID",
+                                                  fmt)
         show_port_res = show_port_req.get_response(self.api)
         self.assertEqual(show_port_res.status_int,
                          self._port_not_found_code)
@@ -492,8 +486,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                   network_id, port_id, fmt)
         show_port_res = show_port_req.get_response(self.api)
         self.assertEqual(show_port_res.status_int, 200)
-        port_data = self._port_deserializers[content_type].\
-                         deserialize(show_port_res.body)['body']
+        port_data = (self._port_deserializers[content_type].
+                     deserialize(show_port_res.body)['body'])
         self.assertEqual(port_id, port_data['port']['id'])
         LOG.debug("_test_create_port_noreqbody - fmt:%s - END", fmt)
 
@@ -507,19 +501,17 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                   network_id, port_id, fmt)
         show_port_res = show_port_req.get_response(self.api)
         self.assertEqual(show_port_res.status_int, 200)
-        port_data = self._port_deserializers[content_type].\
-                         deserialize(show_port_res.body)['body']
+        port_data = (self._port_deserializers[content_type].
+                     deserialize(show_port_res.body)['body'])
         self.assertEqual(port_id, port_data['port']['id'])
         LOG.debug("_test_create_port - fmt:%s - END", fmt)
 
     def _test_create_port_networknotfound(self, fmt):
-        LOG.debug("_test_create_port_networknotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_create_port_networknotfound - fmt:%s - START", fmt)
         port_state = "ACTIVE"
         self._create_port("A_BAD_ID", port_state, fmt,
                           expected_res_status=self._network_not_found_code)
-        LOG.debug("_test_create_port_networknotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_create_port_networknotfound - fmt:%s - END", fmt)
 
     def _test_create_port_badrequest(self, fmt):
         LOG.debug("_test_create_port_badrequest - fmt:%s - START", fmt)
@@ -544,9 +536,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
-        LOG.debug("Deleting port %s for network %s"\
-                  " of tenant %s" % (port_id, network_id,
-                    self.tenant_id))
+        LOG.debug("Deleting port %s for network %s of tenant %s" %
+                  (port_id, network_id, self.tenant_id))
         delete_port_req = testlib.port_delete_request(self.tenant_id,
                                                       network_id, port_id,
                                                       fmt)
@@ -555,8 +546,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
         list_port_req = testlib.port_list_request(self.tenant_id, network_id,
                                                   fmt)
         list_port_res = list_port_req.get_response(self.api)
-        port_list_data = self._port_deserializers[content_type].\
-                              deserialize(list_port_res.body)['body']
+        port_list_data = (self._port_deserializers[content_type].
+                          deserialize(list_port_res.body)['body'])
         port_count = len(port_list_data['ports'])
         self.assertEqual(port_count, 0)
         LOG.debug("_test_delete_port - fmt:%s - END", fmt)
@@ -575,9 +566,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                         attachment_id)
         attachment_res = attachment_req.get_response(self.api)
         self.assertEquals(attachment_res.status_int, 204)
-        LOG.debug("Deleting port %s for network %s"\
-                  " of tenant %s" % (port_id, network_id,
-                    self.tenant_id))
+        LOG.debug("Deleting port %s for network %s of tenant %s" %
+                  (port_id, network_id, self.tenant_id))
         delete_port_req = testlib.port_delete_request(self.tenant_id,
                                                       network_id, port_id,
                                                       fmt)
@@ -587,8 +577,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_delete_port_in_use - fmt:%s - END", fmt)
 
     def _test_delete_port_with_bad_id(self, fmt):
-        LOG.debug("_test_delete_port_with_bad_id - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_delete_port_with_bad_id - fmt:%s - START", fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         self._create_port(network_id, port_state, fmt)
@@ -602,8 +591,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_delete_port_with_bad_id - fmt:%s - END", fmt)
 
     def _test_delete_port_networknotfound(self, fmt):
-        LOG.debug("_test_delete_port_networknotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_delete_port_networknotfound - fmt:%s - START", fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
@@ -613,8 +601,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         delete_port_res = delete_port_req.get_response(self.api)
         self.assertEqual(delete_port_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_delete_port_networknotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_delete_port_networknotfound - fmt:%s - END", fmt)
 
     def _test_set_port_state(self, fmt):
         LOG.debug("_test_set_port_state - fmt:%s - START", fmt)
@@ -624,9 +611,9 @@ class BaseAPIOperationsTest(AbstractAPITest):
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
         update_port_req = testlib.update_port_request(self.tenant_id,
-                                                        network_id, port_id,
-                                                        new_port_state,
-                                                        fmt)
+                                                      network_id, port_id,
+                                                      new_port_state,
+                                                      fmt)
         update_port_res = update_port_req.get_response(self.api)
         self.assertEqual(update_port_res.status_int, 204)
         show_port_req = testlib.show_port_request(self.tenant_id,
@@ -640,9 +627,9 @@ class BaseAPIOperationsTest(AbstractAPITest):
                          port_data=port_data['port'])
         # now set it back to the original value
         update_port_req = testlib.update_port_request(self.tenant_id,
-                                                        network_id, port_id,
-                                                        port_state,
-                                                        fmt)
+                                                      network_id, port_id,
+                                                      port_state,
+                                                      fmt)
         update_port_res = update_port_req.get_response(self.api)
         self.assertEqual(update_port_res.status_int, 204)
         show_port_req = testlib.show_port_request(self.tenant_id,
@@ -657,56 +644,50 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_set_port_state - fmt:%s - END", fmt)
 
     def _test_set_port_state_networknotfound(self, fmt):
-        LOG.debug("_test_set_port_state_networknotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_set_port_state_networknotfound - fmt:%s - START", fmt)
         port_state = 'DOWN'
         new_port_state = 'ACTIVE'
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
         update_port_req = testlib.update_port_request(self.tenant_id,
-                                                        "A_BAD_ID", port_id,
-                                                        new_port_state,
-                                                        fmt)
+                                                      "A_BAD_ID", port_id,
+                                                      new_port_state,
+                                                      fmt)
         update_port_res = update_port_req.get_response(self.api)
         self.assertEqual(update_port_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_set_port_state_networknotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_set_port_state_networknotfound - fmt:%s - END", fmt)
 
     def _test_set_port_state_portnotfound(self, fmt):
-        LOG.debug("_test_set_port_state_portnotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_set_port_state_portnotfound - fmt:%s - START", fmt)
         port_state = 'DOWN'
         new_port_state = 'ACTIVE'
         network_id = self._create_network(fmt)
         self._create_port(network_id, port_state, fmt)
         update_port_req = testlib.update_port_request(self.tenant_id,
-                                                        network_id,
-                                                        "A_BAD_ID",
-                                                        new_port_state,
-                                                        fmt)
+                                                      network_id,
+                                                      "A_BAD_ID",
+                                                      new_port_state,
+                                                      fmt)
         update_port_res = update_port_req.get_response(self.api)
         self.assertEqual(update_port_res.status_int,
                          self._port_not_found_code)
-        LOG.debug("_test_set_port_state_portnotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_set_port_state_portnotfound - fmt:%s - END", fmt)
 
     def _test_set_port_state_stateinvalid(self, fmt):
-        LOG.debug("_test_set_port_state_stateinvalid - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_set_port_state_stateinvalid - fmt:%s - START", fmt)
         port_state = 'DOWN'
         new_port_state = 'A_BAD_STATE'
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
         update_port_req = testlib.update_port_request(self.tenant_id,
-                                                        network_id, port_id,
-                                                        new_port_state,
-                                                        fmt)
+                                                      network_id, port_id,
+                                                      new_port_state,
+                                                      fmt)
         update_port_res = update_port_req.get_response(self.api)
         self.assertEqual(update_port_res.status_int,
                          self._port_state_invalid_code)
-        LOG.debug("_test_set_port_state_stateinvalid - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_set_port_state_stateinvalid - fmt:%s - END", fmt)
 
     def _test_show_attachment(self, fmt):
         LOG.debug("_test_show_attachment - fmt:%s - START", fmt)
@@ -727,8 +708,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                             port_id,
                                                             fmt)
         get_attachment_res = get_attachment_req.get_response(self.api)
-        attachment_data = self._att_deserializers[content_type].\
-                               deserialize(get_attachment_res.body)['body']
+        attachment_data = (self._att_deserializers[content_type].
+                           deserialize(get_attachment_res.body)['body'])
         self.assertEqual(attachment_data['attachment']['id'], interface_id)
         LOG.debug("_test_show_attachment - fmt:%s - END", fmt)
 
@@ -743,8 +724,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
                                                             port_id,
                                                             fmt)
         get_attachment_res = get_attachment_req.get_response(self.api)
-        attachment_data = self._att_deserializers[content_type].\
-                               deserialize(get_attachment_res.body)['body']
+        attachment_data = (self._att_deserializers[content_type].
+                           deserialize(get_attachment_res.body)['body'])
         self.assertTrue('id' not in attachment_data['attachment'])
         LOG.debug("_test_show_attachment_none_set - fmt:%s - END", fmt)
 
@@ -761,12 +742,10 @@ class BaseAPIOperationsTest(AbstractAPITest):
         get_attachment_res = get_attachment_req.get_response(self.api)
         self.assertEqual(get_attachment_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_show_attachment_networknotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_show_attachment_networknotfound - fmt:%s - END", fmt)
 
     def _test_show_attachment_portnotfound(self, fmt):
-        LOG.debug("_test_show_attachment_portnotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_show_attachment_portnotfound - fmt:%s - START", fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         self._create_port(network_id, port_state, fmt)
@@ -777,8 +756,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         get_attachment_res = get_attachment_req.get_response(self.api)
         self.assertEqual(get_attachment_res.status_int,
                          self._port_not_found_code)
-        LOG.debug("_test_show_attachment_portnotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_show_attachment_portnotfound - fmt:%s - END", fmt)
 
     def _test_put_attachment(self, fmt):
         LOG.debug("_test_put_attachment - fmt:%s - START", fmt)
@@ -796,8 +774,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_put_attachment - fmt:%s - END", fmt)
 
     def _test_put_attachment_networknotfound(self, fmt):
-        LOG.debug("_test_put_attachment_networknotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_put_attachment_networknotfound - fmt:%s - START", fmt)
         port_state = 'DOWN'
         interface_id = "test_interface"
         network_id = self._create_network(fmt)
@@ -810,12 +787,10 @@ class BaseAPIOperationsTest(AbstractAPITest):
         put_attachment_res = put_attachment_req.get_response(self.api)
         self.assertEqual(put_attachment_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_put_attachment_networknotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_put_attachment_networknotfound - fmt:%s - END", fmt)
 
     def _test_put_attachment_portnotfound(self, fmt):
-        LOG.debug("_test_put_attachment_portnotfound - fmt:%s - START",
-                  fmt)
+        LOG.debug("_test_put_attachment_portnotfound - fmt:%s - START", fmt)
         port_state = 'DOWN'
         interface_id = "test_interface"
         network_id = self._create_network(fmt)
@@ -828,8 +803,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         put_attachment_res = put_attachment_req.get_response(self.api)
         self.assertEqual(put_attachment_res.status_int,
                          self._port_not_found_code)
-        LOG.debug("_test_put_attachment_portnotfound - fmt:%s - END",
-                  fmt)
+        LOG.debug("_test_put_attachment_portnotfound - fmt:%s - END", fmt)
 
     def _test_delete_attachment(self, fmt):
         LOG.debug("_test_delete_attachment - fmt:%s - START", fmt)
@@ -853,8 +827,8 @@ class BaseAPIOperationsTest(AbstractAPITest):
         LOG.debug("_test_delete_attachment - fmt:%s - END", fmt)
 
     def _test_delete_attachment_networknotfound(self, fmt):
-        LOG.debug("_test_delete_attachment_networknotfound -" \
-                  " fmt:%s - START", fmt)
+        LOG.debug("_test_delete_attachment_networknotfound - fmt:%s - START",
+                  fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         port_id = self._create_port(network_id, port_state, fmt)
@@ -865,12 +839,11 @@ class BaseAPIOperationsTest(AbstractAPITest):
         del_attachment_res = del_attachment_req.get_response(self.api)
         self.assertEqual(del_attachment_res.status_int,
                          self._network_not_found_code)
-        LOG.debug("_test_delete_attachment_networknotfound -" \
-                  " fmt:%s - END", fmt)
+        LOG.debug("_test_delete_attachment_networknotfound - fmt:%s - END",
+                  fmt)
 
     def _test_delete_attachment_portnotfound(self, fmt):
-        LOG.debug("_test_delete_attachment_portnotfound - " \
-                  " fmt:%s - START", fmt)
+        LOG.debug("_test_delete_attachment_portnotfound - fmt:%s - START", fmt)
         port_state = "ACTIVE"
         network_id = self._create_network(fmt)
         self._create_port(network_id, port_state, fmt)
@@ -881,12 +854,10 @@ class BaseAPIOperationsTest(AbstractAPITest):
         del_attachment_res = del_attachment_req.get_response(self.api)
         self.assertEqual(del_attachment_res.status_int,
                          self._port_not_found_code)
-        LOG.debug("_test_delete_attachment_portnotfound - " \
-                  "fmt:%s - END", fmt)
+        LOG.debug("_test_delete_attachment_portnotfound - fmt:%s - END", fmt)
 
     def _test_unparsable_data(self, fmt):
-        LOG.debug("_test_unparsable_data - " \
-                  " fmt:%s - START", fmt)
+        LOG.debug("_test_unparsable_data - fmt:%s - START", fmt)
 
         data = "this is not json or xml"
         method = 'POST'
@@ -897,12 +868,10 @@ class BaseAPIOperationsTest(AbstractAPITest):
         network_res = network_req.get_response(self.api)
         self.assertEqual(network_res.status_int, 400)
 
-        LOG.debug("_test_unparsable_data - " \
-                  "fmt:%s - END", fmt)
+        LOG.debug("_test_unparsable_data - fmt:%s - END", fmt)
 
     def _test_multitenancy(self, fmt):
-        LOG.debug("_test_multitenancy - " \
-                  " fmt:%s - START", fmt)
+        LOG.debug("_test_multitenancy - fmt:%s - START", fmt)
 
         # creates a network for tenant self.tenant_id
         net_id = self._create_network(fmt)
@@ -947,8 +916,7 @@ class BaseAPIOperationsTest(AbstractAPITest):
         assert_net_not_found(attach_path, 'PUT', fmt)
         assert_net_not_found(attach_path, 'DELETE', fmt)
 
-        LOG.debug("_test_multitenancy - " \
-                  "fmt:%s - END", fmt)
+        LOG.debug("_test_multitenancy - fmt:%s - END", fmt)
 
     def test_list_networks_json(self):
         self._test_list_networks('json')
index e4a4db0f70ffd6dc96675562c849ce7c8e8fb547..f4549108240cc88e3da16b6891add34c01533faf 100644 (file)
@@ -13,7 +13,8 @@
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
-from abc import  abstractmethod
+
+from abc import abstractmethod
 
 from quantum.extensions import extensions
 from quantum import wsgi
index 00c177c15085852c64e6e7e92eefa0e4668bbae0..c43764edf82de4a5c27d8b56582f184478dcadea 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+from abc import  abstractmethod
 import json
 
-from quantum import wsgi
 from quantum.extensions import extensions
-from abc import  abstractmethod
+from quantum import wsgi
 
 
 class FoxInSocksController(wsgi.Controller):
@@ -61,7 +61,7 @@ class Foxinsocks(object):
     def get_resources(self):
         resources = []
         resource = extensions.ResourceExtension('foxnsocks',
-                                               FoxInSocksController())
+                                                FoxInSocksController())
         resources.append(resource)
         return resources
 
@@ -85,7 +85,7 @@ class Foxinsocks(object):
             return res
 
         req_ext1 = extensions.RequestExtension('GET', '/dummy_resources/:(id)',
-                                                _goose_handler)
+                                               _goose_handler)
         request_exts.append(req_ext1)
 
         def _bands_handler(req, res):
@@ -97,7 +97,7 @@ class Foxinsocks(object):
             return res
 
         req_ext2 = extensions.RequestExtension('GET', '/dummy_resources/:(id)',
-                                                _bands_handler)
+                                               _bands_handler)
         request_exts.append(req_ext2)
         return request_exts
 
index 061daeee6cfb804306e93f34b7be68e6a65bcd07..a16783e898af9b101811ff7a4f8dc8a410a79a90 100644 (file)
@@ -18,6 +18,7 @@
 
 from quantum.common import flags
 
+
 FLAGS = flags.FLAGS
 
 flags.DEFINE_integer('runtime_answer', 54, 'test flag')
index 7bdf76ae12bb8f2f37d7ccda77ca70eb7ee985c5..eafeaa43af6d8e1d874aec751a043b91e2b66854 100644 (file)
@@ -19,6 +19,7 @@
 import json
 import logging
 import unittest
+
 from lxml import etree
 from webob import exc, request
 
@@ -26,11 +27,10 @@ import quantum.api.attachments as atts
 import quantum.api.networks as nets
 import quantum.api.ports as ports
 import quantum.api.versions as versions
+from quantum.common.test_lib import test_config
 import quantum.tests.unit._test_api as test_api
 import quantum.tests.unit.testlib_api as testlib
 
-from quantum.common.test_lib import test_config
-
 
 LOG = logging.getLogger('quantum.tests.test_api')
 
@@ -40,7 +40,7 @@ class APITestV10(test_api.BaseAPIOperationsTest):
     def assert_network(self, **kwargs):
         self.assertEqual({'id': kwargs['id'],
                           'name': kwargs['name']},
-                          kwargs['network_data'])
+                         kwargs['network_data'])
 
     def assert_network_details(self, **kwargs):
         self.assertEqual({'id': kwargs['id'],
@@ -60,10 +60,13 @@ class APITestV10(test_api.BaseAPIOperationsTest):
                          kwargs['port_data'])
 
     def setUp(self):
-        super(APITestV10, self).setUp('quantum.api.APIRouterV10',
-             {test_api.NETS: nets.ControllerV10._serialization_metadata,
-              test_api.PORTS: ports.ControllerV10._serialization_metadata,
-              test_api.ATTS: atts.ControllerV10._serialization_metadata})
+        super(APITestV10, self).setUp(
+            'quantum.api.APIRouterV10',
+            {
+                test_api.NETS: nets.ControllerV10._serialization_metadata,
+                test_api.PORTS: ports.ControllerV10._serialization_metadata,
+                test_api.ATTS: atts.ControllerV10._serialization_metadata,
+                })
         self._successful_create_code = exc.HTTPOk.code
         self._network_not_found_code = 420
         self._network_in_use_code = 421
@@ -79,7 +82,7 @@ class APITestV11(test_api.BaseAPIOperationsTest):
         self.assertEqual({'id': kwargs['id'],
                           'name': kwargs['name'],
                           'op-status': self.net_op_status},
-                          kwargs['network_data'])
+                         kwargs['network_data'])
 
     def assert_network_details(self, **kwargs):
         self.assertEqual({'id': kwargs['id'],
@@ -107,10 +110,13 @@ class APITestV11(test_api.BaseAPIOperationsTest):
                                              'UNKNOWN')
         self.port_op_status = test_config.get('default_port_op_status',
                                               'UNKNOWN')
-        super(APITestV11, self).setUp('quantum.api.APIRouterV11',
-             {test_api.NETS: nets.ControllerV11._serialization_metadata,
-              test_api.PORTS: ports.ControllerV11._serialization_metadata,
-              test_api.ATTS: atts.ControllerV11._serialization_metadata})
+        super(APITestV11, self).setUp(
+            'quantum.api.APIRouterV11',
+            {
+                test_api.NETS: nets.ControllerV11._serialization_metadata,
+                test_api.PORTS: ports.ControllerV11._serialization_metadata,
+                test_api.ATTS: atts.ControllerV11._serialization_metadata,
+                })
         self._successful_create_code = exc.HTTPAccepted.code
         self._network_not_found_code = exc.HTTPNotFound.code
         self._network_in_use_code = exc.HTTPConflict.code
@@ -131,8 +137,8 @@ class APIFiltersTest(test_api.AbstractAPITest):
                                                         query_string=flt)
         list_network_res = list_network_req.get_response(self.api)
         self.assertEqual(list_network_res.status_int, 200)
-        network_data = self._net_deserializers[self.content_type].\
-                            deserialize(list_network_res.body)['body']
+        network_data = (self._net_deserializers[self.content_type].
+                        deserialize(list_network_res.body)['body'])
         return network_data
 
     def _do_filtered_port_list_request(self, flt, network_id):
@@ -142,15 +148,18 @@ class APIFiltersTest(test_api.AbstractAPITest):
                                                   query_string=flt)
         list_port_res = list_port_req.get_response(self.api)
         self.assertEqual(list_port_res.status_int, 200)
-        port_data = self._port_deserializers[self.content_type].\
-                            deserialize(list_port_res.body)['body']
+        port_data = (self._port_deserializers[self.content_type].
+                     deserialize(list_port_res.body)['body'])
         return port_data
 
     def setUp(self):
-        super(APIFiltersTest, self).setUp('quantum.api.APIRouterV11',
-             {test_api.NETS: nets.ControllerV11._serialization_metadata,
-              test_api.PORTS: ports.ControllerV11._serialization_metadata,
-              test_api.ATTS: atts.ControllerV11._serialization_metadata})
+        super(APIFiltersTest, self).setUp(
+            'quantum.api.APIRouterV11',
+            {
+                test_api.NETS: nets.ControllerV11._serialization_metadata,
+                test_api.PORTS: ports.ControllerV11._serialization_metadata,
+                test_api.ATTS: atts.ControllerV11._serialization_metadata,
+                })
         self._successful_create_code = exc.HTTPAccepted.code
         self.net_op_status = test_config.get('default_net_op_status',
                                              'UNKNOWN')
@@ -387,7 +396,7 @@ class APIRootTest(unittest.TestCase):
 
     def test_invalid_version(self):
         req = testlib.create_request('/v99.99/tenants/tenantX/networks',
-                                    '',
-                                    'application/json')
+                                     '',
+                                     'application/json')
         response = self.app(req)
         self.assertEquals(response.status_int, 404)
index 81ceb1cbd41199c2d64f5bd4f3538c7e9af875b4..1cc5955757c0eb453fc3415cfbbe9e0a413a2d64 100644 (file)
 test_database.py is an independent test suite
 that tests the database api method calls
 """
+
 import logging
 import unittest
 
-
 from quantum.db import api as db
 from quantum.tests.unit import database_stubs as db_stubs
 
@@ -75,7 +75,7 @@ class QuantumDBTest(unittest.TestCase):
         net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
         self.assertTrue(net1["name"] == "plugin_test1")
         net = self.dbtest.update_network(self.tenant_id, net1["id"],
-          {'name': "plugin_test1_renamed"})
+                                         {'name': "plugin_test1_renamed"})
         print net
         self.assertTrue(net["name"] == "plugin_test1_renamed")
 
index 5a60fb13a1d287b52f7137989bac95c89f2a8bdc..7b4c7e93d88df1f83e38cc9d79e6e965def1a0e1 100644 (file)
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
+
 import json
 import logging
 import os
-import routes
+import sys
 import unittest
-from quantum.tests.unit import BaseTest
-from webtest import TestApp
-from webtest import AppError
 
+import routes
+from webtest import AppError
+from webtest import TestApp
 
-from quantum import wsgi
 from quantum.api import faults
 from quantum.common import config
 from quantum.common import exceptions
 from quantum.extensions import extensions
-import sys
-print sys.path
+from quantum.extensions.extensions import (
+    ExtensionManager,
+    ExtensionMiddleware,
+    PluginAwareExtensionManager,
+    )
 from quantum.plugins.sample.SamplePlugin import QuantumEchoPlugin
-from quantum.tests.unit.extension_stubs import (StubExtension, StubPlugin,
-                                        StubPluginInterface,
-                                        StubBaseAppController,
-                                        ExtensionExpectingPluginInterface)
+from quantum.tests.unit import BaseTest
+from quantum.tests.unit.extension_stubs import (
+    ExtensionExpectingPluginInterface,
+    StubBaseAppController,
+    StubExtension,
+    StubPlugin,
+    StubPluginInterface,
+    )
 import quantum.tests.unit.extensions
-from quantum.extensions.extensions import (ExtensionManager,
-                                       PluginAwareExtensionManager,
-                                       ExtensionMiddleware)
+from quantum import wsgi
+
 
 LOG = logging.getLogger('test_extensions')
+
+
 test_conf_file = config.find_config_file({}, None, "quantum.conf.test")
 extensions_path = ':'.join(quantum.tests.unit.extensions.__path__)
 
@@ -86,16 +94,16 @@ class ResourceExtensionTest(unittest.TestCase):
         # anything that is below 200 or above 400 so we can't actually check
         # it.  It thows AppError instead.
         try:
-            response = \
-                test_app.get("/tweedles/some_id/notimplemented_function")
+            response = (
+                test_app.get("/tweedles/some_id/notimplemented_function"))
             # Shouldn't be reached
             self.assertTrue(False)
         except AppError:
             pass
 
     def test_resource_can_be_added_as_extension(self):
-        res_ext = extensions.ResourceExtension('tweedles',
-                                            self.ResourceExtensionController())
+        res_ext = extensions.ResourceExtension(
+            'tweedles', self.ResourceExtensionController())
         test_app = setup_extensions_test_app(SimpleExtensionManager(res_ext))
         index_response = test_app.get("/tweedles")
         self.assertEqual(200, index_response.status_int)
@@ -208,7 +216,8 @@ class ActionExtensionTest(unittest.TestCase):
         action_params = dict(name='Beetle')
         req_body = json.dumps({action_name: action_params})
         response = self.extension_app.post('/dummy_resources/1/action',
-                                     req_body, content_type='application/json')
+                                           req_body,
+                                           content_type='application/json')
         self.assertEqual("Tweedle Beetle Added.", response.body)
 
     def test_extended_action_for_deleting_extra_data(self):
@@ -216,7 +225,8 @@ class ActionExtensionTest(unittest.TestCase):
         action_params = dict(name='Bailey')
         req_body = json.dumps({action_name: action_params})
         response = self.extension_app.post("/dummy_resources/1/action",
-                                     req_body, content_type='application/json')
+                                           req_body,
+                                           content_type='application/json')
         self.assertEqual("Tweedle Bailey Deleted.", response.body)
 
     def test_returns_404_for_non_existant_action(self):
@@ -225,8 +235,9 @@ class ActionExtensionTest(unittest.TestCase):
         req_body = json.dumps({non_existant_action: action_params})
 
         response = self.extension_app.post("/dummy_resources/1/action",
-                                     req_body, content_type='application/json',
-                                     status='*')
+                                           req_body,
+                                           content_type='application/json',
+                                           status='*')
 
         self.assertEqual(404, response.status_int)
 
@@ -236,7 +247,8 @@ class ActionExtensionTest(unittest.TestCase):
         req_body = json.dumps({action_name: action_params})
 
         response = self.extension_app.post("/asdf/1/action", req_body,
-                                   content_type='application/json', status='*')
+                                           content_type='application/json',
+                                           status='*')
         self.assertEqual(404, response.status_int)
 
 
@@ -253,7 +265,7 @@ class RequestExtensionTest(BaseTest):
                            headers={'X-NEW-REQUEST-HEADER': "sox"})
 
         self.assertEqual(response.headers['X-NEW-RESPONSE-HEADER'],
-                                                   "response_header_data")
+                         "response_header_data")
 
     def test_extend_get_resource_response(self):
         def extend_response_data(req, res):
@@ -296,12 +308,13 @@ class RequestExtensionTest(BaseTest):
         ext_app = self._setup_app_with_request_handler(_update_handler,
                                                             'PUT')
         ext_response = ext_app.put("/dummy_resources/1",
-                                    {'uneditable': "new_value"})
+                                   {'uneditable': "new_value"})
         self.assertEqual(ext_response.json['uneditable'], "new_value")
 
     def _setup_app_with_request_handler(self, handler, verb):
         req_ext = extensions.RequestExtension(verb,
-                                   '/dummy_resources/:(id)', handler)
+                                              '/dummy_resources/:(id)',
+                                              handler)
         manager = SimpleExtensionManager(None, None, req_ext)
         return setup_extensions_test_app(manager)
 
@@ -381,7 +394,7 @@ class PluginAwareExtensionManagerTest(unittest.TestCase):
         ext_mgr = PluginAwareExtensionManager('',
                                               PluginWithExpectedInterface())
         ext_mgr.add_extension(
-                ExtensionExpectingPluginInterface("supported_extension"))
+            ExtensionExpectingPluginInterface("supported_extension"))
 
         self.assertTrue("supported_extension" in ext_mgr.extensions)
 
index 2b9c19fdff0a076926cc727f1cd1668db0bdbebd..7768564d9f035c42e142b2ece4d7c275b75442c6 100644 (file)
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
-import gflags
 import os
 import tempfile
 import unittest
 
+import gflags
+
 from quantum.common import flags
 
+
 FLAGS = flags.FLAGS
 flags.DEFINE_string('flags_unittest', 'foo', 'for testing purposes only')
 
index 651b55512d2e9908439bb82794f5cc47f1d65d33..341a9acb8a2e979b279c8fd65f99cd0deff386eb 100644 (file)
@@ -1,3 +1,18 @@
+# Copyright 2012 OpenStack LLC
+# All Rights Reserved.
+#
+#    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.
+
 from quantum import wsgi
 from quantum.wsgi import Serializer
 
@@ -19,8 +34,8 @@ def _network_list_request(tenant_id, format='xml', detail=False,
                           query_string=None):
     method = 'GET'
     detail_str = detail and '/detail' or ''
-    path = "/tenants/%(tenant_id)s/networks" \
-           "%(detail_str)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks"
+            "%(detail_str)s.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method, query_string)
 
@@ -36,8 +51,8 @@ def network_list_detail_request(tenant_id, format='xml'):
 def _show_network_request(tenant_id, network_id, format='xml', detail=False):
     method = 'GET'
     detail_str = detail and '/detail' or ''
-    path = "/tenants/%(tenant_id)s/networks" \
-           "/%(network_id)s%(detail_str)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks"
+            "/%(network_id)s%(detail_str)s.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method)
 
@@ -63,8 +78,8 @@ def new_network_request(tenant_id, network_name='new_name',
 def update_network_request(tenant_id, network_id, network_name, format='xml',
                            custom_req_body=None):
     method = 'PUT'
-    path = "/tenants/%(tenant_id)s/networks" \
-           "/%(network_id)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks"
+            "/%(network_id)s.%(format)s") % locals()
     data = custom_req_body or {'network': {'name': '%s' % network_name}}
     content_type = "application/%s" % format
     body = Serializer().serialize(data, content_type)
@@ -73,8 +88,8 @@ def update_network_request(tenant_id, network_id, network_name, format='xml',
 
 def network_delete_request(tenant_id, network_id, format='xml'):
     method = 'DELETE'
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method)
 
@@ -83,8 +98,8 @@ def _port_list_request(tenant_id, network_id, format='xml',
                        detail=False, query_string=None):
     method = 'GET'
     detail_str = detail and '/detail' or ''
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s/ports%(detail_str)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s/ports%(detail_str)s.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method, query_string)
 
@@ -105,8 +120,8 @@ def _show_port_request(tenant_id, network_id, port_id,
                        format='xml', detail=False):
     method = 'GET'
     detail_str = detail and '/detail' or ''
-    path = "/tenants/%(tenant_id)s/networks/%(network_id)s" \
-           "/ports/%(port_id)s%(detail_str)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/%(network_id)s"
+            "/ports/%(port_id)s%(detail_str)s.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method)
 
@@ -123,10 +138,10 @@ def show_port_detail_request(tenant_id, network_id, port_id, format='xml'):
 def new_port_request(tenant_id, network_id, port_state,
                      format='xml', custom_req_body=None):
     method = 'POST'
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s/ports.%(format)s" % locals()
-    data = custom_req_body or port_state and \
-           {'port': {'state': '%s' % port_state}}
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s/ports.%(format)s") % locals()
+    data = (custom_req_body or port_state and
+            {'port': {'state': '%s' % port_state}})
     content_type = "application/%s" % format
     body = data and Serializer().serialize(data, content_type)
     return create_request(path, body, content_type, method)
@@ -134,8 +149,8 @@ def new_port_request(tenant_id, network_id, port_state,
 
 def port_delete_request(tenant_id, network_id, port_id, format='xml'):
     method = 'DELETE'
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s/ports/%(port_id)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s/ports/%(port_id)s.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method)
 
@@ -143,8 +158,8 @@ def port_delete_request(tenant_id, network_id, port_id, format='xml'):
 def update_port_request(tenant_id, network_id, port_id, port_state,
                         format='xml', custom_req_body=None):
     method = 'PUT'
-    path = "/tenants/%(tenant_id)s/networks" \
-           "/%(network_id)s/ports/%(port_id)s.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks"
+            "/%(network_id)s/ports/%(port_id)s.%(format)s") % locals()
     data = custom_req_body or {'port': {'state': '%s' % port_state}}
     content_type = "application/%s" % format
     body = Serializer().serialize(data, content_type)
@@ -153,17 +168,19 @@ def update_port_request(tenant_id, network_id, port_id, port_state,
 
 def get_attachment_request(tenant_id, network_id, port_id, format='xml'):
     method = 'GET'
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s/ports/%(port_id)s/attachment.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s/ports/%(port_id)s/"
+            "attachment.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method)
 
 
 def put_attachment_request(tenant_id, network_id, port_id,
-                              attachment_id, format='xml'):
+                           attachment_id, format='xml'):
     method = 'PUT'
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s/ports/%(port_id)s/attachment.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s/ports/%(port_id)s/"
+            "attachment.%(format)s") % locals()
     data = {'attachment': {'id': attachment_id}}
     content_type = "application/%s" % format
     body = Serializer().serialize(data, content_type)
@@ -173,7 +190,8 @@ def put_attachment_request(tenant_id, network_id, port_id,
 def delete_attachment_request(tenant_id, network_id, port_id,
                               attachment_id, format='xml'):
     method = 'DELETE'
-    path = "/tenants/%(tenant_id)s/networks/" \
-           "%(network_id)s/ports/%(port_id)s/attachment.%(format)s" % locals()
+    path = ("/tenants/%(tenant_id)s/networks/"
+            "%(network_id)s/ports/%(port_id)s/"
+            "attachment.%(format)s") % locals()
     content_type = "application/%s" % format
     return create_request(path, None, content_type, method)
index 678391033b4600971a1918ff4a9c968ebfb7bc36..5c4b4565596525e14e72c9618f26a05ee8cc27ad 100644 (file)
@@ -21,19 +21,20 @@ Utility methods for working with WSGI servers
 
 import logging
 import sys
+from xml.dom import minidom
+from xml.parsers import expat
+
 import eventlet.wsgi
 eventlet.patcher.monkey_patch(all=False, socket=True)
+from lxml import etree
 import routes.middleware
 import webob.dec
 import webob.exc
 
-from lxml import etree
-from xml.dom import minidom
-from xml.parsers import expat
-
 from quantum.common import exceptions as exception
 from quantum.common import utils
 
+
 LOG = logging.getLogger('quantum.common.wsgi')
 
 
@@ -308,8 +309,8 @@ class ResponseSerializer(object):
         }
         self.body_serializers.update(body_serializers or {})
 
-        self.headers_serializer = headers_serializer or \
-                                    ResponseHeadersSerializer()
+        self.headers_serializer = (headers_serializer or
+                                   ResponseHeadersSerializer())
 
     def serialize(self, response_data, content_type, action='default'):
         """Serialize a dict into a string and wrap in a wsgi.Request object.