# 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)
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'},
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']))
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')
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'
@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)
@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):
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.'
: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
: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
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'
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']
# 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)
"""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"
"""
_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"
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'
# 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
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']
"""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"
"""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"
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"
# 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)
# 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'),
'/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)
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")
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")
__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__
# 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):
"""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):
def loads(s):
return json.loads(s)
+
TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
FLAGS = flags.FLAGS
# 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:
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):
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):
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:
# @author: Dan Wendlandt, Nicira Networks, Inc.
import logging
+
import sqlalchemy as sql
from sqlalchemy import create_engine
from sqlalchemy.exc import DisconnectionError
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)
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)
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)
# 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):
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)
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])
# 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
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
from quantum.api import api_common as common
+
BASE = declarative_base()
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()
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
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Ying Liu, Cisco Systems, Inc.
#
-"""
def get_view_builder(req):
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']))
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Ying Liu, Cisco Systems, Inc.
#
-"""
+
from quantum.plugins.cisco.common import cisco_constants as const
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Nicira Networks, Inc. All rights reserved.
#
# @author: Brad Hall, Nicira Networks, Inc
#
-"""
def get_view_builder(req):
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Ying Liu, Cisco Systems, Inc.
-#
-"""
def get_view_builder(req):
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'],
+ ))
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Ying Liu, Cisco Systems, Inc.
#
-"""
def get_view_builder(req):
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']))
-"""
# 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')
""" 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": {
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)
""" 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)
""" 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)
# 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')
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
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
"""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())
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
-"""
# 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')
""" 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": {
""" 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)
-"""
# 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):
""" 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": {
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:
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
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:
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
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:
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
-"""
# 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):
-"""
# 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")
""" 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)]
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)
-"""
# 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')
""" 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": {
""" 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)
#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)
""" 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)
# 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):
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()
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
#
-"""
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
-"""
# 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 + \
"""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):
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
"""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,
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)
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'}}}
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():
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:
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
-"""
# 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
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
+
PLUGINS = 'PLUGINS'
INVENTORY = 'INVENTORY'
-"""
# 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 os
import logging as LOG
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)
"""
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")
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")
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
-"""
# 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 webob.dec
from quantum import wsgi
code = 450
title = 'Portprofile Not Found'
explanation = ('Unable to find a Portprofile with'
- + ' the specified identifier.')
+ ' the specified identifier.')
class PortNotFound(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):
code = 452
title = 'QoS Not Found'
explanation = ('Unable to find a QoS with'
- + ' the specified identifier.')
+ ' the specified identifier.')
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):
code = 454
title = 'Multiport Not Found'
explanation = ('Unable to find Multiport with'
- + ' the specified identifier.')
+ ' the specified identifier.')
class RequestedStateInvalid(webob.exc.HTTPClientError):
-"""
# 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__)
-"""
# 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):
-"""
# 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):
-"""
# 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):
-"""
# 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
import logging
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
from quantum.plugins.cisco.db import api as db
from quantum.plugins.cisco.db import l2network_db as cdb
+
LOG = logging.getLogger(__name__)
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,
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
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],
[])
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],
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)
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],
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:
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)
"""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],
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):
-"""
# 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']
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']
-"""
# 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):
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
-"""
# 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 inspect
from quantum.plugins.cisco.common import cisco_constants as const
from quantum.plugins.cisco.common import cisco_exceptions as cexc
+
LOG = logging.getLogger(__name__)
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"""
"""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)
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 = []
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)
# 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)
"""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
"""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
"""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
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"""
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"""
-"""
# 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 inspect
from quantum.plugins.cisco.common import cisco_constants as const
from quantum.plugins.cisco.common import cisco_exceptions as cexc
+
LOG = logging.getLogger(__name__)
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"""
"""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)
"""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)
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"))
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__)
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):
from quantum.plugins.cisco.l2device_plugin_base import L2DevicePluginBase
from quantum.plugins.cisco.nexus import cisco_nexus_configuration as conf
+
LOG = logging.getLogger(__name__)
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))
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)
from quantum.plugins.cisco.common import cisco_constants as const
+
LOG = logging.getLogger(__name__)
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',
help='Default tenant id when creating quantum networks'),
]
+
FLAGS = flags.FLAGS
FLAGS.register_opts(quantum_opts)
"""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,
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
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__)
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
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
#
-"""
-"""
# 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__)
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()
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.")
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:
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)
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")
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
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__":
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)
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'
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__)
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:
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]))
"""
_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
# @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):
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()
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,
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
# 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")
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
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
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='*')
""" 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)
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)
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)
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")
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")
""" 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")
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)
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):
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):
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")
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")
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")
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):
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")
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)
# 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)
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)
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')
""" 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,
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="*")
""" 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)
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):
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)
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")
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")
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")
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)
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='*')
""" 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,
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)
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()
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")
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)
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
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)
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
"""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)
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
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
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)
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)
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)
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)
"""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()
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:
"""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
"""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:
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:
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:
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:
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
"""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:
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()
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
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
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:
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)
-"""
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
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')
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)
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'):
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,
'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):
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")
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])
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)
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]
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)
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])
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")
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,
'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',
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)
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)
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)
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
"""
'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
"""
"""
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)
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
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,
'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,
'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")
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")
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")
"""
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:
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):
"""
"""
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'):
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")
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 = []
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)
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',
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")
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',
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',
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):
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):
-"""
# 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
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():
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
# 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:
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:
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)
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")
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])
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])
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")
# 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')
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,
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)
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")
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)
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")
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)
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")
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):
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")
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")
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")
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")
-"""
# 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'
# 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()
#
# @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):
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):
"""
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])
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):
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])
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)
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]))
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):
"""
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):
"""
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])
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):
"""
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)
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],
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'):
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):
"""
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)
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):
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,
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])
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)
-"""
# 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):
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()
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")
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")
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
#
-"""
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Rohit Agarwalla, Cisco Systems Inc.
#
-"""
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
-"""
# 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']
UCSM_DRIVER = SECTION['name']
CP = confp.CiscoConfigParser(find_config_file({'plugin': 'cisco'}, [],
- 'ucs_inventory.ini'))
+ 'ucs_inventory.ini'))
INVENTORY = CP.walk(CP.dummy)
-"""
# 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:
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):
"""
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)
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:
# 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,
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,
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):
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,
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)
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)
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
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,
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
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]
"""
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]
"""
"""
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,
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):
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):
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
-"""
# 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)
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# @author: Sumit Naiksatam, Cisco Systems Inc.
#
-"""
"""
Implements a UCSM XML API Client
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"
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):
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)
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
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"""
"""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,
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,
-"""
# 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
from quantum.plugins.cisco.l2device_plugin_base import L2DevicePluginBase
from quantum.plugins.cisco.ucs import cisco_ucs_configuration as conf
+
LOG = logging.getLogger(__name__)
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
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):
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
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):
-"""
# 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
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):
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
# 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-"
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))
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
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
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):
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):
"""
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)]):
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
"""
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):
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
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)
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'])
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
from configobj import 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"""
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Cisco Systems, Inc. All rights reserved.
# under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
-#
-"""
+
PORT_STATE = 'port-state'
PORT_UP = "ACTIVE"
"""
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")
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
-"""
# 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
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],
+ }
# 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__)
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))
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 []
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)
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()
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
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()
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 []
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 []
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)
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:
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
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)
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):
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):
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)
-"""
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Cisco Systems, Inc. All rights reserved.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
# @author: Rohit Agarwalla, Cisco Systems, Inc.
-"""
import os
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
# 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]
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],
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]
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],
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]
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)
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],
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)
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 = {}
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]
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]
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")
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))
-"""
# 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):
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)
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)
-'''
# 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)
# 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
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):
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):
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 = []
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):
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)
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
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')
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')]
class NVPCluster(object):
- '''Encapsulates controller connection and api_client.
+ """Encapsulates controller connection and api_client.
Initialized within parse_config().
Accessed within the NvpPlugin class.
There may be some redundancy here, but that has been done to provide
future flexibility.
- '''
+ """
def __init__(self, name):
self._name = name
self.controllers = []
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.
: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])
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):
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,
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.
}
]
: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
with network referenced by net-id
}
:raises:
- '''
+ """
kwargs["controller"] = self.controller
return nvplib.create_network(tenant_id, net_name, **kwargs)
controller=controller)
def delete_network(self, tenant_id, netw_id):
- '''
+ """
Deletes the network with the specified network identifier
belonging to the specified tenant.
}
: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)
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.
}
: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"]
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
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.
}
]
:raises: exception.NetworkNotFound
- '''
+ """
ids = []
filters = kwargs.get("filter_opts") or {}
if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
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:
}
: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
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.
}
: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
: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)
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.
}
: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,
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.
: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):
"""
# 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
class NvpApiClientEventlet(object):
- '''Eventlet-based implementation of NvpApiClient ABC.'''
+ """Eventlet-based implementation of NvpApiClient ABC."""
CONN_IDLE_TIMEOUT = 60 * 15
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).
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
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
# 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)
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):
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()
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
# License for the specific language governing permissions and limitations
# under the License.
-
import httplib
+
import mock
# License for the specific language governing permissions and limitations
# under the License.
-
from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
# 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.
httplib.NOT_FOUND,
httplib.CONFLICT,
httplib.INTERNAL_SERVER_ERROR,
- httplib.SERVICE_UNAVAILABLE
+ httplib.SERVICE_UNAVAILABLE,
]
API_REQUEST_POOL = eventlet.GreenPool(API_REQUEST_POOL_SIZE)
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):
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:
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:
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
# 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
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
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
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)
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
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
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
# 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')
#
# @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)
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))
# 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,
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)
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
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"
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)
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):
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,
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)
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)
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)
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)
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")
# 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):
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>
PORT = <port>
USER = <user>
PASSWORD = <pass>
-''')
+""")
cp = ConfigParser.ConfigParser()
cp.readfp(config)
cluster1, plugin_config = parse_config(cp)
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)
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>
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)
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>
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)
cluster1.controllers[0]['redirects'] == 45)
def test_failover_time(self):
- config = StringIO.StringIO('''
+ config = StringIO.StringIO("""
[DEFAULT]
[NVP]
DEFAULT_TZ_UUID = <default uuid>
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>
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)
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")
"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,
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"]
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"]
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)
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)
# 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):
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
# 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
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
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)
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
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)
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)
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")
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()
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)
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
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"])
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"])
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"])
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"])
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"])
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"])
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",
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"],
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")
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)
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,
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)
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,
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)
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")
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)
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)
-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:
# @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.
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:
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))
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):
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):
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"])
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):
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)
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:
# 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.
: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]
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()
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)
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]
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)
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.
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:
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,
# @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 = []
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
# @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
# @author: Dave Lapsley, Nicira Networks, Inc.
import ConfigParser
-import logging as LOG
+import logging
from optparse import OptionParser
import os
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
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)
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)
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):
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)
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":
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 = []
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):
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
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
# @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'
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()
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,
# 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):
# 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"
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")
# 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__)
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):
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__)
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):
# 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
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)
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__':
# 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")
# 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
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
# 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 = """
from quantum.common import exceptions as exc
from quantum.db import api as db
+
LOG = logging.getLogger('quantum.plugins.sample.SamplePlugin')
"""
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 = []
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
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):
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
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)."""
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]:
# 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
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()
# 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')
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
# 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)
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
# 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)
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"
""" 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']
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,
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,
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)
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)
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
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",
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)
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)
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)
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)
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)
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)
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
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"
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,
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)
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)
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)
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)
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)
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)
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)
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)
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)
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,
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,
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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'
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)
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')
# 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
# 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):
def get_resources(self):
resources = []
resource = extensions.ResourceExtension('foxnsocks',
- FoxInSocksController())
+ FoxInSocksController())
resources.append(resource)
return resources
return res
req_ext1 = extensions.RequestExtension('GET', '/dummy_resources/:(id)',
- _goose_handler)
+ _goose_handler)
request_exts.append(req_ext1)
def _bands_handler(req, res):
return res
req_ext2 = extensions.RequestExtension('GET', '/dummy_resources/:(id)',
- _bands_handler)
+ _bands_handler)
request_exts.append(req_ext2)
return request_exts
from quantum.common import flags
+
FLAGS = flags.FLAGS
flags.DEFINE_integer('runtime_answer', 54, 'test flag')
import json
import logging
import unittest
+
from lxml import etree
from webob import exc, request
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')
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'],
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
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'],
'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
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):
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')
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)
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
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")
# 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__)
# 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)
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):
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):
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)
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)
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):
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)
ext_mgr = PluginAwareExtensionManager('',
PluginWithExpectedInterface())
ext_mgr.add_extension(
- ExtensionExpectingPluginInterface("supported_extension"))
+ ExtensionExpectingPluginInterface("supported_extension"))
self.assertTrue("supported_extension" in ext_mgr.extensions)
# 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')
+# 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
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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')
}
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.