Fix H302 violations in plugins package

H302 violation is reported by flake8 when importing separated objects from
modules instead of importing the whole module.
e.g.   from package.module import function
       function()
is changed to
       from package import module
       module.function()

Change-Id: I83372124f4fba7b94bbfb4a56a0c0ef779ee237f
Partial-Bug: #1291032
This commit is contained in:
Jakub Libosvar 2014-04-18 15:29:49 +02:00
parent c2634fa580
commit 1a116d24a9
49 changed files with 537 additions and 537 deletions

View File

@ -88,7 +88,7 @@ from neutron.plugins.bigswitch.db import porttracker_db
from neutron.plugins.bigswitch import extensions from neutron.plugins.bigswitch import extensions
from neutron.plugins.bigswitch import routerrule_db from neutron.plugins.bigswitch import routerrule_db
from neutron.plugins.bigswitch import servermanager from neutron.plugins.bigswitch import servermanager
from neutron.plugins.bigswitch.version import version_string_with_vcs from neutron.plugins.bigswitch import version
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -474,7 +474,7 @@ class NeutronRestProxyV2(NeutronRestProxyV2Base,
def __init__(self, server_timeout=None): def __init__(self, server_timeout=None):
super(NeutronRestProxyV2, self).__init__() super(NeutronRestProxyV2, self).__init__()
LOG.info(_('NeutronRestProxy: Starting plugin. Version=%s'), LOG.info(_('NeutronRestProxy: Starting plugin. Version=%s'),
version_string_with_vcs()) version.version_string_with_vcs())
pl_config.register_config() pl_config.register_config()
self.evpool = eventlet.GreenPool(cfg.CONF.RESTPROXY.thread_pool_size) self.evpool = eventlet.GreenPool(cfg.CONF.RESTPROXY.thread_pool_size)

View File

@ -27,8 +27,8 @@ from __future__ import print_function
import json import json
import re import re
from six.moves import xrange from six import moves
from wsgiref.simple_server import make_server from wsgiref import simple_server
class TestNetworkCtrl(object): class TestNetworkCtrl(object):
@ -93,7 +93,7 @@ class TestNetworkCtrl(object):
def request_handler(self, method, uri, body): def request_handler(self, method, uri, body):
retstatus = self.default_status retstatus = self.default_status
retbody = self.default_response retbody = self.default_response
for i in xrange(len(self.matches)): for i in moves.xrange(len(self.matches)):
(prior, method_regexp, uri_regexp, handler, data, multi) = \ (prior, method_regexp, uri_regexp, handler, data, multi) = \
self.matches[i] self.matches[i]
if re.match(method_regexp, method) and re.match(uri_regexp, uri): if re.match(method_regexp, method) and re.match(uri_regexp, uri):
@ -156,7 +156,7 @@ class TestNetworkCtrl(object):
print('%s: %s' % ('Response', print('%s: %s' % ('Response',
json.dumps(body_data, sort_keys=True, indent=4))) json.dumps(body_data, sort_keys=True, indent=4)))
return body return body
return make_server(self.host, self.port, app) return simple_server.make_server(self.host, self.port, app)
def run(self): def run(self):
print("Serving on port %d ..." % self.port) print("Serving on port %d ..." % self.port)

View File

@ -22,39 +22,27 @@
"""Determine version of NeutronRestProxy plugin""" """Determine version of NeutronRestProxy plugin"""
from __future__ import print_function from __future__ import print_function
# if vcsversion exists, use it. Else, use LOCALBRANCH:LOCALREVISION from neutron.plugins.bigswitch import vcsversion
try:
from neutron.plugins.bigswitch.vcsversion import version_info
except ImportError:
version_info = {'branch_nick': u'LOCALBRANCH',
'revision_id': u'LOCALREVISION',
'revno': 0}
try:
from neutron.plugins.bigswitch.vcsversion import NeutronRestPROXY_VERSION
except ImportError:
NeutronRestPROXY_VERSION = ['2013', '1', None]
try:
from neutron.plugins.bigswitch.vcsversion import FINAL
except ImportError:
FINAL = False # This becomes true at Release Candidate time
YEAR, COUNT, REVISION = NeutronRestPROXY_VERSION YEAR, COUNT, REVISION = vcsversion.NEUTRONRESTPROXY_VERSION
def canonical_version_string(): def canonical_version_string():
return '.'.join(filter(None, NeutronRestPROXY_VERSION)) return '.'.join(filter(None,
vcsversion.NEUTRONRESTPROXY_VERSION))
def version_string(): def version_string():
if FINAL: if vcsversion.FINAL:
return canonical_version_string() return canonical_version_string()
else: else:
return '%s-dev' % (canonical_version_string(),) return '%s-dev' % (canonical_version_string(),)
def vcs_version_string(): def vcs_version_string():
return "%s:%s" % (version_info['branch_nick'], version_info['revision_id']) return "%s:%s" % (vcsversion.version_info['branch_nick'],
vcsversion.version_info['revision_id'])
def version_string_with_vcs(): def version_string_with_vcs():

View File

@ -21,7 +21,7 @@
"""A Vlan Bitmap class to handle allocation/de-allocation of vlan ids.""" """A Vlan Bitmap class to handle allocation/de-allocation of vlan ids."""
from six.moves import xrange from six import moves
from neutron.common import constants from neutron.common import constants
from neutron.plugins.brocade.db import models as brocade_db from neutron.plugins.brocade.db import models as brocade_db
@ -49,7 +49,7 @@ class VlanBitmap(object):
min_vlan_search = vlan_id or MIN_VLAN min_vlan_search = vlan_id or MIN_VLAN
max_vlan_search = (vlan_id and vlan_id + 1) or MAX_VLAN max_vlan_search = (vlan_id and vlan_id + 1) or MAX_VLAN
for vlan in xrange(min_vlan_search, max_vlan_search): for vlan in moves.xrange(min_vlan_search, max_vlan_search):
if vlan not in self.vlans: if vlan not in self.vlans:
self.vlans.add(vlan) self.vlans.add(vlan)
return vlan return vlan

View File

@ -22,7 +22,7 @@ from webob import exc
from neutron.api import api_common as common from neutron.api import api_common as common
from neutron.api import extensions from neutron.api import extensions
from neutron.manager import NeutronManager from neutron import manager
from neutron.plugins.cisco.common import cisco_exceptions as exception from neutron.plugins.cisco.common import cisco_exceptions as exception
from neutron.plugins.cisco.common import cisco_faults as faults from neutron.plugins.cisco.common import cisco_faults as faults
from neutron.plugins.cisco.extensions import _qos_view as qos_view from neutron.plugins.cisco.extensions import _qos_view as qos_view
@ -63,7 +63,7 @@ class Qos(extensions.ExtensionDescriptor):
parent_resource = dict(member_name="tenant", parent_resource = dict(member_name="tenant",
collection_name="extensions/csco/tenants") collection_name="extensions/csco/tenants")
controller = QosController(NeutronManager.get_plugin()) controller = QosController(manager.NeutronManager.get_plugin())
return [extensions.ResourceExtension('qoss', controller, return [extensions.ResourceExtension('qoss', controller,
parent=parent_resource)] parent=parent_resource)]

View File

@ -33,13 +33,13 @@ from neutron.plugins.cisco.common import cisco_exceptions as cisco_exc
from neutron.plugins.cisco.common import config as conf from neutron.plugins.cisco.common import config as conf
from neutron.plugins.cisco.db import network_db_v2 as cdb from neutron.plugins.cisco.db import network_db_v2 as cdb
from neutron.plugins.cisco.db import nexus_db_v2 as nxos_db from neutron.plugins.cisco.db import nexus_db_v2 as nxos_db
from neutron.plugins.cisco.l2device_plugin_base import L2DevicePluginBase from neutron.plugins.cisco import l2device_plugin_base
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
class NexusPlugin(L2DevicePluginBase): class NexusPlugin(l2device_plugin_base.L2DevicePluginBase):
"""Nexus PlugIn Main Class.""" """Nexus PlugIn Main Class."""
_networks = {} _networks = {}

View File

@ -17,7 +17,7 @@
# #
# @author: Ivar Lazzaro, Embrane, Inc. # @author: Ivar Lazzaro, Embrane, Inc.
from functools import wraps import functools
from heleosapi import exceptions as h_exc from heleosapi import exceptions as h_exc
@ -36,7 +36,7 @@ def handler(event, handler):
else: else:
handler[event].append(f) handler[event].append(f)
@wraps(f) @functools.wraps(f)
def wrapped_f(*args, **kwargs): def wrapped_f(*args, **kwargs):
return f(*args, **kwargs) return f(*args, **kwargs)
return wrapped_f return wrapped_f

View File

@ -16,7 +16,7 @@
# under the License. # under the License.
# @author: Alessandro Pilotti, Cloudbase Solutions Srl # @author: Alessandro Pilotti, Cloudbase Solutions Srl
from six.moves import xrange from six import moves
from sqlalchemy.orm import exc from sqlalchemy.orm import exc
from neutron.common import exceptions as n_exc from neutron.common import exceptions as n_exc
@ -201,7 +201,8 @@ class HyperVPluginDB(object):
# physical network # physical network
vlan_ids = set() vlan_ids = set()
for vlan_range in vlan_ranges: for vlan_range in vlan_ranges:
vlan_ids |= set(xrange(vlan_range[0], vlan_range[1] + 1)) vlan_ids |= set(moves.xrange(vlan_range[0],
vlan_range[1] + 1))
# remove from table unallocated vlans not currently allocatable # remove from table unallocated vlans not currently allocatable
self._remove_non_allocatable_vlans(session, self._remove_non_allocatable_vlans(session,

View File

@ -18,7 +18,7 @@
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from neutron.db.models_v2 import model_base from neutron.db import model_base
class VlanAllocation(model_base.BASEV2): class VlanAllocation(model_base.BASEV2):

View File

@ -28,7 +28,7 @@ from neutron.api.v2 import attributes
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
from neutron.plugins.ibm.common import config # noqa from neutron.plugins.ibm.common import config # noqa
from neutron.plugins.ibm.common import constants from neutron.plugins.ibm.common import constants
from neutron.wsgi import Serializer from neutron import wsgi
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -92,7 +92,7 @@ class RequestHandler(object):
'''Serializes a dictionary with a single key.''' '''Serializes a dictionary with a single key.'''
if isinstance(data, dict): if isinstance(data, dict):
return Serializer().serialize(data, self.content_type()) return wsgi.Serializer().serialize(data, self.content_type())
elif data: elif data:
raise TypeError(_("unable to serialize object type: '%s'") % raise TypeError(_("unable to serialize object type: '%s'") %
type(data)) type(data))
@ -106,7 +106,7 @@ class RequestHandler(object):
if status_code == httplib.NO_CONTENT: if status_code == httplib.NO_CONTENT:
return data return data
try: try:
deserialized_data = Serializer( deserialized_data = wsgi.Serializer(
metadata=self._s_meta).deserialize(data, self.content_type()) metadata=self._s_meta).deserialize(data, self.content_type())
deserialized_data = deserialized_data['body'] deserialized_data = deserialized_data['body']
except Exception: except Exception:

View File

@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from six.moves import xrange from six import moves
from sqlalchemy.orm import exc from sqlalchemy.orm import exc
from neutron.common import exceptions as n_exc from neutron.common import exceptions as n_exc
@ -49,7 +49,7 @@ def sync_network_states(network_vlan_ranges):
# physical network # physical network
vlan_ids = set() vlan_ids = set()
for vlan_range in vlan_ranges: for vlan_range in vlan_ranges:
vlan_ids |= set(xrange(vlan_range[0], vlan_range[1] + 1)) vlan_ids |= set(moves.xrange(vlan_range[0], vlan_range[1] + 1))
# remove from table unallocated vlans not currently allocatable # remove from table unallocated vlans not currently allocatable
if physical_network in allocations: if physical_network in allocations:

View File

@ -26,7 +26,7 @@ from neutron import context as ctx
from neutron.extensions import portbindings from neutron.extensions import portbindings
from neutron.openstack.common import log from neutron.openstack.common import log
from neutron.plugins.bigswitch import config as pl_config from neutron.plugins.bigswitch import config as pl_config
from neutron.plugins.bigswitch.plugin import NeutronRestProxyV2Base from neutron.plugins.bigswitch import plugin
from neutron.plugins.bigswitch import servermanager from neutron.plugins.bigswitch import servermanager
from neutron.plugins.ml2 import driver_api as api from neutron.plugins.ml2 import driver_api as api
@ -34,7 +34,7 @@ from neutron.plugins.ml2 import driver_api as api
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
class BigSwitchMechanismDriver(NeutronRestProxyV2Base, class BigSwitchMechanismDriver(plugin.NeutronRestProxyV2Base,
api.MechanismDriver): api.MechanismDriver):
"""Mechanism Driver for Big Switch Networks Controller. """Mechanism Driver for Big Switch Networks Controller.

View File

@ -14,7 +14,7 @@
# under the License. # under the License.
from oslo.config import cfg from oslo.config import cfg
from six.moves import xrange from six import moves
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy.orm import exc as sa_exc from sqlalchemy.orm import exc as sa_exc
@ -139,7 +139,7 @@ class GreTypeDriver(type_tunnel.TunnelTypeDriver):
"%(tun_min)s:%(tun_max)s"), "%(tun_min)s:%(tun_max)s"),
{'tun_min': tun_min, 'tun_max': tun_max}) {'tun_min': tun_min, 'tun_max': tun_max})
else: else:
gre_ids |= set(xrange(tun_min, tun_max + 1)) gre_ids |= set(moves.xrange(tun_min, tun_max + 1))
session = db_api.get_session() session = db_api.get_session()
with session.begin(subtransactions=True): with session.begin(subtransactions=True):

View File

@ -16,7 +16,7 @@
import sys import sys
from oslo.config import cfg from oslo.config import cfg
from six.moves import xrange from six import moves
import sqlalchemy as sa import sqlalchemy as sa
from neutron.common import constants as q_const from neutron.common import constants as q_const
@ -112,7 +112,7 @@ class VlanTypeDriver(api.TypeDriver):
# this physical network # this physical network
vlan_ids = set() vlan_ids = set()
for vlan_min, vlan_max in vlan_ranges: for vlan_min, vlan_max in vlan_ranges:
vlan_ids |= set(xrange(vlan_min, vlan_max + 1)) vlan_ids |= set(moves.xrange(vlan_min, vlan_max + 1))
# remove from table unallocated vlans not currently # remove from table unallocated vlans not currently
# allocatable # allocatable

View File

@ -18,7 +18,7 @@
from neutron.openstack.common import importutils from neutron.openstack.common import importutils
from neutron.openstack.common import jsonutils from neutron.openstack.common import jsonutils
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
from neutron.plugins.mlnx.common.comm_utils import RetryDecorator from neutron.plugins.mlnx.common import comm_utils
from neutron.plugins.mlnx.common import exceptions from neutron.plugins.mlnx.common import exceptions
zmq = importutils.try_import('eventlet.green.zmq') zmq = importutils.try_import('eventlet.green.zmq')
@ -49,7 +49,7 @@ class EswitchUtils(object):
self.poller.register(self._conn, zmq.POLLIN) self.poller.register(self._conn, zmq.POLLIN)
return self.__conn return self.__conn
@RetryDecorator(exceptions.RequestTimeout) @comm_utils.RetryDecorator(exceptions.RequestTimeout)
def send_msg(self, msg): def send_msg(self, msg):
self._conn.send(msg) self._conn.send(msg)

View File

@ -15,7 +15,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from six.moves import xrange from six import moves
from sqlalchemy.orm import exc from sqlalchemy.orm import exc
from neutron.common import exceptions as n_exc from neutron.common import exceptions as n_exc
@ -87,7 +87,7 @@ def sync_network_states(network_vlan_ranges):
# physical network # physical network
vlan_ids = set() vlan_ids = set()
for vlan_range in vlan_ranges: for vlan_range in vlan_ranges:
vlan_ids |= set(xrange(vlan_range[0], vlan_range[1] + 1)) vlan_ids |= set(moves.xrange(vlan_range[0], vlan_range[1] + 1))
# remove from table unallocated vlans not currently allocatable # remove from table unallocated vlans not currently allocatable
_remove_non_allocatable_vlans(session, allocations, _remove_non_allocatable_vlans(session, allocations,

View File

@ -25,7 +25,7 @@ from neutron.api.v2 import attributes
from neutron.api.v2 import base from neutron.api.v2 import base
from neutron.common import constants from neutron.common import constants
from neutron.common import exceptions from neutron.common import exceptions
from neutron.manager import NeutronManager from neutron import manager
from neutron import quota from neutron import quota
@ -195,7 +195,7 @@ class Packetfilter(extensions.ExtensionDescriptor):
quota.QUOTAS.register_resource(qresource) quota.QUOTAS.register_resource(qresource)
resource = base.create_resource(COLLECTION, RESOURCE, resource = base.create_resource(COLLECTION, RESOURCE,
NeutronManager.get_plugin(), manager.NeutronManager.get_plugin(),
PACKET_FILTER_ATTR_PARAMS) PACKET_FILTER_ATTR_PARAMS)
pf_ext = extensions.ResourceExtension( pf_ext = extensions.ResourceExtension(
COLLECTION, resource, attr_map=PACKET_FILTER_ATTR_PARAMS) COLLECTION, resource, attr_map=PACKET_FILTER_ATTR_PARAMS)

View File

@ -14,7 +14,7 @@
# #
# @author: Ronak Shah, Nuage Networks, Alcatel-Lucent USA Inc. # @author: Ronak Shah, Nuage Networks, Alcatel-Lucent USA Inc.
from abc import abstractmethod import abc
from neutron.api import extensions from neutron.api import extensions
from neutron.api.v2 import base from neutron.api.v2 import base
@ -86,22 +86,22 @@ class Netpartition(object):
class NetPartitionPluginBase(object): class NetPartitionPluginBase(object):
@abstractmethod @abc.abstractmethod
def create_net_partition(self, context, router): def create_net_partition(self, context, router):
pass pass
@abstractmethod @abc.abstractmethod
def update_net_partition(self, context, id, router): def update_net_partition(self, context, id, router):
pass pass
@abstractmethod @abc.abstractmethod
def get_net_partition(self, context, id, fields=None): def get_net_partition(self, context, id, fields=None):
pass pass
@abstractmethod @abc.abstractmethod
def delete_net_partition(self, context, id): def delete_net_partition(self, context, id):
pass pass
@abstractmethod @abc.abstractmethod
def get_net_partitions(self, context, filters=None, fields=None): def get_net_partitions(self, context, filters=None, fields=None):
pass pass

View File

@ -18,10 +18,10 @@
import httplib import httplib
import time import time
from urlparse import urljoin
from oslo.config import cfg from oslo.config import cfg
import requests import requests
from six.moves.urllib import parse
from neutron.openstack.common import jsonutils as json from neutron.openstack.common import jsonutils as json
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
@ -65,8 +65,8 @@ class NVSDController(object):
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
login_url = urljoin(self.api_url, login_url = parse.urljoin(self.api_url,
"/pluginhandler/ocplugin/authmgmt/login") "/pluginhandler/ocplugin/authmgmt/login")
data = json.dumps({"user_name": self._user, "passwd": self._password}) data = json.dumps({"user_name": self._user, "passwd": self._password})
@ -114,9 +114,9 @@ class NVSDController(object):
headers = {"Content-Type": content_type} headers = {"Content-Type": content_type}
uri = urljoin(url, "?authToken=%s" % self.auth_token) uri = parse.urljoin(url, "?authToken=%s" % self.auth_token)
url = urljoin(self.api_url, uri) url = parse.urljoin(self.api_url, uri)
request_ok = False request_ok = False
response = None response = None

View File

@ -21,7 +21,7 @@ import time
import eventlet import eventlet
import netaddr import netaddr
from oslo.config import cfg from oslo.config import cfg
from six.moves import xrange from six import moves
from neutron.agent import l2population_rpc from neutron.agent import l2population_rpc
from neutron.agent.linux import ip_lib from neutron.agent.linux import ip_lib
@ -173,8 +173,8 @@ class OVSNeutronAgent(sg_rpc.SecurityGroupAgentRpcCallbackMixin,
''' '''
self.veth_mtu = veth_mtu self.veth_mtu = veth_mtu
self.root_helper = root_helper self.root_helper = root_helper
self.available_local_vlans = set(xrange(q_const.MIN_VLAN_TAG, self.available_local_vlans = set(moves.xrange(q_const.MIN_VLAN_TAG,
q_const.MAX_VLAN_TAG)) q_const.MAX_VLAN_TAG))
self.tunnel_types = tunnel_types or [] self.tunnel_types = tunnel_types or []
self.l2_pop = l2_population self.l2_pop = l2_population
self.agent_state = { self.agent_state = {

View File

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from six.moves import xrange from six import moves
from sqlalchemy import func from sqlalchemy import func
from sqlalchemy.orm import exc from sqlalchemy.orm import exc
@ -72,7 +72,7 @@ def sync_vlan_allocations(network_vlan_ranges):
# physical network # physical network
vlan_ids = set() vlan_ids = set()
for vlan_range in vlan_ranges: for vlan_range in vlan_ranges:
vlan_ids |= set(xrange(vlan_range[0], vlan_range[1] + 1)) vlan_ids |= set(moves.xrange(vlan_range[0], vlan_range[1] + 1))
# remove from table unallocated vlans not currently allocatable # remove from table unallocated vlans not currently allocatable
if physical_network in allocations: if physical_network in allocations:
@ -211,7 +211,7 @@ def sync_tunnel_allocations(tunnel_id_ranges):
"%(tun_min)s:%(tun_max)s"), "%(tun_min)s:%(tun_max)s"),
{'tun_min': tun_min, 'tun_max': tun_max}) {'tun_min': tun_min, 'tun_max': tun_max})
else: else:
tunnel_ids |= set(xrange(tun_min, tun_max + 1)) tunnel_ids |= set(moves.xrange(tun_min, tun_max + 1))
session = db.get_session() session = db.get_session()
with session.begin(): with session.begin():
@ -371,7 +371,7 @@ def add_tunnel_endpoint(ip, max_retries=10):
# doesn't conflict with any other concurrently executed # doesn't conflict with any other concurrently executed
# DB transactions in spite of the specified transactions # DB transactions in spite of the specified transactions
# isolation level value # isolation level value
for i in xrange(max_retries): for i in moves.xrange(max_retries):
LOG.debug(_('Adding a tunnel endpoint for %s'), ip) LOG.debug(_('Adding a tunnel endpoint for %s'), ip)
try: try:
session = db.get_session() session = db.get_session()

View File

@ -17,8 +17,8 @@
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.schema import UniqueConstraint from sqlalchemy.schema import UniqueConstraint
from neutron.db import model_base
from neutron.db import models_v2 from neutron.db import models_v2
from neutron.db.models_v2 import model_base
from sqlalchemy import orm from sqlalchemy import orm

View File

@ -36,7 +36,7 @@ from neutron.extensions import portbindings
from neutron.openstack.common import importutils from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
from neutron.plugins.plumgrid.common import exceptions as plum_excep from neutron.plugins.plumgrid.common import exceptions as plum_excep
from neutron.plugins.plumgrid.plumgrid_plugin.plugin_ver import VERSION from neutron.plugins.plumgrid.plumgrid_plugin import plugin_ver
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
PLUM_DRIVER = 'neutron.plugins.plumgrid.drivers.plumlib.Plumlib' PLUM_DRIVER = 'neutron.plugins.plumgrid.drivers.plumlib.Plumlib'
@ -555,7 +555,7 @@ class NeutronPluginPLUMgridV2(db_base_plugin_v2.NeutronDbPluginV2,
""" """
def _get_plugin_version(self): def _get_plugin_version(self):
return VERSION return plugin_ver.VERSION
def _port_viftype_binding(self, context, port): def _port_viftype_binding(self, context, port):
port[portbindings.VIF_TYPE] = portbindings.VIF_TYPE_IOVISOR port[portbindings.VIF_TYPE] = portbindings.VIF_TYPE_IOVISOR

View File

@ -31,7 +31,6 @@ from ryu.app import rest_nw_id
from neutron.agent.linux import ip_lib from neutron.agent.linux import ip_lib
from neutron.agent.linux import ovs_lib from neutron.agent.linux import ovs_lib
from neutron.agent.linux.ovs_lib import VifPort
from neutron.agent import rpc as agent_rpc from neutron.agent import rpc as agent_rpc
from neutron.agent import securitygroups_rpc as sg_rpc from neutron.agent import securitygroups_rpc as sg_rpc
from neutron.common import config as logging_config from neutron.common import config as logging_config
@ -143,7 +142,7 @@ class OVSBridge(ovs_lib.OVSBridge):
return return
ofport = self.get_ofport(name) ofport = self.get_ofport(name)
return VifPort(name, ofport, None, None, self) return ovs_lib.VifPort(name, ofport, None, None, self)
def get_external_ports(self): def get_external_ports(self):
return self._get_ports(self._get_external_port) return self._get_ports(self._get_external_port)

View File

@ -14,13 +14,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from abc import ABCMeta import abc
import httplib import httplib
import six import six
import time import time
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
from neutron.plugins.vmware.api_client import ctrl_conn_to_str from neutron.plugins.vmware import api_client
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -29,7 +29,7 @@ DEFAULT_CONCURRENT_CONNECTIONS = 3
DEFAULT_CONNECT_TIMEOUT = 5 DEFAULT_CONNECT_TIMEOUT = 5
@six.add_metaclass(ABCMeta) @six.add_metaclass(abc.ABCMeta)
class ApiClientBase(object): class ApiClientBase(object):
"""An abstract baseclass for all API client implementations.""" """An abstract baseclass for all API client implementations."""
@ -109,7 +109,7 @@ class ApiClientBase(object):
if getattr(conn, 'last_used', now) < now - self.CONN_IDLE_TIMEOUT: if getattr(conn, 'last_used', now) < now - self.CONN_IDLE_TIMEOUT:
LOG.info(_("[%(rid)d] Connection %(conn)s idle for %(sec)0.2f " LOG.info(_("[%(rid)d] Connection %(conn)s idle for %(sec)0.2f "
"seconds; reconnecting."), "seconds; reconnecting."),
{'rid': rid, 'conn': ctrl_conn_to_str(conn), {'rid': rid, 'conn': api_client.ctrl_conn_to_str(conn),
'sec': now - conn.last_used}) 'sec': now - conn.last_used})
conn = self._create_connection(*self._conn_params(conn)) conn = self._create_connection(*self._conn_params(conn))
@ -118,7 +118,8 @@ class ApiClientBase(object):
qsize = self._conn_pool.qsize() qsize = self._conn_pool.qsize()
LOG.debug(_("[%(rid)d] Acquired connection %(conn)s. %(qsize)d " LOG.debug(_("[%(rid)d] Acquired connection %(conn)s. %(qsize)d "
"connection(s) available."), "connection(s) available."),
{'rid': rid, 'conn': ctrl_conn_to_str(conn), 'qsize': qsize}) {'rid': rid, 'conn': api_client.ctrl_conn_to_str(conn),
'qsize': qsize})
if auto_login and self.auth_cookie(conn) is None: if auto_login and self.auth_cookie(conn) is None:
self._wait_for_login(conn, headers) self._wait_for_login(conn, headers)
return conn return conn
@ -138,7 +139,8 @@ class ApiClientBase(object):
if self._conn_params(http_conn) not in self._api_providers: if self._conn_params(http_conn) not in self._api_providers:
LOG.debug(_("[%(rid)d] Released connection %(conn)s is not an " LOG.debug(_("[%(rid)d] Released connection %(conn)s is not an "
"API provider for the cluster"), "API provider for the cluster"),
{'rid': rid, 'conn': ctrl_conn_to_str(http_conn)}) {'rid': rid,
'conn': api_client.ctrl_conn_to_str(http_conn)})
return return
elif hasattr(http_conn, "no_release"): elif hasattr(http_conn, "no_release"):
return return
@ -147,7 +149,8 @@ class ApiClientBase(object):
# Reconnect to provider. # Reconnect to provider.
LOG.warn(_("[%(rid)d] Connection returned in bad state, " LOG.warn(_("[%(rid)d] Connection returned in bad state, "
"reconnecting to %(conn)s"), "reconnecting to %(conn)s"),
{'rid': rid, 'conn': ctrl_conn_to_str(http_conn)}) {'rid': rid,
'conn': api_client.ctrl_conn_to_str(http_conn)})
http_conn = self._create_connection(*self._conn_params(http_conn)) http_conn = self._create_connection(*self._conn_params(http_conn))
priority = self._next_conn_priority priority = self._next_conn_priority
self._next_conn_priority += 1 self._next_conn_priority += 1
@ -172,7 +175,7 @@ class ApiClientBase(object):
self._conn_pool.put((priority, http_conn)) self._conn_pool.put((priority, http_conn))
LOG.debug(_("[%(rid)d] Released connection %(conn)s. %(qsize)d " LOG.debug(_("[%(rid)d] Released connection %(conn)s. %(qsize)d "
"connection(s) available."), "connection(s) available."),
{'rid': rid, 'conn': ctrl_conn_to_str(http_conn), {'rid': rid, 'conn': api_client.ctrl_conn_to_str(http_conn),
'qsize': self._conn_pool.qsize()}) 'qsize': self._conn_pool.qsize()})
def _wait_for_login(self, conn, headers=None): def _wait_for_login(self, conn, headers=None):
@ -181,7 +184,7 @@ class ApiClientBase(object):
data = self._get_provider_data(conn) data = self._get_provider_data(conn)
if data is None: if data is None:
LOG.error(_("Login request for an invalid connection: '%s'"), LOG.error(_("Login request for an invalid connection: '%s'"),
ctrl_conn_to_str(conn)) api_client.ctrl_conn_to_str(conn))
return return
provider_sem = data[0] provider_sem = data[0]
if provider_sem.acquire(blocking=False): if provider_sem.acquire(blocking=False):

View File

@ -15,8 +15,7 @@
# under the License. # under the License.
# #
from abc import ABCMeta import abc
from abc import abstractmethod
import copy import copy
import eventlet import eventlet
import httplib import httplib
@ -27,7 +26,7 @@ import six.moves.urllib.parse as urlparse
from neutron.openstack.common import excutils from neutron.openstack.common import excutils
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
from neutron.plugins.vmware.api_client import ctrl_conn_to_str from neutron.plugins.vmware import api_client
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -40,7 +39,7 @@ DEFAULT_MAXIMUM_REQUEST_ID = 4294967295
DOWNLOAD_TIMEOUT = 180 DOWNLOAD_TIMEOUT = 180
@six.add_metaclass(ABCMeta) @six.add_metaclass(abc.ABCMeta)
class ApiRequest(object): class ApiRequest(object):
'''An abstract baseclass for all ApiRequest implementations. '''An abstract baseclass for all ApiRequest implementations.
@ -64,15 +63,15 @@ class ApiRequest(object):
httplib.SERVICE_UNAVAILABLE httplib.SERVICE_UNAVAILABLE
] ]
@abstractmethod @abc.abstractmethod
def start(self): def start(self):
pass pass
@abstractmethod @abc.abstractmethod
def join(self): def join(self):
pass pass
@abstractmethod @abc.abstractmethod
def copy(self): def copy(self):
pass pass
@ -284,4 +283,5 @@ class ApiRequest(object):
def _request_str(self, conn, url): def _request_str(self, conn, url):
'''Return string representation of connection.''' '''Return string representation of connection.'''
return "%s %s/%s" % (self._method, ctrl_conn_to_str(conn), url) return "%s %s/%s" % (self._method, api_client.ctrl_conn_to_str(conn),
url)

View File

@ -17,14 +17,14 @@
import hashlib import hashlib
from neutron.api.v2.attributes import is_attr_set from neutron.api.v2 import attributes
from neutron.openstack.common import log from neutron.openstack.common import log
from neutron.version import version_info from neutron import version
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
MAX_DISPLAY_NAME_LEN = 40 MAX_DISPLAY_NAME_LEN = 40
NEUTRON_VERSION = version_info.release_string() NEUTRON_VERSION = version.version_info.release_string()
# Allowed network types for the NSX Plugin # Allowed network types for the NSX Plugin
@ -61,7 +61,8 @@ def device_id_to_vm_id(device_id, obfuscate=False):
def check_and_truncate(display_name): def check_and_truncate(display_name):
if is_attr_set(display_name) and len(display_name) > MAX_DISPLAY_NAME_LEN: if (attributes.is_attr_set(display_name) and
len(display_name) > MAX_DISPLAY_NAME_LEN):
LOG.debug(_("Specified name:'%s' exceeds maximum length. " LOG.debug(_("Specified name:'%s' exceeds maximum length. "
"It will be truncated on NSX"), display_name) "It will be truncated on NSX"), display_name)
return display_name[:MAX_DISPLAY_NAME_LEN] return display_name[:MAX_DISPLAY_NAME_LEN]

View File

@ -15,13 +15,13 @@
# under the License. # under the License.
# #
from abc import abstractmethod import abc
from oslo.config import cfg from oslo.config import cfg
from neutron.api.v2 import attributes from neutron.api.v2 import attributes
from neutron.api.v2 import resource_helper from neutron.api.v2 import resource_helper
from neutron.plugins.vmware.common.utils import NetworkTypes from neutron.plugins.vmware.common import utils
GATEWAY_RESOURCE_NAME = "network_gateway" GATEWAY_RESOURCE_NAME = "network_gateway"
DEVICE_RESOURCE_NAME = "gateway_device" DEVICE_RESOURCE_NAME = "gateway_device"
@ -113,11 +113,11 @@ def _validate_connector_type(data, valid_values=None):
msg = _("A connector type is required to create a gateway device") msg = _("A connector type is required to create a gateway device")
return msg return msg
connector_types = (valid_values if valid_values else connector_types = (valid_values if valid_values else
[NetworkTypes.GRE, [utils.NetworkTypes.GRE,
NetworkTypes.STT, utils.NetworkTypes.STT,
NetworkTypes.BRIDGE, utils.NetworkTypes.BRIDGE,
'ipsec%s' % NetworkTypes.GRE, 'ipsec%s' % utils.NetworkTypes.GRE,
'ipsec%s' % NetworkTypes.STT]) 'ipsec%s' % utils.NetworkTypes.STT])
if data not in connector_types: if data not in connector_types:
msg = _("Unknown connector type: %s") % data msg = _("Unknown connector type: %s") % data
return msg return msg
@ -196,55 +196,55 @@ class Networkgw(object):
class NetworkGatewayPluginBase(object): class NetworkGatewayPluginBase(object):
@abstractmethod @abc.abstractmethod
def create_network_gateway(self, context, network_gateway): def create_network_gateway(self, context, network_gateway):
pass pass
@abstractmethod @abc.abstractmethod
def update_network_gateway(self, context, id, network_gateway): def update_network_gateway(self, context, id, network_gateway):
pass pass
@abstractmethod @abc.abstractmethod
def get_network_gateway(self, context, id, fields=None): def get_network_gateway(self, context, id, fields=None):
pass pass
@abstractmethod @abc.abstractmethod
def delete_network_gateway(self, context, id): def delete_network_gateway(self, context, id):
pass pass
@abstractmethod @abc.abstractmethod
def get_network_gateways(self, context, filters=None, fields=None, def get_network_gateways(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None, sorts=None, limit=None, marker=None,
page_reverse=False): page_reverse=False):
pass pass
@abstractmethod @abc.abstractmethod
def connect_network(self, context, network_gateway_id, def connect_network(self, context, network_gateway_id,
network_mapping_info): network_mapping_info):
pass pass
@abstractmethod @abc.abstractmethod
def disconnect_network(self, context, network_gateway_id, def disconnect_network(self, context, network_gateway_id,
network_mapping_info): network_mapping_info):
pass pass
@abstractmethod @abc.abstractmethod
def create_gateway_device(self, context, gateway_device): def create_gateway_device(self, context, gateway_device):
pass pass
@abstractmethod @abc.abstractmethod
def update_gateway_device(self, context, id, gateway_device): def update_gateway_device(self, context, id, gateway_device):
pass pass
@abstractmethod @abc.abstractmethod
def delete_gateway_device(self, context, id): def delete_gateway_device(self, context, id):
pass pass
@abstractmethod @abc.abstractmethod
def get_gateway_device(self, context, id, fields=None): def get_gateway_device(self, context, id, fields=None):
pass pass
@abstractmethod @abc.abstractmethod
def get_gateway_devices(self, context, filters=None, fields=None, def get_gateway_devices(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None, sorts=None, limit=None, marker=None,
page_reverse=False): page_reverse=False):

View File

@ -16,7 +16,7 @@
# under the License. # under the License.
# #
from abc import abstractmethod import abc
from neutron.api import extensions from neutron.api import extensions
from neutron.api.v2 import attributes as attr from neutron.api.v2 import attributes as attr
@ -205,19 +205,19 @@ class Qos(object):
class QueuePluginBase(object): class QueuePluginBase(object):
@abstractmethod @abc.abstractmethod
def create_qos_queue(self, context, queue): def create_qos_queue(self, context, queue):
pass pass
@abstractmethod @abc.abstractmethod
def delete_qos_queue(self, context, id): def delete_qos_queue(self, context, id):
pass pass
@abstractmethod @abc.abstractmethod
def get_qos_queue(self, context, id, fields=None): def get_qos_queue(self, context, id, fields=None):
pass pass
@abstractmethod @abc.abstractmethod
def get_qos_queues(self, context, filters=None, fields=None, sorts=None, def get_qos_queues(self, context, filters=None, fields=None, sorts=None,
limit=None, marker=None, page_reverse=False): limit=None, marker=None, page_reverse=False):
pass pass

View File

@ -19,7 +19,7 @@ from neutron.common import exceptions as exception
from neutron.openstack.common import log from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import exceptions as nsx_exc from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.version import version_info from neutron import version
HTTP_GET = "GET" HTTP_GET = "GET"
HTTP_POST = "POST" HTTP_POST = "POST"
@ -27,7 +27,7 @@ HTTP_DELETE = "DELETE"
HTTP_PUT = "PUT" HTTP_PUT = "PUT"
# Prefix to be used for all NSX API calls # Prefix to be used for all NSX API calls
URI_PREFIX = "/ws.v1" URI_PREFIX = "/ws.v1"
NEUTRON_VERSION = version_info.release_string() NEUTRON_VERSION = version.version_info.release_string()
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)

View File

@ -20,9 +20,7 @@ from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import exceptions as nsx_exc from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import do_request
from neutron.plugins.vmware.nsxlib import get_all_query_pages
from neutron.plugins.vmware.nsxlib import switch from neutron.plugins.vmware.nsxlib import switch
HTTP_GET = "GET" HTTP_GET = "GET"
@ -60,8 +58,8 @@ def create_l2_gw_service(cluster, tenant_id, display_name, devices):
"gateways": gateways, "gateways": gateways,
"type": "L2GatewayServiceConfig" "type": "L2GatewayServiceConfig"
} }
return do_request( return nsxlib.do_request(
HTTP_POST, _build_uri_path(GWSERVICE_RESOURCE), HTTP_POST, nsxlib._build_uri_path(GWSERVICE_RESOURCE),
json.dumps(gwservice_obj), cluster=cluster) json.dumps(gwservice_obj), cluster=cluster)
@ -76,9 +74,9 @@ def plug_l2_gw_service(cluster, lswitch_id, lport_id,
def get_l2_gw_service(cluster, gateway_id): def get_l2_gw_service(cluster, gateway_id):
return do_request( return nsxlib.do_request(
HTTP_GET, _build_uri_path(GWSERVICE_RESOURCE, HTTP_GET, nsxlib._build_uri_path(GWSERVICE_RESOURCE,
resource_id=gateway_id), resource_id=gateway_id),
cluster=cluster) cluster=cluster)
@ -88,9 +86,9 @@ def get_l2_gw_services(cluster, tenant_id=None,
if tenant_id: if tenant_id:
actual_filters['tag'] = tenant_id actual_filters['tag'] = tenant_id
actual_filters['tag_scope'] = 'os_tid' actual_filters['tag_scope'] = 'os_tid'
return get_all_query_pages( return nsxlib.get_all_query_pages(
_build_uri_path(GWSERVICE_RESOURCE, nsxlib._build_uri_path(GWSERVICE_RESOURCE,
filters=actual_filters), filters=actual_filters),
cluster) cluster)
@ -101,15 +99,17 @@ def update_l2_gw_service(cluster, gateway_id, display_name):
# Nothing to update # Nothing to update
return gwservice_obj return gwservice_obj
gwservice_obj["display_name"] = utils.check_and_truncate(display_name) gwservice_obj["display_name"] = utils.check_and_truncate(display_name)
return do_request(HTTP_PUT, _build_uri_path(GWSERVICE_RESOURCE, return nsxlib.do_request(HTTP_PUT,
resource_id=gateway_id), nsxlib._build_uri_path(GWSERVICE_RESOURCE,
json.dumps(gwservice_obj), cluster=cluster) resource_id=gateway_id),
json.dumps(gwservice_obj), cluster=cluster)
def delete_l2_gw_service(cluster, gateway_id): def delete_l2_gw_service(cluster, gateway_id):
do_request(HTTP_DELETE, _build_uri_path(GWSERVICE_RESOURCE, nsxlib.do_request(HTTP_DELETE,
resource_id=gateway_id), nsxlib._build_uri_path(GWSERVICE_RESOURCE,
cluster=cluster) resource_id=gateway_id),
cluster=cluster)
def _build_gateway_device_body(tenant_id, display_name, neutron_id, def _build_gateway_device_body(tenant_id, display_name, neutron_id,
@ -148,8 +148,8 @@ def create_gateway_device(cluster, tenant_id, display_name, neutron_id,
connector_type, connector_ip, connector_type, connector_ip,
client_certificate, tz_uuid) client_certificate, tz_uuid)
try: try:
return do_request( return nsxlib.do_request(
HTTP_POST, _build_uri_path(TRANSPORTNODE_RESOURCE), HTTP_POST, nsxlib._build_uri_path(TRANSPORTNODE_RESOURCE),
json.dumps(body), cluster=cluster) json.dumps(body), cluster=cluster)
except api_exc.InvalidSecurityCertificate: except api_exc.InvalidSecurityCertificate:
raise nsx_exc.InvalidSecurityCertificate() raise nsx_exc.InvalidSecurityCertificate()
@ -163,46 +163,48 @@ def update_gateway_device(cluster, gateway_id, tenant_id,
connector_type, connector_ip, connector_type, connector_ip,
client_certificate, tz_uuid) client_certificate, tz_uuid)
try: try:
return do_request( return nsxlib.do_request(
HTTP_PUT, HTTP_PUT,
_build_uri_path(TRANSPORTNODE_RESOURCE, resource_id=gateway_id), nsxlib._build_uri_path(TRANSPORTNODE_RESOURCE,
resource_id=gateway_id),
json.dumps(body), cluster=cluster) json.dumps(body), cluster=cluster)
except api_exc.InvalidSecurityCertificate: except api_exc.InvalidSecurityCertificate:
raise nsx_exc.InvalidSecurityCertificate() raise nsx_exc.InvalidSecurityCertificate()
def delete_gateway_device(cluster, device_uuid): def delete_gateway_device(cluster, device_uuid):
return do_request(HTTP_DELETE, return nsxlib.do_request(HTTP_DELETE,
_build_uri_path(TRANSPORTNODE_RESOURCE, nsxlib._build_uri_path(TRANSPORTNODE_RESOURCE,
device_uuid), device_uuid),
cluster=cluster) cluster=cluster)
def get_gateway_device_status(cluster, device_uuid): def get_gateway_device_status(cluster, device_uuid):
status_res = do_request(HTTP_GET, status_res = nsxlib.do_request(HTTP_GET,
_build_uri_path(TRANSPORTNODE_RESOURCE, nsxlib._build_uri_path(
device_uuid, TRANSPORTNODE_RESOURCE,
extra_action='status'), device_uuid,
cluster=cluster) extra_action='status'),
cluster=cluster)
# Returns the connection status # Returns the connection status
return status_res['connection']['connected'] return status_res['connection']['connected']
def get_gateway_devices_status(cluster, tenant_id=None): def get_gateway_devices_status(cluster, tenant_id=None):
if tenant_id: if tenant_id:
gw_device_query_path = _build_uri_path( gw_device_query_path = nsxlib._build_uri_path(
TRANSPORTNODE_RESOURCE, TRANSPORTNODE_RESOURCE,
fields="uuid,tags", fields="uuid,tags",
relations="TransportNodeStatus", relations="TransportNodeStatus",
filters={'tag': tenant_id, filters={'tag': tenant_id,
'tag_scope': 'os_tid'}) 'tag_scope': 'os_tid'})
else: else:
gw_device_query_path = _build_uri_path( gw_device_query_path = nsxlib._build_uri_path(
TRANSPORTNODE_RESOURCE, TRANSPORTNODE_RESOURCE,
fields="uuid,tags", fields="uuid,tags",
relations="TransportNodeStatus") relations="TransportNodeStatus")
response = get_all_query_pages(gw_device_query_path, cluster) response = nsxlib.get_all_query_pages(gw_device_query_path, cluster)
results = {} results = {}
for item in response: for item in response:
results[item['uuid']] = (item['_relations']['TransportNodeStatus'] results[item['uuid']] = (item['_relations']['TransportNodeStatus']

View File

@ -22,8 +22,7 @@ from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import exceptions as nsx_exc from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import do_request
HTTP_GET = "GET" HTTP_GET = "GET"
HTTP_POST = "POST" HTTP_POST = "POST"
@ -43,10 +42,11 @@ def service_cluster_exists(cluster, svc_cluster_id):
try: try:
exists = ( exists = (
svc_cluster_id and svc_cluster_id and
do_request(HTTP_GET, nsxlib.do_request(HTTP_GET,
_build_uri_path(SERVICECLUSTER_RESOURCE, nsxlib._build_uri_path(
resource_id=svc_cluster_id), SERVICECLUSTER_RESOURCE,
cluster=cluster) is not None) resource_id=svc_cluster_id),
cluster=cluster) is not None)
except exception.NotFound: except exception.NotFound:
pass pass
return exists return exists
@ -57,19 +57,19 @@ def lsn_for_network_create(cluster, network_id):
"edge_cluster_uuid": cluster.default_service_cluster_uuid, "edge_cluster_uuid": cluster.default_service_cluster_uuid,
"tags": utils.get_tags(n_network_id=network_id) "tags": utils.get_tags(n_network_id=network_id)
} }
return do_request(HTTP_POST, return nsxlib.do_request(HTTP_POST,
_build_uri_path(LSERVICESNODE_RESOURCE), nsxlib._build_uri_path(LSERVICESNODE_RESOURCE),
json.dumps(lsn_obj), json.dumps(lsn_obj),
cluster=cluster)["uuid"] cluster=cluster)["uuid"]
def lsn_for_network_get(cluster, network_id): def lsn_for_network_get(cluster, network_id):
filters = {"tag": network_id, "tag_scope": "n_network_id"} filters = {"tag": network_id, "tag_scope": "n_network_id"}
results = do_request(HTTP_GET, results = nsxlib.do_request(HTTP_GET,
_build_uri_path(LSERVICESNODE_RESOURCE, nsxlib._build_uri_path(LSERVICESNODE_RESOURCE,
fields="uuid", fields="uuid",
filters=filters), filters=filters),
cluster=cluster)['results'] cluster=cluster)['results']
if not results: if not results:
raise exception.NotFound() raise exception.NotFound()
elif len(results) == 1: elif len(results) == 1:
@ -77,22 +77,22 @@ def lsn_for_network_get(cluster, network_id):
def lsn_delete(cluster, lsn_id): def lsn_delete(cluster, lsn_id):
do_request(HTTP_DELETE, nsxlib.do_request(HTTP_DELETE,
_build_uri_path(LSERVICESNODE_RESOURCE, nsxlib._build_uri_path(LSERVICESNODE_RESOURCE,
resource_id=lsn_id), resource_id=lsn_id),
cluster=cluster) cluster=cluster)
def lsn_port_host_entries_update( def lsn_port_host_entries_update(
cluster, lsn_id, lsn_port_id, conf, hosts_data): cluster, lsn_id, lsn_port_id, conf, hosts_data):
hosts_obj = {'hosts': hosts_data} hosts_obj = {'hosts': hosts_data}
do_request(HTTP_PUT, nsxlib.do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id, parent_resource_id=lsn_id,
resource_id=lsn_port_id, resource_id=lsn_port_id,
extra_action=conf), extra_action=conf),
json.dumps(hosts_obj), json.dumps(hosts_obj),
cluster=cluster) cluster=cluster)
def lsn_port_create(cluster, lsn_id, port_data): def lsn_port_create(cluster, lsn_id, port_data):
@ -103,28 +103,29 @@ def lsn_port_create(cluster, lsn_id, port_data):
n_subnet_id=port_data["subnet_id"]), n_subnet_id=port_data["subnet_id"]),
"type": "LogicalServicesNodePortConfig", "type": "LogicalServicesNodePortConfig",
} }
return do_request(HTTP_POST, return nsxlib.do_request(HTTP_POST,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id), parent_resource_id=lsn_id),
json.dumps(port_obj), json.dumps(port_obj),
cluster=cluster)["uuid"] cluster=cluster)["uuid"]
def lsn_port_delete(cluster, lsn_id, lsn_port_id): def lsn_port_delete(cluster, lsn_id, lsn_port_id):
return do_request(HTTP_DELETE, return nsxlib.do_request(HTTP_DELETE,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id, parent_resource_id=lsn_id,
resource_id=lsn_port_id), resource_id=lsn_port_id),
cluster=cluster) cluster=cluster)
def _lsn_port_get(cluster, lsn_id, filters): def _lsn_port_get(cluster, lsn_id, filters):
results = do_request(HTTP_GET, results = nsxlib.do_request(HTTP_GET,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(
parent_resource_id=lsn_id, LSERVICESNODEPORT_RESOURCE,
fields="uuid", parent_resource_id=lsn_id,
filters=filters), fields="uuid",
cluster=cluster)['results'] filters=filters),
cluster=cluster)['results']
if not results: if not results:
raise exception.NotFound() raise exception.NotFound()
elif len(results) == 1: elif len(results) == 1:
@ -142,11 +143,12 @@ def lsn_port_by_subnet_get(cluster, lsn_id, subnet_id):
def lsn_port_info_get(cluster, lsn_id, lsn_port_id): def lsn_port_info_get(cluster, lsn_id, lsn_port_id):
result = do_request(HTTP_GET, result = nsxlib.do_request(HTTP_GET,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(
parent_resource_id=lsn_id, LSERVICESNODEPORT_RESOURCE,
resource_id=lsn_port_id), parent_resource_id=lsn_id,
cluster=cluster) resource_id=lsn_port_id),
cluster=cluster)
for tag in result['tags']: for tag in result['tags']:
if tag['scope'] == 'n_subnet_id': if tag['scope'] == 'n_subnet_id':
result['subnet_id'] = tag['tag'] result['subnet_id'] = tag['tag']
@ -160,13 +162,13 @@ def lsn_port_plug_network(cluster, lsn_id, lsn_port_id, lswitch_port_id):
"peer_port_uuid": lswitch_port_id "peer_port_uuid": lswitch_port_id
} }
try: try:
do_request(HTTP_PUT, nsxlib.do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id, parent_resource_id=lsn_id,
resource_id=lsn_port_id, resource_id=lsn_port_id,
is_attachment=True), is_attachment=True),
json.dumps(patch_obj), json.dumps(patch_obj),
cluster=cluster) cluster=cluster)
except api_exc.Conflict: except api_exc.Conflict:
# This restriction might be lifted at some point # This restriction might be lifted at some point
msg = (_("Attempt to plug Logical Services Node %(lsn)s into " msg = (_("Attempt to plug Logical Services Node %(lsn)s into "
@ -181,29 +183,29 @@ def _lsn_configure_action(
cluster, lsn_id, action, is_enabled, obj): cluster, lsn_id, action, is_enabled, obj):
lsn_obj = {"enabled": is_enabled} lsn_obj = {"enabled": is_enabled}
lsn_obj.update(obj) lsn_obj.update(obj)
do_request(HTTP_PUT, nsxlib.do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODE_RESOURCE, nsxlib._build_uri_path(LSERVICESNODE_RESOURCE,
resource_id=lsn_id, resource_id=lsn_id,
extra_action=action), extra_action=action),
json.dumps(lsn_obj), json.dumps(lsn_obj),
cluster=cluster) cluster=cluster)
def _lsn_port_configure_action( def _lsn_port_configure_action(
cluster, lsn_id, lsn_port_id, action, is_enabled, obj): cluster, lsn_id, lsn_port_id, action, is_enabled, obj):
do_request(HTTP_PUT, nsxlib.do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODE_RESOURCE, nsxlib._build_uri_path(LSERVICESNODE_RESOURCE,
resource_id=lsn_id, resource_id=lsn_id,
extra_action=action), extra_action=action),
json.dumps({"enabled": is_enabled}), json.dumps({"enabled": is_enabled}),
cluster=cluster) cluster=cluster)
do_request(HTTP_PUT, nsxlib.do_request(HTTP_PUT,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id, parent_resource_id=lsn_id,
resource_id=lsn_port_id, resource_id=lsn_port_id,
extra_action=action), extra_action=action),
json.dumps(obj), json.dumps(obj),
cluster=cluster) cluster=cluster)
def _get_opts(name, value): def _get_opts(name, value):
@ -239,14 +241,14 @@ def lsn_metadata_configure(
def _lsn_port_host_action( def _lsn_port_host_action(
cluster, lsn_id, lsn_port_id, host_obj, extra_action, action): cluster, lsn_id, lsn_port_id, host_obj, extra_action, action):
do_request(HTTP_POST, nsxlib.do_request(HTTP_POST,
_build_uri_path(LSERVICESNODEPORT_RESOURCE, nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
parent_resource_id=lsn_id, parent_resource_id=lsn_id,
resource_id=lsn_port_id, resource_id=lsn_port_id,
extra_action=extra_action, extra_action=extra_action,
filters={"action": action}), filters={"action": action}),
json.dumps(host_obj), json.dumps(host_obj),
cluster=cluster) cluster=cluster)
def lsn_port_dhcp_host_add(cluster, lsn_id, lsn_port_id, host_data): def lsn_port_dhcp_host_add(cluster, lsn_id, lsn_port_id, host_data):

View File

@ -20,8 +20,7 @@ from neutron.openstack.common import jsonutils
from neutron.openstack.common import log from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import do_request
HTTP_POST = "POST" HTTP_POST = "POST"
HTTP_DELETE = "DELETE" HTTP_DELETE = "DELETE"
@ -50,10 +49,10 @@ def create_lqueue(cluster, queue_data):
queue_obj['tags'] = utils.get_tags() queue_obj['tags'] = utils.get_tags()
try: try:
return do_request(HTTP_POST, return nsxlib.do_request(HTTP_POST,
_build_uri_path(LQUEUE_RESOURCE), nsxlib._build_uri_path(LQUEUE_RESOURCE),
jsonutils.dumps(queue_obj), jsonutils.dumps(queue_obj),
cluster=cluster)['uuid'] cluster=cluster)['uuid']
except api_exc.NsxApiException: except api_exc.NsxApiException:
# FIXME(salv-orlando): This should not raise NeutronException # FIXME(salv-orlando): This should not raise NeutronException
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
@ -62,10 +61,10 @@ def create_lqueue(cluster, queue_data):
def delete_lqueue(cluster, queue_id): def delete_lqueue(cluster, queue_id):
try: try:
do_request(HTTP_DELETE, nsxlib.do_request(HTTP_DELETE,
_build_uri_path(LQUEUE_RESOURCE, nsxlib._build_uri_path(LQUEUE_RESOURCE,
resource_id=queue_id), resource_id=queue_id),
cluster=cluster) cluster=cluster)
except Exception: except Exception:
# FIXME(salv-orlando): This should not raise NeutronException # FIXME(salv-orlando): This should not raise NeutronException
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():

View File

@ -22,12 +22,9 @@ from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import exceptions as nsx_exc from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import do_request from neutron.plugins.vmware.nsxlib import switch
from neutron.plugins.vmware.nsxlib import get_all_query_pages from neutron.plugins.vmware.nsxlib import versioning
from neutron.plugins.vmware.nsxlib.switch import get_port
from neutron.plugins.vmware.nsxlib.versioning import DEFAULT_VERSION
from neutron.plugins.vmware.nsxlib.versioning import versioned
HTTP_GET = "GET" HTTP_GET = "GET"
HTTP_POST = "POST" HTTP_POST = "POST"
@ -80,8 +77,9 @@ def _create_implicit_routing_lrouter(cluster, neutron_router_id, tenant_id,
"SingleDefaultRouteImplicitRoutingConfig", "SingleDefaultRouteImplicitRoutingConfig",
distributed=distributed, distributed=distributed,
**implicit_routing_config) **implicit_routing_config)
return do_request(HTTP_POST, _build_uri_path(LROUTER_RESOURCE), return nsxlib.do_request(HTTP_POST,
jsonutils.dumps(lrouter_obj), cluster=cluster) nsxlib._build_uri_path(LROUTER_RESOURCE),
jsonutils.dumps(lrouter_obj), cluster=cluster)
def create_implicit_routing_lrouter(cluster, neutron_router_id, tenant_id, def create_implicit_routing_lrouter(cluster, neutron_router_id, tenant_id,
@ -125,33 +123,36 @@ def create_explicit_routing_lrouter(cluster, neutron_router_id, tenant_id,
lrouter_obj = _prepare_lrouter_body( lrouter_obj = _prepare_lrouter_body(
display_name, neutron_router_id, tenant_id, display_name, neutron_router_id, tenant_id,
"RoutingTableRoutingConfig", distributed=distributed) "RoutingTableRoutingConfig", distributed=distributed)
router = do_request(HTTP_POST, _build_uri_path(LROUTER_RESOURCE), router = nsxlib.do_request(HTTP_POST,
jsonutils.dumps(lrouter_obj), cluster=cluster) nsxlib._build_uri_path(LROUTER_RESOURCE),
jsonutils.dumps(lrouter_obj), cluster=cluster)
default_gw = {'prefix': '0.0.0.0/0', 'next_hop_ip': nexthop} default_gw = {'prefix': '0.0.0.0/0', 'next_hop_ip': nexthop}
create_explicit_route_lrouter(cluster, router['uuid'], default_gw) create_explicit_route_lrouter(cluster, router['uuid'], default_gw)
return router return router
def delete_lrouter(cluster, lrouter_id): def delete_lrouter(cluster, lrouter_id):
do_request(HTTP_DELETE, _build_uri_path(LROUTER_RESOURCE, nsxlib.do_request(HTTP_DELETE,
resource_id=lrouter_id), nsxlib._build_uri_path(LROUTER_RESOURCE,
cluster=cluster) resource_id=lrouter_id),
def get_lrouter(cluster, lrouter_id):
return do_request(HTTP_GET,
_build_uri_path(LROUTER_RESOURCE,
resource_id=lrouter_id,
relations='LogicalRouterStatus'),
cluster=cluster) cluster=cluster)
def get_lrouter(cluster, lrouter_id):
return nsxlib.do_request(HTTP_GET,
nsxlib._build_uri_path(
LROUTER_RESOURCE,
resource_id=lrouter_id,
relations='LogicalRouterStatus'),
cluster=cluster)
def query_lrouters(cluster, fields=None, filters=None): def query_lrouters(cluster, fields=None, filters=None):
return get_all_query_pages( return nsxlib.get_all_query_pages(
_build_uri_path(LROUTER_RESOURCE, nsxlib._build_uri_path(LROUTER_RESOURCE,
fields=fields, fields=fields,
relations='LogicalRouterStatus', relations='LogicalRouterStatus',
filters=filters), filters=filters),
cluster) cluster)
@ -180,39 +181,40 @@ def update_implicit_routing_lrouter(cluster, r_id, display_name, nexthop):
"default_route_next_hop") "default_route_next_hop")
if nh_element: if nh_element:
nh_element["gateway_ip_address"] = nexthop nh_element["gateway_ip_address"] = nexthop
return do_request(HTTP_PUT, _build_uri_path(LROUTER_RESOURCE, return nsxlib.do_request(HTTP_PUT,
resource_id=r_id), nsxlib._build_uri_path(LROUTER_RESOURCE,
jsonutils.dumps(lrouter_obj), resource_id=r_id),
cluster=cluster) jsonutils.dumps(lrouter_obj),
cluster=cluster)
def get_explicit_routes_lrouter(cluster, router_id, protocol_type='static'): def get_explicit_routes_lrouter(cluster, router_id, protocol_type='static'):
static_filter = {'protocol': protocol_type} static_filter = {'protocol': protocol_type}
existing_routes = do_request( existing_routes = nsxlib.do_request(
HTTP_GET, HTTP_GET,
_build_uri_path(LROUTERRIB_RESOURCE, nsxlib._build_uri_path(LROUTERRIB_RESOURCE,
filters=static_filter, filters=static_filter,
fields="*", fields="*",
parent_resource_id=router_id), parent_resource_id=router_id),
cluster=cluster)['results'] cluster=cluster)['results']
return existing_routes return existing_routes
def delete_explicit_route_lrouter(cluster, router_id, route_id): def delete_explicit_route_lrouter(cluster, router_id, route_id):
do_request(HTTP_DELETE, nsxlib.do_request(HTTP_DELETE,
_build_uri_path(LROUTERRIB_RESOURCE, nsxlib._build_uri_path(LROUTERRIB_RESOURCE,
resource_id=route_id, resource_id=route_id,
parent_resource_id=router_id), parent_resource_id=router_id),
cluster=cluster) cluster=cluster)
def create_explicit_route_lrouter(cluster, router_id, route): def create_explicit_route_lrouter(cluster, router_id, route):
next_hop_ip = route.get("nexthop") or route.get("next_hop_ip") next_hop_ip = route.get("nexthop") or route.get("next_hop_ip")
prefix = route.get("destination") or route.get("prefix") prefix = route.get("destination") or route.get("prefix")
uuid = do_request( uuid = nsxlib.do_request(
HTTP_POST, HTTP_POST,
_build_uri_path(LROUTERRIB_RESOURCE, nsxlib._build_uri_path(LROUTERRIB_RESOURCE,
parent_resource_id=router_id), parent_resource_id=router_id),
jsonutils.dumps({ jsonutils.dumps({
"action": "accept", "action": "accept",
"next_hop_ip": next_hop_ip, "next_hop_ip": next_hop_ip,
@ -267,12 +269,12 @@ def update_explicit_routes_lrouter(cluster, router_id, routes):
def get_default_route_explicit_routing_lrouter_v33(cluster, router_id): def get_default_route_explicit_routing_lrouter_v33(cluster, router_id):
static_filter = {"protocol": "static", static_filter = {"protocol": "static",
"prefix": "0.0.0.0/0"} "prefix": "0.0.0.0/0"}
default_route = do_request( default_route = nsxlib.do_request(
HTTP_GET, HTTP_GET,
_build_uri_path(LROUTERRIB_RESOURCE, nsxlib._build_uri_path(LROUTERRIB_RESOURCE,
filters=static_filter, filters=static_filter,
fields="*", fields="*",
parent_resource_id=router_id), parent_resource_id=router_id),
cluster=cluster)["results"][0] cluster=cluster)["results"][0]
return default_route return default_route
@ -293,12 +295,13 @@ def update_default_gw_explicit_routing_lrouter(cluster, router_id, next_hop):
"next_hop_ip": next_hop, "next_hop_ip": next_hop,
"prefix": "0.0.0.0/0", "prefix": "0.0.0.0/0",
"protocol": "static"} "protocol": "static"}
do_request(HTTP_PUT, nsxlib.do_request(HTTP_PUT,
_build_uri_path(LROUTERRIB_RESOURCE, nsxlib._build_uri_path(
resource_id=default_route['uuid'], LROUTERRIB_RESOURCE,
parent_resource_id=router_id), resource_id=default_route['uuid'],
jsonutils.dumps(new_default_route), parent_resource_id=router_id),
cluster=cluster) jsonutils.dumps(new_default_route),
cluster=cluster)
def update_explicit_routing_lrouter(cluster, router_id, def update_explicit_routing_lrouter(cluster, router_id,
@ -313,9 +316,11 @@ def update_explicit_routing_lrouter(cluster, router_id,
def query_lrouter_lports(cluster, lr_uuid, fields="*", def query_lrouter_lports(cluster, lr_uuid, fields="*",
filters=None, relations=None): filters=None, relations=None):
uri = _build_uri_path(LROUTERPORT_RESOURCE, parent_resource_id=lr_uuid, uri = nsxlib._build_uri_path(LROUTERPORT_RESOURCE,
fields=fields, filters=filters, relations=relations) parent_resource_id=lr_uuid,
return do_request(HTTP_GET, uri, cluster=cluster)['results'] fields=fields, filters=filters,
relations=relations)
return nsxlib.do_request(HTTP_GET, uri, cluster=cluster)['results']
def create_router_lport(cluster, lrouter_uuid, tenant_id, neutron_port_id, def create_router_lport(cluster, lrouter_uuid, tenant_id, neutron_port_id,
@ -333,10 +338,10 @@ def create_router_lport(cluster, lrouter_uuid, tenant_id, neutron_port_id,
# when creating the fake_ext_gw there is no mac_address present. # when creating the fake_ext_gw there is no mac_address present.
if mac_address: if mac_address:
lport_obj['mac_address'] = mac_address lport_obj['mac_address'] = mac_address
path = _build_uri_path(LROUTERPORT_RESOURCE, path = nsxlib._build_uri_path(LROUTERPORT_RESOURCE,
parent_resource_id=lrouter_uuid) parent_resource_id=lrouter_uuid)
result = do_request(HTTP_POST, path, jsonutils.dumps(lport_obj), result = nsxlib.do_request(HTTP_POST, path, jsonutils.dumps(lport_obj),
cluster=cluster) cluster=cluster)
LOG.debug(_("Created logical port %(lport_uuid)s on " LOG.debug(_("Created logical port %(lport_uuid)s on "
"logical router %(lrouter_uuid)s"), "logical router %(lrouter_uuid)s"),
@ -360,12 +365,12 @@ def update_router_lport(cluster, lrouter_uuid, lrouter_port_uuid,
for key in lport_obj.keys(): for key in lport_obj.keys():
if lport_obj[key] is None: if lport_obj[key] is None:
del lport_obj[key] del lport_obj[key]
path = _build_uri_path(LROUTERPORT_RESOURCE, path = nsxlib._build_uri_path(LROUTERPORT_RESOURCE,
lrouter_port_uuid, lrouter_port_uuid,
parent_resource_id=lrouter_uuid) parent_resource_id=lrouter_uuid)
result = do_request(HTTP_PUT, path, result = nsxlib.do_request(HTTP_PUT, path,
jsonutils.dumps(lport_obj), jsonutils.dumps(lport_obj),
cluster=cluster) cluster=cluster)
LOG.debug(_("Updated logical port %(lport_uuid)s on " LOG.debug(_("Updated logical port %(lport_uuid)s on "
"logical router %(lrouter_uuid)s"), "logical router %(lrouter_uuid)s"),
{'lport_uuid': lrouter_port_uuid, 'lrouter_uuid': lrouter_uuid}) {'lport_uuid': lrouter_port_uuid, 'lrouter_uuid': lrouter_uuid})
@ -374,8 +379,9 @@ def update_router_lport(cluster, lrouter_uuid, lrouter_port_uuid,
def delete_router_lport(cluster, lrouter_uuid, lport_uuid): def delete_router_lport(cluster, lrouter_uuid, lport_uuid):
"""Creates a logical port on the assigned logical router.""" """Creates a logical port on the assigned logical router."""
path = _build_uri_path(LROUTERPORT_RESOURCE, lport_uuid, lrouter_uuid) path = nsxlib._build_uri_path(LROUTERPORT_RESOURCE, lport_uuid,
do_request(HTTP_DELETE, path, cluster=cluster) lrouter_uuid)
nsxlib.do_request(HTTP_DELETE, path, cluster=cluster)
LOG.debug(_("Delete logical router port %(lport_uuid)s on " LOG.debug(_("Delete logical router port %(lport_uuid)s on "
"logical router %(lrouter_uuid)s"), "logical router %(lrouter_uuid)s"),
{'lport_uuid': lport_uuid, {'lport_uuid': lport_uuid,
@ -383,8 +389,8 @@ def delete_router_lport(cluster, lrouter_uuid, lport_uuid):
def delete_peer_router_lport(cluster, lr_uuid, ls_uuid, lp_uuid): def delete_peer_router_lport(cluster, lr_uuid, ls_uuid, lp_uuid):
nsx_port = get_port(cluster, ls_uuid, lp_uuid, nsx_port = switch.get_port(cluster, ls_uuid, lp_uuid,
relations="LogicalPortAttachment") relations="LogicalPortAttachment")
relations = nsx_port.get('_relations') relations = nsx_port.get('_relations')
if relations: if relations:
att_data = relations.get('LogicalPortAttachment') att_data = relations.get('LogicalPortAttachment')
@ -419,8 +425,8 @@ def plug_router_port_attachment(cluster, router_id, port_id,
- L3GatewayAttachment [-> L3GatewayService uuid] - L3GatewayAttachment [-> L3GatewayService uuid]
For the latter attachment type a VLAN ID can be specified as well. For the latter attachment type a VLAN ID can be specified as well.
""" """
uri = _build_uri_path(LROUTERPORT_RESOURCE, port_id, router_id, uri = nsxlib._build_uri_path(LROUTERPORT_RESOURCE, port_id, router_id,
is_attachment=True) is_attachment=True)
attach_obj = {} attach_obj = {}
attach_obj["type"] = nsx_attachment_type attach_obj["type"] = nsx_attachment_type
if nsx_attachment_type == "PatchAttachment": if nsx_attachment_type == "PatchAttachment":
@ -432,7 +438,7 @@ def plug_router_port_attachment(cluster, router_id, port_id,
else: else:
raise nsx_exc.InvalidAttachmentType( raise nsx_exc.InvalidAttachmentType(
attachment_type=nsx_attachment_type) attachment_type=nsx_attachment_type)
return do_request( return nsxlib.do_request(
HTTP_PUT, uri, jsonutils.dumps(attach_obj), cluster=cluster) HTTP_PUT, uri, jsonutils.dumps(attach_obj), cluster=cluster)
@ -447,9 +453,10 @@ def _create_nat_match_obj(**kwargs):
def _create_lrouter_nat_rule(cluster, router_id, nat_rule_obj): def _create_lrouter_nat_rule(cluster, router_id, nat_rule_obj):
LOG.debug(_("Creating NAT rule: %s"), nat_rule_obj) LOG.debug(_("Creating NAT rule: %s"), nat_rule_obj)
uri = _build_uri_path(LROUTERNAT_RESOURCE, parent_resource_id=router_id) uri = nsxlib._build_uri_path(LROUTERNAT_RESOURCE,
return do_request(HTTP_POST, uri, jsonutils.dumps(nat_rule_obj), parent_resource_id=router_id)
cluster=cluster) return nsxlib.do_request(HTTP_POST, uri, jsonutils.dumps(nat_rule_obj),
cluster=cluster)
def _build_snat_rule_obj(min_src_ip, max_src_ip, nat_match_obj): def _build_snat_rule_obj(min_src_ip, max_src_ip, nat_match_obj):
@ -568,14 +575,15 @@ def delete_nat_rules_by_match(cluster, router_id, rule_type,
def delete_router_nat_rule(cluster, router_id, rule_id): def delete_router_nat_rule(cluster, router_id, rule_id):
uri = _build_uri_path(LROUTERNAT_RESOURCE, rule_id, router_id) uri = nsxlib._build_uri_path(LROUTERNAT_RESOURCE, rule_id, router_id)
do_request(HTTP_DELETE, uri, cluster=cluster) nsxlib.do_request(HTTP_DELETE, uri, cluster=cluster)
def query_nat_rules(cluster, router_id, fields="*", filters=None): def query_nat_rules(cluster, router_id, fields="*", filters=None):
uri = _build_uri_path(LROUTERNAT_RESOURCE, parent_resource_id=router_id, uri = nsxlib._build_uri_path(LROUTERNAT_RESOURCE,
fields=fields, filters=filters) parent_resource_id=router_id,
return get_all_query_pages(uri, cluster) fields=fields, filters=filters)
return nsxlib.get_all_query_pages(uri, cluster)
# NOTE(salvatore-orlando): The following FIXME applies in general to # NOTE(salvatore-orlando): The following FIXME applies in general to
@ -583,9 +591,9 @@ def query_nat_rules(cluster, router_id, fields="*", filters=None):
# FIXME(salvatore-orlando): need a lock around the list of IPs on an iface # FIXME(salvatore-orlando): need a lock around the list of IPs on an iface
def update_lrouter_port_ips(cluster, lrouter_id, lport_id, def update_lrouter_port_ips(cluster, lrouter_id, lport_id,
ips_to_add, ips_to_remove): ips_to_add, ips_to_remove):
uri = _build_uri_path(LROUTERPORT_RESOURCE, lport_id, lrouter_id) uri = nsxlib._build_uri_path(LROUTERPORT_RESOURCE, lport_id, lrouter_id)
try: try:
port = do_request(HTTP_GET, uri, cluster=cluster) port = nsxlib.do_request(HTTP_GET, uri, cluster=cluster)
# TODO(salvatore-orlando): Enforce ips_to_add intersection with # TODO(salvatore-orlando): Enforce ips_to_add intersection with
# ips_to_remove is empty # ips_to_remove is empty
ip_address_set = set(port['ip_addresses']) ip_address_set = set(port['ip_addresses'])
@ -593,7 +601,8 @@ def update_lrouter_port_ips(cluster, lrouter_id, lport_id,
ip_address_set = ip_address_set | set(ips_to_add) ip_address_set = ip_address_set | set(ips_to_add)
# Set is not JSON serializable - convert to list # Set is not JSON serializable - convert to list
port['ip_addresses'] = list(ip_address_set) port['ip_addresses'] = list(ip_address_set)
do_request(HTTP_PUT, uri, jsonutils.dumps(port), cluster=cluster) nsxlib.do_request(HTTP_PUT, uri, jsonutils.dumps(port),
cluster=cluster)
except exception.NotFound: except exception.NotFound:
# FIXME(salv-orlando):avoid raising different exception # FIXME(salv-orlando):avoid raising different exception
data = {'lport_id': lport_id, 'lrouter_id': lrouter_id} data = {'lport_id': lport_id, 'lrouter_id': lrouter_id}
@ -610,33 +619,34 @@ def update_lrouter_port_ips(cluster, lrouter_id, lport_id,
ROUTER_FUNC_DICT = { ROUTER_FUNC_DICT = {
'create_lrouter': { 'create_lrouter': {
2: {DEFAULT_VERSION: create_implicit_routing_lrouter, }, 2: {versioning.DEFAULT_VERSION: create_implicit_routing_lrouter, },
3: {DEFAULT_VERSION: create_implicit_routing_lrouter, 3: {versioning.DEFAULT_VERSION: create_implicit_routing_lrouter,
1: create_implicit_routing_lrouter_with_distribution, 1: create_implicit_routing_lrouter_with_distribution,
2: create_explicit_routing_lrouter, }, }, 2: create_explicit_routing_lrouter, }, },
'update_lrouter': { 'update_lrouter': {
2: {DEFAULT_VERSION: update_implicit_routing_lrouter, }, 2: {versioning.DEFAULT_VERSION: update_implicit_routing_lrouter, },
3: {DEFAULT_VERSION: update_implicit_routing_lrouter, 3: {versioning.DEFAULT_VERSION: update_implicit_routing_lrouter,
2: update_explicit_routing_lrouter, }, }, 2: update_explicit_routing_lrouter, }, },
'create_lrouter_dnat_rule': { 'create_lrouter_dnat_rule': {
2: {DEFAULT_VERSION: create_lrouter_dnat_rule_v2, }, 2: {versioning.DEFAULT_VERSION: create_lrouter_dnat_rule_v2, },
3: {DEFAULT_VERSION: create_lrouter_dnat_rule_v3, }, }, 3: {versioning.DEFAULT_VERSION: create_lrouter_dnat_rule_v3, }, },
'create_lrouter_snat_rule': { 'create_lrouter_snat_rule': {
2: {DEFAULT_VERSION: create_lrouter_snat_rule_v2, }, 2: {versioning.DEFAULT_VERSION: create_lrouter_snat_rule_v2, },
3: {DEFAULT_VERSION: create_lrouter_snat_rule_v3, }, }, 3: {versioning.DEFAULT_VERSION: create_lrouter_snat_rule_v3, }, },
'create_lrouter_nosnat_rule': { 'create_lrouter_nosnat_rule': {
2: {DEFAULT_VERSION: create_lrouter_nosnat_rule_v2, }, 2: {versioning.DEFAULT_VERSION: create_lrouter_nosnat_rule_v2, },
3: {DEFAULT_VERSION: create_lrouter_nosnat_rule_v3, }, }, 3: {versioning.DEFAULT_VERSION: create_lrouter_nosnat_rule_v3, }, },
'create_lrouter_nodnat_rule': { 'create_lrouter_nodnat_rule': {
2: {DEFAULT_VERSION: create_lrouter_nodnat_rule_v2, }, 2: {versioning.DEFAULT_VERSION: create_lrouter_nodnat_rule_v2, },
3: {DEFAULT_VERSION: create_lrouter_nodnat_rule_v3, }, }, 3: {versioning.DEFAULT_VERSION: create_lrouter_nodnat_rule_v3, }, },
'get_default_route_explicit_routing_lrouter': { 'get_default_route_explicit_routing_lrouter': {
3: {DEFAULT_VERSION: get_default_route_explicit_routing_lrouter_v32, 3: {versioning.DEFAULT_VERSION:
get_default_route_explicit_routing_lrouter_v32,
2: get_default_route_explicit_routing_lrouter_v32, }, }, 2: get_default_route_explicit_routing_lrouter_v32, }, },
} }
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def create_lrouter(cluster, *args, **kwargs): def create_lrouter(cluster, *args, **kwargs):
if kwargs.get('distributed', None): if kwargs.get('distributed', None):
v = cluster.api_client.get_version() v = cluster.api_client.get_version()
@ -645,12 +655,12 @@ def create_lrouter(cluster, *args, **kwargs):
return v return v
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def get_default_route_explicit_routing_lrouter(cluster, *args, **kwargs): def get_default_route_explicit_routing_lrouter(cluster, *args, **kwargs):
pass pass
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def update_lrouter(cluster, *args, **kwargs): def update_lrouter(cluster, *args, **kwargs):
if kwargs.get('routes', None): if kwargs.get('routes', None):
v = cluster.api_client.get_version() v = cluster.api_client.get_version()
@ -659,21 +669,21 @@ def update_lrouter(cluster, *args, **kwargs):
return v return v
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def create_lrouter_dnat_rule(cluster, *args, **kwargs): def create_lrouter_dnat_rule(cluster, *args, **kwargs):
pass pass
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def create_lrouter_snat_rule(cluster, *args, **kwargs): def create_lrouter_snat_rule(cluster, *args, **kwargs):
pass pass
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def create_lrouter_nosnat_rule(cluster, *args, **kwargs): def create_lrouter_nosnat_rule(cluster, *args, **kwargs):
pass pass
@versioned(ROUTER_FUNC_DICT) @versioning.versioned(ROUTER_FUNC_DICT)
def create_lrouter_nodnat_rule(cluster, *args, **kwargs): def create_lrouter_nodnat_rule(cluster, *args, **kwargs):
pass pass

View File

@ -20,10 +20,7 @@ from neutron.common import exceptions
from neutron.openstack.common import excutils from neutron.openstack.common import excutils
from neutron.openstack.common import log from neutron.openstack.common import log
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import do_request
from neutron.plugins.vmware.nsxlib import format_exception
from neutron.plugins.vmware.nsxlib import get_all_query_pages
HTTP_GET = "GET" HTTP_GET = "GET"
HTTP_POST = "POST" HTTP_POST = "POST"
@ -45,10 +42,10 @@ def mk_body(**kwargs):
def query_security_profiles(cluster, fields=None, filters=None): def query_security_profiles(cluster, fields=None, filters=None):
return get_all_query_pages( return nsxlib.get_all_query_pages(
_build_uri_path(SECPROF_RESOURCE, nsxlib._build_uri_path(SECPROF_RESOURCE,
fields=fields, fields=fields,
filters=filters), filters=filters),
cluster) cluster)
@ -82,7 +79,7 @@ def create_security_profile(cluster, tenant_id, neutron_id, security_profile):
hidden_rules['logical_port_ingress_rules']), hidden_rules['logical_port_ingress_rules']),
logical_port_egress_rules=hidden_rules['logical_port_egress_rules'] logical_port_egress_rules=hidden_rules['logical_port_egress_rules']
) )
rsp = do_request(HTTP_POST, path, body, cluster=cluster) rsp = nsxlib.do_request(HTTP_POST, path, body, cluster=cluster)
if security_profile.get('name') == 'default': if security_profile.get('name') == 'default':
# If security group is default allow ip traffic between # If security group is default allow ip traffic between
# members of the same security profile is allowed and ingress traffic # members of the same security profile is allowed and ingress traffic
@ -116,9 +113,9 @@ def update_security_group_rules(cluster, spid, rules):
body = mk_body( body = mk_body(
logical_port_ingress_rules=rules['logical_port_ingress_rules'], logical_port_ingress_rules=rules['logical_port_ingress_rules'],
logical_port_egress_rules=rules['logical_port_egress_rules']) logical_port_egress_rules=rules['logical_port_egress_rules'])
rsp = do_request(HTTP_PUT, path, body, cluster=cluster) rsp = nsxlib.do_request(HTTP_PUT, path, body, cluster=cluster)
except exceptions.NotFound as e: except exceptions.NotFound as e:
LOG.error(format_exception("Unknown", e, locals())) LOG.error(nsxlib.format_exception("Unknown", e, locals()))
#FIXME(salvatore-orlando): This should not raise NeutronException #FIXME(salvatore-orlando): This should not raise NeutronException
raise exceptions.NeutronException() raise exceptions.NeutronException()
LOG.debug(_("Updated Security Profile: %s"), rsp) LOG.debug(_("Updated Security Profile: %s"), rsp)
@ -126,19 +123,20 @@ def update_security_group_rules(cluster, spid, rules):
def update_security_profile(cluster, spid, name): def update_security_profile(cluster, spid, name):
return do_request(HTTP_PUT, return nsxlib.do_request(HTTP_PUT,
_build_uri_path(SECPROF_RESOURCE, resource_id=spid), nsxlib._build_uri_path(SECPROF_RESOURCE,
json.dumps({ resource_id=spid),
"display_name": utils.check_and_truncate(name) json.dumps({
}), "display_name": utils.check_and_truncate(name)
cluster=cluster) }),
cluster=cluster)
def delete_security_profile(cluster, spid): def delete_security_profile(cluster, spid):
path = "/ws.v1/security-profile/%s" % spid path = "/ws.v1/security-profile/%s" % spid
try: try:
do_request(HTTP_DELETE, path, cluster=cluster) nsxlib.do_request(HTTP_DELETE, path, cluster=cluster)
except exceptions.NotFound: except exceptions.NotFound:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
# This is not necessarily an error condition # This is not necessarily an error condition

View File

@ -24,9 +24,7 @@ from neutron.openstack.common import log
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.common import exceptions as nsx_exc from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.nsxlib import _build_uri_path from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import do_request
from neutron.plugins.vmware.nsxlib import get_all_query_pages
HTTP_GET = "GET" HTTP_GET = "GET"
HTTP_POST = "POST" HTTP_POST = "POST"
@ -68,10 +66,10 @@ def _configure_extensions(lport_obj, mac_address, fixed_ips,
def get_lswitch_by_id(cluster, lswitch_id): def get_lswitch_by_id(cluster, lswitch_id):
try: try:
lswitch_uri_path = _build_uri_path( lswitch_uri_path = nsxlib._build_uri_path(
LSWITCH_RESOURCE, lswitch_id, LSWITCH_RESOURCE, lswitch_id,
relations="LogicalSwitchStatus") relations="LogicalSwitchStatus")
return do_request(HTTP_GET, lswitch_uri_path, cluster=cluster) return nsxlib.do_request(HTTP_GET, lswitch_uri_path, cluster=cluster)
except exception.NotFound: except exception.NotFound:
# FIXME(salv-orlando): this should not raise a neutron exception # FIXME(salv-orlando): this should not raise a neutron exception
raise exception.NetworkNotFound(net_id=lswitch_id) raise exception.NetworkNotFound(net_id=lswitch_id)
@ -81,19 +79,19 @@ def get_lswitches(cluster, neutron_net_id):
def lookup_switches_by_tag(): def lookup_switches_by_tag():
# Fetch extra logical switches # Fetch extra logical switches
lswitch_query_path = _build_uri_path( lswitch_query_path = nsxlib._build_uri_path(
LSWITCH_RESOURCE, LSWITCH_RESOURCE,
fields="uuid,display_name,tags,lport_count", fields="uuid,display_name,tags,lport_count",
relations="LogicalSwitchStatus", relations="LogicalSwitchStatus",
filters={'tag': neutron_net_id, filters={'tag': neutron_net_id,
'tag_scope': 'quantum_net_id'}) 'tag_scope': 'quantum_net_id'})
return get_all_query_pages(lswitch_query_path, cluster) return nsxlib.get_all_query_pages(lswitch_query_path, cluster)
lswitch_uri_path = _build_uri_path(LSWITCH_RESOURCE, neutron_net_id, lswitch_uri_path = nsxlib._build_uri_path(LSWITCH_RESOURCE, neutron_net_id,
relations="LogicalSwitchStatus") relations="LogicalSwitchStatus")
results = [] results = []
try: try:
ls = do_request(HTTP_GET, lswitch_uri_path, cluster=cluster) ls = nsxlib.do_request(HTTP_GET, lswitch_uri_path, cluster=cluster)
results.append(ls) results.append(ls)
for tag in ls['tags']: for tag in ls['tags']:
if (tag['scope'] == "multi_lswitch" and if (tag['scope'] == "multi_lswitch" and
@ -127,23 +125,23 @@ def create_lswitch(cluster, neutron_net_id, tenant_id, display_name,
"scope": "shared"}) "scope": "shared"})
if "tags" in kwargs: if "tags" in kwargs:
lswitch_obj["tags"].extend(kwargs["tags"]) lswitch_obj["tags"].extend(kwargs["tags"])
uri = _build_uri_path(LSWITCH_RESOURCE) uri = nsxlib._build_uri_path(LSWITCH_RESOURCE)
lswitch = do_request(HTTP_POST, uri, json.dumps(lswitch_obj), lswitch = nsxlib.do_request(HTTP_POST, uri, json.dumps(lswitch_obj),
cluster=cluster) cluster=cluster)
LOG.debug(_("Created logical switch: %s"), lswitch['uuid']) LOG.debug(_("Created logical switch: %s"), lswitch['uuid'])
return lswitch return lswitch
def update_lswitch(cluster, lswitch_id, display_name, def update_lswitch(cluster, lswitch_id, display_name,
tenant_id=None, **kwargs): tenant_id=None, **kwargs):
uri = _build_uri_path(LSWITCH_RESOURCE, resource_id=lswitch_id) uri = nsxlib._build_uri_path(LSWITCH_RESOURCE, resource_id=lswitch_id)
lswitch_obj = {"display_name": utils.check_and_truncate(display_name), lswitch_obj = {"display_name": utils.check_and_truncate(display_name),
"tags": utils.get_tags(os_tid=tenant_id)} "tags": utils.get_tags(os_tid=tenant_id)}
if "tags" in kwargs: if "tags" in kwargs:
lswitch_obj["tags"].extend(kwargs["tags"]) lswitch_obj["tags"].extend(kwargs["tags"])
try: try:
return do_request(HTTP_PUT, uri, json.dumps(lswitch_obj), return nsxlib.do_request(HTTP_PUT, uri, json.dumps(lswitch_obj),
cluster=cluster) cluster=cluster)
except exception.NotFound as e: except exception.NotFound as e:
LOG.error(_("Network not found, Error: %s"), str(e)) LOG.error(_("Network not found, Error: %s"), str(e))
raise exception.NetworkNotFound(net_id=lswitch_id) raise exception.NetworkNotFound(net_id=lswitch_id)
@ -158,7 +156,7 @@ def delete_networks(cluster, net_id, lswitch_ids):
for ls_id in lswitch_ids: for ls_id in lswitch_ids:
path = "/ws.v1/lswitch/%s" % ls_id path = "/ws.v1/lswitch/%s" % ls_id
try: try:
do_request(HTTP_DELETE, path, cluster=cluster) nsxlib.do_request(HTTP_DELETE, path, cluster=cluster)
except exception.NotFound as e: except exception.NotFound as e:
LOG.error(_("Network not found, Error: %s"), str(e)) LOG.error(_("Network not found, Error: %s"), str(e))
raise exception.NetworkNotFound(net_id=ls_id) raise exception.NetworkNotFound(net_id=ls_id)
@ -170,15 +168,18 @@ def query_lswitch_lports(cluster, ls_uuid, fields="*",
if filters and "attachment" in filters: if filters and "attachment" in filters:
filters['attachment_vif_uuid'] = filters["attachment"] filters['attachment_vif_uuid'] = filters["attachment"]
del filters['attachment'] del filters['attachment']
uri = _build_uri_path(LSWITCHPORT_RESOURCE, parent_resource_id=ls_uuid, uri = nsxlib._build_uri_path(LSWITCHPORT_RESOURCE,
fields=fields, filters=filters, relations=relations) parent_resource_id=ls_uuid,
return do_request(HTTP_GET, uri, cluster=cluster)['results'] fields=fields,
filters=filters,
relations=relations)
return nsxlib.do_request(HTTP_GET, uri, cluster=cluster)['results']
def delete_port(cluster, switch, port): def delete_port(cluster, switch, port):
uri = "/ws.v1/lswitch/" + switch + "/lport/" + port uri = "/ws.v1/lswitch/" + switch + "/lport/" + port
try: try:
do_request(HTTP_DELETE, uri, cluster=cluster) nsxlib.do_request(HTTP_DELETE, uri, cluster=cluster)
except exception.NotFound: except exception.NotFound:
LOG.exception(_("Port or Network not found")) LOG.exception(_("Port or Network not found"))
raise exception.PortNotFoundOnNetwork( raise exception.PortNotFoundOnNetwork(
@ -234,9 +235,10 @@ def get_ports(cluster, networks=None, devices=None, tenants=None):
# call. In release L-** or M-**, we might want to swap the calls # call. In release L-** or M-**, we might want to swap the calls
# as it's likely that ports with the new tag would outnumber the # as it's likely that ports with the new tag would outnumber the
# ones with the old tag # ones with the old tag
ports = get_all_query_pages(lport_query_path_obsolete, cluster) ports = nsxlib.get_all_query_pages(lport_query_path_obsolete,
cluster)
if not ports: if not ports:
ports = get_all_query_pages(lport_query_path, cluster) ports = nsxlib.get_all_query_pages(lport_query_path, cluster)
except exception.NotFound: except exception.NotFound:
LOG.warn(_("Lswitch %s not found in NSX"), lswitch) LOG.warn(_("Lswitch %s not found in NSX"), lswitch)
ports = None ports = None
@ -259,16 +261,16 @@ def get_port_by_neutron_tag(cluster, lswitch_uuid, neutron_port_id):
Returns the NSX UUID of the logical port with tag q_port_id equal to Returns the NSX UUID of the logical port with tag q_port_id equal to
neutron_port_id or None if the port is not Found. neutron_port_id or None if the port is not Found.
""" """
uri = _build_uri_path(LSWITCHPORT_RESOURCE, uri = nsxlib._build_uri_path(LSWITCHPORT_RESOURCE,
parent_resource_id=lswitch_uuid, parent_resource_id=lswitch_uuid,
fields='uuid', fields='uuid',
filters={'tag': neutron_port_id, filters={'tag': neutron_port_id,
'tag_scope': 'q_port_id'}) 'tag_scope': 'q_port_id'})
LOG.debug(_("Looking for port with q_port_id tag '%(neutron_port_id)s' " LOG.debug(_("Looking for port with q_port_id tag '%(neutron_port_id)s' "
"on: '%(lswitch_uuid)s'"), "on: '%(lswitch_uuid)s'"),
{'neutron_port_id': neutron_port_id, {'neutron_port_id': neutron_port_id,
'lswitch_uuid': lswitch_uuid}) 'lswitch_uuid': lswitch_uuid})
res = do_request(HTTP_GET, uri, cluster=cluster) res = nsxlib.do_request(HTTP_GET, uri, cluster=cluster)
num_results = len(res["results"]) num_results = len(res["results"])
if num_results >= 1: if num_results >= 1:
if num_results > 1: if num_results > 1:
@ -287,7 +289,7 @@ def get_port(cluster, network, port, relations=None):
if relations: if relations:
uri += "relations=%s" % relations uri += "relations=%s" % relations
try: try:
return do_request(HTTP_GET, uri, cluster=cluster) return nsxlib.do_request(HTTP_GET, uri, cluster=cluster)
except exception.NotFound as e: except exception.NotFound as e:
LOG.error(_("Port or Network not found, Error: %s"), str(e)) LOG.error(_("Port or Network not found, Error: %s"), str(e))
raise exception.PortNotFoundOnNetwork( raise exception.PortNotFoundOnNetwork(
@ -313,8 +315,8 @@ def update_port(cluster, lswitch_uuid, lport_uuid, neutron_port_id, tenant_id,
path = "/ws.v1/lswitch/" + lswitch_uuid + "/lport/" + lport_uuid path = "/ws.v1/lswitch/" + lswitch_uuid + "/lport/" + lport_uuid
try: try:
result = do_request(HTTP_PUT, path, json.dumps(lport_obj), result = nsxlib.do_request(HTTP_PUT, path, json.dumps(lport_obj),
cluster=cluster) cluster=cluster)
LOG.debug(_("Updated logical port %(result)s " LOG.debug(_("Updated logical port %(result)s "
"on logical switch %(uuid)s"), "on logical switch %(uuid)s"),
{'result': result['uuid'], 'uuid': lswitch_uuid}) {'result': result['uuid'], 'uuid': lswitch_uuid})
@ -345,10 +347,10 @@ def create_lport(cluster, lswitch_uuid, tenant_id, neutron_port_id,
queue_id, mac_learning_enabled, queue_id, mac_learning_enabled,
allowed_address_pairs) allowed_address_pairs)
path = _build_uri_path(LSWITCHPORT_RESOURCE, path = nsxlib._build_uri_path(LSWITCHPORT_RESOURCE,
parent_resource_id=lswitch_uuid) parent_resource_id=lswitch_uuid)
result = do_request(HTTP_POST, path, json.dumps(lport_obj), result = nsxlib.do_request(HTTP_POST, path, json.dumps(lport_obj),
cluster=cluster) cluster=cluster)
LOG.debug(_("Created logical port %(result)s on logical switch %(uuid)s"), LOG.debug(_("Created logical port %(result)s on logical switch %(uuid)s"),
{'result': result['uuid'], 'uuid': lswitch_uuid}) {'result': result['uuid'], 'uuid': lswitch_uuid})
@ -358,9 +360,9 @@ def create_lport(cluster, lswitch_uuid, tenant_id, neutron_port_id,
def get_port_status(cluster, lswitch_id, port_id): def get_port_status(cluster, lswitch_id, port_id):
"""Retrieve the operational status of the port.""" """Retrieve the operational status of the port."""
try: try:
r = do_request(HTTP_GET, r = nsxlib.do_request(HTTP_GET,
"/ws.v1/lswitch/%s/lport/%s/status" % "/ws.v1/lswitch/%s/lport/%s/status" %
(lswitch_id, port_id), cluster=cluster) (lswitch_id, port_id), cluster=cluster)
except exception.NotFound as e: except exception.NotFound as e:
LOG.error(_("Port not found, Error: %s"), str(e)) LOG.error(_("Port not found, Error: %s"), str(e))
raise exception.PortNotFoundOnNetwork( raise exception.PortNotFoundOnNetwork(
@ -372,12 +374,12 @@ def get_port_status(cluster, lswitch_id, port_id):
def plug_interface(cluster, lswitch_id, lport_id, att_obj): def plug_interface(cluster, lswitch_id, lport_id, att_obj):
return do_request(HTTP_PUT, return nsxlib.do_request(HTTP_PUT,
_build_uri_path(LSWITCHPORT_RESOURCE, nsxlib._build_uri_path(LSWITCHPORT_RESOURCE,
lport_id, lswitch_id, lport_id, lswitch_id,
is_attachment=True), is_attachment=True),
json.dumps(att_obj), json.dumps(att_obj),
cluster=cluster) cluster=cluster)
def plug_vif_interface( def plug_vif_interface(

View File

@ -60,7 +60,7 @@ from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import nsx_utils from neutron.plugins.vmware.common import nsx_utils
from neutron.plugins.vmware.common import securitygroups as sg_utils from neutron.plugins.vmware.common import securitygroups as sg_utils
from neutron.plugins.vmware.common import sync from neutron.plugins.vmware.common import sync
from neutron.plugins.vmware.common.utils import NetworkTypes from neutron.plugins.vmware.common import utils as c_utils
from neutron.plugins.vmware.dbexts import db as nsx_db from neutron.plugins.vmware.dbexts import db as nsx_db
from neutron.plugins.vmware.dbexts import distributedrouter as dist_rtr from neutron.plugins.vmware.dbexts import distributedrouter as dist_rtr
from neutron.plugins.vmware.dbexts import maclearning as mac_db from neutron.plugins.vmware.dbexts import maclearning as mac_db
@ -374,8 +374,8 @@ class NsxPluginV2(addr_pair_db.AllowedAddressPairsMixin,
max_ports = self.nsx_opts.max_lp_per_overlay_ls max_ports = self.nsx_opts.max_lp_per_overlay_ls
allow_extra_lswitches = False allow_extra_lswitches = False
for network_binding in network_bindings: for network_binding in network_bindings:
if network_binding.binding_type in (NetworkTypes.FLAT, if network_binding.binding_type in (c_utils.NetworkTypes.FLAT,
NetworkTypes.VLAN): c_utils.NetworkTypes.VLAN):
max_ports = self.nsx_opts.max_lp_per_bridged_ls max_ports = self.nsx_opts.max_lp_per_bridged_ls
allow_extra_lswitches = True allow_extra_lswitches = True
break break
@ -621,7 +621,7 @@ class NsxPluginV2(addr_pair_db.AllowedAddressPairsMixin,
True, True,
ip_addresses) ip_addresses)
ext_network = self.get_network(context, port_data['network_id']) ext_network = self.get_network(context, port_data['network_id'])
if ext_network.get(pnet.NETWORK_TYPE) == NetworkTypes.L3_EXT: if ext_network.get(pnet.NETWORK_TYPE) == c_utils.NetworkTypes.L3_EXT:
# Update attachment # Update attachment
physical_network = (ext_network[pnet.PHYSICAL_NETWORK] or physical_network = (ext_network[pnet.PHYSICAL_NETWORK] or
self.cluster.default_l3_gw_service_uuid) self.cluster.default_l3_gw_service_uuid)
@ -758,12 +758,13 @@ class NsxPluginV2(addr_pair_db.AllowedAddressPairsMixin,
err_msg = None err_msg = None
if not network_type_set: if not network_type_set:
err_msg = _("%s required") % pnet.NETWORK_TYPE err_msg = _("%s required") % pnet.NETWORK_TYPE
elif network_type in (NetworkTypes.GRE, NetworkTypes.STT, elif network_type in (c_utils.NetworkTypes.GRE,
NetworkTypes.FLAT): c_utils.NetworkTypes.STT,
c_utils.NetworkTypes.FLAT):
if segmentation_id_set: if segmentation_id_set:
err_msg = _("Segmentation ID cannot be specified with " err_msg = _("Segmentation ID cannot be specified with "
"flat network type") "flat network type")
elif network_type == NetworkTypes.VLAN: elif network_type == c_utils.NetworkTypes.VLAN:
if not segmentation_id_set: if not segmentation_id_set:
err_msg = _("Segmentation ID must be specified with " err_msg = _("Segmentation ID must be specified with "
"vlan network type") "vlan network type")
@ -782,7 +783,7 @@ class NsxPluginV2(addr_pair_db.AllowedAddressPairsMixin,
raise n_exc.VlanIdInUse( raise n_exc.VlanIdInUse(
vlan_id=segmentation_id, vlan_id=segmentation_id,
physical_network=physical_network) physical_network=physical_network)
elif network_type == NetworkTypes.L3_EXT: elif network_type == c_utils.NetworkTypes.L3_EXT:
if (segmentation_id_set and if (segmentation_id_set and
not utils.is_valid_vlan_tag(segmentation_id)): not utils.is_valid_vlan_tag(segmentation_id)):
err_msg = (_("%(segmentation_id)s out of range " err_msg = (_("%(segmentation_id)s out of range "
@ -888,9 +889,10 @@ class NsxPluginV2(addr_pair_db.AllowedAddressPairsMixin,
if bindings: if bindings:
transport_entry = {} transport_entry = {}
for binding in bindings: for binding in bindings:
if binding.binding_type in [NetworkTypes.FLAT, if binding.binding_type in [c_utils.NetworkTypes.FLAT,
NetworkTypes.VLAN]: c_utils.NetworkTypes.VLAN]:
transport_entry['transport_type'] = NetworkTypes.BRIDGE transport_entry['transport_type'] = (
c_utils.NetworkTypes.BRIDGE)
transport_entry['binding_config'] = {} transport_entry['binding_config'] = {}
vlan_id = binding.vlan_id vlan_id = binding.vlan_id
if vlan_id: if vlan_id:
@ -910,8 +912,9 @@ class NsxPluginV2(addr_pair_db.AllowedAddressPairsMixin,
transport_entry = {} transport_entry = {}
transport_type = transport_zone.get(pnet.NETWORK_TYPE) transport_type = transport_zone.get(pnet.NETWORK_TYPE)
if transport_type in [NetworkTypes.FLAT, NetworkTypes.VLAN]: if transport_type in [c_utils.NetworkTypes.FLAT,
transport_entry['transport_type'] = NetworkTypes.BRIDGE c_utils.NetworkTypes.VLAN]:
transport_entry['transport_type'] = c_utils.NetworkTypes.BRIDGE
transport_entry['binding_config'] = {} transport_entry['binding_config'] = {}
vlan_id = transport_zone.get(pnet.SEGMENTATION_ID) vlan_id = transport_zone.get(pnet.SEGMENTATION_ID)
if vlan_id: if vlan_id:

View File

@ -43,10 +43,8 @@ from neutron.plugins.vmware.nsxlib import router as routerlib
from neutron.plugins.vmware.nsxlib import switch as switchlib from neutron.plugins.vmware.nsxlib import switch as switchlib
from neutron.plugins.vmware.plugins import base from neutron.plugins.vmware.plugins import base
from neutron.plugins.vmware.vshield.common import constants as vcns_const from neutron.plugins.vmware.vshield.common import constants as vcns_const
from neutron.plugins.vmware.vshield.common.constants import RouterStatus
from neutron.plugins.vmware.vshield.common import exceptions from neutron.plugins.vmware.vshield.common import exceptions
from neutron.plugins.vmware.vshield.tasks.constants import TaskState from neutron.plugins.vmware.vshield.tasks import constants as tasks_const
from neutron.plugins.vmware.vshield.tasks.constants import TaskStatus
from neutron.plugins.vmware.vshield import vcns_driver from neutron.plugins.vmware.vshield import vcns_driver
from sqlalchemy.orm import exc as sa_exc from sqlalchemy.orm import exc as sa_exc
@ -64,15 +62,15 @@ ROUTER_STATUS = [
] ]
ROUTER_STATUS_LEVEL = { ROUTER_STATUS_LEVEL = {
service_constants.ACTIVE: RouterStatus.ROUTER_STATUS_ACTIVE, service_constants.ACTIVE: vcns_const.RouterStatus.ROUTER_STATUS_ACTIVE,
service_constants.DOWN: RouterStatus.ROUTER_STATUS_DOWN, service_constants.DOWN: vcns_const.RouterStatus.ROUTER_STATUS_DOWN,
service_constants.PENDING_CREATE: ( service_constants.PENDING_CREATE: (
RouterStatus.ROUTER_STATUS_PENDING_CREATE vcns_const.RouterStatus.ROUTER_STATUS_PENDING_CREATE
), ),
service_constants.PENDING_DELETE: ( service_constants.PENDING_DELETE: (
RouterStatus.ROUTER_STATUS_PENDING_DELETE vcns_const.RouterStatus.ROUTER_STATUS_PENDING_DELETE
), ),
service_constants.ERROR: RouterStatus.ROUTER_STATUS_ERROR service_constants.ERROR: vcns_const.RouterStatus.ROUTER_STATUS_ERROR
} }
@ -310,7 +308,7 @@ class NsxAdvancedPlugin(sr_db.ServiceRouter_mixin,
self.vcns_driver.external_network, self.vcns_driver.external_network,
addr, mask, secondary=secondary) addr, mask, secondary=secondary)
if sync: if sync:
task.wait(TaskState.RESULT) task.wait(tasks_const.TaskState.RESULT)
def _update_router_gw_info(self, context, router_id, info): def _update_router_gw_info(self, context, router_id, info):
if not self._is_advanced_service_router(context, router_id): if not self._is_advanced_service_router(context, router_id):
@ -576,11 +574,11 @@ class NsxAdvancedPlugin(sr_db.ServiceRouter_mixin,
lrouter = routerlib.get_lrouter(self.cluster, id) lrouter = routerlib.get_lrouter(self.cluster, id)
lr_status = lrouter["_relations"]["LogicalRouterStatus"] lr_status = lrouter["_relations"]["LogicalRouterStatus"]
if lr_status["fabric_status"]: if lr_status["fabric_status"]:
nsx_status = RouterStatus.ROUTER_STATUS_ACTIVE nsx_status = vcns_const.RouterStatus.ROUTER_STATUS_ACTIVE
else: else:
nsx_status = RouterStatus.ROUTER_STATUS_DOWN nsx_status = vcns_const.RouterStatus.ROUTER_STATUS_DOWN
except n_exc.NotFound: except n_exc.NotFound:
nsx_status = RouterStatus.ROUTER_STATUS_ERROR nsx_status = vcns_const.RouterStatus.ROUTER_STATUS_ERROR
return nsx_status return nsx_status
@ -606,11 +604,11 @@ class NsxAdvancedPlugin(sr_db.ServiceRouter_mixin,
if (nsx_lrouter["_relations"]["LogicalRouterStatus"] if (nsx_lrouter["_relations"]["LogicalRouterStatus"]
["fabric_status"]): ["fabric_status"]):
nsx_status[nsx_lrouter['uuid']] = ( nsx_status[nsx_lrouter['uuid']] = (
RouterStatus.ROUTER_STATUS_ACTIVE vcns_const.RouterStatus.ROUTER_STATUS_ACTIVE
) )
else: else:
nsx_status[nsx_lrouter['uuid']] = ( nsx_status[nsx_lrouter['uuid']] = (
RouterStatus.ROUTER_STATUS_DOWN vcns_const.RouterStatus.ROUTER_STATUS_DOWN
) )
return nsx_status return nsx_status
@ -685,7 +683,8 @@ class NsxAdvancedPlugin(sr_db.ServiceRouter_mixin,
if router_type == ROUTER_TYPE_ADVANCED: if router_type == ROUTER_TYPE_ADVANCED:
vse_status_level = vse_status_all.get(router['id']) vse_status_level = vse_status_all.get(router['id'])
if vse_status_level is None: if vse_status_level is None:
vse_status_level = RouterStatus.ROUTER_STATUS_ERROR vse_status_level = (
vcns_const.RouterStatus.ROUTER_STATUS_ERROR)
if vse_status_level > ROUTER_STATUS_LEVEL[router['status']]: if vse_status_level > ROUTER_STATUS_LEVEL[router['status']]:
router['status'] = ROUTER_STATUS[vse_status_level] router['status'] = ROUTER_STATUS[vse_status_level]
@ -1729,7 +1728,7 @@ class VcnsCallbacks(object):
# Router might have been deleted before deploy finished # Router might have been deleted before deploy finished
LOG.exception(_("Router %s not found"), lrouter['uuid']) LOG.exception(_("Router %s not found"), lrouter['uuid'])
if task.status == TaskStatus.COMPLETED: if task.status == tasks_const.TaskStatus.COMPLETED:
LOG.debug(_("Successfully deployed %(edge_id)s for " LOG.debug(_("Successfully deployed %(edge_id)s for "
"router %(name)s"), { "router %(name)s"), {
'edge_id': task.userdata['edge_id'], 'edge_id': task.userdata['edge_id'],
@ -1757,7 +1756,7 @@ class VcnsCallbacks(object):
jobdata = task.userdata['jobdata'] jobdata = task.userdata['jobdata']
router_id = task.userdata['router_id'] router_id = task.userdata['router_id']
context = jobdata['context'] context = jobdata['context']
if task.status == TaskStatus.COMPLETED: if task.status == tasks_const.TaskStatus.COMPLETED:
vcns_db.delete_vcns_router_binding(context.session, vcns_db.delete_vcns_router_binding(context.session,
router_id) router_id)

View File

@ -15,8 +15,7 @@
# under the License. # under the License.
# #
from neutronclient.neutron.v2_0 import find_resourceid_by_name_or_id from neutronclient.neutron import v2_0 as client
from neutronclient.neutron.v2_0 import NeutronCommand
LSN_PATH = '/lsns' LSN_PATH = '/lsns'
@ -29,7 +28,7 @@ def print_report(write_func, report):
write_func(_("Port uuids = %s\n\n") % ports) write_func(_("Port uuids = %s\n\n") % ports)
class NetworkReport(NeutronCommand): class NetworkReport(client.NeutronCommand):
"""Retrieve network migration report.""" """Retrieve network migration report."""
def get_parser(self, prog_name): def get_parser(self, prog_name):
@ -40,14 +39,15 @@ class NetworkReport(NeutronCommand):
def run(self, parsed_args): def run(self, parsed_args):
net = parsed_args.network net = parsed_args.network
net_id = find_resourceid_by_name_or_id(self.app.client, 'network', net) net_id = client.find_resourceid_by_name_or_id(self.app.client,
'network', net)
res = self.app.client.get("%s/%s" % (LSN_PATH, net_id)) res = self.app.client.get("%s/%s" % (LSN_PATH, net_id))
if res: if res:
self.app.stdout.write(_('Migration report is:\n')) self.app.stdout.write(_('Migration report is:\n'))
print_report(self.app.stdout.write, res['lsn']) print_report(self.app.stdout.write, res['lsn'])
class NetworkMigrate(NeutronCommand): class NetworkMigrate(client.NeutronCommand):
"""Perform network migration.""" """Perform network migration."""
def get_parser(self, prog_name): def get_parser(self, prog_name):
@ -58,7 +58,8 @@ class NetworkMigrate(NeutronCommand):
def run(self, parsed_args): def run(self, parsed_args):
net = parsed_args.network net = parsed_args.network
net_id = find_resourceid_by_name_or_id(self.app.client, 'network', net) net_id = client.find_resourceid_by_name_or_id(self.app.client,
'network', net)
body = {'network': net_id} body = {'network': net_id}
res = self.app.client.post(LSN_PATH, body={'lsn': body}) res = self.app.client.post(LSN_PATH, body={'lsn': body})
if res: if res:

View File

@ -23,10 +23,9 @@ from neutron.openstack.common import log as logging
from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.vshield.common import ( from neutron.plugins.vmware.vshield.common import (
constants as vcns_const) constants as vcns_const)
from neutron.plugins.vmware.vshield.common.constants import RouterStatus from neutron.plugins.vmware.vshield.common import constants as common_constants
from neutron.plugins.vmware.vshield.common import exceptions from neutron.plugins.vmware.vshield.common import exceptions
from neutron.plugins.vmware.vshield.tasks.constants import TaskState from neutron.plugins.vmware.vshield.tasks import constants
from neutron.plugins.vmware.vshield.tasks.constants import TaskStatus
from neutron.plugins.vmware.vshield.tasks import tasks from neutron.plugins.vmware.vshield.tasks import tasks
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -114,11 +113,11 @@ class EdgeApplianceDriver(object):
def _edge_status_to_level(self, status): def _edge_status_to_level(self, status):
if status == 'GREEN': if status == 'GREEN':
status_level = RouterStatus.ROUTER_STATUS_ACTIVE status_level = common_constants.RouterStatus.ROUTER_STATUS_ACTIVE
elif status in ('GREY', 'YELLOW'): elif status in ('GREY', 'YELLOW'):
status_level = RouterStatus.ROUTER_STATUS_DOWN status_level = common_constants.RouterStatus.ROUTER_STATUS_DOWN
else: else:
status_level = RouterStatus.ROUTER_STATUS_ERROR status_level = common_constants.RouterStatus.ROUTER_STATUS_ERROR
return status_level return status_level
def _enable_loadbalancer(self, edge): def _enable_loadbalancer(self, edge):
@ -137,12 +136,13 @@ class EdgeApplianceDriver(object):
except exceptions.VcnsApiException as e: except exceptions.VcnsApiException as e:
LOG.exception(_("VCNS: Failed to get edge status:\n%s"), LOG.exception(_("VCNS: Failed to get edge status:\n%s"),
e.response) e.response)
status_level = RouterStatus.ROUTER_STATUS_ERROR status_level = common_constants.RouterStatus.ROUTER_STATUS_ERROR
try: try:
desc = jsonutils.loads(e.response) desc = jsonutils.loads(e.response)
if desc.get('errorCode') == ( if desc.get('errorCode') == (
vcns_const.VCNS_ERROR_CODE_EDGE_NOT_RUNNING): vcns_const.VCNS_ERROR_CODE_EDGE_NOT_RUNNING):
status_level = RouterStatus.ROUTER_STATUS_DOWN status_level = (
common_constants.RouterStatus.ROUTER_STATUS_DOWN)
except ValueError: except ValueError:
LOG.exception(e.response) LOG.exception(e.response)
@ -175,7 +175,7 @@ class EdgeApplianceDriver(object):
LOG.exception(_("VCNS: Failed to update vnic %d"), LOG.exception(_("VCNS: Failed to update vnic %d"),
config['index']) config['index'])
return TaskStatus.COMPLETED return constants.TaskStatus.COMPLETED
def update_interface(self, router_id, edge_id, index, network, def update_interface(self, router_id, edge_id, index, network,
address=None, netmask=None, secondary=None, address=None, netmask=None, secondary=None,
@ -220,7 +220,7 @@ class EdgeApplianceDriver(object):
edge_id = response['edgeId'] edge_id = response['edgeId']
LOG.debug(_("VCNS: deploying edge %s"), edge_id) LOG.debug(_("VCNS: deploying edge %s"), edge_id)
userdata['edge_id'] = edge_id userdata['edge_id'] = edge_id
status = TaskStatus.PENDING status = constants.TaskStatus.PENDING
except exceptions.VcnsApiException: except exceptions.VcnsApiException:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception(_("VCNS: deploy edge failed for router %s."), LOG.exception(_("VCNS: deploy edge failed for router %s."),
@ -235,11 +235,11 @@ class EdgeApplianceDriver(object):
task.userdata['retries'] = 0 task.userdata['retries'] = 0
system_status = response.get('systemStatus', None) system_status = response.get('systemStatus', None)
if system_status is None: if system_status is None:
status = TaskStatus.PENDING status = constants.TaskStatus.PENDING
elif system_status == 'good': elif system_status == 'good':
status = TaskStatus.COMPLETED status = constants.TaskStatus.COMPLETED
else: else:
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
except exceptions.VcnsApiException: except exceptions.VcnsApiException:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception(_("VCNS: Edge %s status query failed."), edge_id) LOG.exception(_("VCNS: Edge %s status query failed."), edge_id)
@ -252,19 +252,19 @@ class EdgeApplianceDriver(object):
'edge_id': edge_id, 'edge_id': edge_id,
'retries': retries} 'retries': retries}
LOG.exception(msg) LOG.exception(msg)
status = TaskStatus.PENDING status = constants.TaskStatus.PENDING
else: else:
msg = _("VCNS: Unable to retrieve edge %s status. " msg = _("VCNS: Unable to retrieve edge %s status. "
"Abort.") % edge_id "Abort.") % edge_id
LOG.exception(msg) LOG.exception(msg)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
LOG.debug(_("VCNS: Edge %s status"), edge_id) LOG.debug(_("VCNS: Edge %s status"), edge_id)
return status return status
def _result_edge(self, task): def _result_edge(self, task):
router_name = task.userdata['router_name'] router_name = task.userdata['router_name']
edge_id = task.userdata.get('edge_id') edge_id = task.userdata.get('edge_id')
if task.status != TaskStatus.COMPLETED: if task.status != constants.TaskStatus.COMPLETED:
LOG.error(_("VCNS: Failed to deploy edge %(edge_id)s " LOG.error(_("VCNS: Failed to deploy edge %(edge_id)s "
"for %(name)s, status %(status)d"), { "for %(name)s, status %(status)d"), {
'edge_id': edge_id, 'edge_id': edge_id,
@ -280,7 +280,7 @@ class EdgeApplianceDriver(object):
def _delete_edge(self, task): def _delete_edge(self, task):
edge_id = task.userdata['edge_id'] edge_id = task.userdata['edge_id']
LOG.debug(_("VCNS: start destroying edge %s"), edge_id) LOG.debug(_("VCNS: start destroying edge %s"), edge_id)
status = TaskStatus.COMPLETED status = constants.TaskStatus.COMPLETED
if edge_id: if edge_id:
try: try:
self.vcns.delete_edge(edge_id) self.vcns.delete_edge(edge_id)
@ -291,10 +291,10 @@ class EdgeApplianceDriver(object):
"%(response)s") % { "%(response)s") % {
'edge_id': edge_id, 'response': e.response} 'edge_id': edge_id, 'response': e.response}
LOG.exception(msg) LOG.exception(msg)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
except Exception: except Exception:
LOG.exception(_("VCNS: Failed to delete %s"), edge_id) LOG.exception(_("VCNS: Failed to delete %s"), edge_id)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
return status return status
@ -347,7 +347,7 @@ class EdgeApplianceDriver(object):
if wait_for_exec: if wait_for_exec:
# wait until the deploy task is executed so edge_id is available # wait until the deploy task is executed so edge_id is available
task.wait(TaskState.EXECUTED) task.wait(constants.TaskState.EXECUTED)
return task return task
@ -402,11 +402,11 @@ class EdgeApplianceDriver(object):
try: try:
self.vcns.update_nat_config(edge_id, nat) self.vcns.update_nat_config(edge_id, nat)
status = TaskStatus.COMPLETED status = constants.TaskStatus.COMPLETED
except exceptions.VcnsApiException as e: except exceptions.VcnsApiException as e:
LOG.exception(_("VCNS: Failed to create snat rule:\n%s"), LOG.exception(_("VCNS: Failed to create snat rule:\n%s"),
e.response) e.response)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
return status return status
@ -439,7 +439,7 @@ class EdgeApplianceDriver(object):
'type': addrtype, 'addr': address}) 'type': addrtype, 'addr': address})
nat = self.get_nat_config(edge_id) nat = self.get_nat_config(edge_id)
del nat['version'] del nat['version']
status = TaskStatus.COMPLETED status = constants.TaskStatus.COMPLETED
for nat_rule in nat['rules']['natRulesDtos']: for nat_rule in nat['rules']['natRulesDtos']:
if nat_rule[addrtype] == address: if nat_rule[addrtype] == address:
rule_id = nat_rule['ruleId'] rule_id = nat_rule['ruleId']
@ -448,7 +448,7 @@ class EdgeApplianceDriver(object):
except exceptions.VcnsApiException as e: except exceptions.VcnsApiException as e:
LOG.exception(_("VCNS: Failed to delete snat rule:\n" LOG.exception(_("VCNS: Failed to delete snat rule:\n"
"%s"), e.response) "%s"), e.response)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
return status return status
@ -513,7 +513,7 @@ class EdgeApplianceDriver(object):
if task != self.updated_task['nat'][edge_id]: if task != self.updated_task['nat'][edge_id]:
# this task does not have the latest config, abort now # this task does not have the latest config, abort now
# for speedup # for speedup
return TaskStatus.ABORT return constants.TaskStatus.ABORT
rules = task.userdata['rules'] rules = task.userdata['rules']
LOG.debug(_("VCNS: start updating nat rules: %s"), rules) LOG.debug(_("VCNS: start updating nat rules: %s"), rules)
@ -527,11 +527,11 @@ class EdgeApplianceDriver(object):
try: try:
self.vcns.update_nat_config(edge_id, nat) self.vcns.update_nat_config(edge_id, nat)
status = TaskStatus.COMPLETED status = constants.TaskStatus.COMPLETED
except exceptions.VcnsApiException as e: except exceptions.VcnsApiException as e:
LOG.exception(_("VCNS: Failed to create snat rule:\n%s"), LOG.exception(_("VCNS: Failed to create snat rule:\n%s"),
e.response) e.response)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
return status return status
@ -572,7 +572,7 @@ class EdgeApplianceDriver(object):
task.userdata.get('skippable', True)): task.userdata.get('skippable', True)):
# this task does not have the latest config, abort now # this task does not have the latest config, abort now
# for speedup # for speedup
return TaskStatus.ABORT return constants.TaskStatus.ABORT
gateway = task.userdata['gateway'] gateway = task.userdata['gateway']
routes = task.userdata['routes'] routes = task.userdata['routes']
LOG.debug(_("VCNS: start updating routes for %s"), edge_id) LOG.debug(_("VCNS: start updating routes for %s"), edge_id)
@ -597,11 +597,11 @@ class EdgeApplianceDriver(object):
} }
try: try:
self.vcns.update_routes(edge_id, request) self.vcns.update_routes(edge_id, request)
status = TaskStatus.COMPLETED status = constants.TaskStatus.COMPLETED
except exceptions.VcnsApiException as e: except exceptions.VcnsApiException as e:
LOG.exception(_("VCNS: Failed to update routes:\n%s"), LOG.exception(_("VCNS: Failed to update routes:\n%s"),
e.response) e.response)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
return status return status

View File

@ -22,8 +22,7 @@ from eventlet import greenthread
from neutron.common import exceptions from neutron.common import exceptions
from neutron.openstack.common import log as logging from neutron.openstack.common import log as logging
from neutron.openstack.common import loopingcall from neutron.openstack.common import loopingcall
from neutron.plugins.vmware.vshield.tasks.constants import TaskState from neutron.plugins.vmware.vshield.tasks import constants
from neutron.plugins.vmware.vshield.tasks.constants import TaskStatus
DEFAULT_INTERVAL = 1000 DEFAULT_INTERVAL = 1000
@ -31,7 +30,7 @@ LOG = logging.getLogger(__name__)
def nop(task): def nop(task):
return TaskStatus.COMPLETED return constants.TaskStatus.COMPLETED
class TaskException(exceptions.NeutronException): class TaskException(exceptions.NeutronException):
@ -64,12 +63,12 @@ class Task():
self.status = None self.status = None
self._monitors = { self._monitors = {
TaskState.START: [], constants.TaskState.START: [],
TaskState.EXECUTED: [], constants.TaskState.EXECUTED: [],
TaskState.RESULT: [] constants.TaskState.RESULT: []
} }
self._states = [None, None, None, None] self._states = [None, None, None, None]
self._state = TaskState.NONE self._state = constants.TaskState.NONE
def _add_monitor(self, action, func): def _add_monitor(self, action, func):
self._monitors[action].append(func) self._monitors[action].append(func)
@ -106,10 +105,10 @@ class Task():
return self return self
def _start(self): def _start(self):
return self._invoke_monitor(TaskState.START) return self._invoke_monitor(constants.TaskState.START)
def _executed(self): def _executed(self):
return self._invoke_monitor(TaskState.EXECUTED) return self._invoke_monitor(constants.TaskState.EXECUTED)
def _update_status(self, status): def _update_status(self, status):
if self.status == status: if self.status == status:
@ -118,21 +117,21 @@ class Task():
self.status = status self.status = status
def _finished(self): def _finished(self):
return self._invoke_monitor(TaskState.RESULT) return self._invoke_monitor(constants.TaskState.RESULT)
def add_start_monitor(self, func): def add_start_monitor(self, func):
return self._add_monitor(TaskState.START, func) return self._add_monitor(constants.TaskState.START, func)
def add_executed_monitor(self, func): def add_executed_monitor(self, func):
return self._add_monitor(TaskState.EXECUTED, func) return self._add_monitor(constants.TaskState.EXECUTED, func)
def add_result_monitor(self, func): def add_result_monitor(self, func):
return self._add_monitor(TaskState.RESULT, func) return self._add_monitor(constants.TaskState.RESULT, func)
def wait(self, state): def wait(self, state):
if (state < TaskState.START or if (state < constants.TaskState.START or
state > TaskState.RESULT or state > constants.TaskState.RESULT or
state == TaskState.STATUS): state == constants.TaskState.STATUS):
raise InvalidState(state=state) raise InvalidState(state=state)
if state <= self._state: if state <= self._state:
@ -190,7 +189,7 @@ class TaskManager():
'task': str(task), 'task': str(task),
'cb': str(task._execute_callback)} 'cb': str(task._execute_callback)}
LOG.exception(msg) LOG.exception(msg)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
LOG.debug(_("Task %(task)s return %(status)s"), { LOG.debug(_("Task %(task)s return %(status)s"), {
'task': str(task), 'task': str(task),
@ -233,9 +232,9 @@ class TaskManager():
'task': str(task), 'task': str(task),
'cb': str(task._status_callback)} 'cb': str(task._status_callback)}
LOG.exception(msg) LOG.exception(msg)
status = TaskStatus.ERROR status = constants.TaskStatus.ERROR
task._update_status(status) task._update_status(status)
if status != TaskStatus.PENDING: if status != constants.TaskStatus.PENDING:
self._dequeue(task, True) self._dequeue(task, True)
def _enqueue(self, task): def _enqueue(self, task):
@ -262,7 +261,7 @@ class TaskManager():
while tasks: while tasks:
task = tasks[0] task = tasks[0]
status = self._execute(task) status = self._execute(task)
if status == TaskStatus.PENDING: if status == constants.TaskStatus.PENDING:
break break
self._dequeue(task, False) self._dequeue(task, False)
@ -277,7 +276,7 @@ class TaskManager():
for resource_id in self._tasks.keys(): for resource_id in self._tasks.keys():
tasks = list(self._tasks[resource_id]) tasks = list(self._tasks[resource_id])
for task in tasks: for task in tasks:
task._update_status(TaskStatus.ABORT) task._update_status(constants.TaskStatus.ABORT)
self._dequeue(task, False) self._dequeue(task, False)
def _get_task(self): def _get_task(self):
@ -314,7 +313,7 @@ class TaskManager():
# The thread is killed during _execute(). To guarantee # The thread is killed during _execute(). To guarantee
# the task been aborted correctly, put it to the queue. # the task been aborted correctly, put it to the queue.
self._enqueue(task) self._enqueue(task)
elif task.status != TaskStatus.PENDING: elif task.status != constants.TaskStatus.PENDING:
self._result(task) self._result(task)
else: else:
self._enqueue(task) self._enqueue(task)

View File

@ -410,7 +410,7 @@ class TestOVSBridge(RyuAgentTestCase):
side_effect=[None, {'opts': 'opts_val'}]), side_effect=[None, {'opts': 'opts_val'}]),
mock.patch(self._AGENT_NAME + '.OVSBridge.get_ofport', mock.patch(self._AGENT_NAME + '.OVSBridge.get_ofport',
return_value=1), return_value=1),
mock.patch(self._AGENT_NAME + '.VifPort') mock.patch('neutron.agent.linux.ovs_lib.VifPort')
) as (mock_db, mock_ofport, mock_vif): ) as (mock_db, mock_ofport, mock_vif):
br = self.mod_agent.OVSBridge('br_name', 'helper') br = self.mod_agent.OVSBridge('br_name', 'helper')
vifport = br._get_external_port('iface') vifport = br._get_external_port('iface')
@ -434,7 +434,7 @@ class TestOVSBridge(RyuAgentTestCase):
{'opts': 'opts_val'}]), {'opts': 'opts_val'}]),
mock.patch(self._AGENT_NAME + '.OVSBridge.get_ofport', mock.patch(self._AGENT_NAME + '.OVSBridge.get_ofport',
return_value=1), return_value=1),
mock.patch(self._AGENT_NAME + '.VifPort') mock.patch('neutron.agent.linux.ovs_lib.VifPort')
) as (mock_db, mock_ofport, mock_vif): ) as (mock_db, mock_ofport, mock_vif):
br = self.mod_agent.OVSBridge('br_name', 'helper') br = self.mod_agent.OVSBridge('br_name', 'helper')
vifport = br._get_external_port('iface') vifport = br._get_external_port('iface')
@ -452,7 +452,7 @@ class TestOVSBridge(RyuAgentTestCase):
side_effect=[None, {'remote_ip': '0.0.0.0'}]), side_effect=[None, {'remote_ip': '0.0.0.0'}]),
mock.patch(self._AGENT_NAME + '.OVSBridge.get_ofport', mock.patch(self._AGENT_NAME + '.OVSBridge.get_ofport',
return_value=1), return_value=1),
mock.patch(self._AGENT_NAME + '.VifPort') mock.patch('neutron.agent.linux.ovs_lib.VifPort')
) as (mock_db, mock_ofport, mock_vif): ) as (mock_db, mock_ofport, mock_vif):
br = self.mod_agent.OVSBridge('br_name', 'helper') br = self.mod_agent.OVSBridge('br_name', 'helper')
vifport = br._get_external_port('iface') vifport = br._get_external_port('iface')

View File

@ -21,9 +21,7 @@ import contextlib
import mock import mock
from neutron.common import exceptions from neutron.common import exceptions
from neutron.services.loadbalancer.drivers.haproxy import ( from neutron.services.loadbalancer.drivers.haproxy import namespace_driver
namespace_driver
)
from neutron.tests import base from neutron.tests import base

View File

@ -94,7 +94,7 @@ class TestQoSQueue(test_nsx_plugin.NsxPluginV2TestCase):
def test_create_trusted_qos_queue(self): def test_create_trusted_qos_queue(self):
with mock.patch.object(qos_db.LOG, 'info') as log: with mock.patch.object(qos_db.LOG, 'info') as log:
with mock.patch.object(nsxlib.queue, 'do_request', with mock.patch.object(nsxlib, 'do_request',
return_value={"uuid": "fake_queue"}): return_value={"uuid": "fake_queue"}):
with self.qos_queue(name='fake_lqueue', min=34, max=44, with self.qos_queue(name='fake_lqueue', min=34, max=44,
qos_marking='trusted', default=False) as q: qos_marking='trusted', default=False) as q:

View File

@ -180,7 +180,7 @@ class L2GatewayTestCase(base.NsxlibTestCase):
connector_type = 'stt' connector_type = 'stt'
connector_ip = '1.1.1.1' connector_ip = '1.1.1.1'
client_certificate = 'this_should_be_a_certificate' client_certificate = 'this_should_be_a_certificate'
with mock.patch.object(l2gwlib, 'do_request') as request_mock: with mock.patch.object(nsxlib, 'do_request') as request_mock:
expected_req_body = self._create_expected_req_body( expected_req_body = self._create_expected_req_body(
display_name, neutron_id, connector_type.upper(), display_name, neutron_id, connector_type.upper(),
connector_ip, client_certificate) connector_ip, client_certificate)
@ -202,7 +202,7 @@ class L2GatewayTestCase(base.NsxlibTestCase):
connector_type = 'stt' connector_type = 'stt'
connector_ip = '1.1.1.1' connector_ip = '1.1.1.1'
client_certificate = 'this_should_be_a_certificate' client_certificate = 'this_should_be_a_certificate'
with mock.patch.object(l2gwlib, 'do_request') as request_mock: with mock.patch.object(nsxlib, 'do_request') as request_mock:
expected_req_body = self._create_expected_req_body( expected_req_body = self._create_expected_req_body(
display_name, neutron_id, connector_type.upper(), display_name, neutron_id, connector_type.upper(),
connector_ip, client_certificate) connector_ip, client_certificate)
@ -225,7 +225,7 @@ class L2GatewayTestCase(base.NsxlibTestCase):
neutron_id = 'whatever' neutron_id = 'whatever'
connector_type = 'stt' connector_type = 'stt'
connector_ip = '1.1.1.1' connector_ip = '1.1.1.1'
with mock.patch.object(l2gwlib, 'do_request') as request_mock: with mock.patch.object(nsxlib, 'do_request') as request_mock:
expected_req_body = self._create_expected_req_body( expected_req_body = self._create_expected_req_body(
display_name, neutron_id, connector_type.upper(), display_name, neutron_id, connector_type.upper(),
connector_ip, None) connector_ip, None)
@ -244,7 +244,7 @@ class L2GatewayTestCase(base.NsxlibTestCase):
def test_get_gw_device_status(self): def test_get_gw_device_status(self):
# NOTE(salv-orlando): This unit test mocks backend calls rather than # NOTE(salv-orlando): This unit test mocks backend calls rather than
# leveraging the fake NVP API client # leveraging the fake NVP API client
with mock.patch.object(l2gwlib, 'do_request') as request_mock: with mock.patch.object(nsxlib, 'do_request') as request_mock:
l2gwlib.get_gateway_device_status(self.fake_cluster, 'whatever') l2gwlib.get_gateway_device_status(self.fake_cluster, 'whatever')
request_mock.assert_called_once_with( request_mock.assert_called_once_with(
"GET", "GET",
@ -288,7 +288,7 @@ class L2GatewayTestCase(base.NsxlibTestCase):
def test_delete_gw_device(self): def test_delete_gw_device(self):
# NOTE(salv-orlando): This unit test mocks backend calls rather than # NOTE(salv-orlando): This unit test mocks backend calls rather than
# leveraging the fake NVP API client # leveraging the fake NVP API client
with mock.patch.object(l2gwlib, 'do_request') as request_mock: with mock.patch.object(nsxlib, 'do_request') as request_mock:
l2gwlib.delete_gateway_device(self.fake_cluster, 'whatever') l2gwlib.delete_gateway_device(self.fake_cluster, 'whatever')
request_mock.assert_called_once_with( request_mock.assert_called_once_with(
"DELETE", "DELETE",

View File

@ -28,7 +28,8 @@ class LSNTestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
super(LSNTestCase, self).setUp() super(LSNTestCase, self).setUp()
self.mock_request_p = mock.patch.object(lsnlib, 'do_request') self.mock_request_p = mock.patch(
'neutron.plugins.vmware.nsxlib.do_request')
self.mock_request = self.mock_request_p.start() self.mock_request = self.mock_request_p.start()
self.cluster = mock.Mock() self.cluster = mock.Mock()
self.cluster.default_service_cluster_uuid = 'foo' self.cluster.default_service_cluster_uuid = 'foo'

View File

@ -18,6 +18,7 @@ import mock
from neutron.common import exceptions from neutron.common import exceptions
from neutron.plugins.vmware.api_client import exception as api_exc from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import queue as queuelib from neutron.plugins.vmware.nsxlib import queue as queuelib
from neutron.tests.unit.vmware.nsxlib import base from neutron.tests.unit.vmware.nsxlib import base
@ -35,9 +36,9 @@ class TestLogicalQueueLib(base.NsxlibTestCase):
def test_create_and_get_lqueue(self): def test_create_and_get_lqueue(self):
queue_id = queuelib.create_lqueue( queue_id = queuelib.create_lqueue(
self.fake_cluster, self.fake_queue) self.fake_cluster, self.fake_queue)
queue_res = queuelib.do_request( queue_res = nsxlib.do_request(
'GET', 'GET',
queuelib._build_uri_path('lqueue', resource_id=queue_id), nsxlib._build_uri_path('lqueue', resource_id=queue_id),
cluster=self.fake_cluster) cluster=self.fake_cluster)
self.assertEqual(queue_id, queue_res['uuid']) self.assertEqual(queue_id, queue_res['uuid'])
self.assertEqual('fake_queue', queue_res['display_name']) self.assertEqual('fake_queue', queue_res['display_name'])
@ -46,7 +47,7 @@ class TestLogicalQueueLib(base.NsxlibTestCase):
def raise_nsx_exc(*args, **kwargs): def raise_nsx_exc(*args, **kwargs):
raise api_exc.NsxApiException() raise api_exc.NsxApiException()
with mock.patch.object(queuelib, 'do_request', new=raise_nsx_exc): with mock.patch.object(nsxlib, 'do_request', new=raise_nsx_exc):
self.assertRaises( self.assertRaises(
exceptions.NeutronException, queuelib.create_lqueue, exceptions.NeutronException, queuelib.create_lqueue,
self.fake_cluster, self.fake_queue) self.fake_cluster, self.fake_queue)
@ -56,9 +57,9 @@ class TestLogicalQueueLib(base.NsxlibTestCase):
self.fake_cluster, self.fake_queue) self.fake_cluster, self.fake_queue)
queuelib.delete_lqueue(self.fake_cluster, queue_id) queuelib.delete_lqueue(self.fake_cluster, queue_id)
self.assertRaises(exceptions.NotFound, self.assertRaises(exceptions.NotFound,
queuelib.do_request, nsxlib.do_request,
'GET', 'GET',
queuelib._build_uri_path( nsxlib._build_uri_path(
'lqueue', resource_id=queue_id), 'lqueue', resource_id=queue_id),
cluster=self.fake_cluster) cluster=self.fake_cluster)

View File

@ -150,7 +150,7 @@ class TestExplicitLRouters(base.NsxlibTestCase):
'type': 'LogicalRouterStatus', 'type': 'LogicalRouterStatus',
'lport_link_up_count': 0, }, } 'lport_link_up_count': 0, }, }
with mock.patch.object(routerlib, 'do_request', with mock.patch.object(nsxlib, 'do_request',
return_value=self._get_lrouter(tenant_id, return_value=self._get_lrouter(tenant_id,
router_name, router_name,
router_id, router_id,
@ -165,7 +165,7 @@ class TestExplicitLRouters(base.NsxlibTestCase):
router_id = 'fake_router_id' router_id = 'fake_router_id'
nexthop_ip = '10.0.0.1' nexthop_ip = '10.0.0.1'
with mock.patch.object( with mock.patch.object(
routerlib, 'do_request', nsxlib, 'do_request',
return_value=self._get_lrouter(tenant_id, return_value=self._get_lrouter(tenant_id,
router_name, router_name,
router_id)): router_id)):
@ -599,7 +599,7 @@ class TestLogicalRouters(base.NsxlibTestCase):
return {'_relations': {'LogicalPortAttachment': return {'_relations': {'LogicalPortAttachment':
{'peer_port_uuid': lrouter_port['uuid']}}} {'peer_port_uuid': lrouter_port['uuid']}}}
# mock get_port # mock get_port
with mock.patch.object(routerlib, 'get_port', new=fakegetport): with mock.patch.object(switchlib, 'get_port', new=fakegetport):
routerlib.delete_peer_router_lport(self.fake_cluster, routerlib.delete_peer_router_lport(self.fake_cluster,
lrouter_port['uuid'], lrouter_port['uuid'],
'whatwever', 'whatever') 'whatwever', 'whatever')
@ -678,7 +678,7 @@ class TestLogicalRouters(base.NsxlibTestCase):
def raise_nsx_exc(*args, **kwargs): def raise_nsx_exc(*args, **kwargs):
raise api_exc.NsxApiException() raise api_exc.NsxApiException()
with mock.patch.object(routerlib, 'do_request', new=raise_nsx_exc): with mock.patch.object(nsxlib, 'do_request', new=raise_nsx_exc):
self.assertRaises( self.assertRaises(
nsx_exc.NsxPluginException, routerlib.update_lrouter_port_ips, nsx_exc.NsxPluginException, routerlib.update_lrouter_port_ips,
self.fake_cluster, lrouter['uuid'], self.fake_cluster, lrouter['uuid'],

View File

@ -40,10 +40,10 @@ from neutron.plugins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.api_client import version as version_module from neutron.plugins.vmware.api_client import version as version_module
from neutron.plugins.vmware.common import exceptions as nsx_exc from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import sync from neutron.plugins.vmware.common import sync
from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware.dbexts import db as nsx_db from neutron.plugins.vmware.dbexts import db as nsx_db
from neutron.plugins.vmware.extensions import distributedrouter as dist_router from neutron.plugins.vmware.extensions import distributedrouter as dist_router
from neutron.plugins.vmware import nsxlib from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.plugins import base
from neutron.tests.unit import _test_extension_portbindings as test_bindings from neutron.tests.unit import _test_extension_portbindings as test_bindings
import neutron.tests.unit.test_db_plugin as test_plugin import neutron.tests.unit.test_db_plugin as test_plugin
import neutron.tests.unit.test_extension_ext_gw_mode as test_ext_gw_mode import neutron.tests.unit.test_extension_ext_gw_mode as test_ext_gw_mode
@ -221,7 +221,7 @@ class TestPortsV2(NsxPluginV2TestCase,
def test_create_port_maintenance_returns_503(self): def test_create_port_maintenance_returns_503(self):
with self.network() as net: with self.network() as net:
with mock.patch.object(nsxlib.switch, 'do_request', with mock.patch.object(nsxlib, 'do_request',
side_effect=nsx_exc.MaintenanceInProgress): side_effect=nsx_exc.MaintenanceInProgress):
data = {'port': {'network_id': net['network']['id'], data = {'port': {'network_id': net['network']['id'],
'admin_state_up': False, 'admin_state_up': False,
@ -322,7 +322,7 @@ class TestNetworksV2(test_plugin.TestNetworksV2, NsxPluginV2TestCase):
data = {'network': {'name': 'foo', data = {'network': {'name': 'foo',
'admin_state_up': True, 'admin_state_up': True,
'tenant_id': self._tenant_id}} 'tenant_id': self._tenant_id}}
with mock.patch.object(nsxlib.switch, 'do_request', with mock.patch.object(nsxlib, 'do_request',
side_effect=nsx_exc.MaintenanceInProgress): side_effect=nsx_exc.MaintenanceInProgress):
net_req = self.new_create_request('networks', data, self.fmt) net_req = self.new_create_request('networks', data, self.fmt)
res = net_req.get_response(self.api) res = net_req.get_response(self.api)
@ -380,13 +380,6 @@ class TestSecurityGroup(ext_sg.TestSecurityGroups, SecurityGroupsTestCase):
self.deserialize(self.fmt, res) self.deserialize(self.fmt, res)
self.assertEqual(res.status_int, 400) self.assertEqual(res.status_int, 400)
def test_update_security_group_deal_with_exc(self):
name = 'foo security group'
with mock.patch.object(nsxlib.switch, 'do_request',
side_effect=api_exc.NsxApiException):
with self.security_group(name=name) as sg:
self.assertEqual(sg['security_group']['name'], name)
class TestL3ExtensionManager(object): class TestL3ExtensionManager(object):
@ -459,7 +452,7 @@ class L3NatTest(test_l3_plugin.L3BaseForIntTests, NsxPluginV2TestCase):
def _create_l3_ext_network(self, vlan_id=None): def _create_l3_ext_network(self, vlan_id=None):
name = 'l3_ext_net' name = 'l3_ext_net'
net_type = base.NetworkTypes.L3_EXT net_type = utils.NetworkTypes.L3_EXT
providernet_args = {pnet.NETWORK_TYPE: net_type, providernet_args = {pnet.NETWORK_TYPE: net_type,
pnet.PHYSICAL_NETWORK: 'l3_gw_uuid'} pnet.PHYSICAL_NETWORK: 'l3_gw_uuid'}
if vlan_id: if vlan_id:
@ -478,7 +471,7 @@ class TestL3NatTestCase(L3NatTest,
def _test_create_l3_ext_network(self, vlan_id=None): def _test_create_l3_ext_network(self, vlan_id=None):
name = 'l3_ext_net' name = 'l3_ext_net'
net_type = base.NetworkTypes.L3_EXT net_type = utils.NetworkTypes.L3_EXT
expected = [('subnets', []), ('name', name), ('admin_state_up', True), expected = [('subnets', []), ('name', name), ('admin_state_up', True),
('status', 'ACTIVE'), ('shared', False), ('status', 'ACTIVE'), ('shared', False),
(external_net.EXTERNAL, True), (external_net.EXTERNAL, True),
@ -957,7 +950,7 @@ class TestL3NatTestCase(L3NatTest,
with self._create_l3_ext_network() as net: with self._create_l3_ext_network() as net:
with self.subnet(network=net) as s: with self.subnet(network=net) as s:
with mock.patch.object( with mock.patch.object(
nsxlib.router, nsxlib,
'do_request', 'do_request',
side_effect=nsx_exc.MaintenanceInProgress): side_effect=nsx_exc.MaintenanceInProgress):
data = {'router': {'tenant_id': 'whatever'}} data = {'router': {'tenant_id': 'whatever'}}