示例#1
0
文件: ports.py 项目: insequent/quark
def split_and_validate_requested_subnets(context, net_id, segment_id,
                                         fixed_ips):
    subnets = []
    ip_addresses = {}
    for fixed_ip in fixed_ips:
        subnet_id = fixed_ip.get("subnet_id")
        ip_address = fixed_ip.get("ip_address")
        if not subnet_id:
            raise exceptions.BadRequest(resource="fixed_ips",
                                        msg="subnet_id required")
        if ip_address:
            ip_addresses[ip_address] = subnet_id
        else:
            subnets.append(subnet_id)

    subnets = ip_addresses.values() + subnets

    sub_models = db_api.subnet_find(context, id=subnets, scope=db_api.ALL)
    if len(sub_models) == 0:
        raise exceptions.NotFound(msg="Requested subnet(s) not found")

    for s in sub_models:
        if s["network_id"] != net_id:
            raise exceptions.InvalidInput(
                error_message="Requested subnet doesn't belong to requested "
                              "network")

        if segment_id and segment_id != s["segment_id"]:
            raise q_exc.AmbiguousNetworkId(net_id=net_id)

    return ip_addresses, subnets
示例#2
0
def update_ip_address(context, id, ip_address):
    LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id))

    with context.session.begin():
        address = db_api.ip_address_find(context,
                                         id=id,
                                         tenant_id=context.tenant_id,
                                         scope=db_api.ONE)

        if not address:
            raise exceptions.NotFound(
                message="No IP address found with id=%s" % id)

        reset = ip_address['ip_address'].get('reset_allocation_time', False)
        if reset and address['deallocated'] == 1:
            if context.is_admin:
                LOG.info("IP's deallocated time being manually reset")
                address['deallocated_at'] = _get_deallocated_override()
            else:
                msg = "Modification of reset_allocation_time requires admin"
                raise webob.exc.HTTPForbidden(detail=msg)

        old_ports = address['ports']
        port_ids = ip_address['ip_address'].get('port_ids')
        if port_ids is None:
            return v._make_ip_dict(address)

        for port in old_ports:
            port['ip_addresses'].remove(address)

        if port_ids:
            ports = db_api.port_find(context,
                                     tenant_id=context.tenant_id,
                                     id=port_ids,
                                     scope=db_api.ALL)

            # NOTE: could be considered inefficient because we're converting
            #       to a list to check length. Maybe revisit
            if len(ports) != len(port_ids):
                raise exceptions.NotFound(
                    message="No ports not found with ids=%s" % port_ids)
            for port in ports:
                port['ip_addresses'].extend([address])
        else:
            address["deallocated"] = 1

    return v._make_ip_dict(address)
示例#3
0
 def test_neutron_nonfound_to_webob_exception(self):
     # this endpoint raises a Neutron notfound exception. make sure it gets
     # translated into a 404 error
     with mock.patch(
             'neutron.pecan_wsgi.controllers.root.CollectionsController.get',
             side_effect=n_exc.NotFound()):
         response = self.app.get('/v2.0/ports.json', expect_errors=True)
         self.assertEqual(response.status_int, 404)
示例#4
0
 def test__check_requirements_fail_on_missing_pools(self):
     with mock.patch.object(
         self.mixin, '_get_default_external_network'),\
         mock.patch.object(
             self.mixin, '_get_supported_subnetpools') as g:
         g.side_effect = n_exc.NotFound()
         self.assertRaises(exceptions.AutoAllocationFailure,
             self.mixin._check_requirements, self.ctx, 'foo_tenant')
示例#5
0
 def delete_dummy(self, context, id):
     try:
         svc_type_id = self.dummys[id]['service_type']
         del self.dummys[id]
         self.svctype_mgr.decrease_service_type_refcount(
             context, svc_type_id)
     except KeyError:
         raise exceptions.NotFound()
示例#6
0
def lsn_for_network_get(cluster, network_id):
    filters = {"tag": network_id, "tag_scope": "n_network_id"}
    results = do_request(HTTP_GET,
                         _build_uri_path(LSERVICESNODE_RESOURCE,
                                         fields="uuid",
                                         filters=filters),
                         cluster=cluster)['results']
    if not results:
        raise exception.NotFound()
    elif len(results) == 1:
        return results[0]['uuid']
示例#7
0
def _lsn_port_get(cluster, lsn_id, filters):
    results = do_request(HTTP_GET,
                         _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                                         parent_resource_id=lsn_id,
                                         fields="uuid",
                                         filters=filters),
                         cluster=cluster)['results']
    if not results:
        raise exception.NotFound()
    elif len(results) == 1:
        return results[0]['uuid']
示例#8
0
 def deallocate_mac_address(self, context, address):
     mac = db_api.mac_address_find(context,
                                   address=address,
                                   scope=db_api.ONE)
     if not mac:
         raise exceptions.NotFound(message="No MAC address %s found" %
                                   netaddr.EUI(address))
     db_api.mac_address_update(context,
                               mac,
                               deallocated=True,
                               deallocated_at=timeutils.utcnow())
示例#9
0
文件: db.py 项目: kitch/neutron
    def _get_supported_subnetpools(self, context):
        """Return the default subnet pools available."""
        default_subnet_pools = [
            self.core_plugin.get_default_subnetpool(context, ver)
            for ver in (4, 6)
        ]
        available_pools = [s for s in default_subnet_pools if s]
        if not available_pools:
            LOG.error(_LE("No default pools available"))
            raise n_exc.NotFound()

        return available_pools
示例#10
0
 def router_id_get(self, context, subnet=None):
     """Return the router and interface used for the subnet."""
     if not subnet:
         return
     network_id = subnet['network_id']
     filters = {
         'network_id': [network_id],
         'device_owner': [const.DEVICE_OWNER_ROUTER_INTF]
     }
     ports = self.plugin.get_ports(context, filters=filters)
     for port in ports:
         if port['fixed_ips'][0]['subnet_id'] == subnet['id']:
             return port['device_id']
     else:
         raise n_exc.NotFound()
示例#11
0
    def deallocate_mac_address(self, context, address):
        admin_context = context.elevated()
        mac = db_api.mac_address_find(admin_context,
                                      address=address,
                                      scope=db_api.ONE)
        if not mac:
            raise exceptions.NotFound(message="No MAC address %s found" %
                                      netaddr.EUI(address))

        if mac["mac_address_range"]["do_not_use"]:
            db_api.mac_address_delete(admin_context, mac)
        else:
            db_api.mac_address_update(admin_context,
                                      mac,
                                      deallocated=True,
                                      deallocated_at=timeutils.utcnow())
示例#12
0
def do_request(*args, **kwargs):
    """Issue a request to the cluster specified in kwargs.

    :param args: a list of positional arguments.
    :param kwargs: a list of keyworkds arguments.
    :returns: the result of the operation loaded into a python
        object or None.
    """
    cluster = kwargs["cluster"]
    try:
        res = cluster.api_client.request(*args)
        if res:
            return json.loads(res)
    except api_exc.ResourceNotFound:
        raise exception.NotFound()
    except api_exc.ReadOnlyMode:
        raise nsx_exc.MaintenanceInProgress()
示例#13
0
 def get_dummy(self, context, id, fields):
     try:
         return self.dummys[id]
     except KeyError:
         raise exceptions.NotFound()
 def create_port(self, context, port):
     p = port['port']
     if 'network_id' not in p:
         raise exc.NotFound()
     plugin = self._get_plugin_by_network_id(context, p['network_id'])
     return plugin.create_port(context, port)
示例#15
0
 def test_service_cluster_not_found(self):
     self.mock_request.side_effect = exceptions.NotFound()
     expected = lsnlib.service_cluster_exists(None, 'foo_uuid')
     self.assertFalse(expected)
 def create_subnet(self, context, subnet):
     s = subnet['subnet']
     if 'network_id' not in s:
         raise exc.NotFound()
     plugin = self._get_plugin_by_network_id(context, s['network_id'])
     return plugin.create_subnet(context, subnet)
示例#17
0
def update_ip_address(context, id, ip_address):
    """Due to NCP-1592 ensure that address_type cannot change after update."""
    LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id))
    ports = []
    if 'ip_address' not in ip_address:
        raise exceptions.BadRequest(resource="ip_addresses",
                                    msg="Invalid request body.")
    with context.session.begin():
        address = db_api.ip_address_find(context, id=id, scope=db_api.ONE)
        if not address:
            raise exceptions.NotFound(
                message="No IP address found with id=%s" % id)
        iptype = address.address_type
        if iptype == ip_types.FIXED and not CONF.QUARK.ipaddr_allow_fixed_ip:
            raise exceptions.BadRequest(
                resource="ip_addresses",
                msg="Fixed ips cannot be updated using this interface.")

        reset = ip_address['ip_address'].get('reset_allocation_time', False)
        if reset and address['deallocated'] == 1:
            if context.is_admin:
                LOG.info("IP's deallocated time being manually reset")
                address['deallocated_at'] = _get_deallocated_override()
            else:
                msg = "Modification of reset_allocation_time requires admin"
                raise webob.exc.HTTPForbidden(detail=msg)

        port_ids = ip_address['ip_address'].get('port_ids', None)

        if port_ids is not None and not port_ids:
            raise exceptions.BadRequest(
                resource="ip_addresses",
                msg="Cannot be updated with empty port_id list")

        if iptype == ip_types.SHARED:
            has_owner = address.has_any_shared_owner()

        if port_ids:
            if iptype == ip_types.FIXED and len(port_ids) > 1:
                raise exceptions.BadRequest(
                    resource="ip_addresses",
                    msg="Fixed ips cannot be updated with more than one port.")

            _raise_if_shared_and_enabled(ip_address, address)
            ports = db_api.port_find(context,
                                     tenant_id=context.tenant_id,
                                     id=port_ids,
                                     scope=db_api.ALL)
            # NOTE(name): could be considered inefficient because we're
            # converting to a list to check length. Maybe revisit
            if len(ports) != len(port_ids):
                raise exceptions.NotFound(
                    message="No ports not found with ids=%s" % port_ids)

            validate_and_fetch_segment(ports, address["network_id"])
            validate_port_ip_quotas(context, address.network_id, ports)

            if iptype == ip_types.SHARED and has_owner:
                for assoc in address.associations:
                    pid = assoc.port_id
                    if pid not in port_ids and 'none' != assoc.service:
                        raise quark_exceptions.PortRequiresDisassociation()

            LOG.info("Updating IP address, %s, to only be used by the"
                     "following ports:  %s" %
                     (address.address_readable, [p.id for p in ports]))
            new_address = db_api.update_port_associations_for_ip(
                context, ports, address)
        elif iptype == ip_types.SHARED and has_owner:
            raise quark_exceptions.PortRequiresDisassociation()
        else:
            ipam_driver.deallocate_ip_address(context, address)
            return v._make_ip_dict(address)
    return v._make_ip_dict(new_address)