def resource_list(self, context, filters=None, fields=None):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        ret_list = []
        # collect phase
        all_sgs = []
        if filters and 'tenant_id' in filters:
            project_ids = self._validate_project_ids(context,
                                                     filters['tenant_id'])
            for p_id in project_ids:
                project_sgs = SecurityGroupHandler(
                    self._vnc_lib).resource_list_by_project(p_id)

                all_sgs.append(project_sgs)
        else:  # no filters
            p_id = None
            if context and not context['is_admin']:
                p_id = self._project_id_neutron_to_vnc(
                    get_tenant_id(context))
            project_sgs = SecurityGroupHandler(
                self._vnc_lib).resource_list_by_project(p_id)

            all_sgs.append(project_sgs)

        # prune phase
        for project_sgs in all_sgs:
            for sg_obj in project_sgs:
                # TODO() implement same for name specified in filter
                sgr_info = self.security_group_rules_read(sg_obj,
                                                          fields=fields,
                                                          filters=filters)
                if sgr_info:
                    ret_list.extend(sgr_info)

        return ret_list
Пример #2
0
    def _prepare_res_handlers(self):
        contrail_extension_enabled = cfg.CONF.APISERVER.contrail_extensions
        apply_subnet_host_routes = cfg.CONF.APISERVER.apply_subnet_host_routes
        kwargs = {'contrail_extensions_enabled': contrail_extension_enabled,
                  'apply_subnet_host_routes': apply_subnet_host_routes}

        self._res_handlers['network'] = VNetworkHandler(
            self._vnc_lib, **kwargs)

        self._res_handlers['subnet'] = SubnetHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['port'] = VMInterfaceHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['router'] = LogicalRouterHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['floatingip'] = FloatingIpHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['security_group'] = SecurityGroupHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['security_group_rule'] = (
            SecurityGroupRuleHandler(self._vnc_lib, **kwargs))

        self._res_handlers['ipam'] = IPamHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['policy'] = PolicyHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['route_table'] = (
            RouteTableHandler(self._vnc_lib, **kwargs))
        self._res_handlers['svc'] = SvcInstanceHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['virtual_router'] = \
            VirtualRouterHandler(self._vnc_lib, **kwargs)
    def _create_vmi_obj(self, port_q, vn_obj):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        project_id = self._project_id_neutron_to_vnc(port_q['tenant_id'])
        try:
            proj_obj = self._project_read(proj_id=project_id)
        except vnc_exc.NoIdError:
            self._raise_contrail_exception('ProjectNotFound',
                                           projec_id=project_id,
                                           resource='port')
        id_perms = vnc_api.IdPermsType(enable=True)
        vmi_uuid = str(uuid.uuid4())
        if port_q.get('name'):
            vmi_name = port_q['name']
        else:
            vmi_name = vmi_uuid
        vmi_obj = vnc_api.VirtualMachineInterface(vmi_name,
                                                  proj_obj,
                                                  id_perms=id_perms)
        vmi_obj.uuid = vmi_uuid
        vmi_obj.set_virtual_network(vn_obj)
        vmi_obj.set_security_group_list([])
        if ('security_groups' not in port_q
                or port_q['security_groups'].__class__ is object):
            sg_obj = vnc_api.SecurityGroup("default", proj_obj)
            uid = SecurityGroupHandler(
                self._vnc_lib)._ensure_default_security_group_exists(
                    proj_obj.uuid)
            sg_obj.uuid = uid
            vmi_obj.add_security_group(sg_obj)

        return vmi_obj
    def _security_group_rule_delete(self, sg_obj, sg_rule):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        rules = sg_obj.get_security_group_entries()
        rules.get_policy_rule().remove(sg_rule)
        sg_obj.set_security_group_entries(rules)
        SecurityGroupHandler(self._vnc_lib).resource_update_obj(sg_obj)
        return
    def _security_group_rule_create(self, sg_id, sg_rule, project_id):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        sghandler = SecurityGroupHandler(self._vnc_lib)
        try:
            sg_vnc = sghandler.get_sg_obj(id=sg_id)
        except vnc_exc.NoIdError:
            self._raise_contrail_exception('SecurityGroupNotFound', id=sg_id,
                                           resource='security_group')

        if project_id and sg_vnc.parent_uuid != self._project_id_neutron_to_vnc(project_id):
            self._raise_contrail_exception('NotFound')
        rules = sg_vnc.get_security_group_entries()
        if rules is None:
            rules = vnc_api.PolicyEntriesType([sg_rule])
        else:
            rules.add_policy_rule(sg_rule)

        sg_vnc.set_security_group_entries(rules)
        try:
            sghandler.resource_update_obj(sg_vnc)
        except vnc_exc.PermissionDenied as e:
            self._raise_contrail_exception(
                'BadRequest',
                resource='security_group_rule', msg=str(e))
        except vnc_exc.BadRequest as e:
            self._raise_contrail_exception(
                'BadRequest',
                resource='security_group_rule', msg=str(e.content))
        except vnc_exc.RefsExistError as e:
            try:
                rule_uuid = str(e).split(':')[1].strip()
            except IndexError:
                rule_uuid = None
            self._raise_contrail_exception('SecurityGroupRuleExists',
                                           resource='security_group_rule',
                                           id=rule_uuid)
        return
    def _security_group_rule_find(self, sgr_id, project_uuid=None):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        if not project_uuid:
            dom_projects = self._project_list_domain(None)
        else:
            dom_projects = [{'uuid': project_uuid}]

        for project in dom_projects:
            proj_id = project['uuid']
            project_sgs = SecurityGroupHandler(
                self._vnc_lib).resource_list_by_project(proj_id)

            for sg_obj in project_sgs:
                sgr_entries = sg_obj.get_security_group_entries()
                if sgr_entries is None:
                    continue

                for sg_rule in sgr_entries.get_policy_rule():
                    if sg_rule.get_rule_uuid() == sgr_id:
                        return sg_obj, sg_rule

        return None, None
    def _security_group_rule_vnc_to_neutron(self, sg_id, sg_rule,
                                            sg_obj=None, fields=None):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        sgr_q_dict = {}
        if sg_id is None:
            return sgr_q_dict

        if not sg_obj:
            try:
                sg_obj = SecurityGroupHandler(
                    self._vnc_lib).get_sg_obj(id=sg_id)
            except vnc_exc.NoIdError:
                self._raise_contrail_exception(
                    'SecurityGroupNotFound',
                    id=sg_id, resource='security_group_rule')

        remote_cidr = None
        remote_sg_uuid = None
        saddr = sg_rule.get_src_addresses()[0]
        daddr = sg_rule.get_dst_addresses()[0]
        if saddr.get_security_group() == 'local':
            direction = 'egress'
            addr = daddr
        elif daddr.get_security_group() == 'local':
            direction = 'ingress'
            addr = saddr
        else:
            self._raise_contrail_exception(
                'SecurityGroupRuleNotFound',
                id=sg_rule.get_rule_uuid(), resource='security_group_rule')

        if addr.get_subnet():
            remote_cidr = '%s/%s' % (addr.get_subnet().get_ip_prefix(),
                                     addr.get_subnet().get_ip_prefix_len())
        elif addr.get_security_group():
            if addr.get_security_group() != 'any' and (
                    addr.get_security_group() != 'local'):
                remote_sg = addr.get_security_group()
                if remote_sg != ':'.join(sg_obj.get_fq_name()):
                    try:
                        remote_sg_uuid = self._vnc_lib.fq_name_to_id(
                            'security-group', remote_sg.split(':'))
                    except vnc_exc.NoIdError:
                        # Filter rule out as the remote security group does not
                        # exist anymore
                        return sgr_q_dict
                else:
                    remote_sg_uuid = sg_obj.uuid

        sgr_q_dict['id'] = sg_rule.get_rule_uuid()
        sgr_q_dict['tenant_id'] = self._project_id_vnc_to_neutron(
            sg_obj.parent_uuid)
        sgr_q_dict['project_id'] = sgr_q_dict['tenant_id']
        sgr_q_dict['security_group_id'] = sg_obj.uuid
        if hasattr(sg_rule, 'get_ethertype'):
            sgr_q_dict['ethertype'] = sg_rule.get_ethertype()
        else:
            sgr_q_dict['ethertype'] = 'IPv4'
        sgr_q_dict['direction'] = direction
        proto = sg_rule.get_protocol()
        sgr_q_dict['protocol'] = None if proto == 'any' else proto
        port_min = sg_rule.get_dst_ports()[0].get_start_port()
        if sgr_q_dict['protocol'] in (constants.PROTO_NAME_ICMP,
                                      str(constants.PROTO_NUM_ICMP)):
            sgr_q_dict['port_range_min'] = port_min
        else:
            sgr_q_dict['port_range_min'] = None if port_min == 0 else port_min
        port_max = (sg_rule.get_dst_ports()[0].get_end_port())
        sgr_q_dict['port_range_max'] = None if port_max == 65535 else port_max
        sgr_q_dict['remote_ip_prefix'] = remote_cidr
        sgr_q_dict['remote_group_id'] = remote_sg_uuid

        if fields:
            sgr_q_dict = self._filter_res_dict(sgr_q_dict, fields)
        return sgr_q_dict
    def _security_group_rule_neutron_to_vnc(self, sgr_q):
        from neutron_plugin_contrail.plugins.opencontrail.vnc_client.sg_res_handler import SecurityGroupHandler

        # default port values
        if sgr_q['protocol'] in (constants.PROTO_NAME_ICMP,
                                 str(constants.PROTO_NUM_ICMP)):
            port_min = None
            port_max = None
        else:
            port_min = 0
            port_max = 65535

        if sgr_q['port_range_min'] is not None:
            port_min = sgr_q['port_range_min']
        if sgr_q['port_range_max'] is not None:
            port_max = sgr_q['port_range_max']

        if sgr_q['remote_ip_prefix'] and sgr_q['remote_group_id']:
            self._raise_contrail_exception("BadRequest",
                                           msg="Can't set remote_ip_prefix with remote_group_id",
                                           resource="security_group_rule")

        endpt = [vnc_api.AddressType(security_group='any')]
        if sgr_q['remote_ip_prefix']:
            cidr = sgr_q['remote_ip_prefix'].split('/')
            pfx = cidr[0]
            pfx_len = int(cidr[1])
            endpt = [vnc_api.AddressType(
                subnet=vnc_api.SubnetType(pfx, pfx_len))]
        elif sgr_q['remote_group_id']:
            try:
                sg_obj = SecurityGroupHandler(
                    self._vnc_lib).get_sg_obj(id=sgr_q['remote_group_id'])
            except vnc_exc.NoIdError:
                self._raise_contrail_exception('SecurityGroupNotFound',
                                               id=sgr_q['remote_group_id'],
                                               resource='security_group_rule')

            if sgr_q.get('tenant_id') and (
                    sg_obj.parent_uuid != self._project_id_neutron_to_vnc(sgr_q['tenant_id'])):
                self._raise_contrail_exception("NotFound")

            endpt = [vnc_api.AddressType(
                security_group=sg_obj.get_fq_name_str())]

        if sgr_q['direction'] == 'ingress':
            _dir = '>'
            local = endpt
            remote = [vnc_api.AddressType(security_group='local')]
        else:
            _dir = '>'
            remote = endpt
            local = [vnc_api.AddressType(security_group='local')]

        if not sgr_q['protocol']:
            sgr_q['protocol'] = 'any'

        if not sgr_q['remote_ip_prefix'] and not sgr_q['remote_group_id']:
            if not sgr_q['ethertype']:
                sgr_q['ethertype'] = 'IPv4'

        sgr_uuid = str(uuid.uuid4()) if 'id' not in sgr_q else sgr_q['id']

        rule = vnc_api.PolicyRuleType(
            rule_uuid=sgr_uuid, direction=_dir,
            protocol=sgr_q['protocol'],
            src_addresses=local,
            src_ports=[vnc_api.PortType(0, 65535)],
            dst_addresses=remote,
            dst_ports=[vnc_api.PortType(port_min, port_max)],
            ethertype=sgr_q['ethertype'])
        return rule