def process_create_policy_target_group(self, session, data, result):
     data = data['policy_target_group']
     proxied = data.get('proxied_group_id')
     if attributes.is_attr_set(proxied):
         # Set value for proxied group
         record = (session.query(db.GroupProxyMapping).filter_by(
             policy_target_group_id=proxied).first())
         if record:
             if record.proxy_group_id:
                 raise driver_proxy_group.InvalidProxiedGroup(
                     group_id=proxied)
             record.proxy_group_id = result['id']
         else:
             # Record may not exist for that PTG yet
             record = db.GroupProxyMapping(
                 policy_target_group_id=proxied,
                 proxy_group_id=result['id'],
                 proxied_group_id=None)
             session.add(record)
         if not attributes.is_attr_set(data.get('proxy_type')):
             data['proxy_type'] = driver_proxy_group.DEFAULT_PROXY_TYPE
             record = (session.query(db.GroupProxyMapping).filter_by(
                 policy_target_group_id=result['id']).one())
             record.proxy_type = data['proxy_type']
             result['proxy_type'] = data['proxy_type']
     elif attributes.is_attr_set(data.get('proxy_type')):
         raise driver_proxy_group.ProxyTypeSetWithoutProxiedPTG()
Пример #2
0
    def _process_provider_create(self, network):
        segments = []

        if any(attributes.is_attr_set(network.get(f))
               for f in (provider.NETWORK_TYPE, provider.PHYSICAL_NETWORK,
                         provider.SEGMENTATION_ID)):
            # Verify that multiprovider and provider attributes are not set
            # at the same time.
            if attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
                raise mpnet.SegmentsSetInConjunctionWithProviders()

            network_type = self._get_attribute(network, provider.NETWORK_TYPE)
            physical_network = self._get_attribute(network,
                                                   provider.PHYSICAL_NETWORK)
            segmentation_id = self._get_attribute(network,
                                                  provider.SEGMENTATION_ID)
            segments = [{provider.NETWORK_TYPE: network_type,
                         provider.PHYSICAL_NETWORK: physical_network,
                         provider.SEGMENTATION_ID: segmentation_id}]
        elif attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
            segments = network[mpnet.SEGMENTS]
        else:
            return

        return [self._process_provider_segment(s) for s in segments]
Пример #3
0
    def _determine_port_security_and_has_ip(self, context, port):
        """Returns a tuple of booleans (port_security_enabled, has_ip).

        Port_security is the value associated with the port if one is present
        otherwise the value associated with the network is returned. has_ip is
        if the port is associated with an ip or not.
        """
        has_ip = self._ip_on_port(port)
        # we don't apply security groups for dhcp, router
        if (port.get('device_owner') and
                port['device_owner'].startswith('network:')):
            return (False, has_ip)

        if attrs.is_attr_set(port.get(psec.PORTSECURITY)):
            port_security_enabled = port[psec.PORTSECURITY]

        # If port has an ip and security_groups are passed in
        # conveniently set port_security_enabled to true this way
        # user doesn't also have to pass in port_security_enabled=True
        # when creating ports.
        elif (has_ip and attrs.is_attr_set(port.get('security_groups'))):
            port_security_enabled = True
        else:
            port_security_enabled = self._get_network_security_binding(
                context, port['network_id'])

        return (port_security_enabled, has_ip)
Пример #4
0
    def create_subnet(self, context, subnet):

        s = subnet['subnet']
        cidr = s.get('cidr', attributes.ATTR_NOT_SPECIFIED)
        prefixlen = s.get('prefixlen', attributes.ATTR_NOT_SPECIFIED)
        has_cidr = attributes.is_attr_set(cidr)
        has_prefixlen = attributes.is_attr_set(prefixlen)

        if has_cidr and has_prefixlen:
            msg = _('cidr and prefixlen must not be supplied together')
            raise n_exc.BadRequest(resource='subnets', msg=msg)

        if has_cidr:
            # turn the CIDR into a proper subnet
            net = netaddr.IPNetwork(s['cidr'])
            subnet['subnet']['cidr'] = '%s/%s' % (net.network, net.prefixlen)

        s['tenant_id'] = self._get_tenant_id_for_create(context, s)
        subnetpool_id = self._get_subnetpool_id(s)
        if subnetpool_id:
            self.ipam.validate_pools_with_subnetpool(s)
        else:
            if not has_cidr:
                msg = _('A cidr must be specified in the absence of a '
                        'subnet pool')
                raise n_exc.BadRequest(resource='subnets', msg=msg)
            self._validate_subnet(context, s)

        return self._create_subnet(context, subnet, subnetpool_id)
    def process_update_network(self, context, data, result):
        """Implementation of abstract method from ExtensionDriver class."""
    	LOG.debug("RK: process_update_network().  data: %s" , data)

        net_id = result.get('id')
	net_min_attr = data.get(rk_const.RK_MIN_RATE)
	net_max_attr = data.get(rk_const.RK_MAX_RATE)

    	LOG.debug("RK: update_network: %s and %s", net_min_attr, net_max_attr)
        if attributes.is_attr_set(net_min_attr) and \
               attributes.is_attr_set(net_max_attr):

            with context.session.begin(subtransactions=True):
                try:
                    res = rk_db.get_vnet_profile(net_id, context.session)

		    if res:
           	        rk_db.update_vnet_rate_limit(net_id, net_min_attr, net_max_attr, context.session)

		    else:
                        # Network not found and can't be updated.  Create instead
		        try:
                    	    rk_db.create_vnet_record(net_id, net_min_attr, net_max_attr, context.session)
            	        except Exception as e:
                	    LOG.error(_LE("RK: update_network: error %s" % e)) 
                	    raise ml2_exc.MechanismDriverError()

    		    LOG.debug("RK: update_network: res: %s", res)

		except Exception as a:
                    LOG.error(_LE("RK: update_network: error %s" % a))
                    raise ml2_exc.MechanismDriverError()
Пример #6
0
    def _save_subnet(self, context,
                     network,
                     subnet_args,
                     dns_nameservers,
                     host_routes,
                     allocation_pools):
        allocation_pools = self._prepare_allocation_pools(context,
                                                          allocation_pools,
                                                          subnet_args)
        self._validate_subnet_cidr(context, network, subnet_args['cidr'])
        self._validate_network_subnetpools(network,
                                           subnet_args['subnetpool_id'],
                                           subnet_args['ip_version'])

        subnet = models_v2.Subnet(**subnet_args)
        context.session.add(subnet)
        if attributes.is_attr_set(dns_nameservers):
            for addr in dns_nameservers:
                ns = models_v2.DNSNameServer(address=addr,
                                             subnet_id=subnet.id)
                context.session.add(ns)

        if attributes.is_attr_set(host_routes):
            for rt in host_routes:
                route = models_v2.SubnetRoute(
                    subnet_id=subnet.id,
                    destination=rt['destination'],
                    nexthop=rt['nexthop'])
                context.session.add(route)

        self._save_allocation_pools(context, subnet, allocation_pools)

        return subnet
Пример #7
0
    def _get_subnetpool_id(self, subnet):
        """Returns the subnetpool id for this request

        If the pool id was explicitly set in the request then that will be
        returned, even if it is None.

        Otherwise, the default pool for the IP version requested will be
        returned.  This will either be a pool id or None (the default for each
        configuration parameter).  This implies that the ip version must be
        either set implicitly with a specific cidr or explicitly using
        ip_version attribute.

        :param subnet: The subnet dict from the request
        """
        subnetpool_id = subnet.get('subnetpool_id',
                                   attributes.ATTR_NOT_SPECIFIED)
        if subnetpool_id != attributes.ATTR_NOT_SPECIFIED:
            return subnetpool_id

        cidr = subnet.get('cidr')
        if attributes.is_attr_set(cidr):
            ip_version = netaddr.IPNetwork(cidr).version
        else:
            ip_version = subnet.get('ip_version')
            if not attributes.is_attr_set(ip_version):
                msg = _('ip_version must be specified in the absence of '
                        'cidr and subnetpool_id')
                raise n_exc.BadRequest(resource='subnets', msg=msg)

        if ip_version == 4:
            return cfg.CONF.default_ipv4_subnet_pool
        return cfg.CONF.default_ipv6_subnet_pool
Пример #8
0
    def _save_subnet(self, context,
                     network,
                     subnet_args,
                     dns_nameservers,
                     host_routes,
                     subnet_request):
        self._validate_subnet_cidr(context, network, subnet_args['cidr'])
        self._validate_network_subnetpools(network,
                                           subnet_args['subnetpool_id'],
                                           subnet_args['ip_version'])

        subnet = models_v2.Subnet(**subnet_args)
        context.session.add(subnet)
        # NOTE(changzhi) Store DNS nameservers with order into DB one
        # by one when create subnet with DNS nameservers
        if attributes.is_attr_set(dns_nameservers):
            for order, server in enumerate(dns_nameservers):
                dns = models_v2.DNSNameServer(
                    address=server,
                    order=order,
                    subnet_id=subnet.id)
                context.session.add(dns)

        if attributes.is_attr_set(host_routes):
            for rt in host_routes:
                route = models_v2.SubnetRoute(
                    subnet_id=subnet.id,
                    destination=rt['destination'],
                    nexthop=rt['nexthop'])
                context.session.add(route)

        self.save_allocation_pools(context, subnet,
                                   subnet_request.allocation_pools)

        return subnet
Пример #9
0
    def _process_portbindings_create_and_update(self, context, port_data,
                                                port):
        binding_profile = port.get(portbindings.PROFILE)
        binding_profile_set = attr.is_attr_set(binding_profile)
        if not binding_profile_set and binding_profile is not None:
            del port[portbindings.PROFILE]

        binding_vnic = port.get(portbindings.VNIC_TYPE)
        binding_vnic_set = attr.is_attr_set(binding_vnic)
        if not binding_vnic_set and binding_vnic is not None:
            del port[portbindings.VNIC_TYPE]

        host = port_data.get(portbindings.HOST_ID)
        host_set = attr.is_attr_set(host)
        with context.session.begin(subtransactions=True):
            bind_port = context.session.query(
                models.PortBinding).filter_by(port_id=port['id']).first()
            if host_set:
                if not bind_port:
                    context.session.add(models.PortBinding(
                        port_id=port['id'],
                        host=host,
                        vif_type=self.vif_type))
                else:
                    bind_port.host = host
            else:
                host = bind_port.host if bind_port else None
        self._extend_port_dict_binding_host(port, host)
Пример #10
0
    def create_subnet(self, context, subnet):

        s = subnet["subnet"]
        cidr = s.get("cidr", attributes.ATTR_NOT_SPECIFIED)
        prefixlen = s.get("prefixlen", attributes.ATTR_NOT_SPECIFIED)
        has_cidr = attributes.is_attr_set(cidr)
        has_prefixlen = attributes.is_attr_set(prefixlen)

        if has_cidr and has_prefixlen:
            msg = _("cidr and prefixlen must not be supplied together")
            raise n_exc.BadRequest(resource="subnets", msg=msg)

        if has_cidr:
            # turn the CIDR into a proper subnet
            net = netaddr.IPNetwork(s["cidr"])
            subnet["subnet"]["cidr"] = "%s/%s" % (net.network, net.prefixlen)

        s["tenant_id"] = self._get_tenant_id_for_create(context, s)
        subnetpool_id = self._get_subnetpool_id(s)
        if subnetpool_id:
            self._validate_pools_with_subnetpool(s)
        else:
            if not has_cidr:
                msg = _("A cidr must be specified in the absence of a " "subnet pool")
                raise n_exc.BadRequest(resource="subnets", msg=msg)
            self._validate_subnet(context, s)

        return self._create_subnet(context, subnet, subnetpool_id)
    def create_nuage_redirect_target(self, context, nuage_redirect_target):
        redirect_target = nuage_redirect_target['nuage_redirect_target']
        has_subnet_id = is_attr_set(redirect_target.get('subnet_id'))
        has_router_id = is_attr_set(redirect_target.get('router_id'))

        if not has_subnet_id and not has_router_id:
            msg = _('subnet_id or router_id should be specified')
            raise n_exc.BadRequest(resource='subnets', msg=msg)

        subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
            context.session, redirect_target.get('subnet_id')) or {}
        router_mapping = nuagedb.get_ent_rtr_mapping_by_rtrid(
            context.session, redirect_target.get('router_id')) or {}
        if not subnet_mapping and not router_mapping:
            raise ext_rtarget.RedirectTargetNoDomainOrL2Domain()

        try:
            nuage_redirect_target = self.nuageclient\
                .create_nuage_redirect_target(
                    redirect_target,
                    subnet_id=subnet_mapping.get('nuage_subnet_id'),
                    domain_id=router_mapping.get('nuage_router_id'))
        except Exception as e:
            if getattr(e, "vsd_code", None) == '7016':
                msg = _("A Nuage redirect target with name '%s' already "
                        "exists") % redirect_target['name']
                raise nuage_exc.NuageBadRequest(msg=msg)
            raise e
        return self._make_redirect_target_dict(nuage_redirect_target,
                                               context=context)
Пример #12
0
    def _process_port_binding(self, mech_context, attrs):
        binding = mech_context._binding
        port = mech_context.current
        self._update_port_dict_binding(port, binding)
        host = attrs and attrs.get(portbindings.HOST_ID)
        host_set = attributes.is_attr_set(host)
        vnic_type = attrs and attrs.get(portbindings.VNIC_TYPE)
        vnic_type_set = attributes.is_attr_set(vnic_type)

        if binding.vif_type != portbindings.VIF_TYPE_UNBOUND:
            if (not host_set and not vnic_type_set and binding.segment and
                self.mechanism_manager.validate_port_binding(mech_context)):
                return False
            self.mechanism_manager.unbind_port(mech_context)
            self._update_port_dict_binding(port, binding)

        # Return True only if an agent notification is needed.
        # This will happen if a new host or vnic_type was specified that
        # differs from the current one. Note that host_set is True
        # even if the host is an empty string
        ret_value = ((host_set and binding.get('host') != host) or
                     (vnic_type_set and binding.get('vnic_type') != vnic_type))
        if host_set:
            binding.host = host
            port[portbindings.HOST_ID] = host

        if vnic_type_set:
            binding.vnic_type = vnic_type
            port[portbindings.VNIC_TYPE] = vnic_type

        if binding.host:
            self.mechanism_manager.bind_port(mech_context)
            self._update_port_dict_binding(port, binding)

        return ret_value
    def create_port(self, context, port):
        if attr.is_attr_set(port['port'][psec.PORTSECURITY]):
            self._enforce_set_auth(context, port,
                                   self.port_security_enabled_create)
        p = port['port']
        with context.session.begin(subtransactions=True):
            p[ext_sg.SECURITYGROUPS] = self._get_security_groups_on_port(
                context, port)
            neutron_db = super(PortSecurityTestPlugin, self).create_port(
                context, port)
            p.update(neutron_db)

            (port_security, has_ip) = self._determine_port_security_and_has_ip(
                context, p)
            p[psec.PORTSECURITY] = port_security
            self._process_port_security_create(context, p)

            if (attr.is_attr_set(p.get(ext_sg.SECURITYGROUPS)) and
                not (port_security and has_ip)):
                raise psec.PortSecurityAndIPRequiredForSecurityGroups()

            # Port requires ip and port_security enabled for security group
            if has_ip and port_security:
                self._ensure_default_security_group_on_port(context, port)

            if (p.get(ext_sg.SECURITYGROUPS) and p[psec.PORTSECURITY]):
                self._process_port_create_security_group(
                    context, p, p[ext_sg.SECURITYGROUPS])

            self._extend_port_port_security_dict(context, p)

        return port['port']
Пример #14
0
    def create_subnet(self, context, subnet):

        s = subnet["subnet"]
        cidr = s.get("cidr", attributes.ATTR_NOT_SPECIFIED)
        prefixlen = s.get("prefixlen", attributes.ATTR_NOT_SPECIFIED)
        has_cidr = attributes.is_attr_set(cidr)
        has_prefixlen = attributes.is_attr_set(prefixlen)

        if has_cidr and has_prefixlen:
            msg = _("cidr and prefixlen must not be supplied together")
            raise n_exc.BadRequest(resource="subnets", msg=msg)

        if has_cidr:
            # turn the CIDR into a proper subnet
            net = netaddr.IPNetwork(s["cidr"])
            subnet["subnet"]["cidr"] = "%s/%s" % (net.network, net.prefixlen)

        s["tenant_id"] = self._get_tenant_id_for_create(context, s)
        subnetpool_id = self._get_subnetpool_id(s)
        if not subnetpool_id:
            if not has_cidr:
                msg = _("A cidr must be specified in the absence of a " "subnet pool")
                raise n_exc.BadRequest(resource="subnets", msg=msg)
            # Create subnet from the implicit(AKA null) pool
            created_subnet = self._create_subnet_from_implicit_pool(context, subnet)
        else:
            created_subnet = self._create_subnet_from_pool(context, subnet, subnetpool_id)

        # If this subnet supports auto-addressing, then update any
        # internal ports on the network with addresses for this subnet.
        if ipv6_utils.is_auto_address_subnet(created_subnet):
            self._add_auto_addrs_on_network_ports(context, created_subnet)

        return created_subnet
Пример #15
0
    def create_device_template(self, context, device_template):
        template = device_template['device_template']
        LOG.debug(_('template %s'), template)

        infra_driver = template.get('infra_driver')
        if not attributes.is_attr_set(infra_driver):
            LOG.debug(_('hosting device driver must be specified'))
            raise servicevm.InfraDriverNotSpecified()

        if infra_driver not in cfg.CONF.servicevm.infra_driver:
            LOG.debug(_('unknown hosting device driver '
                        '%(infra_driver)s in %(drivers)s'),
                      {'infra_driver': infra_driver,
                       'drivers': cfg.CONF.servicevm.infra_driver})
            raise servicevm.InvalidInfraDriver(infra_driver=infra_driver)

        service_types = template.get('service_types')
        if not attributes.is_attr_set(service_types):
            LOG.debug(_('service type must be specified'))
            raise servicevm.ServiceTypesNotSpecified()
        for service_type in service_types:
            # TODO(yamahata):
            # framework doesn't know what services are valid for now.
            # so doesn't check it here yet.
            pass

        self._device_manager.invoke(
            infra_driver, 'create_device_template_pre', plugin=self,
            context=context, device_template=device_template)

        return super(ServiceVMPlugin, self).create_device_template(
            context, device_template)
Пример #16
0
    def _process_dvr_port_binding(self, mech_context, context, attrs):
        binding = mech_context.binding

        host = attrs and attrs.get(portbindings.HOST_ID)
        host_set = attributes.is_attr_set(host)

        vnic_type = attrs and attrs.get(portbindings.VNIC_TYPE)
        vnic_type_set = attributes.is_attr_set(vnic_type)

        profile = attrs and attrs.get(portbindings.PROFILE)
        profile_set = profile is not attributes.ATTR_NOT_SPECIFIED

        if binding.vif_type != portbindings.VIF_TYPE_UNBOUND:
            if (not host_set and not vnic_type_set and
                not profile_set and binding.segment):
                return False
            self._delete_port_binding(mech_context)

        if host_set:
            binding.host = host

        if binding.host:
            self.mechanism_manager.bind_port(mech_context)

        return True
Пример #17
0
    def _process_portbindings_create_and_update(self, context, port_data,
                                                port):
        binding_profile = port.get(portbindings.PROFILE)
        binding_profile_set = attributes.is_attr_set(binding_profile)
        if not binding_profile_set and binding_profile is not None:
            del port[portbindings.PROFILE]

        binding_vnic = port.get(portbindings.VNIC_TYPE)
        binding_vnic_set = attributes.is_attr_set(binding_vnic)
        if not binding_vnic_set and binding_vnic is not None:
            del port[portbindings.VNIC_TYPE]
        # REVISIT(irenab) Add support for vnic_type for plugins that
        # can handle more than one type.
        # Currently implemented for ML2 plugin that does not use
        # PortBindingMixin.

        host = port_data.get(portbindings.HOST_ID)
        host_set = attributes.is_attr_set(host)
        with context.session.begin(subtransactions=True):
            bind_port = context.session.query(
                PortBindingPort).filter_by(port_id=port['id']).first()
            if host_set:
                if not bind_port:
                    context.session.add(PortBindingPort(port_id=port['id'],
                                                        host=host))
                else:
                    bind_port.host = host
            else:
                host = bind_port.host if bind_port else None
        self._extend_port_dict_binding_host(port, host)
    def process_create_network(self, context, data, result):
        """Implementation of abstract method from ExtensionDriver class."""
	LOG.debug("RK: process_create_network(). data: %s", data)

        net_id = result.get('id')
	port_min_attr = data.get(rk_const.RK_MIN_RATE)
	port_max_attr = data.get(rk_const.RK_MAX_RATE)

        if not attributes.is_attr_set(port_min_attr) or \
                not attributes.is_attr_set(port_max_attr):
            port_min_attr = cfg.CONF.RATEKEEPER.default_min_rate
            port_max_attr = cfg.CONF.RATEKEEPER.default_max_rate

	port_min_attr, port_max_attr = self._validate_rates(port_min_attr, port_max_attr)

	LOG.debug("RK: port_min_attr %s, port_max_attr %s", port_min_attr, port_max_attr)

        with context.session.begin(subtransactions=True):
            try:
                rk_db.create_vnet_record(net_id, port_min_attr, port_max_attr, context.session)
	    except Exception as e:
		LOG.error(_LE("RK: error %s" % e))
                raise ml2_exc.MechanismDriverError()

	result[rk_const.RK_MIN_RATE] = port_min_attr
	result[rk_const.RK_MAX_RATE] = port_max_attr
Пример #19
0
    def _process_provider_create(self, context, attrs):
        network_type = attrs.get(providernet.NETWORK_TYPE)
        physical_network = attrs.get(providernet.PHYSICAL_NETWORK)
        segmentation_id = attrs.get(providernet.SEGMENTATION_ID)

        network_type_set = attributes.is_attr_set(network_type)
        physical_network_set = attributes.is_attr_set(physical_network)
        segmentation_id_set = attributes.is_attr_set(segmentation_id)

        if not (network_type_set or physical_network_set or
                segmentation_id_set):
            return (None, None, None)

        # Authorize before exposing plugin details to client
        self._enforce_provider_set_auth(context, attrs)

        if not network_type_set:
            msg = _("provider:network_type required")
            raise q_exc.InvalidInput(error_message=msg)
        elif network_type == c_const.NETWORK_TYPE_VLAN:
            if not segmentation_id_set:
                msg = _("provider:segmentation_id required")
                raise q_exc.InvalidInput(error_message=msg)
            if segmentation_id < 1 or segmentation_id > 4094:
                msg = _("provider:segmentation_id out of range "
                        "(1 through 4094)")
                raise q_exc.InvalidInput(error_message=msg)
        elif network_type == c_const.NETWORK_TYPE_VXLAN:
            if physical_network_set:
                msg = _("provider:physical_network specified for VXLAN "
                        "network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                physical_network = None
            if not segmentation_id_set:
                msg = _("provider:segmentation_id required")
                raise q_exc.InvalidInput(error_message=msg)
            if segmentation_id < 5000:
                msg = _("provider:segmentation_id out of range "
                        "(5000+)")
                raise q_exc.InvalidInput(error_message=msg)
        else:
            msg = _("provider:network_type %s not supported"), network_type
            raise q_exc.InvalidInput(error_message=msg)

        if network_type == c_const.NETWORK_TYPE_VLAN:
            if physical_network_set:
                if physical_network not in self.network_vlan_ranges:
                    msg = (_("unknown provider:physical_network %s"),
                           physical_network)
                    raise q_exc.InvalidInput(error_message=msg)
            elif 'default' in self.network_vlan_ranges:
                physical_network = 'default'
            else:
                msg = _("provider:physical_network required")
                raise q_exc.InvalidInput(error_message=msg)

        return (network_type, physical_network, segmentation_id)
Пример #20
0
    def _process_provider_create(self, context, attrs):
        network_type = attrs.get(provider.NETWORK_TYPE)
        physical_network = attrs.get(provider.PHYSICAL_NETWORK)
        segmentation_id = attrs.get(provider.SEGMENTATION_ID)

        network_type_set = attributes.is_attr_set(network_type)
        physical_network_set = attributes.is_attr_set(physical_network)
        segmentation_id_set = attributes.is_attr_set(segmentation_id)

        if not (network_type_set or physical_network_set or segmentation_id_set):
            return (None, None, None)

        if not network_type_set:
            msg = _("provider:network_type required")
            raise q_exc.InvalidInput(error_message=msg)
        elif network_type == constants.TYPE_FLAT:
            if segmentation_id_set:
                msg = _("provider:segmentation_id specified for flat network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                segmentation_id = constants.FLAT_VLAN_ID
        elif network_type == constants.TYPE_VLAN:
            if not segmentation_id_set:
                msg = _("provider:segmentation_id required")
                raise q_exc.InvalidInput(error_message=msg)
            if not utils.is_valid_vlan_tag(segmentation_id):
                msg = _("provider:segmentation_id out of range " "(%(min_id)s through %(max_id)s)") % {
                    "min_id": q_const.MIN_VLAN_TAG,
                    "max_id": q_const.MAX_VLAN_TAG,
                }
                raise q_exc.InvalidInput(error_message=msg)
        elif network_type == constants.TYPE_LOCAL:
            if physical_network_set:
                msg = _("provider:physical_network specified for local " "network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                physical_network = None
            if segmentation_id_set:
                msg = _("provider:segmentation_id specified for local " "network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                segmentation_id = constants.LOCAL_VLAN_ID
        else:
            msg = _("provider:network_type %s not supported") % network_type
            raise q_exc.InvalidInput(error_message=msg)

        if network_type in [constants.TYPE_VLAN, constants.TYPE_FLAT]:
            if physical_network_set:
                if physical_network not in self.network_vlan_ranges:
                    msg = _("Unknown provider:physical_network %s") % physical_network
                    raise q_exc.InvalidInput(error_message=msg)
            elif "default" in self.network_vlan_ranges:
                physical_network = "default"
            else:
                msg = _("provider:physical_network required")
                raise q_exc.InvalidInput(error_message=msg)

        return (network_type, physical_network, segmentation_id)
Пример #21
0
    def test_is_attr_set(self):
        data = attributes.ATTR_NOT_SPECIFIED
        self.assertIs(attributes.is_attr_set(data), False)

        data = None
        self.assertIs(attributes.is_attr_set(data), False)

        data = "I'm set"
        self.assertIs(attributes.is_attr_set(data), True)
Пример #22
0
    def create_port(self, context, port):
        # If PORTSECURITY is not the default value ATTR_NOT_SPECIFIED
        # then we pass the port to the policy engine. The reason why we don't
        # pass the value to the policy engine when the port is
        # ATTR_NOT_SPECIFIED is for the case where a port is created on a
        # shared network that is not owned by the tenant.
        port_data = port['port']

        with context.session.begin(subtransactions=True):
            # First we allocate port in neutron database
            neutron_db = super(NsxDvsV2, self).create_port(context, port)
            port_security = self._get_network_security_binding(
                context, neutron_db['network_id'])
            port_data[psec.PORTSECURITY] = port_security
            self._process_port_port_security_create(
                context, port_data, neutron_db)
            # Update fields obtained from neutron db (eg: MAC address)
            port["port"].update(neutron_db)
            has_ip = self._ip_on_port(neutron_db)

            # security group extension checks
            if has_ip:
                self._ensure_default_security_group_on_port(context, port)
            elif attr.is_attr_set(port_data.get(ext_sg.SECURITYGROUPS)):
                raise psec.PortSecurityAndIPRequiredForSecurityGroups()
            port_data[ext_sg.SECURITYGROUPS] = (
                self._get_security_groups_on_port(context, port))
            self._process_port_create_security_group(
                context, port_data, port_data[ext_sg.SECURITYGROUPS])
            self._process_portbindings_create_and_update(context,
                                                         port['port'],
                                                         port_data)

            # allowed address pair checks
            if attr.is_attr_set(port_data.get(addr_pair.ADDRESS_PAIRS)):
                if not port_security:
                    raise addr_pair.AddressPairAndPortSecurityRequired()
                else:
                    self._process_create_allowed_address_pairs(
                        context, neutron_db,
                        port_data[addr_pair.ADDRESS_PAIRS])
            else:
                # remove ATTR_NOT_SPECIFIED
                port_data[addr_pair.ADDRESS_PAIRS] = []

            LOG.debug("create_port completed on NSX for tenant "
                      "%(tenant_id)s: (%(id)s)", port_data)

            self._process_portbindings_create_and_update(context,
                                                         port['port'],
                                                         port_data)
        # DB Operation is complete, perform DVS operation
        port_data = port['port']

        self.handle_port_dhcp_access(context, port_data, action='create_port')
        return port_data
Пример #23
0
    def _process_port_binding(self, mech_context, attrs):
        binding = mech_context._binding
        port = mech_context.current
        self._update_port_dict_binding(port, binding)

        host = attrs and attrs.get(portbindings.HOST_ID)
        host_set = attributes.is_attr_set(host)

        vnic_type = attrs and attrs.get(portbindings.VNIC_TYPE)
        vnic_type_set = attributes.is_attr_set(vnic_type)

        # CLI can't send {}, so treat None as {}
        profile = attrs and attrs.get(portbindings.PROFILE)
        profile_set = profile is not attributes.ATTR_NOT_SPECIFIED
        if profile_set and not profile:
            profile = {}

        if binding.vif_type != portbindings.VIF_TYPE_UNBOUND:
            if (not host_set and not vnic_type_set and not profile_set and
                binding.segment and
                self.mechanism_manager.validate_port_binding(mech_context)):
                return False
            self.mechanism_manager.unbind_port(mech_context)
            self._update_port_dict_binding(port, binding)

        # Return True only if an agent notification is needed.
        # This will happen if a new host, vnic_type, or profile was specified
        # that differs from the current one. Note that host_set is True
        # even if the host is an empty string
        ret_value = ((host_set and binding.get('host') != host) or
                     (vnic_type_set and
                      binding.get('vnic_type') != vnic_type) or
                     (profile_set and self._get_profile(binding) != profile))

        if host_set:
            binding.host = host
            port[portbindings.HOST_ID] = host

        if vnic_type_set:
            binding.vnic_type = vnic_type
            port[portbindings.VNIC_TYPE] = vnic_type

        if profile_set:
            binding.profile = jsonutils.dumps(profile)
            if len(binding.profile) > models.BINDING_PROFILE_LEN:
                msg = _("binding:profile value too large")
                raise exc.InvalidInput(error_message=msg)
            port[portbindings.PROFILE] = profile

        # To try to [re]bind if host is non-empty.
        if binding.host:
            self.mechanism_manager.bind_port(mech_context)
            self._update_port_dict_binding(port, binding)

        return ret_value
Пример #24
0
    def validate_pools_with_subnetpool(self, subnet):
        """Verifies that allocation pools are set correctly

        Allocation pools can be set for specific subnet request only
        """
        has_allocpool = attributes.is_attr_set(subnet['allocation_pools'])
        is_any_subnetpool_request = not attributes.is_attr_set(subnet['cidr'])
        if is_any_subnetpool_request and has_allocpool:
            reason = _("allocation_pools allowed only "
                       "for specific subnet requests.")
            raise n_exc.BadRequest(resource='subnets', msg=reason)
Пример #25
0
 def _validate_ipv6_attributes(self, subnet, cur_subnet):
     if cur_subnet:
         self._validate_ipv6_update_dhcp(subnet, cur_subnet)
         return
     ra_mode_set = attributes.is_attr_set(subnet.get("ipv6_ra_mode"))
     address_mode_set = attributes.is_attr_set(subnet.get("ipv6_address_mode"))
     self._validate_ipv6_dhcp(ra_mode_set, address_mode_set, subnet["enable_dhcp"])
     if ra_mode_set and address_mode_set:
         self._validate_ipv6_combination(subnet["ipv6_ra_mode"], subnet["ipv6_address_mode"])
     if address_mode_set or ra_mode_set:
         self._validate_eui64_applicable(subnet)
 def network_matches_filters(self, network, filters):
     if not filters:
         return True
     if any(attributes.is_attr_set(network.get(attr))
            for attr in provider.ATTRIBUTES):
         segments = [self._get_provider_segment(network)]
     elif attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
         segments = self._get_attribute(network, mpnet.SEGMENTS)
     else:
         return True
     return any(self._match_segment(s, filters) for s in segments)
Пример #27
0
 def create_network(self, session, attrs):
     segmentation_id = attrs.get(provider.SEGMENTATION_ID)
     if attributes.is_attr_set(segmentation_id):
         physical_network = attrs.get(provider.PHYSICAL_NETWORK)
         if not attributes.is_attr_set(physical_network):
             msg = _("physical_network not provided")
             raise n_exc.InvalidInput(error_message=msg)
         self._db.reserve_specific_vlan(session, physical_network, segmentation_id)
     else:
         (physical_network, segmentation_id) = self._db.reserve_vlan(session)
         attrs[provider.SEGMENTATION_ID] = segmentation_id
         attrs[provider.PHYSICAL_NETWORK] = physical_network
Пример #28
0
    def _process_provider_create(self, context, attrs):
        network_type = attrs.get(provider.NETWORK_TYPE)
        physical_network = attrs.get(provider.PHYSICAL_NETWORK)
        segmentation_id = attrs.get(provider.SEGMENTATION_ID)

        network_type_set = attributes.is_attr_set(network_type)
        physical_network_set = attributes.is_attr_set(physical_network)
        segmentation_id_set = attributes.is_attr_set(segmentation_id)

        if not (network_type_set or physical_network_set or
                segmentation_id_set):
            return (None, None, None)

        if not network_type_set:
            msg = _("provider:network_type required")
            raise n_exc.InvalidInput(error_message=msg)
        elif network_type == svc_constants.TYPE_FLAT:
            if segmentation_id_set:
                msg = _("provider:segmentation_id specified for flat network")
                raise n_exc.InvalidInput(error_message=msg)
            else:
                segmentation_id = None
        elif network_type == svc_constants.TYPE_VLAN:
            if not segmentation_id_set:
                msg = _("provider:segmentation_id required")
                raise n_exc.InvalidInput(error_message=msg)
            if not utils.is_valid_vlan_tag(segmentation_id):
                msg = (_("provider:segmentation_id out of range "
                         "(%(min_id)s through %(max_id)s)") %
                       {'min_id': constants.MIN_VLAN_TAG,
                        'max_id': constants.MAX_VLAN_TAG})
                raise n_exc.InvalidInput(error_message=msg)
        elif network_type == svc_constants.TYPE_LOCAL:
            if physical_network_set:
                msg = _("provider:physical_network specified for local "
                        "network")
                raise n_exc.InvalidInput(error_message=msg)
            else:
                physical_network = None
            if segmentation_id_set:
                msg = _("provider:segmentation_id specified for local "
                        "network")
                raise n_exc.InvalidInput(error_message=msg)
            else:
                segmentation_id = None
        else:
            if not segmentation_id_set:
                segmentation_id = None
            if not physical_network_set:
                physical_network = None

        return network_type, physical_network, segmentation_id
Пример #29
0
    def create_network(self, session, attrs):
        network_type = attrs.get(provider.NETWORK_TYPE)
        segmentation_id = attrs.get(provider.SEGMENTATION_ID)
        if attributes.is_attr_set(segmentation_id):
            msg = _("segmentation_id specified " "for %s network") % network_type
            raise n_exc.InvalidInput(error_message=msg)
        attrs[provider.SEGMENTATION_ID] = None

        physical_network = attrs.get(provider.PHYSICAL_NETWORK)
        if attributes.is_attr_set(physical_network):
            msg = _("physical_network specified " "for %s network") % network_type
            raise n_exc.InvalidInput(error_message=msg)
        attrs[provider.PHYSICAL_NETWORK] = None
 def _process_provider_create(self, network):
     if any(attributes.is_attr_set(network.get(attr))
            for attr in provider.ATTRIBUTES):
         # Verify that multiprovider and provider attributes are not set
         # at the same time.
         if attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
             raise mpnet.SegmentsSetInConjunctionWithProviders()
         segment = self._get_provider_segment(network)
         return [self._process_provider_segment(segment)]
     elif attributes.is_attr_set(network.get(mpnet.SEGMENTS)):
         segments = [self._process_provider_segment(s)
                     for s in network[mpnet.SEGMENTS]]
         mpnet.check_duplicate_segments(segments, self.is_partial_segment)
         return segments
Пример #31
0
    def _process_provider_create(self, context, attrs):
        network_type = attrs.get(provider.NETWORK_TYPE)
        physical_network = attrs.get(provider.PHYSICAL_NETWORK)
        segmentation_id = attrs.get(provider.SEGMENTATION_ID)

        network_type_set = attributes.is_attr_set(network_type)
        physical_network_set = attributes.is_attr_set(physical_network)
        segmentation_id_set = attributes.is_attr_set(segmentation_id)

        if not (network_type_set or physical_network_set
                or segmentation_id_set):
            return (None, None, None)

        if not network_type_set:
            msg = _("provider:network_type required")
            raise q_exc.InvalidInput(error_message=msg)
        elif network_type == constants.TYPE_FLAT:
            if segmentation_id_set:
                msg = _("provider:segmentation_id specified for flat network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                segmentation_id = constants.FLAT_VLAN_ID
        elif network_type == constants.TYPE_VLAN:
            if not segmentation_id_set:
                msg = _("provider:segmentation_id required")
                raise q_exc.InvalidInput(error_message=msg)
            if not utils.is_valid_vlan_tag(segmentation_id):
                msg = (_("provider:segmentation_id out of range "
                         "(%(min_id)s through %(max_id)s)") % {
                             'min_id': q_const.MIN_VLAN_TAG,
                             'max_id': q_const.MAX_VLAN_TAG
                         })
                raise q_exc.InvalidInput(error_message=msg)
        elif network_type in constants.TUNNEL_NETWORK_TYPES:
            if not self.enable_tunneling:
                msg = _("%s networks are not enabled") % network_type
                raise q_exc.InvalidInput(error_message=msg)
            if physical_network_set:
                msg = _("provider:physical_network specified for %s "
                        "network") % network_type
                raise q_exc.InvalidInput(error_message=msg)
            else:
                physical_network = None
            if not segmentation_id_set:
                msg = _("provider:segmentation_id required")
                raise q_exc.InvalidInput(error_message=msg)
        elif network_type == constants.TYPE_LOCAL:
            if physical_network_set:
                msg = _("provider:physical_network specified for local "
                        "network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                physical_network = None
            if segmentation_id_set:
                msg = _("provider:segmentation_id specified for local "
                        "network")
                raise q_exc.InvalidInput(error_message=msg)
            else:
                segmentation_id = None
        else:
            msg = _("provider:network_type %s not supported") % network_type
            raise q_exc.InvalidInput(error_message=msg)

        if network_type in [constants.TYPE_VLAN, constants.TYPE_FLAT]:
            if physical_network_set:
                if physical_network not in self.network_vlan_ranges:
                    msg = _("Unknown provider:physical_network "
                            "%s") % physical_network
                    raise q_exc.InvalidInput(error_message=msg)
            elif 'default' in self.network_vlan_ranges:
                physical_network = 'default'
            else:
                msg = _("provider:physical_network required")
                raise q_exc.InvalidInput(error_message=msg)

        return (network_type, physical_network, segmentation_id)
Пример #32
0
    def _validate_subnet(self, context, s, cur_subnet=None):
        """Validate a subnet spec."""

        # This method will validate attributes which may change during
        # create_subnet() and update_subnet().
        # The method requires the subnet spec 's' has 'ip_version' field.
        # If 's' dict does not have 'ip_version' field in an API call
        # (e.g., update_subnet()), you need to set 'ip_version' field
        # before calling this method.

        ip_ver = s['ip_version']

        if attributes.is_attr_set(s.get('cidr')):
            self._validate_ip_version(ip_ver, s['cidr'], 'cidr')

        # TODO(watanabe.isao): After we found a way to avoid the re-sync
        # from the agent side, this restriction could be removed.
        if cur_subnet:
            dhcp_was_enabled = cur_subnet.enable_dhcp
        else:
            dhcp_was_enabled = False
        if s.get('enable_dhcp') and not dhcp_was_enabled:
            subnet_prefixlen = netaddr.IPNetwork(s['cidr']).prefixlen
            error_message = _("Subnet has a prefix length that is "
                              "incompatible with DHCP service enabled.")
            if ((ip_ver == 4 and subnet_prefixlen > 30)
                    or (ip_ver == 6 and subnet_prefixlen > 126)):
                raise n_exc.InvalidInput(error_message=error_message)
            else:
                # NOTE(watanabe.isao): The following restriction is necessary
                # only when updating subnet.
                if cur_subnet:
                    range_qry = context.session.query(
                        models_v2.IPAvailabilityRange).join(
                            models_v2.IPAllocationPool)
                    ip_range = range_qry.filter_by(subnet_id=s['id']).first()
                    if not ip_range:
                        raise n_exc.IpAddressGenerationFailure(
                            net_id=cur_subnet.network_id)

        if attributes.is_attr_set(s.get('gateway_ip')):
            self._validate_ip_version(ip_ver, s['gateway_ip'], 'gateway_ip')
            if (cfg.CONF.force_gateway_on_subnet
                    and not self._check_gateway_in_subnet(
                        s['cidr'], s['gateway_ip'])):
                error_message = _("Gateway is not valid on subnet")
                raise n_exc.InvalidInput(error_message=error_message)
            # Ensure the gateway IP is not assigned to any port
            # skip this check in case of create (s parameter won't have id)
            # NOTE(salv-orlando): There is slight chance of a race, when
            # a subnet-update and a router-interface-add operation are
            # executed concurrently
            if cur_subnet:
                alloc_qry = context.session.query(models_v2.IPAllocation)
                allocated = alloc_qry.filter_by(
                    ip_address=cur_subnet['gateway_ip'],
                    subnet_id=cur_subnet['id']).first()
                if allocated and allocated['port_id']:
                    raise n_exc.GatewayIpInUse(
                        ip_address=cur_subnet['gateway_ip'],
                        port_id=allocated['port_id'])

        if attributes.is_attr_set(s.get('dns_nameservers')):
            if len(s['dns_nameservers']) > cfg.CONF.max_dns_nameservers:
                raise n_exc.DNSNameServersExhausted(
                    subnet_id=s.get('id', _('new subnet')),
                    quota=cfg.CONF.max_dns_nameservers)
            for dns in s['dns_nameservers']:
                try:
                    netaddr.IPAddress(dns)
                except Exception:
                    raise n_exc.InvalidInput(
                        error_message=(_("Error parsing dns address %s") %
                                       dns))
                self._validate_ip_version(ip_ver, dns, 'dns_nameserver')

        if attributes.is_attr_set(s.get('host_routes')):
            if len(s['host_routes']) > cfg.CONF.max_subnet_host_routes:
                raise n_exc.HostRoutesExhausted(
                    subnet_id=s.get('id', _('new subnet')),
                    quota=cfg.CONF.max_subnet_host_routes)
            # check if the routes are all valid
            for rt in s['host_routes']:
                self._validate_host_route(rt, ip_ver)

        if ip_ver == 4:
            if attributes.is_attr_set(s.get('ipv6_ra_mode')):
                raise n_exc.InvalidInput(
                    error_message=(_("ipv6_ra_mode is not valid when "
                                     "ip_version is 4")))
            if attributes.is_attr_set(s.get('ipv6_address_mode')):
                raise n_exc.InvalidInput(
                    error_message=(_("ipv6_address_mode is not valid when "
                                     "ip_version is 4")))
        if ip_ver == 6:
            self._validate_ipv6_attributes(s, cur_subnet)
Пример #33
0
 def _is_ha(cls, router):
     ha = router.get('ha')
     if not attributes.is_attr_set(ha):
         ha = cfg.CONF.l3_ha
     return ha