Beispiel #1
0
 def get_subnet(self, context, _id, fields=None):
     t_ctx = t_context.get_context_from_neutron_context(context)
     try:
         b_subnet = self.core_plugin.get_subnet(context, _id)
     except q_exceptions.NotFound:
         if self._skip_non_api_query(t_ctx):
             raise q_exceptions.SubnetNotFound(subnet_id=_id)
         t_subnet = self.neutron_handle.handle_get(t_ctx, 'subnet', _id)
         if not t_subnet:
             raise q_exceptions.SubnetNotFound(subnet_id=_id)
         b_subnet = self._create_bottom_subnet(t_ctx, context, t_subnet)
     if b_subnet['enable_dhcp']:
         self._ensure_subnet_dhcp_port(t_ctx, context, b_subnet)
     return self._fields(b_subnet, fields)
Beispiel #2
0
    def get_subnet(self, subnet_id):
        """Gets the matching subnet if it has been allocated

        :param subnet_id: the subnet identifier
        :type subnet_id: str uuid
        :returns: An instance of IPAM Subnet
        :raises: IPAMAllocationNotFound
        """

	subnet_request = neutron_ipam_req.SpecificSubnetRequest(self.subnet_json['tenant_id'],subnet_id,
			self.subnet_json['cidr'],None,[])

	subnetpool_name = self._subnetpool['name'] if self._subnetpool else self.pool_json['name']
	
	start_addr,_,__ = str(self.subnet_json['cidr']).partition('/')

	if self.subnet_json['ip_version'] == 4:
		s = eip_rest.get_subnet_list_v4(start_addr,self.sitename,subnetpool_name)
		
	elif self.subnet_json['ip_version'] == 6:
		s = eip_rest.get_subnet_list_v6(start_addr,self.sitename,subnetpool_name)

	if s is None:
		LOG.error("Failed : to retrieve "+subnet_id+" in IPAM")
		raise neutron_lib_exc.SubnetNotFound(subnet_id=subnet_id)


	ret = eipSubnet(subnet_request)
	return ret
Beispiel #3
0
    def load(cls, neutron_subnet_id, ctx):
        """Load an IPAM subnet from the database given its neutron ID.

        :param neutron_subnet_id: neutron subnet identifier.
        """
        ipam_subnet = ipam_db_api.IpamSubnetManager.load_by_neutron_subnet_id(
            ctx.session, neutron_subnet_id)
        if not ipam_subnet:
            LOG.error(
                _LE("IPAM subnet referenced to "
                    "Neutron subnet %s does not exist"), neutron_subnet_id)
            raise n_exc.SubnetNotFound(subnet_id=neutron_subnet_id)
        pools = []
        for pool in ipam_subnet.allocation_pools:
            pools.append(netaddr.IPRange(pool['first_ip'], pool['last_ip']))

        neutron_subnet = cls._fetch_subnet(ctx, neutron_subnet_id)

        return cls(ipam_subnet['id'],
                   ctx,
                   cidr=neutron_subnet['cidr'],
                   allocation_pools=pools,
                   gateway_ip=neutron_subnet['gateway_ip'],
                   tenant_id=neutron_subnet['tenant_id'],
                   subnet_id=neutron_subnet_id)
Beispiel #4
0
    def remove_subnet(self, subnet_id):
        """Remove data structures for a given subnet.

        IPAM-related data has no foreign key relationships to neutron subnet,
        so removing ipam subnet manually
        """

        count = ipam_db_api.IpamSubnetManager.delete(self._context,
                                                     subnet_id)
        if count < 1:
            LOG.error(_LE("BCN: IPAM subnet referenced to "
                          "Neutron subnet %s does not exist"),
                      subnet_id)
            raise n_exc.SubnetNotFound(subnet_id=subnet_id)
            
        # BlueCat additions
        paramsBAM = getBCNConfig(BC_configFileName, "BAM")
            
        if (paramsBAM['bam_updatemodify_networks'] == "True"):    
			soap_client = _bam_login(paramsBAM)
			configID = _get_bam_configid(paramsBAM, soap_client)
			LOG.info("BCN: Got configID %s" % (configID))

			LOG.info("BCN: Removing Network %s from BAM  ...\n" % (subnet_id))

			delBCNetwork(configID, subnet_id)
			_bam_logout(paramsBAM, soap_client)
Beispiel #5
0
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 n_exc.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 n_exc.SubnetNotFound(subnet_id=subnets)

    for s in sub_models:
        if s["network_id"] != net_id:
            raise n_exc.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
Beispiel #6
0
    def allocate(self, address_request):
        # NOTE(pbondar): Ipam driver is always called in context of already
        # running transaction, which is started on create_port or upper level.
        # To be able to do rollback/retry actions correctly ipam driver
        # should not create new nested transaction blocks.
        # NOTE(salv-orlando): It would probably better to have a simpler
        # model for address requests and just check whether there is a
        # specific IP address specified in address_request
        if isinstance(address_request, ipam_req.SpecificAddressRequest):
            # This handles both specific and automatic address requests
            # Check availability of requested IP
            ip_address = str(address_request.address)
            self._verify_ip(self._context, ip_address)
        else:
            prefer_next = isinstance(address_request,
                                     ipam_req.PreferNextAddressRequest)
            ip_address = self._generate_ip(self._context, prefer_next)

        # Create IP allocation request object
        # The only defined status at this stage is 'ALLOCATED'.
        # More states will be available in the future - e.g.: RECYCLABLE
        try:
            with db_api.CONTEXT_WRITER.using(self._context):
                self.subnet_manager.create_allocation(self._context,
                                                      ip_address)
        except db_exc.DBReferenceError:
            raise n_exc.SubnetNotFound(
                subnet_id=self.subnet_manager.neutron_id)
        return ip_address
Beispiel #7
0
    def allocate(self, address_request):
        # NOTE(pbondar): Ipam driver is always called in context of already
        # running transaction, which is started on create_port or upper level.
        # To be able to do rollback/retry actions correctly ipam driver
        # should not create new nested transaction blocks.
        session = self._context.session
        all_pool_id = None
        # NOTE(salv-orlando): It would probably better to have a simpler
        # model for address requests and just check whether there is a
        # specific IP address specified in address_request
        if isinstance(address_request, ipam_req.SpecificAddressRequest):
            # This handles both specific and automatic address requests
            # Check availability of requested IP
            ip_address = str(address_request.address)
            self._verify_ip(session, ip_address)
        else:
            prefer_next = isinstance(address_request,
                                     ipam_req.PreferNextAddressRequest)
            ip_address, all_pool_id = self._generate_ip(session, prefer_next)

        # Create IP allocation request object
        # The only defined status at this stage is 'ALLOCATED'.
        # More states will be available in the future - e.g.: RECYCLABLE
        try:
            with session.begin(subtransactions=True):
                # NOTE(kevinbenton): we use a subtransaction to force
                # a flush here so we can capture DBReferenceErrors due
                # to concurrent subnet deletions. (galera would deadlock
                # later on final commit)
                self.subnet_manager.create_allocation(session, ip_address)
        except db_exc.DBReferenceError:
            raise n_exc.SubnetNotFound(
                subnet_id=self.subnet_manager.neutron_id)
        return ip_address
Beispiel #8
0
def get_subnet(context, id, fields=None):
    """Retrieve a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to fetch.
    : param fields: a list of strings that are valid keys in a
        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.
    """
    LOG.info("get_subnet %s for tenant %s with fields %s" %
             (id, context.tenant_id, fields))
    subnet = db_api.subnet_find(context=context,
                                limit=None,
                                page_reverse=False,
                                sorts=['id'],
                                marker_obj=None,
                                fields=None,
                                id=id,
                                join_dns=True,
                                join_routes=True,
                                scope=db_api.ONE)
    if not subnet:
        raise n_exc.SubnetNotFound(subnet_id=id)

    cache = subnet.get("_allocation_pool_cache")
    if not cache:
        new_cache = subnet.allocation_pools
        db_api.subnet_update_set_alloc_pool_cache(context, subnet, new_cache)
    return v._make_subnet_dict(subnet)
 def _get_subnet(self, context, id):
     # TODO(slaweq): remove this method when all will be switched to use OVO
     # objects only
     try:
         subnet = model_query.get_by_id(context, models_v2.Subnet, id)
     except exc.NoResultFound:
         raise n_exc.SubnetNotFound(subnet_id=id)
     return subnet
Beispiel #10
0
 def test_unknown_subnet_in_endpoint_group(self):
     subnet_id = _uuid()
     self.core_plugin.get_subnet.side_effect = nexception.SubnetNotFound(
         subnet_id=subnet_id)
     endpoint_group = {'type': v_constants.SUBNET_ENDPOINT,
                       'endpoints': [subnet_id]}
     self.assertRaises(vpnaas.NonExistingSubnetInEndpointGroup,
                       self.validator.validate_endpoint_group,
                       self.context, endpoint_group)
 def test_create_port_catch_and_handle_ip_generation_failure(self):
     self.plugin.get_subnet.side_effect = (exceptions.SubnetNotFound(
         subnet_id='foo_subnet_id'))
     self._test__port_action_with_failures(
         exc=exceptions.IpAddressGenerationFailure(net_id='foo_network_id'),
         action='create_port')
     self._test__port_action_with_failures(
         exc=exceptions.InvalidInput(error_message='sorry'),
         action='create_port')
Beispiel #12
0
    def remove_subnet(self, subnet_id):
        """Remove data structures for a given subnet.

        IPAM-related data has no foreign key relationships to neutron subnet,
        so removing ipam subnet manually
        """
        count = ipam_db_api.IpamSubnetManager.delete(self._context, subnet_id)
        if count < 1:
            LOG.error(
                "IPAM subnet referenced to "
                "Neutron subnet %s does not exist", subnet_id)
            raise n_exc.SubnetNotFound(subnet_id=subnet_id)
Beispiel #13
0
def create_ip_policy(context, ip_policy):
    LOG.info("create_ip_policy for tenant %s" % context.tenant_id)

    ipp = ip_policy['ip_policy']

    if not ipp.get("exclude"):
        raise n_exc.BadRequest(resource="ip_policy",
                               msg="Empty ip_policy.exclude")

    network_ids = ipp.get("network_ids")
    subnet_ids = ipp.get("subnet_ids")

    if subnet_ids and network_ids:
        raise n_exc.BadRequest(
            resource="ip_policy",
            msg="network_ids and subnet_ids specified. only one allowed")

    if not subnet_ids and not network_ids:
        raise n_exc.BadRequest(resource="ip_policy",
                               msg="network_ids or subnet_ids not specified")

    with context.session.begin():
        if subnet_ids:
            subnets = db_api.subnet_find(context,
                                         id=subnet_ids,
                                         scope=db_api.ALL)
            if not subnets:
                raise n_exc.SubnetNotFound(subnet_id=subnet_ids)
            _check_for_pre_existing_policies_in(subnets)
            ensure_default_policy(ipp["exclude"], subnets)
            _validate_cidrs_fit_into_subnets(ipp["exclude"], subnets)
            ipp.pop("subnet_ids")
            ipp["subnets"] = subnets

        if network_ids:
            nets = db_api.network_find(context,
                                       id=network_ids,
                                       scope=db_api.ALL)
            if not nets:
                raise n_exc.NetworkNotFound(net_id=network_ids)
            _check_for_pre_existing_policies_in(nets)
            subnets = [
                subnet for net in nets for subnet in net.get("subnets", [])
            ]
            ensure_default_policy(ipp["exclude"], subnets)
            _validate_cidrs_fit_into_subnets(ipp["exclude"], subnets)
            ipp.pop("network_ids")
            ipp["networks"] = nets

        ip_policy = db_api.ip_policy_create(context, **ipp)
    return v._make_ip_policy_dict(ip_policy)
Beispiel #14
0
    def create_floatingip(self, context, floatingip):
        floatingip_port = None
        try:
            floatingip_dict = super(DFL3RouterPlugin, self).create_floatingip(
                context,
                floatingip,
                initial_status=const.FLOATINGIP_STATUS_DOWN)
            fip_version = floatingip_dict['revision_number']
            # Note: Here the context is elevated, because the floatingip port
            # will not have tenant and floatingip subnet might be in other
            # tenant.
            admin_context = context.elevated()
            floatingip_port = self._get_floatingip_port(
                admin_context, floatingip_dict['id'])
            if not floatingip_port:
                raise n_common_exc.DeviceNotFoundError(
                    device_name=floatingip_dict['id'])
            subnet_id = floatingip_port['fixed_ips'][0]['subnet_id']
            floatingip_subnet = self._get_floatingip_subnet(
                admin_context, subnet_id)
            if floatingip_subnet is None:
                raise n_exc.SubnetNotFound(subnet_id=subnet_id)
        except Exception:
            with excutils.save_and_reraise_exception() as ctxt:
                ctxt.reraise = True
                # delete the stale floatingip port
                try:
                    if floatingip_port:
                        self.nb_api.delete_lport(floatingip_port['id'],
                                                 floatingip_port['tenant_id'])
                except df_exceptions.DBKeyNotFound:
                    pass

        self.nb_api.create_floatingip(
            id=floatingip_dict['id'],
            topic=floatingip_dict['tenant_id'],
            name=floatingip_dict.get('name', df_const.DF_FIP_DEFAULT_NAME),
            floating_ip_address=floatingip_dict['floating_ip_address'],
            floating_network_id=floatingip_dict['floating_network_id'],
            router_id=floatingip_dict['router_id'],
            port_id=floatingip_dict['port_id'],
            fixed_ip_address=floatingip_dict['fixed_ip_address'],
            status=floatingip_dict['status'],
            floating_port_id=floatingip_port['id'],
            floating_mac_address=floatingip_port['mac_address'],
            external_gateway_ip=floatingip_subnet['gateway_ip'],
            version=fip_version,
            external_cidr=floatingip_subnet['cidr'])

        return floatingip_dict
Beispiel #15
0
def create_route(context, route):
    LOG.info("create_route for tenant %s" % context.tenant_id)
    if not route:
        raise n_exc.BadRequest(resource="routes", msg="Malformed body")
    route = route.get("route")
    if not route:
        raise n_exc.BadRequest(resource="routes", msg="Malformed body")
    for key in ["gateway", "cidr", "subnet_id"]:
        if key not in route:
            raise n_exc.BadRequest(resource="routes",
                                   msg="%s is required" % key)

    subnet_id = route["subnet_id"]
    with context.session.begin():
        subnet = db_api.subnet_find(context, id=subnet_id, scope=db_api.ONE)
        if not subnet:
            raise n_exc.SubnetNotFound(subnet_id=subnet_id)

        if subnet["ip_policy"]:
            policies = subnet["ip_policy"].get_cidrs_ip_set()
        else:
            policies = netaddr.IPSet([])

        alloc_pools = allocation_pool.AllocationPools(subnet["cidr"],
                                                      policies=policies)
        try:
            alloc_pools.validate_gateway_excluded(route["gateway"])
        except neutron_exc.GatewayConflictWithAllocationPools as e:
            LOG.exception(str(e))
            raise n_exc.BadRequest(resource="routes", msg=str(e))

        # TODO(anyone): May want to denormalize the cidr values into columns
        #               to achieve single db lookup on conflict check
        route_cidr = netaddr.IPNetwork(route["cidr"])
        subnet_routes = db_api.route_find(context, subnet_id=subnet_id,
                                          scope=db_api.ALL)

        quota.QUOTAS.limit_check(context, context.tenant_id,
                                 routes_per_subnet=len(subnet_routes) + 1)

        for sub_route in subnet_routes:
            sub_route_cidr = netaddr.IPNetwork(sub_route["cidr"])
            if sub_route_cidr.value == DEFAULT_ROUTE.value:
                continue
            if route_cidr in sub_route_cidr or sub_route_cidr in route_cidr:
                raise q_exc.RouteConflict(route_id=sub_route["id"],
                                          cidr=str(route_cidr))
        new_route = db_api.route_create(context, **route)
    return v._make_route_dict(new_route)
Beispiel #16
0
def delete_subnet(context, id):
    """Delete a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to delete.
    """
    LOG.info("delete_subnet %s for tenant %s" % (id, context.tenant_id))
    with context.session.begin():
        subnet = db_api.subnet_find(context, id=id, scope=db_api.ONE)
        if not subnet:
            raise n_exc.SubnetNotFound(subnet_id=id)

        if not context.is_admin:
            if STRATEGY.is_provider_network(subnet.network_id):
                if subnet.tenant_id == context.tenant_id:
                    # A tenant can't delete subnets on provider network
                    raise n_exc.NotAuthorized(subnet_id=id)
                else:
                    # Raise a NotFound here because the foreign tenant
                    # does not have to know about other tenant's subnet
                    # existence.
                    raise n_exc.SubnetNotFound(subnet_id=id)

        _delete_subnet(context, subnet)
Beispiel #17
0
 def bulk_allocate(self, address_request):
     # The signature of this function differs from allocate only in that it
     # returns a list of addresses, as opposed to a single address.
     if not isinstance(address_request, ipam_req.BulkAddressRequest):
         return [self.allocate(address_request)]
     num_addrs = address_request.num_addresses
     allocated_ip_pool = self._generate_ips(self._context, False, num_addrs)
     # Create IP allocation request objects
     try:
         with db_api.CONTEXT_WRITER.using(self._context):
             for ip_address in allocated_ip_pool:
                 self.subnet_manager.create_allocation(
                     self._context, ip_address)
     except db_exc.DBReferenceError:
         raise n_exc.SubnetNotFound(
             subnet_id=self.subnet_manager.neutron_id)
     return allocated_ip_pool
Beispiel #18
0
def delete_subnet(context, id):
    """Delete a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to delete.
    """
    LOG.info("delete_subnet %s for tenant %s" % (id, context.tenant_id))
    with context.session.begin():
        subnet = db_api.subnet_find(context, id=id, scope=db_api.ONE)
        if not subnet:
            raise n_exc.SubnetNotFound(subnet_id=id)

        payload = dict(tenant_id=subnet["tenant_id"],
                       ip_block_id=subnet["id"],
                       created_at=subnet["created_at"],
                       deleted_at=timeutils.utcnow())

        _delete_subnet(context, subnet)

        n_rpc.get_notifier("network").info(context, "ip_block.delete", payload)
Beispiel #19
0
	def wrap_function(*args,**kwargs):
		if isinstance(args[0],eipPool):
			if args[0]._subnetpool is not None:
				args[0].scope_json = connector.NeutronConnector().get_connector().list_address_scopes(id=args[0]._subnetpool['address_scope_id'])['address_scopes'][0]
			else: 
				subnet_id = args[1].subnet_id if hasattr(args[1],'subnet_id') else args[1]
				args[0].subnet_json = connector.NeutronConnector().get_connector().list_subnets(id=subnet_id)['subnets'][0]
				args[0].pool_json = connector.NeutronConnector().get_connector().list_subnetpools(id=args[0].subnet_json['subnetpool_id'])['subnetpools'][0] if args[0].subnet_json['subnetpool_id'] else None
				args[0].scope_json = connector.NeutronConnector().get_connector().list_address_scopes(id=args[0].pool_json['address_scope_id'])['address_scopes'][0] if args[0].pool_json and args[0].pool_json['address_scope_id'] else None


		elif isinstance(args[0],eipSubnet):
			args[0].subnet_json = connector.NeutronConnector().get_connector().list_subnets(id=args[0].subnet_id)['subnets'][0]
		        args[0].pool_json = connector.NeutronConnector().get_connector().list_subnetpools(id=args[0].subnet_json['subnetpool_id'])['subnetpools'][0]
		        args[0].scope_json = connector.NeutronConnector().get_connector().list_address_scopes(id=args[0].pool_json['address_scope_id'])['address_scopes'][0]

		if args[0].scope_json is None:
			# This subnet is not complient with our IPAM : it has no site
	                LOG.error("Failed : to retrieve "+subnet_id+" in IPAM")
        	        raise neutron_lib_exc.SubnetNotFound(subnet_id=subnet_id)

		args[0].sitename = args[0].scope_json['name']

		return function(*args,**kwargs)
Beispiel #20
0
    def remove_subnet(self, subnet_id):
        """Removes an allocation

        The initial reference implementation will probably do nothing.

        :param subnet_id: the subnet identifier
        :type subnet_id: str uuid
        :raises: IPAMAllocationNotFound
        """

        if self.subnet_json['ip_version'] == 4:
		subnet_addr,_,subnet_prefix = str(self.subnet_json['cidr']).partition('/')
		r = eip_rest.delete_subnet_v4(self.sitename,subnet_addr,subnet_prefix)

        elif self.subnet_json['ip_version'] == 6:
		subnet_addr,_,subnet_prefix = str(self.subnet_json['cidr']).partition('/')
		r = eip_rest.delete_subnet_v6(self.sitename,subnet_addr,subnet_prefix)

	if r is None:
                LOG.error("Failed : to retrieve "+subnet_id+" in IPAM")
                raise neutron_lib_exc.SubnetNotFound(subnet_id=subnet_id)


	return
Beispiel #21
0
 def test_create_port_catch_and_handle_ip_generation_failure(self):
     self.plugin.get_subnet.side_effect = (n_exc.SubnetNotFound(
         subnet_id='foo_subnet_id'))
     self._test__port_action_with_failures(
         exc=n_exc.IpAddressGenerationFailure(net_id='foo_network_id'),
         action='create_port')
Beispiel #22
0
def get_subnet(network, resource_group, network_name, name):
    try:
        return network.subnets.get(resource_group, network_name, name)
    except CloudError:
        raise n_exceptions.SubnetNotFound(subnet_id=name)
 def _get_subnet_object(self, context, id):
     subnet = subnet_obj.Subnet.get_object(context, id=id)
     if not subnet:
         raise n_exc.SubnetNotFound(subnet_id=id)
     return subnet
 def _get_subnet(self, context, id):
     try:
         subnet = self._get_by_id(context, models_v2.Subnet, id)
     except exc.NoResultFound:
         raise n_exc.SubnetNotFound(subnet_id=id)
     return subnet
Beispiel #25
0
    def allocate(self, address_request):
        # NOTE(pbondar): Ipam driver is always called in context of already
        # running transaction, which is started on create_port or upper level.
        # To be able to do rollback/retry actions correctly ipam driver
        # should not create new nested transaction blocks.
        all_pool_id = None
        # NOTE(salv-orlando): It would probably better to have a simpler
        # model for address requests and just check whether there is a
        # specific IP address specified in address_request
        if isinstance(address_request, ipam_req.SpecificAddressRequest):
            # This handles both specific and automatic address requests
            # Check availability of requested IP
            ip_address = str(address_request.address)
 
            self._verify_ip(self._context, ip_address)
        else:
            prefer_next = isinstance(address_request,
                                     ipam_req.PreferNextAddressRequest)
            ip_address, all_pool_id = self._generate_ip(self._context,
                                                        prefer_next)

        # Create IP allocation request object
        # The only defined status at this stage is 'ALLOCATED'.
        # More states will be available in the future - e.g.: RECYCLABLE
        try:
            with self._context.session.begin(subtransactions=True):
                # NOTE(kevinbenton): we use a subtransaction to force
                # a flush here so we can capture DBReferenceErrors due
                # to concurrent subnet deletions. (galera would deadlock
                # later on final commit)
                self.subnet_manager.create_allocation(self._context,
                                                      ip_address)
        except db_exc.DBReferenceError:
            raise n_exc.SubnetNotFound(
                subnet_id=self.subnet_manager.neutron_id)

        ipObj = netaddr.IPAddress(ip_address)
        
        # BlueCat additions
        paramsBAM = getBCNConfig(BC_configFileName, "BAM")
        
        soap_client = _bam_login(paramsBAM)
        configID = _get_bam_configid(paramsBAM, soap_client)

        LOG.info("BCN: Creating host %s in BAM  ..." % (ip_address))

        if hasattr(address_request, 'port_name') :
            hostName = address_request.port_name
            LOG.info("BCN: Hostname is %s" % (hostName))
        else:
            LOG.info("BCN: port_name not set in request...")
            if ipObj.version == 4:
                hostName = "ip-"
                hostName += ip_address.replace('.', "-")
            else:
                hostName = "ip-"
                hostName += ip_address.replace(':', "-")

        id = ""
        if hasattr(address_request, "id"):
                id = address_request.id

        mac = ""
        if hasattr(address_request, "mac_address"):
                mac = address_request.mac_address

        if ipObj.version == 4:
            createBCIP4Obj(ip_address, hostName, id, mac, configID, soap_client)
        else:
            createBCPI6Obj(ip_address, hostName, id, mac, configID, soap_client)        

        _bam_logout(paramsBAM, soap_client)
        return ip_address
Beispiel #26
0
    def allocate(self, address_request):
        # NOTE(pbondar): Ipam driver is always called in context of already
        # running transaction, which is started on create_port or upper level.
        # To be able to do rollback/retry actions correctly ipam driver
        # should not create new nested transaction blocks.
        if isinstance(address_request, TransparentSpecificAddressrequest):
            return super(NuageIpamSubnet, self).allocate(
                ipam_req.SpecificAddressRequest(address_request.address))
        if isinstance(address_request, TransparentPreferNextAddressRequest):
            return super(NuageIpamSubnet,
                         self).allocate(ipam_req.PreferNextAddressRequest())

        subnet_mapping = self._get_subnet_mapping()
        if not subnet_mapping:
            raise n_exc.BadRequest(resource='ipam',
                                   msg='Unable to find vsd subnet '
                                   'for requested ip allocation')
        is_l2 = utils.SubnetUtilsBase._is_l2(subnet_mapping)
        nuage_parent_id = subnet_mapping['nuage_subnet_id']
        vsdclient = self._get_vsdclient()
        ip_address = None
        max_retries = 5
        nr_retries = 0
        while not ip_address and nr_retries < max_retries:
            try:
                ip_address = self.create_vmipreservation(
                    address_request, vsdclient, is_l2, nuage_parent_id)
                if not ip_address:
                    reason = "Unable to reserve IP on VSD"
                    raise ipam_exc.InvalidAddressRequest(reason=reason)
                break
            except restproxy.ResourceNotFoundException:
                # l2domain or l3domain not found, due to router attach may have
                # moved.
                nr_retries += 1
                if nr_retries < max_retries:
                    LOG.debug('Could not find VSD Domain/Subnet. '
                              'Retrying {}/{}.'.format(nr_retries,
                                                       max_retries))
                    # Find on VSD parent based on reverse of is_l2, as we
                    # assume router-attach/detach scenario
                    is_l2 = not is_l2
                    try:
                        nuage_parent_id = self._get_nuage_id_from_vsd(
                            vsdclient, is_l2)
                    except restproxy.ResourceNotFoundException:
                        pass
                else:
                    LOG.debug('Could not find VSD Domain/Subnet after '
                              'retrying {}/{} times.'.format(
                                  nr_retries, max_retries))
                    raise

        # Create IP allocation request object
        # The only defined status at this stage is 'ALLOCATED'.
        # More states will be available in the future - e.g.: RECYCLABLE
        try:
            with self._context.session.begin(subtransactions=True):
                # NOTE(kevinbenton): we use a subtransaction to force
                # a flush here so we can capture DBReferenceErrors due
                # to concurrent subnet deletions. (galera would deadlock
                # later on final commit)
                self.subnet_manager.create_allocation(self._context,
                                                      ip_address)
        except db_exc.DBReferenceError:
            raise n_exc.SubnetNotFound(
                subnet_id=self.subnet_manager.neutron_id)
        return ip_address
 def test_create_port_catch_subnet_not_found(self):
     self._test__port_action_with_failures(
         exc=exceptions.SubnetNotFound(subnet_id='foo_subnet_id'),
         action='create_port')
Beispiel #28
0
def update_subnet(context, id, subnet):
    """Update values of a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to update.
    : param subnet: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.
    """
    LOG.info("update_subnet %s for tenant %s" % (id, context.tenant_id))

    with context.session.begin():
        subnet_db = db_api.subnet_find(context=context,
                                       limit=None,
                                       page_reverse=False,
                                       sorts=['id'],
                                       marker_obj=None,
                                       fields=None,
                                       id=id,
                                       scope=db_api.ONE)
        if not subnet_db:
            raise n_exc.SubnetNotFound(subnet_id=id)

        s = subnet["subnet"]
        always_pop = [
            "_cidr", "cidr", "first_ip", "last_ip", "ip_version", "segment_id",
            "network_id"
        ]
        admin_only = [
            "do_not_use", "created_at", "tenant_id", "next_auto_assign_ip",
            "enable_dhcp"
        ]
        utils.filter_body(context, s, admin_only, always_pop)

        dns_ips = utils.pop_param(s, "dns_nameservers", [])
        host_routes = utils.pop_param(s, "host_routes", [])
        gateway_ip = utils.pop_param(s, "gateway_ip", None)
        allocation_pools = utils.pop_param(s, "allocation_pools", None)
        if not CONF.QUARK.allow_allocation_pool_update:
            if allocation_pools:
                raise n_exc.BadRequest(
                    resource="subnets",
                    msg="Allocation pools cannot be updated.")

            if subnet_db["ip_policy"] is not None:
                ip_policy_cidrs = subnet_db["ip_policy"].get_cidrs_ip_set()
            else:
                ip_policy_cidrs = netaddr.IPSet([])

            alloc_pools = allocation_pool.AllocationPools(
                subnet_db["cidr"], policies=ip_policy_cidrs)
        else:
            alloc_pools = allocation_pool.AllocationPools(
                subnet_db["cidr"], allocation_pools)
            original_pools = subnet_db.allocation_pools
            ori_pools = allocation_pool.AllocationPools(
                subnet_db["cidr"], original_pools)
            # Check if the pools are growing or shrinking
            is_growing = _pool_is_growing(ori_pools, alloc_pools)
            if not CONF.QUARK.allow_allocation_pool_growth and is_growing:
                raise n_exc.BadRequest(
                    resource="subnets",
                    msg="Allocation pools may not be updated to be larger "
                    "do to configuration settings")

        quota.QUOTAS.limit_check(context,
                                 context.tenant_id,
                                 alloc_pools_per_subnet=len(alloc_pools))
        if gateway_ip:
            alloc_pools.validate_gateway_excluded(gateway_ip)
            default_route = None
            for route in host_routes:
                netaddr_route = netaddr.IPNetwork(route["destination"])
                if netaddr_route.value == routes.DEFAULT_ROUTE.value:
                    default_route = route
                    break

            if default_route is None:
                route_model = db_api.route_find(context,
                                                cidr=str(routes.DEFAULT_ROUTE),
                                                subnet_id=id,
                                                scope=db_api.ONE)
                if route_model:
                    db_api.route_update(context,
                                        route_model,
                                        gateway=gateway_ip)
                else:
                    db_api.route_create(context,
                                        cidr=str(routes.DEFAULT_ROUTE),
                                        gateway=gateway_ip,
                                        subnet_id=id)

        if dns_ips:
            subnet_db["dns_nameservers"] = []
            quota.QUOTAS.limit_check(context,
                                     context.tenant_id,
                                     dns_nameservers_per_subnet=len(dns_ips))

        for dns_ip in dns_ips:
            subnet_db["dns_nameservers"].append(
                db_api.dns_create(context, ip=netaddr.IPAddress(dns_ip)))

        if host_routes:
            subnet_db["routes"] = []
            quota.QUOTAS.limit_check(context,
                                     context.tenant_id,
                                     routes_per_subnet=len(host_routes))

        for route in host_routes:
            subnet_db["routes"].append(
                db_api.route_create(context,
                                    cidr=route["destination"],
                                    gateway=route["nexthop"]))
        if CONF.QUARK.allow_allocation_pool_update:
            if isinstance(allocation_pools, list):
                cidrs = alloc_pools.get_policy_cidrs()
                ip_policies.ensure_default_policy(cidrs, [subnet_db])
                subnet_db["ip_policy"] = db_api.ip_policy_update(
                    context, subnet_db["ip_policy"], exclude=cidrs)
                # invalidate the cache
                db_api.subnet_update_set_alloc_pool_cache(context, subnet_db)
        subnet = db_api.subnet_update(context, subnet_db, **s)
    return v._make_subnet_dict(subnet)
Beispiel #29
0
def update_ip_policy(context, id, ip_policy):
    LOG.info("update_ip_policy for tenant %s" % context.tenant_id)

    ipp = ip_policy["ip_policy"]

    with context.session.begin():
        ipp_db = db_api.ip_policy_find(context, id=id, scope=db_api.ONE)
        if not ipp_db:
            raise q_exc.IPPolicyNotFound(id=id)

        ip_policy_cidrs = ipp.get("exclude")
        network_ids = ipp.get("network_ids")
        subnet_ids = ipp.get("subnet_ids")

        if subnet_ids and network_ids:
            raise n_exc.BadRequest(
                resource="ip_policy",
                msg="network_ids and subnet_ids specified. only one allowed")

        models = []
        all_subnets = []
        if subnet_ids:
            for subnet in ipp_db["subnets"]:
                subnet["ip_policy"] = None
            subnets = db_api.subnet_find(context,
                                         id=subnet_ids,
                                         scope=db_api.ALL)
            if len(subnets) != len(subnet_ids):
                raise n_exc.SubnetNotFound(subnet_id=subnet_ids)
            if ip_policy_cidrs is not None:
                ensure_default_policy(ip_policy_cidrs, subnets)
                _validate_cidrs_fit_into_subnets(ip_policy_cidrs, subnets)
            all_subnets.extend(subnets)
            models.extend(subnets)

        if network_ids:
            for network in ipp_db["networks"]:
                network["ip_policy"] = None
            nets = db_api.network_find(context,
                                       id=network_ids,
                                       scope=db_api.ALL)
            if len(nets) != len(network_ids):
                raise n_exc.NetworkNotFound(net_id=network_ids)
            subnets = [
                subnet for net in nets for subnet in net.get("subnets", [])
            ]
            if ip_policy_cidrs is not None:
                ensure_default_policy(ip_policy_cidrs, subnets)
                _validate_cidrs_fit_into_subnets(ip_policy_cidrs, subnets)
            all_subnets.extend(subnets)
            models.extend(nets)

        if not subnet_ids and not network_ids and ip_policy_cidrs is not None:
            ensure_default_policy(ip_policy_cidrs, ipp_db["subnets"])
            _validate_cidrs_fit_into_subnets(ip_policy_cidrs,
                                             ipp_db["subnets"])

        for model in models:
            if model["ip_policy"]:
                raise q_exc.IPPolicyAlreadyExists(id=model["ip_policy"]["id"],
                                                  n_id=model["id"])
            model["ip_policy"] = ipp_db

        if ip_policy_cidrs:
            _validate_policy_with_routes(context, ip_policy_cidrs, all_subnets)
        ipp_db = db_api.ip_policy_update(context, ipp_db, **ipp)
    return v._make_ip_policy_dict(ipp_db)