Esempio n. 1
0
    def test_chain_fails_if_no_drivers_available(self):
        self._add_node_driver('test')
        drivers = [
            x.obj for x in self.sc_plugin.driver_manager.ordered_drivers
        ]
        create_1 = drivers[0].validate_create = mock.Mock()
        create_1.side_effect = n_exc.NeutronException()
        create_2 = drivers[1].validate_create = mock.Mock()
        create_2.side_effect = n_exc.NeutronException()

        profile = self._create_service_profile(
            service_type="TYPE",
            vendor=self.SERVICE_PROFILE_VENDOR)['service_profile']
        node = self.create_servicechain_node(
            service_profile_id=profile['id'],
            config=self.DEFAULT_LB_CONFIG)['servicechain_node']
        spec = self.create_servicechain_spec(
            nodes=[node['id']])['servicechain_spec']
        provider = self.create_policy_target_group()['policy_target_group']
        classifier = self.create_policy_classifier()['policy_classifier']
        self.create_servicechain_instance(provider_ptg_id=provider['id'],
                                          consumer_ptg_id='N/A',
                                          servicechain_specs=[spec['id']],
                                          classifier_id=classifier['id'],
                                          expected_res_status=400)
Esempio n. 2
0
 def test_delete_port_group_with_exception(self, fake_get_moref):
     with (mock.patch.object(self._dvs._session,
                             'wait_for_task',
                             side_effect=exp.NeutronException())):
         self.assertRaises(exp.NeutronException,
                           self._dvs.delete_port_group, 'fake-uuid')
         fake_get_moref.assert_called_once_with('fake-uuid')
Esempio n. 3
0
def update_security_group_rules(cluster, spid, rules):
    path = "/ws.v1/security-profile/%s" % spid

    # Allow all dhcp responses in
    rules['logical_port_egress_rules'].append({
        'ethertype': 'IPv4',
        'protocol': constants.PROTO_NUM_UDP,
        'port_range_min': constants.DHCP_RESPONSE_PORT,
        'port_range_max': constants.DHCP_RESPONSE_PORT,
        'ip_prefix': '0.0.0.0/0'
    })
    # If there are no ingress rules add bunk rule to drop all ingress traffic
    if not rules['logical_port_ingress_rules']:
        rules['logical_port_ingress_rules'].append({
            'ethertype': 'IPv4',
            'ip_prefix': '127.0.0.1/32'
        })
    try:
        body = mk_body(
            logical_port_ingress_rules=summarize_security_group_rules(
                rules['logical_port_ingress_rules']),
            logical_port_egress_rules=summarize_security_group_rules(
                rules['logical_port_egress_rules']))
        rsp = nsxlib.do_request(HTTP_PUT, path, body, cluster=cluster)
    except exceptions.NotFound as e:
        LOG.error(nsxlib.format_exception("Unknown", e, locals()))
        #FIXME(salvatore-orlando): This should not raise NeutronException
        raise exceptions.NeutronException()
    LOG.debug("Updated Security Profile: %s", rsp)
    return rsp
Esempio n. 4
0
def create_lqueue(cluster, queue_data):
    params = {
        'name': 'display_name',
        'qos_marking': 'qos_marking',
        'min': 'min_bandwidth_rate',
        'max': 'max_bandwidth_rate',
        'dscp': 'dscp'
    }
    queue_obj = dict((nsx_name, queue_data.get(api_name))
                     for api_name, nsx_name in six.iteritems(params)
                     if validators.is_attr_set(queue_data.get(api_name)))
    if 'display_name' in queue_obj:
        queue_obj['display_name'] = utils.check_and_truncate(
            queue_obj['display_name'])

    queue_obj['tags'] = utils.get_tags()
    try:
        return nsxlib.do_request(HTTP_POST,
                                 nsxlib._build_uri_path(LQUEUE_RESOURCE),
                                 jsonutils.dumps(queue_obj),
                                 cluster=cluster)['uuid']
    except api_exc.NsxApiException:
        # FIXME(salv-orlando): This should not raise NeutronException
        with excutils.save_and_reraise_exception():
            raise exception.NeutronException()
Esempio n. 5
0
def delete_port(cluster, switch, port):
    uri = "/ws.v1/lswitch/" + switch + "/lport/" + port
    try:
        nsxlib.do_request(HTTP_DELETE, uri, cluster=cluster)
    except exception.NotFound as e:
        LOG.error("Port or Network not found, Error: %s", str(e))
        raise exception.PortNotFoundOnNetwork(net_id=switch, port_id=port)
    except api_exc.NsxApiException:
        raise exception.NeutronException()
Esempio n. 6
0
def delete_lqueue(cluster, queue_id):
    try:
        nsxlib.do_request(HTTP_DELETE,
                          nsxlib._build_uri_path(LQUEUE_RESOURCE,
                                                 resource_id=queue_id),
                          cluster=cluster)
    except Exception:
        # FIXME(salv-orlando): This should not raise NeutronException
        with excutils.save_and_reraise_exception():
            raise exception.NeutronException()
Esempio n. 7
0
 def test_add_port_group_with_exception(self, fake_get_spec):
     with (
         mock.patch.object(self._dvs.dvs._session, 'wait_for_task',
                           side_effect=exp.NeutronException())
     ):
         self.assertRaises(exp.NeutronException,
                           self._dvs.add_port_group,
                           'fake-uuid', 7,
                           trunk_mode=False)
         fake_get_spec.assert_called_once_with('fake-uuid', 7,
                                               trunk_mode=False)
Esempio n. 8
0
def handle_port_dhcp_access(plugin, context, port, action):
    LOG.info("Performing DHCP %(action)s for resource: %(resource)s", {
        "action": action,
        "resource": port
    })
    if port["device_owner"] == const.DEVICE_OWNER_DHCP:
        network_id = port["network_id"]
        if action == "create_port":
            # at this point the port must have a subnet and a fixed ip
            subnet_id = port["fixed_ips"][0]['subnet_id']
            subnet = plugin.get_subnet(context, subnet_id)
            subnet_data = {
                "mac_address": port["mac_address"],
                "ip_address": subnet['cidr'],
                "subnet_id": subnet['id']
            }
            try:
                plugin.lsn_manager.lsn_port_dhcp_setup(context, network_id,
                                                       port['id'], subnet_data,
                                                       subnet)
            except p_exc.PortConfigurationError:
                LOG.error("Error while configuring DHCP for "
                          "port %s", port['id'])
                raise n_exc.NeutronException()
        elif action == "delete_port":
            plugin.lsn_manager.lsn_port_dispose(context, network_id,
                                                port['mac_address'])
    elif port["device_owner"] != const.DEVICE_OWNER_DHCP:
        if port.get("fixed_ips"):
            # do something only if there are IP's and dhcp is enabled
            subnet_id = port["fixed_ips"][0]['subnet_id']
            if not plugin.get_subnet(context, subnet_id)['enable_dhcp']:
                LOG.info("DHCP is disabled for subnet %s: nothing "
                         "to do", subnet_id)
                return
            host_data = {
                "mac_address": port["mac_address"],
                "ip_address": port["fixed_ips"][0]['ip_address']
            }
            network_id = port["network_id"]
            if action == "create_port":
                handler = plugin.lsn_manager.lsn_port_dhcp_host_add
            elif action == "delete_port":
                handler = plugin.lsn_manager.lsn_port_dhcp_host_remove
            try:
                handler(context, network_id, subnet_id, host_data)
            except p_exc.PortConfigurationError:
                with excutils.save_and_reraise_exception():
                    if action == 'create_port':
                        db_base_plugin_v2.NeutronDbPluginV2.delete_port(
                            plugin, context, port['id'])
    LOG.info("DHCP for port %s configured successfully", port['id'])
def _raise_contrail_error(info, obj_name):
    exc_name = info.get('exception')
    if exc_name:
        if exc_name == 'BadRequest' and 'resource' not in info:
            info['resource'] = obj_name
        if exc_name == 'VirtualRouterNotFound':
            raise exceptions.HttpResponseError(info)
        if hasattr(l3, exc_name):
            raise getattr(l3, exc_name)(**info)
        if hasattr(securitygroup, exc_name):
            raise getattr(securitygroup, exc_name)(**info)
        if hasattr(allowedaddresspairs, exc_name):
            raise getattr(allowedaddresspairs, exc_name)(**info)
        if neutron_lib_exc and hasattr(neutron_lib_exc, exc_name):
            raise getattr(neutron_lib_exc, exc_name)(**info)
    raise neutron_lib_exc.NeutronException(**info)
 def test_create_pool_with_snatportcreate_failure(self):
     with self.subnet() as subnet, \
             mock.patch.object(self.driver.plugin._core_plugin,
                               'get_subnet') as mock_get_subnet, \
             mock.patch.object(self.driver.plugin._core_plugin,
                               'get_ports') as mock_get_ports, \
             mock.patch.object(self.driver.plugin._core_plugin,
                               'create_port') as mock_create_port:
         mock_get_subnet.return_value = subnet['subnet']
         mock_get_ports.return_value = None
         mock_create_port.side_effect = exceptions.NeutronException()
         testpool = self._build_testpool_contents(subnet['subnet'])
         #reset the create_resource() mock
         self.create_resource_mock.reset_mock()
         # execute the method under test.
         self.assertRaises(exceptions.NeutronException,
                           self.driver.create_pool, self.context, testpool)
Esempio n. 11
0
#    under the License.
#

import mock

from neutron_lib.callbacks import events
from neutron_lib.callbacks import resources

from neutron.tests.unit import testlib_api

from neutron_lib import exceptions

from networking_opencontrail.ml2 import opencontrail_sg_callback as sgc


CREATE_SG_FAILS_EXCEPTION = exceptions.NeutronException()
DELETE_SG_FAILS_EXCEPTION = exceptions.NeutronException()
UPDATE_SG_FAILS_EXCEPTION = exceptions.NeutronException()
CREATE_SG_RULE_FAILS_EXCEPTION = exceptions.NeutronException()
DELETE_SG_RULE_FAILS_EXCEPTION = exceptions.NeutronException()


class SecurityGroupTestCases(testlib_api.SqlTestCase):
    """Test cases for ML2 security group handler.

    Callbacks for create, delete, and update operations of security
    groups and rules.
    """

    def setUp(self):
        super(SecurityGroupTestCases, self).setUp()