Python neutron_lib.exceptions.BadRequest() Examples

The following are 18 code examples of neutron_lib.exceptions.BadRequest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module neutron_lib.exceptions , or try the search function .
Example #1
Source File: plugin.py    From networking-bgpvpn with Apache License 2.0 6 votes vote down vote up
def create_bgpvpn_router_association(self, context, bgpvpn_id,
                                         router_association):
        router_assoc = router_association['router_association']
        router = self._validate_router(context, router_assoc['router_id'])
        bgpvpn = self.get_bgpvpn(context, bgpvpn_id)
        if not bgpvpn['type'] == constants.BGPVPN_L3:
            msg = ("Router associations require the bgpvpn to be of type %s"
                   % constants.BGPVPN_L3)
            raise n_exc.BadRequest(resource='bgpvpn', msg=msg)
        if not router['tenant_id'] == bgpvpn['tenant_id']:
            msg = "router doesn't belong to the bgpvpn owner"
            raise n_exc.NotAuthorized(resource='bgpvpn', msg=msg)
        if not (router_assoc['tenant_id'] == bgpvpn['tenant_id']):
            msg = "router association and bgpvpn should " \
                  "belong to the same tenant"
            raise n_exc.NotAuthorized(resource='bgpvpn', msg=msg)
        return self.driver.create_router_assoc(context, bgpvpn_id,
                                               router_assoc) 
Example #2
Source File: plugin.py    From networking-bgpvpn with Apache License 2.0 6 votes vote down vote up
def _validate_router_has_net_assocs(self, context, router, plugin):
        filter = {'device_id': [router['id']],
                  'device_owner': [const.DEVICE_OWNER_ROUTER_INTF]}
        router_ports = plugin.get_ports(context, filters=filter)
        if router_ports:
            filter = {'tenant_id': [router['tenant_id']]}
            bgpvpns = self.driver.get_bgpvpns(context, filters=filter)
            for port in router_ports:
                bgpvpns = [str(bgpvpn['id']) for bgpvpn in bgpvpns
                           if port['network_id'] in bgpvpn['networks']]
                if bgpvpns:
                    msg = ('router %(rtr_id)s has an attached network '
                           '%(net_id)s which is already associated to '
                           'bgpvpn(s) %(bgpvpns)s'
                           % {'rtr_id': router['id'],
                              'net_id': port['network_id'],
                              'bgpvpns': bgpvpns})
                    raise n_exc.BadRequest(resource='bgpvpn', msg=msg) 
Example #3
Source File: plugin.py    From networking-bgpvpn with Apache License 2.0 6 votes vote down vote up
def _validate_network_has_router_assoc(self, context, network, plugin):
        filter = {'network_id': [network['id']],
                  'device_owner': [const.DEVICE_OWNER_ROUTER_INTF]}
        router_port = plugin.get_ports(context, filters=filter)
        if router_port:
            router_id = router_port[0]['device_id']
            filter = {'tenant_id': [network['tenant_id']]}
            bgpvpns = self.driver.get_bgpvpns(context, filters=filter)
            bgpvpns = [str(bgpvpn['id']) for bgpvpn in bgpvpns
                       if router_id in bgpvpn['routers']]
            if bgpvpns:
                msg = ('Network %(net_id)s is linked to a router which is '
                       'already associated to bgpvpn(s) %(bgpvpns)s'
                       % {'net_id': network['id'],
                          'bgpvpns': bgpvpns}
                       )
                raise n_exc.BadRequest(resource='bgpvpn', msg=msg) 
Example #4
Source File: plugin.py    From networking-bgpvpn with Apache License 2.0 5 votes vote down vote up
def _notify_adding_interface_to_router(self, resource, event, trigger,
                                           **kwargs):
        context = kwargs.get('context')
        network_id = kwargs.get('network_id')
        router_id = kwargs.get('router_id')
        try:
            routers_bgpvpns = self.driver.get_bgpvpns(
                context,
                filters={
                    'routers': [router_id],
                },
            )
        except bgpvpn.BGPVPNRouterAssociationNotSupported:
            return
        nets_bgpvpns = self.driver.get_bgpvpns(
            context,
            filters={
                'networks': [network_id],
                'type': [constants.BGPVPN_L3],
            },
        )

        if routers_bgpvpns and nets_bgpvpns:
            msg = _('It is not allowed to add an interface to a router if '
                    'both the router and the network are bound to an '
                    'L3 BGPVPN.')
            raise n_exc.BadRequest(resource='bgpvpn', msg=msg) 
Example #5
Source File: test_utils.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_get_and_validate_sort_keys_by_relationship_fails(self):
        sorts = [('gw_port', True)]
        self.assertRaises(n_exc.BadRequest,
                          utils.get_and_validate_sort_keys, sorts, FakeRouter) 
Example #6
Source File: test_utils.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_get_and_validate_sort_keys_bad_key_fails(self):
        sorts = [('master', True)]
        self.assertRaises(n_exc.BadRequest,
                          utils.get_and_validate_sort_keys, sorts, FakePort) 
Example #7
Source File: test_exceptions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_bad_request_misused(self):
        try:
            self._check_nexc(
                ne.BadRequest,
                _('Bad A request: B.'),
                resource='A', msg='B')
        except AttributeError:
            pass 
Example #8
Source File: test_exceptions.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def test_bad_request(self):
        self._check_nexc(
            ne.BadRequest,
            _('Bad A request: B.'),
            resource='A', msg='B') 
Example #9
Source File: utils.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def get_and_validate_sort_keys(sorts, model):
    """Extract sort keys from sorts and ensure they are valid for the model.

    :param sorts: A list of (key, direction) tuples.
    :param model: A sqlalchemy ORM model class.
    :returns: A list of the extracted sort keys.
    :raises BadRequest: If a sort key attribute references another resource
        and cannot be used in the sort.
    """

    sort_keys = [s[0] for s in sorts]
    for sort_key in sort_keys:
        try:
            sort_key_attr = getattr(model, sort_key)
        except AttributeError:
            # Extension attributes don't support sorting. Because it
            # existed in attr_info, it will be caught here.
            msg = _("'%s' is an invalid attribute for sort key") % sort_key
            raise n_exc.BadRequest(resource=model.__tablename__, msg=msg)
        if isinstance(sort_key_attr.property,
                      properties.RelationshipProperty):
            msg = _("Attribute '%(attr)s' references another resource and "
                    "cannot be used to sort '%(resource)s' resources"
                    ) % {'attr': sort_key, 'resource': model.__tablename__}
            raise n_exc.BadRequest(resource=model.__tablename__, msg=msg)

    return sort_keys 
Example #10
Source File: bgp_db.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def _get_id_for(self, resource, id_name):
        try:
            uuid = resource[id_name]
            msg = validators.validate_uuid(uuid)
        except KeyError:
            msg = _("%s must be specified") % id_name
        if msg:
            raise n_exc.BadRequest(resource=bgp_ext.BGP_SPEAKER_RESOURCE_NAME,
                                   msg=msg)
        return uuid 
Example #11
Source File: mech_driver.py    From networking-midonet with Apache License 2.0 5 votes vote down vote up
def _validate_port_create(self, port):
        if (port.get('device_owner') == n_const.DEVICE_OWNER_ROUTER_GW
                and not port['fixed_ips']):
            msg = (_("No IPs assigned to the gateway port for"
                     " router %s") % port['device_id'])
            raise n_exc.BadRequest(resource='router', msg=msg) 
Example #12
Source File: port_binding_db.py    From networking-midonet with Apache License 2.0 5 votes vote down vote up
def _process_mido_portbindings_create_and_update(self, context, port_data,
                                                     port):

        port_id = port['id']

        # Set profile to {} if the binding:profile key exists but set to None.
        # This is for the special handling in the case the user wants to remove
        # the binding.
        profile = None
        if portbindings.PROFILE in port_data:
            profile = port_data.get(portbindings.PROFILE) or {}
        profile_set = validators.is_attr_set(profile)

        if_name = profile.get('interface_name') if profile_set else None
        if profile_set and profile:
            # Update or create, so validate the inputs
            if not if_name:
                msg = 'The interface name was not provided or empty'
                raise n_exc.BadRequest(resource='port', msg=msg)

            if self.get_port_host(context, port_id) is None:
                msg = 'Cannot set binding because the host is not bound'
                raise n_exc.BadRequest(resource='port', msg=msg)

        with context.session.begin(subtransactions=True):
            bind_port = context.session.query(PortBindingInfo).filter_by(
                port_id=port_id).first()
            if profile_set:
                if bind_port:
                    if if_name:
                        bind_port.interface_name = if_name
                    else:
                        context.session.delete(bind_port)
                elif if_name:
                    context.session.add(PortBindingInfo(
                        port_id=port_id, interface_name=if_name))
            else:
                if_name = bind_port.interface_name if bind_port else None

        self._extend_mido_portbinding(port, if_name) 
Example #13
Source File: l3_db_midonet.py    From networking-midonet with Apache License 2.0 5 votes vote down vote up
def _validate_network_for_floatingip(self, context, net_id):
        if not any(self._core_plugin._get_network(context, net_id).subnets):
            msg = _("Network %s does not contain any subnet") % net_id
            raise n_exc.BadRequest(resource='floatingip', msg=msg)

    # REVISIT(bikfalvi): This method is a copy of the base class method,
    # modified to use the _port_fixed_ips hook and replace the network
    # validation from IPv4 to any IP.
    # NOTE(yamamoto): And Floating IP QoS stuff commented out 
Example #14
Source File: plugin.py    From networking-midonet with Apache License 2.0 5 votes vote down vote up
def add_bgp_peer(self, context, bgp_speaker_id, bgp_peer_info):
        # TODO(kengo): This is temporary workaround until upstream raise
        # an error when dictionary without 'bgp_peer_id' key is specified.
        if not self._get_id_for(bgp_peer_info, 'bgp_peer_id'):
            raise nexception.BadRequest(
                resource=bgp.BGP_SPEAKER_RESOURCE_NAME,
                msg="bgp_peer_id must be specified")
        with db_api.CONTEXT_WRITER.using(context):
            # In MidoNet, bgp-peer can be related to only one bgp-speaker.
            if self._get_bgp_speakers_by_bgp_peer_binding(
                    context, bgp_peer_info['bgp_peer_id']):
                raise bsri.MidonetBgpPeerInUse(
                    id=bgp_peer_info['bgp_peer_id'])
            if not self.get_router_associated_with_bgp_speaker(
                    context, bgp_speaker_id):
                # External network must be associated with the bgp speaker.
                raise bsri.ExternalNetworkUnbound()
            info = super(MidonetBgpPlugin, self).add_bgp_peer(
                context, bgp_speaker_id, bgp_peer_info)
            # get peer info for MidoNet
            bgp_peer = super(MidonetBgpPlugin, self).get_bgp_peer(
                context, info['bgp_peer_id'])
            # merge bgp_speaker information for MidoNet
            bgp_peer['bgp_speaker'] = self.get_bgp_speaker(
                context, bgp_speaker_id)
            self.client.create_bgp_peer_precommit(context, bgp_peer)

        try:
            self.client.create_bgp_peer_postcommit(bgp_peer)
        except Exception as ex:
            LOG.error("Failed to create MidoNet resources to add bgp "
                      "peer. bgp_peer=%(bgp_peer)s, "
                      "bgp_speaker_id=%(bgp_speaker_id)s, error=%(err)r",
                      {"bgp_peer": bgp_peer, "bgp_speaker_id": bgp_speaker_id,
                       "err": ex})
            with excutils.save_and_reraise_exception():
                super(MidonetBgpPlugin, self).remove_bgp_peer(
                    context, bgp_speaker_id, bgp_peer_info)

        return info 
Example #15
Source File: l3_midonet.py    From networking-midonet with Apache License 2.0 5 votes vote down vote up
def _validate_network_type(self, context, network_id):
        our_types = [m_const.TYPE_MIDONET, m_const.TYPE_UPLINK]
        network = self._core_plugin.get_network(context, network_id)
        for seg in self._segments(network):
            if seg[pnet.NETWORK_TYPE] in our_types:
                return
        LOG.warning("Incompatible network %s", network)
        raise n_exc.BadRequest(resource='router', msg='Incompatible network') 
Example #16
Source File: test_bgp_db.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def test_add_bgp_peer_with_none_id(self):
        with self.subnetpool_with_address_scope(4,
                                                prefixes=['8.0.0.0/8']) as sp:
            with self.bgp_speaker(sp['ip_version'], 1234) as speaker:
                self.assertRaises(n_exc.BadRequest,
                                  self.bgp_plugin.add_bgp_peer,
                                  self.context,
                                  speaker['id'],
                                  {'bgp_peer_id': None}) 
Example #17
Source File: test_bgp_db.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def test_add_bgp_peer_with_bad_id(self):
        with self.subnetpool_with_address_scope(4,
                                                prefixes=['8.0.0.0/8']) as sp:
            with self.bgp_speaker(sp['ip_version'], 1234) as speaker:
                self.assertRaises(n_exc.BadRequest,
                                  self.bgp_plugin.add_bgp_peer,
                                  self.context,
                                  speaker['id'],
                                  {'bgp_peer_id': 'aaa'}) 
Example #18
Source File: test_bgp_db.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def test_add_bgp_peer_without_id(self):
        with self.subnetpool_with_address_scope(4,
                                                prefixes=['8.0.0.0/8']) as sp:
            with self.bgp_speaker(sp['ip_version'], 1234) as speaker:
                self.assertRaises(n_exc.BadRequest,
                                  self.bgp_plugin.add_bgp_peer,
                                  self.context,
                                  speaker['id'],
                                  {})