示例#1
0
    def resource_list(self, context, filters=None, fields=None):
        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 = sg_handler.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(context['tenant'])
            project_sgs = sg_handler.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 _security_group_rule_delete(self, sg_obj, sg_rule):
     rules = sg_obj.get_security_group_entries()
     rules.get_policy_rule().remove(sg_rule)
     sg_obj.set_security_group_entries(rules)
     sg_handler.SecurityGroupHandler(
         self._vnc_lib).resource_update_obj(sg_obj)
     return
示例#3
0
    def _create_vmi_obj(self, port_q, vn_obj):
        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 = sg_handler.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
示例#4
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'] = vn_handler.VNetworkHandler(
            self._vnc_lib, **kwargs)

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

        self._res_handlers['ipam'] = ipam_handler.IPamHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['policy'] = policy_handler.PolicyHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['route_table'] = (
            route_table_handler.RouteTableHandler(self._vnc_lib, **kwargs))
        self._res_handlers['svc'] = svc_instance_handler.SvcInstanceHandler(
            self._vnc_lib, **kwargs)
        self._res_handlers['virtual_router'] = \
            vrouter_handler.VirtualRouterHandler(self._vnc_lib, **kwargs)
示例#5
0
    def _security_group_rule_find(self, sgr_id, project_uuid=None):
        dom_projects = []
        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 = sg_handler.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
示例#6
0
    def _security_group_rule_create(self, sg_id, sg_rule, project_id):
        sghandler = sg_handler.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
示例#7
0
    def _security_group_rule_neutron_to_vnc(self, sgr_q):
        # 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 = sg_handler.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
示例#8
0
    def _security_group_rule_vnc_to_neutron(self,
                                            sg_id,
                                            sg_rule,
                                            sg_obj=None,
                                            fields=None):
        sgr_q_dict = {}
        if sg_id is None:
            return sgr_q_dict

        if not sg_obj:
            try:
                sg_obj = sg_handler.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['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 initialize(self):
        logger.info("Initializing ConGl (Contrail Gluon) mechanism driver ...")

        logger.warn("Cfg is %s %d" % (cfg.CONF.ml2_driver_contrail.controller,
                                      cfg.CONF.ml2_driver_contrail.port))

        cfg.CONF.register_opts(vnc_extra_opts, 'APISERVER')
        admin_user = cfg.CONF.keystone_authtoken.admin_user
        admin_password = cfg.CONF.keystone_authtoken.admin_password
        admin_tenant_name = cfg.CONF.keystone_authtoken.admin_tenant_name
        try:
            api_srvr_ip = cfg.CONF.ml2_driver_contrail.controller
        except cfg.NoSuchOptError:
            logger.info("No controller address in config - using default")
            api_srvr_ip = "127.0.0.1"

        try:
            api_srvr_port = cfg.CONF.ml2_driver_contrail.port
        except cfg.NoSuchOptError:
            logger.info("No controller port in config - using default")
            api_srvr_port = 8082

        try:
            auth_host = cfg.CONF.keystone_authtoken.auth_host
        except cfg.NoSuchOptError:
            auth_host = "127.0.0.1"

        try:
            auth_protocol = cfg.CONF.keystone_authtoken.auth_protocol
        except cfg.NoSuchOptError:
            auth_protocol = "http"

        try:
            auth_port = cfg.CONF.keystone_authtoken.auth_port
        except cfg.NoSuchOptError:
            auth_port = "35357"

        try:
            auth_url = cfg.CONF.keystone_authtoken.auth_url
        except cfg.NoSuchOptError:
            auth_url = "/v2.0/tokens"

        try:
            auth_type = cfg.CONF.auth_strategy
        except cfg.NoSuchOptError:
            auth_type = "keystone"

        try:
            api_server_url = cfg.CONF.APISERVER.api_server_url
        except cfg.NoSuchOptError:
            api_server_url = "/"

        logger.info("Connecting to Contrail server %s : %s" %
                    (api_srvr_ip, api_srvr_port))

        connected = False
        while not connected:
            try:
                self._vnc_lib = vnc_api.VncApi(admin_user,
                                               admin_password,
                                               admin_tenant_name,
                                               api_srvr_ip,
                                               api_srvr_port,
                                               api_server_url,
                                               auth_host=auth_host,
                                               auth_port=auth_port,
                                               auth_protocol=auth_protocol,
                                               auth_url=auth_url,
                                               auth_type=auth_type)
                connected = True
            except requests.exceptions.RequestException:
                time.sleep(3)

        self.handlers = {
            Hndl.VirtualNetwork: vn_res_handler.VNetworkHandler(self._vnc_lib),
            Hndl.Subnet: subnet_res_handler.SubnetHandler(self._vnc_lib),
            Hndl.VMInterface:
            vmi_res_handler.VMInterfaceHandler(self._vnc_lib),
            Hndl.SecurityGroup:
            sg_res_handler.SecurityGroupHandler(self._vnc_lib),
            Hndl.SGRule: sgrule_handler.SecurityGroupRuleHandler(self._vnc_lib)
        }