Update codebase for HACKING compliance.

* 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
changes/45/6545/4
Maru Newby 11 years ago
parent f6c71b52e9
commit 6c97b81bf3
  1. 5
      quantum/__init__.py
  2. 18
      quantum/api/__init__.py
  3. 1
      quantum/api/api_common.py
  4. 35
      quantum/api/attachments.py
  5. 17
      quantum/api/faults.py
  6. 73
      quantum/api/networks.py
  7. 57
      quantum/api/ports.py
  8. 22
      quantum/common/config.py
  9. 12
      quantum/common/exceptions.py
  10. 2
      quantum/common/flags.py
  11. 9
      quantum/common/test_lib.py
  12. 28
      quantum/common/utils.py
  13. 73
      quantum/db/api.py
  14. 6
      quantum/db/models.py
  15. 6
      quantum/extensions/_credential_view.py
  16. 3
      quantum/extensions/_novatenant_view.py
  17. 2
      quantum/extensions/_portstats_view.py
  18. 21
      quantum/extensions/_pprofiles.py
  19. 6
      quantum/extensions/_qos_view.py
  20. 50
      quantum/extensions/credential.py
  21. 36
      quantum/extensions/extensions.py
  22. 37
      quantum/extensions/multiport.py
  23. 54
      quantum/extensions/novatenant.py
  24. 8
      quantum/extensions/portprofile.py
  25. 19
      quantum/extensions/portstats.py
  26. 47
      quantum/extensions/qos.py
  27. 23
      quantum/manager.py
  28. 2
      quantum/plugins/cisco/__init__.py
  29. 3
      quantum/plugins/cisco/client/__init__.py
  30. 88
      quantum/plugins/cisco/client/cli.py
  31. 3
      quantum/plugins/cisco/common/__init__.py
  32. 4
      quantum/plugins/cisco/common/cisco_configparser.py
  33. 4
      quantum/plugins/cisco/common/cisco_constants.py
  34. 6
      quantum/plugins/cisco/common/cisco_credentials.py
  35. 60
      quantum/plugins/cisco/common/cisco_exceptions.py
  36. 14
      quantum/plugins/cisco/common/cisco_faults.py
  37. 7
      quantum/plugins/cisco/common/cisco_utils.py
  38. 5
      quantum/plugins/cisco/l2device_inventory_base.py
  39. 5
      quantum/plugins/cisco/l2device_plugin_base.py
  40. 5
      quantum/plugins/cisco/l2network_model_base.py
  41. 36
      quantum/plugins/cisco/l2network_plugin.py
  42. 19
      quantum/plugins/cisco/l2network_plugin_configuration.py
  43. 5
      quantum/plugins/cisco/l2network_segmentation_base.py
  44. 3
      quantum/plugins/cisco/models/__init__.py
  45. 47
      quantum/plugins/cisco/models/l2network_multi_blade.py
  46. 20
      quantum/plugins/cisco/models/l2network_single_blade.py
  47. 1
      quantum/plugins/cisco/nexus/cisco_nexus_configuration.py
  48. 5
      quantum/plugins/cisco/nexus/cisco_nexus_network_driver.py
  49. 13
      quantum/plugins/cisco/nexus/cisco_nexus_plugin.py
  50. 1
      quantum/plugins/cisco/nexus/cisco_nexus_snippets.py
  51. 29
      quantum/plugins/cisco/nova/quantum_port_aware_scheduler.py
  52. 2
      quantum/plugins/cisco/nova/vifdirect.py
  53. 3
      quantum/plugins/cisco/run_tests.py
  54. 2
      quantum/plugins/cisco/segmentation/__init__.py
  55. 8
      quantum/plugins/cisco/segmentation/l2network_vlan_mgr.py
  56. 94
      quantum/plugins/cisco/services/service_insertion.py
  57. 3
      quantum/plugins/cisco/services/services_constants.py
  58. 13
      quantum/plugins/cisco/services/services_logistics.py
  59. 602
      quantum/plugins/cisco/tests/unit/test_cisco_extension.py
  60. 137
      quantum/plugins/cisco/tests/unit/test_database.py
  61. 323
      quantum/plugins/cisco/tests/unit/test_l2networkApi.py
  62. 68
      quantum/plugins/cisco/tests/unit/test_l2network_multi_blade.py
  63. 45
      quantum/plugins/cisco/tests/unit/test_nexus_plugin.py
  64. 112
      quantum/plugins/cisco/tests/unit/test_ucs_driver.py
  65. 19
      quantum/plugins/cisco/tests/unit/test_ucs_inventory.py
  66. 323
      quantum/plugins/cisco/tests/unit/test_ucs_plugin.py
  67. 27
      quantum/plugins/cisco/tests/unit/test_vlan_mgr.py
  68. 2
      quantum/plugins/cisco/ucs/__init__.py
  69. 26
      quantum/plugins/cisco/ucs/cisco_getvif.py
  70. 8
      quantum/plugins/cisco/ucs/cisco_ucs_configuration.py
  71. 308
      quantum/plugins/cisco/ucs/cisco_ucs_inventory.py
  72. 4
      quantum/plugins/cisco/ucs/cisco_ucs_inventory_configuration.py
  73. 80
      quantum/plugins/cisco/ucs/cisco_ucs_network_driver.py
  74. 59
      quantum/plugins/cisco/ucs/cisco_ucs_plugin.py
  75. 16
      quantum/plugins/linuxbridge/LinuxBridgePlugin.py
  76. 61
      quantum/plugins/linuxbridge/agent/linuxbridge_quantum_agent.py
  77. 3
      quantum/plugins/linuxbridge/common/__init__.py
  78. 5
      quantum/plugins/linuxbridge/common/configparser.py
  79. 4
      quantum/plugins/linuxbridge/common/constants.py
  80. 24
      quantum/plugins/linuxbridge/common/exceptions.py
  81. 23
      quantum/plugins/linuxbridge/common/utils.py
  82. 93
      quantum/plugins/linuxbridge/db/l2network_db.py
  83. 8
      quantum/plugins/linuxbridge/db/l2network_models.py
  84. 2
      quantum/plugins/linuxbridge/plugin_configuration.py
  85. 3
      quantum/plugins/linuxbridge/run_tests.py
  86. 239
      quantum/plugins/linuxbridge/tests/unit/_test_linuxbridgeAgent.py
  87. 18
      quantum/plugins/linuxbridge/tests/unit/test_database.py
  88. 46
      quantum/plugins/nicira/nicira_nvp_plugin/NvpApiClient.py
  89. 171
      quantum/plugins/nicira/nicira_nvp_plugin/QuantumPlugin.py
  90. 62
      quantum/plugins/nicira/nicira_nvp_plugin/api_client/client_eventlet.py
  91. 2
      quantum/plugins/nicira/nicira_nvp_plugin/api_client/common.py
  92. 1
      quantum/plugins/nicira/nicira_nvp_plugin/api_client/request.py
  93. 73
      quantum/plugins/nicira/nicira_nvp_plugin/api_client/request_eventlet.py
  94. 11
      quantum/plugins/nicira/nicira_nvp_plugin/cli.py
  95. 66
      quantum/plugins/nicira/nicira_nvp_plugin/nvplib.py
  96. 0
      quantum/plugins/nicira/nicira_nvp_plugin/tests/__init__.py
  97. 5
      quantum/plugins/nicira/nicira_nvp_plugin/tests/test_check.py
  98. 44
      quantum/plugins/nicira/nicira_nvp_plugin/tests/test_config.py
  99. 24
      quantum/plugins/nicira/nicira_nvp_plugin/tests/test_network.py
  100. 5
      quantum/plugins/nicira/nicira_nvp_plugin/tests/test_nvp_api_common.py
  101. Some files were not shown because too many files have changed in this diff Show More

@ -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)

@ -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']))

@ -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')

@ -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):

@ -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

@ -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"

@ -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"

@ -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)

@ -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")

@ -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__

@ -37,15 +37,14 @@
# 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):

@ -20,27 +20,28 @@
"""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:

@ -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

@ -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

@ -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']))

@ -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

@ -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):

@ -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'],
))

@ -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']))

@ -1,4 +1,3 @@
"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
@ -16,18 +15,19 @@
# 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)

@ -16,20 +16,22 @@
# 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

@ -1,4 +1,3 @@
"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
@ -16,18 +15,19 @@
# 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):