Exemple #1
0
 def _validate_flow_classifier(self, context, fc_info):
     port_list = []
     logical_source_port = fc_info['logical_source_port']
     logical_destination_port = fc_info['logical_destination_port']
     if not logical_source_port or not logical_destination_port:
         msg = ("Nuage does not support port chain without"
                " logical-source-port and"
                " logical-destination-port.")
         raise nuage_exc.NuageBadRequest(msg=msg)
     src_prt_details = self._get_logical_port_details(context,
                                                      logical_source_port,
                                                      port_list, 'source')
     dst_prt_details = self._get_logical_port_details(
         context,
         logical_destination_port,
         port_list,
         'destination')
     subnet_ids = {}
     for port in port_list:
         if subnet_ids:
             subnet_ids.add(port['fixed_ips'][0]['subnet_id'])
         else:
             subnet_ids = {port['fixed_ips'][0]['subnet_id']}
     if len(subnet_ids) != 1:
         msg = ('Nuage only supports logical ports'
                ' belonging to one subnet.')
         raise nuage_exc.NuageBadRequest(msg=msg)
     return src_prt_details, dst_prt_details
def fip_value_validator(fip_value, attribute, units='mbps'):
    if fip_value is None:
        msg = (_("Missing value for %s") % attribute)
        raise nuage_exc.NuageBadRequest(msg=msg)
    if isinstance(fip_value, bool):
        return send_fip_rate_limit_info(attribute)
    try:
        fip_value = float(fip_value)
        if units == 'kbps' and int(fip_value) != fip_value:
            msg = (_('%s value cannot be in fraction') % attribute)
            raise nuage_exc.NuageBadRequest(msg=msg)
        else:
            fip_value = int(fip_value)
    except (ValueError, TypeError):
        return send_fip_rate_limit_info(attribute)

    if fip_value < -1:
        return send_fip_rate_limit_info(attribute)

    if fip_value > constants.MAX_VSD_INTEGER:
        msg = (_("%(attr)s cannot be > %(max)s") % {
            'attr': attribute,
            'max': constants.MAX_VSD_INTEGER
        })
        raise nuage_exc.NuageBadRequest(msg=msg)
Exemple #3
0
    def get_nuage_redirect_target_rules(self, context, filters=None,
                                        fields=None):
        params = {}
        resource_id = None
        if filters.get('subnet'):
            subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
                context.session, filters['subnet'][0])
            if subnet_mapping:
                if self._is_l3(subnet_mapping):
                    message = ("Subnet %s doesn't have mapping l2domain on "
                               "VSD " % filters['subnet'][0])
                    raise nuage_exc.NuageBadRequest(msg=message)
                params['subnet'] = filters.get('subnet')[0]
                params['subnet_mapping'] = subnet_mapping
            else:
                message = ("Subnet %s doesn't have mapping l2domain on "
                           "VSD " % filters['subnet'][0])
                raise nuage_exc.NuageBadRequest(msg=message)
        elif filters.get('router'):
            params['router'] = filters.get('router')[0]
        elif filters.get('id'):
            params['id'] = filters.get('id')[0]
            resource_id = params['id']

        try:
            rtarget_rules = self.vsdclient.get_nuage_redirect_target_rules(
                params)
        except Exception:
            raise nuage_exc.NuageNotFound(
                resource='nuage-redirect-target-rule',
                resource_id=resource_id)

        return [self._make_redirect_target_rule_dict(
            rtarget_rule, context, fields) for rtarget_rule in rtarget_rules]
 def _validate_port_request_attributes(self, current, original=None):
     unsupported_attributes = ['extra_dhcp_opts']
     no_update_attributes = ['admin_state_up']
     for attribute in unsupported_attributes:
         if current.get(attribute):
             msg = _("Unsupported attribute %(attr)s can't be set for "
                     "ports which have one of the following vnic "
                     "types %(vnic)s")
             raise exceptions.NuageBadRequest(
                 msg=msg % {
                     'attr': attribute,
                     'vnic': self._supported_vnic_types()
                 })
     if original is None:
         return
     for attribute in no_update_attributes:
         if current[attribute] != original[attribute]:
             msg = _("No update support for attribute %(attr)s for "
                     "ports which have one of the following vnic "
                     "types %(vnic)s")
             raise exceptions.NuageBadRequest(
                 msg=msg % {
                     'attr': attribute,
                     'vnic': self._supported_vnic_types()
                 })
    def get_nuage_external_security_group_rules(self, context, filters=None,
                                                fields=None):
        params = {}
        resource_id = None
        if filters.get('subnet'):
            subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
                context.session, filters['subnet'][0])
            if subnet_mapping:
                if self._is_l3(subnet_mapping):
                    message = ("Subnet %s doesn't have mapping l2domain on "
                               "VSD " % filters['subnet'][0])
                    raise nuage_exc.NuageBadRequest(msg=message)
                params['subnet'] = filters.get('subnet')[0]
            else:
                message = ("Subnet %s doesn't have mapping l2domain on "
                           "VSD " % filters['subnet'][0])
                raise nuage_exc.NuageBadRequest(msg=message)
        elif filters.get('router'):
            params['router'] = filters.get('router')[0]
        elif filters.get('external_group'):
            params['external_group'] = filters.get('external_group')[0]
            resource_id = params['external_group']
        try:
            ext_rules = self.vsdclient.get_nuage_external_sg_rules(
                params)
        except Exception:
            raise nuage_exc.NuageNotFound(
                resource='nuage-external-security-group-rule',
                resource_id=resource_id)

        return [self._make_external_security_group_rule_dict(ext_rule, context,
                                                             fields) for
                ext_rule in ext_rules]
    def _validate_security_groups(self, context):
        port = context.current
        db_context = context._plugin_context
        subnet_id = port['fixed_ips'][0]['subnet_id']
        sg_ids = port[ext_sg.SECURITYGROUPS]
        if not sg_ids:
            return

        subnet_mapping = nuagedb.get_subnet_l2dom_by_id(db_context.session,
                                                        subnet_id)
        if self._is_vsd_mgd(subnet_mapping):
            return

        normal_ports = nuagedb.get_port_bindings_for_sg(
            db_context.session,
            sg_ids,
            [portbindings.VNIC_NORMAL],
            bound_only=True)
        if len(normal_ports) > 0:
            msg = ("Security Groups for baremetal and normal ports "
                   "are mutualy exclusive")
            raise exceptions.NuageBadRequest(msg=msg)

        sg_rules = self.core_plugin.get_security_group_rules(
            db_context,
            {'security_group_id': sg_ids})
        bad_rule = next((rule for rule in sg_rules if rule['remote_group_id']),
                        None)
        if bad_rule:
            msg = ("Security Groups for baremetal ports can't have "
                   "rules with remote-group-id")
            raise exceptions.NuageBadRequest(msg=msg)
    def create_project_net_partition_mapping(self, context,
                                             project_net_partition_mapping):
        session = context.session
        p2n = project_net_partition_mapping['project_net_partition_mapping']
        project = p2n['project']
        net_partition_id = p2n['net_partition_id']

        err = validators.validate_uuid(project)
        if err:
            raise nuage_exc.NuageBadRequest(resource='net_partition', msg=err)
        # Validate netpartition
        netpart = nuagedb.get_net_partition_by_id(session, net_partition_id)
        if not netpart:
            msg = _('Net partition {} is not a valid netpartition '
                    'ID.').format(net_partition_id)
            raise nuage_exc.NuageBadRequest(
                resource='project_net_partition_mapping', msg=msg)

        with session.begin(subtransactions=True):
            existing_mapping = nuagedb.get_project_net_partition_mapping(
                session, project)
            if existing_mapping:
                session.delete(existing_mapping)
            mapping = nuagedb.add_project_net_partition_mapping(
                session, net_partition_id, project)
        return self._make_project_net_partition_mapping(context, mapping)
    def get_nuage_gateway_vlans(self, context, filters=None, fields=None):
        if not filters:
            # No gateway or gatewayport specified by user
            if context.is_admin:
                msg = (_('--gatewayport or --gateway and --gatewayport option '
                         'is required'))
                raise nuage_exc.NuageBadRequest(msg=msg)

            fetch_tenant = context.tenant_id
        else:
            if context.is_admin:
                if 'gateway' in filters and 'gatewayport' not in filters:
                    msg = (_('--gateway and --gatewayport option '
                             'should be provided'))
                    raise nuage_exc.NuageBadRequest(msg=msg)
            else:
                if 'gateway' in filters or 'gatewayport' in filters:
                    msg = (_('--gateway or --gatewayport option not '
                             'supported'))
                    raise nuage_exc.NuageBadRequest(msg=msg)

            user_tenant = filters.get('tenant')
            fetch_tenant = self._check_for_permissions(context, user_tenant)

        def_netpart = cfg.CONF.RESTPROXY.default_net_partition_name
        netpart = nuagedb.get_default_net_partition(context, def_netpart)
        resp = self.vsdclient.get_gateway_port_vlans(fetch_tenant,
                                                     netpart['id'],
                                                     filters=filters)
        if resp:
            return [self._make_vlan_dict(
                vlan, fields=fields, context=context) for vlan in resp]
        else:
            return []
def validate_switchports(vsdclient, tenant_id, switchports):
    vsdports = set()
    vsd_port = None
    if not len(switchports):
        return None
    for switchport in switchports:
        filters = {'system_id': [switchport.get('switch_info')]}
        gws = vsdclient.get_gateways(tenant_id, filters)
        if len(gws) == 0:
            msg = (_("No gateway found: %s") % filters['system_id'][0])
            raise exceptions.NuageBadRequest(msg=msg)
        port_mnemonic = _convert_ifindex_to_ifname(switchport.get('port_id'))
        filters = {'gateway': [gws[0]['gw_id']], 'name': [port_mnemonic]}
        gw_ports = vsdclient.get_gateway_ports(tenant_id, filters)
        if len(gw_ports) == 0:
            msg = (_("No gateway port found: %s") % filters['name'][0])
            raise exceptions.NuageBadRequest(msg=msg)
        port = gw_ports[0]
        if port.get('gw_redundant_port_id') is not None:
            port_id = port.get('gw_redundant_port_id')
            redundant = True
        else:
            port_id = port.get('gw_port_id')
            redundant = False
        vsd_port = {
            'port_id': port_id,
            'personality': gws[0]['gw_type'],
            'redundant': redundant
        }
        vsdports.add(port_id)
    if len(vsdports) > 1:
        msg = (_("Not all switchports belong to the same redundancy Group"))
        raise exceptions.NuageBadRequest(msg=msg)
    return vsd_port
Exemple #10
0
    def create_nuage_gateway_vport(self, context, nuage_gateway_vport):
        vport = nuage_gateway_vport['nuage_gateway_vport']
        subnet_id = vport.get('subnet')
        port_id = vport.get('port')
        params = {
            'gatewayinterface': vport['gatewayvlan'],
            'tenant': vport.get('tenant')
        }

        if subnet_id:
            params['subnet'] = self.core_plugin.get_subnet(context, subnet_id)

        if port_id:
            p = self.core_plugin.get_port(context, port_id)
            if p.get('fixed_ips'):
                subnet_id = p['fixed_ips'][0]['subnet_id']
                subnet = self.core_plugin.get_subnet(context, subnet_id)
                params['enable_dhcp'] = subnet.get('enable_dhcp')
            params['port'] = p

        subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
            context.session, subnet_id)
        if subnet_mapping:
            params['np_id'] = subnet_mapping['net_partition_id']
            params['nuage_managed_subnet'] = (
                subnet_mapping['nuage_managed_subnet'])
        else:
            msg = 'No neutron subnet to nuage subnet mapping found'
            raise nuage_exc.NuageBadRequest(msg=msg)

        try:
            vsd_subnet = self.vsdclient.get_nuage_subnet_by_id(subnet_mapping)
            params['vsd_subnet'] = vsd_subnet
            resp = self.vsdclient.create_gateway_vport(context.tenant_id,
                                                       params)
            vport = resp['vport']
        except Exception as ex:
            if hasattr(ex, 'code'):
                if ex.code == constants.RES_CONFLICT:
                    # gridinv - do not map resource in conflict to 500
                    raise nuage_exc.NuageBadRequest(msg=ex.message)
            raise
        if port_id and not subnet_mapping['nuage_managed_subnet']:
            port = params['port']
            self.l3_plugin._check_floatingip_update(
                context,
                port,
                vport_type=constants.HOST_VPORT,
                vport_id=vport['ID'])
        resp_dict = {
            'vport_id': resp['vport']['ID'],
            'vport_type': resp['vport']['type'],
            'vport_name': resp['vport']['name'],
            'interface': resp['interface']['ID'],
            'vport_gw_type': resp['vport_gw_type'],
            'subnet_id': subnet_id
        }
        if port_id:
            resp_dict['port_id'] = port_id
        return self._make_vport_dict(resp_dict, context=context)
 def _update_extra_dhcp_options(self, categorised_dhcp_opts, ip_version,
                                subnet_mapping, port_id, current_owner,
                                old_dhcp_opts, vport):
     if not subnet_mapping:
         # For preventing updating of a port on External Network
         msg = ("Cannot Update a port that does not have corresponding"
                " Vport on Nuage")
         raise nuage_exc.NuageBadRequest(msg=msg)
     if not vport:
         if (subnet_mapping['nuage_l2dom_tmplt_id']
                 and current_owner == constants.DEVICE_OWNER_DHCP_NUAGE):
             msg = ("Cannot set DHCP options for a port owned by Nuage, "
                    "which was created for internal use only.")
             raise nuage_exc.NuageBadRequest(msg=msg)
         else:
             msg = ("Could not find corresponding Vport for the specified"
                    " Neutron Port-ID: " + port_id)
             raise nuage_exc.NuageBadRequest(msg=msg)
     try:
         created_rollback_opts = self._create_update_extra_dhcp_options(
             categorised_dhcp_opts['new'], vport, port_id, False)
     except Exception as e:
         LOG.error(_("Port Update failed due to: {}").format(e))
         raise
     try:
         # Delete
         delete_rollback = self._delete_extra_dhcp_options(
             categorised_dhcp_opts['delete'], vport, port_id)
         # Update
         update_rollback = self._create_update_extra_dhcp_options(
             categorised_dhcp_opts['update'], vport, port_id, True)
         if "error" in update_rollback:
             update_rollback.remove("error")
             e = update_rollback.pop(-1)
             include_rollback_opt = ([
                 categorised_dhcp_opts['update'][i]['opt_name']
                 for i in range(len(update_rollback))
             ] + [
                 categorised_dhcp_opts['delete'][i]['opt_name']
                 for i in range(len(delete_rollback))
             ])
             for dhcp_opt in old_dhcp_opts:
                 if dhcp_opt['opt_name'] not in include_rollback_opt:
                     old_dhcp_opts.remove(dhcp_opt)
             raise e
     except Exception as e:
         # Roll back create
         for rollback_opt in created_rollback_opts:
             self.vsdclient.delete_vport_dhcp_option(
                 rollback_opt[3][0]['ID'], ip_version, True)
         # Roll back update & delete
         self._create_update_extra_dhcp_options(old_dhcp_opts, vport,
                                                port_id, True)
         LOG.error(_("Port Update failed due to: {}").format(e))
         raise e
 def _build_dhcp_option_error_message(dhcp_option, ip_version, e):
     for name, number in six.iteritems(
             constants.DHCP_OPTION_NAME_TO_NUMBER[ip_version]):
         if number == dhcp_option:
             if hasattr(e, 'msg'):
                 error = "For DHCP option " + name + ", " + e.msg
                 return nuage_exc.NuageBadRequest(msg=error)
             else:
                 error = ("Error encountered while processing option value"
                          " of {} due to: {}".format(name, e))
                 return nuage_exc.NuageBadRequest(msg=error)
Exemple #13
0
    def get_nuage_external_security_groups(self,
                                           context,
                                           filters=None,
                                           fields=None):
        # get all redirect targets
        domain_type = None
        domain_id = None
        vsd_filters = {'external': 'true'}
        if filters.get('subnet'):
            subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
                context.session, filters['subnet'][0])
            if subnet_mapping:
                if self._is_l3(subnet_mapping):
                    message = ("Subnet %s doesn't have mapping l2domain on "
                               "VSD " % filters['subnet'][0])
                    raise nuage_exc.NuageBadRequest(msg=message)
                domain_type = vsd_constants.L2DOMAIN
                domain_id = subnet_mapping['nuage_subnet_id']
            else:
                message = ("Subnet %s doesn't have mapping l2domain on "
                           "VSD " % filters['subnet'][0])
                raise nuage_exc.NuageBadRequest(msg=message)
        elif filters.get('router'):
            router_id = filters.get('router')[0]
            nuage_router = self.vsdclient.get_l3domain_by_external_id(
                router_id)
            if nuage_router:
                domain_type = vsd_constants.DOMAIN
                domain_id = nuage_router['ID']
            else:
                msg = _("VSD domain not found for router %s") % router_id
                raise n_exc.BadRequest(
                    resource='nuage_external_security_group', msg=msg)
        elif filters.get('id'):
            return self.get_nuage_external_security_group(
                context,
                filters.get('id')[0])
        elif filters.get('name'):
            vsd_filters['name'] = filters.get('name')[0]

        try:
            ext_sgs = self.vsdclient.get_policygroups(parent_type=domain_type,
                                                      parent_id=domain_id,
                                                      **vsd_filters)
        except Exception:
            raise nuage_exc.NuageNotFound(
                resource='nuage-external-security-group')
        return [
            self._make_external_security_group_dict(sg, context, fields)
            for sg in ext_sgs
        ]
Exemple #14
0
    def create_nuage_gateway_vport(self, context, nuage_gateway_vport):
        vport = nuage_gateway_vport['nuage_gateway_vport']
        subnet_id = vport.get('subnet')
        port_id = vport.get('port')
        params = {
            'gatewayinterface': vport['gatewayvlan'],
            'tenant': vport.get('tenant')
        }

        if subnet_id:
            params['subnet'] = self.get_subnet(context, subnet_id)

        if port_id:
            p = self.get_port(context, port_id)
            if p.get('fixed_ips'):
                subnet_id = p['fixed_ips'][0]['subnet_id']
                subnet = self.get_subnet(context, subnet_id)
                params['enable_dhcp'] = subnet.get('enable_dhcp')
            params['port'] = p

        subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
            context.session, subnet_id)
        if subnet_mapping:
            params['nuage_subnet_id'] = subnet_mapping['nuage_subnet_id']
            params['np_id'] = subnet_mapping['net_partition_id']
            params['nuage_managed_subnet'] = (
                subnet_mapping['nuage_managed_subnet'])
        else:
            msg = 'No neutron subnet to nuage subnet mapping found'
            raise nuage_exc.NuageBadRequest(msg=msg)

        try:
            resp = self.nuageclient.create_gateway_vport(
                context.tenant_id, params)
        except Exception as ex:
            if ex.code == constants.RES_CONFLICT:
                # gridinv - do not map resource in conflict to 500
                raise nuage_exc.NuageBadRequest(msg=ex.message)
            raise
        if port_id and not subnet_mapping['nuage_managed_subnet']:
            port = params['port']
            if resp['vport_gw_type'] == constants.SOFTWARE:
                self._delete_port_security_group_bindings(context, port['id'])
                self._process_port_create_security_group(
                    context, port, port[ext_sg.SECURITYGROUPS])
                LOG.debug("Created security group for port %s", port['id'])
            self._check_floatingip_update(context,
                                          port,
                                          vport_type=constants.HOST_VPORT,
                                          vport_id=resp['vport_id'])
        return self._make_vport_dict(resp, context=context)
def fip_rate_limit_validator(rate_limit, attribute):
    if rate_limit is None:
        return
    msg = _("'{}' should be an integer number between 0 and {}, "
            "-1 for unlimited or 'default' for "
            "the configured default value.").format(attribute,
                                                    constants.MAX_VSD_INTEGER)
    try:
        rate_limit = float(rate_limit)
    except (ValueError, TypeError):
        raise nuage_exc.NuageBadRequest(msg=msg)

    if not is_valid_rate_limit(rate_limit):
        raise nuage_exc.NuageBadRequest(msg=msg)
Exemple #16
0
 def _validate_switchport(self, context, switchport_mapping):
     filters = {'system_id': [switchport_mapping['switch_id']]}
     gws = self.vsdclient.get_gateways(context.tenant_id, filters)
     if len(gws) == 0:
         msg = (_("No gateway found %s") % filters['system_id'][0])
         raise nuage_exc.NuageBadRequest(msg=msg)
     filters = {
         'gateway': [gws[0]['gw_id']],
         'name': [switchport_mapping['port_id']]
     }
     gw_ports = self.vsdclient.get_gateway_ports(context.tenant_id, filters)
     if len(gw_ports) == 0:
         msg = (_("No gateway port found %s") % filters['name'][0])
         raise nuage_exc.NuageBadRequest(msg=msg)
     return gw_ports[0].get('gw_port_id'), gws[0]['gw_redundant']
Exemple #17
0
 def osfilters_to_vsdfilters(self, filters):
     if not all(x in self.vsd_filterables for x in filters or []):
         msg = (_("Only %s are filterable fields") %
                (self.vsd_filterables + self.extra_filters))
         raise exceptions.NuageBadRequest(msg=msg)
     return nuage_utils.filters_to_vsd_filters(self.vsd_filterables,
                                               filters, self.os_to_vsd)
Exemple #18
0
 def validate_policy_group(self, policy_group_id):
     policy_group = self.vsdclient.get_nuage_policy_group(policy_group_id,
                                                          required=True)
     if policy_group['externalID']:
         msg = _("Policy group %s has externalID, it can't be used with "
                 "this API.") % policy_group['ID']
         raise exceptions.NuageBadRequest(msg=msg)
Exemple #19
0
    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()
        if has_subnet_id:
            subnet = self.core_plugin.get_subnet(context,
                                                 redirect_target['subnet_id'])
            if subnet:
                redirect_target['external_id'] = \
                    cms_id_helper.get_vsd_external_id(subnet['network_id'])
        try:
            nuage_redirect_target = self.vsdclient\
                .create_nuage_redirect_target(
                    redirect_target,
                    l2dom_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
        return self._make_redirect_target_dict(nuage_redirect_target,
                                               context=context)
Exemple #20
0
    def _process_port_security_group(self, context, port, vport, sg_ids,
                                     vsd_subnet):
        if len(sg_ids) > 6:
            msg = (_("Exceeds maximum num of security groups on a port "
                     "supported on nuage VSP"))
            raise nuage_exc.NuageBadRequest(msg=msg)

        if not port.get('fixed_ips'):
            return

        successful = False
        attempt = 1
        max_attempts = 3
        while not successful:
            try:
                policygroup_ids = []
                for sg_id in sg_ids:
                    vsd_policygroup = self._find_or_create_policygroup(
                        context, sg_id, vsd_subnet)
                    policygroup_ids.append(vsd_policygroup['ID'])

                self.vsdclient.update_vport_policygroups(
                    vport['ID'], policygroup_ids)
                successful = True
            except restproxy.RESTProxyError as e:
                msg = e.msg.lower()
                if (e.code not in (404, 409) and 'policygroup' not in msg
                        and 'policy group' not in msg):
                    raise
                elif attempt < max_attempts:
                    attempt += 1
                else:
                    LOG.debug("Retry failed %s times.", max_attempts)
                    raise
Exemple #21
0
    def get_nuage_gateway_vports(self, context, filters=None, fields=None):
        user_tenant = filters.get('tenant')
        fetch_tenant = self._check_for_permissions(context, user_tenant)

        def_netpart = cfg.CONF.RESTPROXY.default_net_partition_name
        netpart = nuagedb.get_default_net_partition(context, def_netpart)

        subnet_id = filters['subnet'][0]
        subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
            context.session, subnet_id)
        if subnet_mapping:
            filters['nuage_subnet_id'] = [subnet_mapping['nuage_subnet_id']]
        else:
            msg = 'No neutron subnet to nuage subnet mapping found'
            raise nuage_exc.NuageBadRequest(msg=msg)

        resp = self.nuageclient.get_gateway_vports(fetch_tenant, netpart['id'],
                                                   filters)
        if resp:
            return [
                self._make_vport_dict(vport, fields=fields, context=context)
                for vport in resp
            ]
        else:
            return []
Exemple #22
0
def require(result, resource, id):
    if result:
        return
    try:
        raise result.exception
    except Exception:
        raise exceptions.NuageBadRequest(msg="Can't find %s '%s'" %
                                         (resource, id))
 def _build_dhcp_option_error_message(self, dhcpoption, e):
     for name, number in constants.DHCP_OPTION_NAME_TO_NUMBER.iteritems():
         if number == dhcpoption:
             if isinstance(e, n_exc.InvalidInput):
                 error = ("Neutron Error: DHCP Option %s that is being set"
                          " for the first time cannot be mentioned more"
                          " than once") % name
                 e.message = error
                 e.msg = error
                 return e
             elif hasattr(e, 'msg'):
                 error = "For DHCP option " + name + ", " + e.msg
                 return nuage_exc.NuageBadRequest(msg=error)
             else:
                 error = ("Error encountered while processing option value"
                          " of " + name + " due to: " + e.message)
                 return nuage_exc.NuageBadRequest(msg=error)
 def delete_project_net_partition_mapping(self, context, project_id):
     session = context.session
     err = validators.validate_uuid(project_id)
     if err:
         raise nuage_exc.NuageBadRequest(
             resource='project_net_partition_mapping', msg=err)
     with session.begin(subtransactions=True):
         existing_mapping = nuagedb.get_project_net_partition_mapping(
             session, project_id)
         if existing_mapping:
             session.delete(existing_mapping)
         else:
             msg = _('Project {} does not currently '
                     'have a default net-partition associated.').format(
                         project_id)
             raise nuage_exc.NuageBadRequest(
                 resource='project_net_partition_mapping', msg=msg)
Exemple #25
0
    def _validate_create_redirect_target_vip(self, context, redirect_target,
                                             subnet_mapping, vip):
        # VIP not allowed if redudancyEnabled is False
        if redirect_target.get('redundancy_enabled') == "False":
            if redirect_target.get('virtual_ip_address'):
                msg = (_("VIP can be addded to a redirect target only "
                         "when redundancyEnabled is True"))
                raise nuage_exc.NuageBadRequest(msg=msg)

        # VIP should be in the same subnet as redirect_target['subnet_id']
        if vip:
            subnet = self.core_plugin.get_subnet(context,
                                                 subnet_mapping['subnet_id'])
            if not ipam_utils.check_subnet_ip(subnet['cidr'], vip):
                msg = ("VIP should be in the same subnet as subnet %s " %
                       subnet_mapping['subnet_id'])
                raise nuage_exc.NuageBadRequest(msg=msg)
 def _translate_dhcp_option(self, dhcp_option):
     if dhcp_option['opt_name'] in constants.DHCP_OPTION_NAME_TO_NUMBER:
         dhcp_option['opt_name'] = (constants.DHCP_OPTION_NAME_TO_NUMBER
                                    [dhcp_option['opt_name']])
         dhcp_option['opt_value'] = dhcp_option['opt_value'].split(";")
     else:
         msg = _("There is no DHCP option available with the "
                 "opt_ name: %s ") % dhcp_option['opt_name']
         raise nuage_exc.NuageBadRequest(msg=msg)
    def _validate_create_subnet(self, db_context, network, prefixlen, subnet,
                                vsd_managed, l2bridge):
        network_subnets = self.core_plugin.get_subnets(
            db_context, filters={'network_id': [subnet['network_id']]})
        if vsd_managed:
            self._validate_create_vsd_managed_subnet(network, subnet)
        else:
            self._validate_create_openstack_managed_subnet(
                db_context, subnet, network_subnets)
        subnet_ids = [s['id'] for s in network_subnets]
        subnet_mappings = nuagedb.get_subnet_l2doms_by_subnet_ids(
            db_context.session, subnet_ids)
        if len(
                set([vsd_managed] +
                    [m['nuage_managed_subnet'] for m in subnet_mappings])) > 1:
            msg = _("Can't mix openstack and vsd managed subnets under 1 "
                    "network.")
            raise exceptions.NuageBadRequest(resource='subnet', msg=msg)

        ipv4s = len([s for s in network_subnets if self._is_ipv4(s)])
        ipv6s = len([s for s in network_subnets if self._is_ipv6(s)])

        if ipv4s > 1 or ipv6s > 1:
            msg = _("HWVTEP driver only supports single subnet networks "
                    "or dualstack networks")
            raise exceptions.NuageBadRequest(msg=msg)

        # nuage_l2bridge tests
        if l2bridge:
            # For l2bridges, certain parameters need to be equal for all
            # bridged subnets, as they are reflected on VSD.
            bridged_subnets = nuagedb.get_subnets_for_nuage_l2bridge(
                db_context.session, l2bridge['id'])
            # Make subnet dict to include extensions
            ipv_bridged = [
                self.core_plugin._make_subnet_dict(s) for s in bridged_subnets
                if s['id'] != subnet['id']
                and s['ip_version'] == subnet['ip_version']
            ]
            if not ipv_bridged:
                return
            for param in p_const.L2BRIDGE_SUBNET_EQUAL_ATTRIBUTES:
                self._validate_l2bridge_added_subnet_parameter(
                    ipv_bridged[0], subnet, param, l2bridge)
Exemple #28
0
    def _validate_port_redirect_target(self, context, port, rtargets):
        if not is_attr_set(rtargets):
            return
        if len(rtargets) > 1:
            msg = (_("Multiple redirect targets on a port not supported "))
            raise nuage_exc.NuageBadRequest(msg=msg)
        subnet_mapping = nuagedb.get_subnet_l2dom_by_id(
            context.session, port['fixed_ips'][0]['subnet_id'])
        nuage_rtargets_ids = []
        for rtarget in rtargets:
            uuid_match = re.match(lib_constants.UUID_PATTERN, rtarget)
            if not uuid_match:
                nuage_rtarget = self._resource_finder(context, 'port',
                                                      'nuage_redirect_target',
                                                      rtarget)
                nuage_rtarget_id = nuage_rtarget['id']
                nuage_rtargets_ids.append(nuage_rtarget_id)
            else:
                nuage_rtarget_id = rtarget
                nuage_rtargets_ids.append(rtarget)
            # validate rtarget is in the same subnet as port
            rtarget_resp = self.vsdclient.get_nuage_redirect_target(
                nuage_rtarget_id)
            if not rtarget_resp:
                msg = (_("Redirect target %s does not exist on VSD ") %
                       nuage_rtarget_id)
                raise nuage_exc.NuageBadRequest(msg=msg)
            parent_type = rtarget_resp['parentType']
            parent = rtarget_resp['parentID']
            validate_params = {
                'parent': parent,
                'parent_type': parent_type,
                'nuage_subnet_id': subnet_mapping['nuage_subnet_id']
            }
            if subnet_mapping and (
                    not self.vsdclient.validate_port_create_redirect_target(
                        validate_params)):
                msg = ("Redirect Target belongs to subnet %s that is "
                       "different from port subnet %s" %
                       (subnet_mapping['subnet_id'],
                        port['fixed_ips'][0]['subnet_id']))
                raise nuage_exc.NuageBadRequest(msg=msg)

        return nuage_rtargets_ids
Exemple #29
0
 def wrapped(*args, **kwargs):
     try:
         return fn(*args, **kwargs)
     except RESTProxyError as e:
         # raise nuage_exc.NuageBadRequest(msg=ERROR_DICT.get(
         #     str(e.vsd_code), e.message)), None, sys.exc_info()[2]
         e = nuage_exc.NuageBadRequest(
             msg=ERROR_DICT.get(str(e.vsd_code), e.message))
         e.__traceback__ = sys.exc_info()[2]
         raise e
 def _validate_no_transparent_network(self, context, trunk_port):
     network = self.core_plugin.get_network(context,
                                            trunk_port.get('network_id'))
     is_vlan_transparant = (network.get('vlan_transparent')
                            if network is not None else False)
     if is_vlan_transparant:
         msg = ("Network {} is vlan_transparent. It is not"
                "allowed to create a trunk on a "
                "vlan_transparent network").format(network['id'])
         raise nuage_exc.NuageBadRequest(msg=msg)