def create_intvn_and_ref(cls, obj_dict):
        vn_fq_name = (obj_dict['fq_name'][:-1] +
                      [get_lr_internal_vn_name(obj_dict['uuid'])])
        kwargs = {'id_perms': IdPermsType(user_visible=False)}
        vn_property = VirtualNetworkType(forwarding_mode='l3')
        if 'vxlan_network_identifier' in obj_dict:
            vn_property.set_vxlan_network_identifier(
                obj_dict['vxlan_network_identifier'])
        kwargs['virtual_network_properties'] = vn_property
        rt_list = obj_dict.get(
            'configured_route_target_list', {}).get('route_target')
        if rt_list:
            kwargs['route_target_list'] = RouteTargetList(rt_list)
        ok, result = cls.server.get_resource_class(
            'virtual_network').locate(vn_fq_name, **kwargs)
        if not ok:
            return False, result

        attr_obj = LogicalRouterVirtualNetworkType('InternalVirtualNetwork')
        attr_dict = attr_obj.__dict__
        api_server = cls.server

        try:
            api_server.internal_request_ref_update(
                'logical-router',
                obj_dict['uuid'],
                'ADD',
                'virtual-network',
                result['uuid'],
                result['fq_name'],
                attr=attr_dict)
        except HttpError as e:
            return False, (e.status_code, e.content)
        return True, ''
Esempio n. 2
0
    def create_pt_vn_refs(cls, obj_dict, db_conn):
        left_vn_int_name = '__contrail_pt_internal_vn_' + \
            obj_dict.get('uuid') + '-left' + '__'
        right_vn_int_name = '__contrail_pt_internal_vn_' + \
            obj_dict.get('uuid') + '-right' + '__'
        vn_list = [left_vn_int_name, right_vn_int_name]

        api_server = db_conn.get_api_server()
        for vn in vn_list:
            vn_obj = VirtualNetwork(name=vn)
            id_perms = IdPermsType(enable=True, user_visible=False)
            vn_obj.set_id_perms(id_perms)

            int_vn_property = VirtualNetworkType(forwarding_mode='l3')
            vn_obj.set_virtual_network_properties(int_vn_property)

            vn_int_dict = json.dumps(vn_obj, default=_obj_serializer_all)
            status, obj = api_server.internal_request_create(
                'virtual-network', json.loads(vn_int_dict))
            api_server.internal_request_ref_update(
                'port-tuple',
                obj_dict['uuid'],
                'ADD',
                'virtual-network',
                obj['virtual-network']['uuid'],
                obj['virtual-network']['fq_name'])
        return True, ''
Esempio n. 3
0
    def create_dci_vn(cls, obj_dict, db_conn):
        vn_int_name = get_dci_internal_vn_name(obj_dict.get('uuid'))
        vn_obj = VirtualNetwork(name=vn_int_name)
        id_perms = IdPermsType(enable=True, user_visible=False)
        vn_obj.set_id_perms(id_perms)

        int_vn_property = VirtualNetworkType(forwarding_mode='l3')
        if 'data_center_interconnect_vxlan_network_identifier' in obj_dict:
            vni_id = obj_dict[
                'data_center_interconnect_vxlan_network_identifier']
            int_vn_property.set_vxlan_network_identifier(vni_id)
        vn_obj.set_virtual_network_properties(int_vn_property)

        rt_list = obj_dict.get(
            'data_center_interconnect_configured_route_target_list',
            {}).get('route_target')
        if rt_list:
            vn_obj.set_route_target_list(RouteTargetList(rt_list))

        vn_int_dict = json.dumps(vn_obj, default=_obj_serializer_all)
        api_server = cls.server
        try:
            return api_server.internal_request_create('virtual-network',
                                                      json.loads(vn_int_dict))
        except HttpError as e:
            return False, (e.status_code, e.content)
Esempio n. 4
0
    def test_vm_port_not_added_to_lr(self):
        project = self._vnc_lib.project_read(
            ['default-domain', 'default-project'])
        ipam = self._vnc_lib.network_ipam_read(
            ['default-domain', 'default-project', 'default-network-ipam'])

        # Create subnets
        ipam_sn_v4_vn = IpamSubnetType(subnet=SubnetType('11.1.1.0', 24))

        # Create VN my-vn
        vn = VirtualNetwork('%s-vn' % self.id(), project)
        vn.add_network_ipam(ipam, VnSubnetsType([ipam_sn_v4_vn]))
        self._vnc_lib.virtual_network_create(vn)
        net_obj = self._vnc_lib.virtual_network_read(id=vn.uuid)

        # Create v4 Ip object
        ip_obj = InstanceIp(name=str(uuid.uuid4()), instance_ip_family='v4')
        ip_obj.uuid = ip_obj.name

        # Create VM
        vm_inst_obj = VirtualMachine(str(uuid.uuid4()))
        vm_inst_obj.uuid = vm_inst_obj.name
        self._vnc_lib.virtual_machine_create(vm_inst_obj)

        id_perms = IdPermsType(enable=True)
        vm_port_obj = VirtualMachineInterface(str(uuid.uuid4()),
                                              vm_inst_obj,
                                              id_perms=id_perms)
        vm_port_obj.uuid = vm_port_obj.name
        vm_port_obj.set_virtual_network(vn)
        ip_obj.set_virtual_machine_interface(vm_port_obj)
        ip_obj.set_virtual_network(net_obj)
        self._vnc_lib.virtual_machine_interface_create(vm_port_obj)

        self._vnc_lib.instance_ip_create(ip_obj)

        # Create Logical Router
        lr = LogicalRouter('router-test-v4-%s' % self.id(), project)
        self._vnc_lib.logical_router_create(lr)

        # Add Router Interface
        lr.add_virtual_machine_interface(vm_port_obj)
        with ExpectedException(RefsExistError):
            self._vnc_lib.logical_router_update(lr)
        lr.del_virtual_machine_interface(vm_port_obj)

        # Create Port
        port_obj = self.create_port(project, net_obj)
        lr.add_virtual_machine_interface(port_obj)
        self._vnc_lib.logical_router_update(lr)
        with ExpectedException(BadRequest):
            port_obj.add_virtual_machine(vm_inst_obj)
            self._vnc_lib.virtual_machine_interface_update(port_obj)
        self._vnc_lib.logical_router_delete(id=lr.uuid)
    def test_delete_lr_missing_vn_refs(self):
        # Get Project Ref
        project = self._vnc_lib.project_read(
            fq_name=['default-domain', 'default-project'])
        lr = LogicalRouter('router-test-missing_vn_refs-%s' % (self.id()),
                           project)

        lr.set_logical_router_type('vxlan-routing')
        lr_uuid = self._vnc_lib.logical_router_create(lr)
        lr = self._vnc_lib.logical_router_read(id=lr_uuid)
        logger.debug('Created Logical Router ')

        # Create a VN Object
        vn = VirtualNetwork('%s-vn' % self.id(), project)
        self._vnc_lib.virtual_network_create(vn)
        # Create a Virtual Machine Interface that does not have VN Ref
        id_perms = IdPermsType(enable=True)
        vmi_no_vn_ref = VirtualMachineInterface(str(uuid.uuid4()),
                                                parent_obj=project,
                                                id_perms=id_perms)

        vmi_no_vn_ref.set_virtual_network(vn)
        vmi_uuid = self._vnc_lib.virtual_machine_interface_create(
            vmi_no_vn_ref)
        # Do not associate VN Ref to VMI and create
        lr.add_virtual_machine_interface(vmi_no_vn_ref)
        self._vnc_lib.logical_router_update(lr)
        vmi_obj = self._vnc_lib.virtual_machine_interface_read(id=vmi_uuid)
        vn_refs = vmi_obj.get_virtual_network_refs()
        vn_uuid = vn_refs[0]['uuid']
        self._vnc_lib.ref_update('virtual_machine_interface', vmi_uuid,
                                 'virtual_network', vn_uuid, None, 'DELETE')
        vmi_obj = self._vnc_lib.virtual_machine_interface_read(id=vmi_uuid)
        vn_refs = vmi_obj.get_virtual_network_refs()
        self.assertIsNone(vn_refs)

        # Create a VN Object
        vn2 = VirtualNetwork('%s-vn2' % self.id(), project)
        self._vnc_lib.virtual_network_create(vn2)
        # Create a Virtual Machine Interface that does not have VN Ref
        vmi_no_vn_ref_2 = VirtualMachineInterface(str(uuid.uuid4()),
                                                  parent_obj=project,
                                                  id_perms=id_perms)

        vmi_no_vn_ref_2.set_virtual_network(vn2)
        self._vnc_lib.virtual_machine_interface_create(vmi_no_vn_ref_2)
        # Do not associate VN Ref to VMI and create
        lr.add_virtual_machine_interface(vmi_no_vn_ref_2)
        self._vnc_lib.logical_router_update(lr)
        # Deleting directly from api-server as api server
        # will not allow deletion
        self._vnc_lib.logical_router_delete(id=lr.uuid)
    def __init__(self):
        perms = PermType('cloud-admin', PERMS_RWX, 'cloud-admin-group',
                         PERMS_RWX, PERMS_RWX)
        self.perms = IdPermsType(permissions=perms, enable=True)

        # set default perms2 of a new object
        # cloud-admin owner with full access, not shared with anyone
        self.perms2 = PermType2(
            'cloud-admin',
            PERMS_RWX,  # tenant, tenant-access
            PERMS_NONE,  # global-access
            [])  # share list
        super(Defaults, self).__init__()
Esempio n. 7
0
 def _create_inbuilt_alarms_config(self):
     self._inbuilt_alarms = {}
     for table, plugins in self._alarm_plugins.iteritems():
         for extn in plugins[table]:
             alarm_name = camel_case_to_hyphen(extn.obj.__class__.__name__)
             if self._inbuilt_alarms.has_key(alarm_name):
                 uve_keys = self._inbuilt_alarms[alarm_name].get_uve_keys()
                 uve_keys.uve_key.append(_INVERSE_UVE_MAP[table])
                 self._inbuilt_alarms[alarm_name].set_uve_keys(uve_keys)
             else:
                 alarm_or_list = None
                 if extn.obj.rules():
                     alarm_or_list = []
                     for and_list in extn.obj.rules()['or_list']:
                         alarm_and_list = []
                         for exp in and_list['and_list']:
                             alarm_and_list.append(
                                 AlarmExpression(
                                     operation=exp['operation'],
                                     operand1=exp['operand1'],
                                     operand2=AlarmOperand2(
                                         uve_attribute=exp['operand2'].get(
                                             'uve_attribute'),
                                         json_value=exp['operand2'].get(
                                             'json_value')),
                                     variables=exp.get('variables')))
                         alarm_or_list.append(AlarmAndList(alarm_and_list))
                 desc = ' '.join([l.strip() \
                     for l in extn.obj.__doc__.splitlines()])
                 id_perms = IdPermsType(creator='system', description=desc)
                 kwargs = {
                     'parent_type': 'global-system-config',
                     'fq_name':
                     ['default-global-system-config', alarm_name]
                 }
                 self._inbuilt_alarms[alarm_name] = Alarm(
                     name=alarm_name,
                     uve_keys=UveKeysType([_INVERSE_UVE_MAP[table]]),
                     alarm_severity=extn.obj.severity(),
                     alarm_rules=AlarmOrList(alarm_or_list),
                     id_perms=id_perms,
                     **kwargs)
             extn.obj._config = self._inbuilt_alarms[alarm_name]
             fqname_str = self._fqname_to_str(extn.obj._config.fq_name)
             uve_keys = [_INVERSE_UVE_MAP[table]]
             self._update_alarm_config_table(fqname_str, extn.obj, uve_keys,
                                             'CREATE')
Esempio n. 8
0
    def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
        type_str = obj_dict['tag_type_name']

        if obj_dict.get('tag_id') is not None:
            msg = "Tag ID is not setable"
            return False, (400, msg)

        if obj_dict.get('tag_type_refs') is not None:
            msg = "Tag Type reference is not setable"
            return False, (400, msg)

        ok, result = cls.server.get_resource_class('tag_type').locate(
            [type_str], id_perms=IdPermsType(user_visible=False))
        if not ok:
            return False, result
        tag_type = result

        def undo_tag_type():
            cls.server.internal_request_delete('tag-type', tag_type['uuid'])
            return True, ''

        get_context().push_undo(undo_tag_type)

        obj_dict['tag_type_refs'] = [
            {
                'uuid': tag_type['uuid'],
                'to': tag_type['fq_name'],
            },
        ]

        # Allocate ID for tag value. Use the all fq_name to distinguish same
        # tag values between global and scoped
        value_id = cls.vnc_zk_client.alloc_tag_value_id(
            type_str, ':'.join(obj_dict['fq_name']))

        def undo_value_id():
            cls.vnc_zk_client.free_tag_value_id(type_str, value_id,
                                                ':'.join(obj_dict['fq_name']))
            return True, ""

        get_context().push_undo(undo_value_id)

        # Compose Tag ID with the type ID and value ID
        obj_dict['tag_id'] = "{}{:04x}".format(tag_type['tag_type_id'],
                                               value_id)

        return True, ""
Esempio n. 9
0
    def create(self,
               ll_obj,
               proj_obj,
               port,
               lb_algorithm=None,
               annotations=None):
        """
        Create a loadbalancer_pool object.
        """
        pool_uuid = str(uuid.uuid4())
        props = LoadbalancerPoolType()
        if port['protocol'] == "TCP":
            props.set_protocol("TCP")
        elif port['protocol'] == "HTTP":
            props.set_protocol("HTTP")
        elif port['protocol'] == "HTTPS":
            props.set_protocol("HTTPS")
        else:
            props.set_protocol("UDP")
        if lb_algorithm:
            props.set_loadbalancer_method(lb_algorithm)
        id_perms = IdPermsType(enable=True)
        pool_obj = LoadbalancerPool(ll_obj.name,
                                    proj_obj,
                                    uuid=pool_uuid,
                                    loadbalancer_pool_properties=props,
                                    id_perms=id_perms)

        if ll_obj:
            pool_exists = ll_obj.get_loadbalancer_pool_back_refs()
            if pool_exists is not None:
                raise Exception("Pool {} already exists ".format(
                    pool_exists[0]['uuid']))
            pool_obj.set_loadbalancer_listener(ll_obj)

        if annotations:
            for key in annotations:
                pool_obj.add_annotations(
                    KeyValuePair(key=key, value=annotations[key]))
        try:
            self._vnc_lib.loadbalancer_pool_create(pool_obj)
        except RefsExistError:
            self._vnc_lib.loadbalancer_pool_update(pool_obj)

        return pool_obj
Esempio n. 10
0
    def create(self, lb_obj, proj_obj, port):

        if not port:
            self.logger.error("Port is Missing for LB %s" % lb_obj.name)
            return None
        ll_uuid = str(uuid.uuid4())
        name = lb_obj.name + "-" + port['protocol'] + "-" + str(
            port['port']) + "-" + ll_uuid

        id_perms = IdPermsType(enable=True)
        ll_obj = LoadbalancerListener(name,
                                      proj_obj,
                                      id_perms=id_perms,
                                      display_name=name)
        ll_obj.uuid = ll_uuid

        if lb_obj:
            ll_obj.set_loadbalancer(lb_obj)

        props = LoadbalancerListenerType()
        default_protocol = 'UDP'
        supported_protocols = ['TCP', 'HTTP', 'HTTPS', 'TERMINATED_HTTPS']
        props.set_protocol(default_protocol)
        if 'protocol' in port:
            if port['protocol'] in supported_protocols:
                props.set_protocol(port['protocol'])
        if 'port' in port:
            props.set_protocol_port(port['port'])
        if 'default_tls_container' in port:
            setattr(props, 'default_tls_container',
                    port['default_tls_container'])
        if 'sni_containers' in port:
            setattr(props, 'sni_containers', port['sni_containers'])

        ll_obj.set_loadbalancer_listener_properties(props)
        if 'name' in port:
            ll_obj.add_annotations(
                KeyValuePair(key='portName', value=str(port['name'])))

        try:
            self._vnc_lib.loadbalancer_listener_create(ll_obj)
        except RefsExistError:
            self._vnc_lib.loadbalancer_listener_update(ll_obj)

        return ll_obj
Esempio n. 11
0
    def create_port(self, project, vn):
        # Create v4 Ip object
        ip_obj = InstanceIp(name=str(uuid.uuid4()), instance_ip_family='v4')
        ip_obj.uuid = ip_obj.name

        # Create Port
        id_perms = IdPermsType(enable=True)
        port_obj = VirtualMachineInterface(str(uuid.uuid4()),
                                           parent_obj=project,
                                           id_perms=id_perms)
        port_obj.uuid = port_obj.name
        port_obj.set_virtual_network(vn)
        ip_obj.set_virtual_machine_interface(port_obj)
        ip_obj.set_virtual_network(vn)
        self._vnc_lib.virtual_machine_interface_create(port_obj)

        self._vnc_lib.instance_ip_create(ip_obj)
        return port_obj
Esempio n. 12
0
    def create(self, pool_obj, address, port, annotations):
        """
        Create a loadbalancer_member object.
        """
        lm_uuid = str(uuid.uuid4())
        props = LoadbalancerMemberType(address=address, protocol_port=port)
        id_perms = IdPermsType(enable=True)

        member_obj = LoadbalancerMember(lm_uuid,
                                        pool_obj,
                                        loadbalancer_member_properties=props,
                                        id_perms=id_perms)
        member_obj.uuid = lm_uuid

        if annotations:
            for key in annotations:
                member_obj.add_annotations(
                    KeyValuePair(key=key, value=annotations[key]))
        self._vnc_lib.loadbalancer_member_create(member_obj)
        return member_obj
    def create_intvn_and_ref(cls, obj_dict, db_conn):
        ok, proj_dict = db_conn.dbe_read('project', obj_dict['parent_uuid'])
        if not ok:
            return (ok, proj_dict)

        vn_int_name = get_lr_internal_vn_name(obj_dict.get('uuid'))
        proj_obj = Project(name=proj_dict.get('fq_name')[-1],
                           parent_type='domain',
                           fq_name=proj_dict.get('fq_name'))

        vn_obj = VirtualNetwork(name=vn_int_name, parent_obj=proj_obj)
        id_perms = IdPermsType(enable=True, user_visible=False)
        vn_obj.set_id_perms(id_perms)

        int_vn_property = VirtualNetworkType(forwarding_mode='l3')
        if 'vxlan_network_identifier' in obj_dict:
            vni_id = obj_dict['vxlan_network_identifier']
            int_vn_property.set_vxlan_network_identifier(vni_id)
        vn_obj.set_virtual_network_properties(int_vn_property)

        rt_list = obj_dict.get('configured_route_target_list',
                               {}).get('route_target')
        if rt_list:
            vn_obj.set_route_target_list(RouteTargetList(rt_list))

        vn_int_dict = json.dumps(vn_obj, default=_obj_serializer_all)
        api_server = db_conn.get_api_server()
        status, obj = api_server.internal_request_create(
            'virtual-network', json.loads(vn_int_dict))
        attr_obj = LogicalRouterVirtualNetworkType('InternalVirtualNetwork')
        attr_dict = attr_obj.__dict__
        api_server.internal_request_ref_update(
            'logical-router',
            obj_dict['uuid'],
            'ADD',
            'virtual-network',
            obj['virtual-network']['uuid'],
            obj['virtual-network']['fq_name'],
            attr=attr_dict)
        return True, ''
Esempio n. 14
0
    def create(self,
               k8s_event_type,
               service_ns,
               service_id,
               service_name,
               proj_obj,
               vn_obj,
               vip_address=None,
               subnet_uuid=None,
               tags=None):
        """
        Create a loadbalancer.
        """
        lb_name = VncCommon.make_name(service_name, service_id)
        lb_display_name = VncCommon.make_display_name(service_ns, service_name)
        if k8s_event_type == 'Service':
            lb_provider = 'native'
        elif k8s_event_type == 'Ingress':
            lb_provider = 'opencontrail'
        lb_obj = Loadbalancer(name=lb_name,
                              parent_obj=proj_obj,
                              loadbalancer_provider=lb_provider,
                              display_name=lb_display_name)

        lb_obj.uuid = service_id
        sas_obj = self._check_provider_exists(
            loadbalancer_provider=lb_provider)
        if sas_obj is not None:
            lb_obj.set_service_appliance_set(sas_obj)

        vmi_obj, vip_address = self._create_virtual_interface(proj_obj,
                                                              vn_obj,
                                                              service_ns,
                                                              service_name,
                                                              service_id,
                                                              k8s_event_type,
                                                              vip_address,
                                                              subnet_uuid,
                                                              tags=tags)
        if vmi_obj is None:
            return None
        lb_obj.set_virtual_machine_interface(vmi_obj)

        id_perms = IdPermsType(enable=True)
        props = LoadbalancerType(provisioning_status='ACTIVE',
                                 id_perms=id_perms,
                                 operating_status='ONLINE',
                                 vip_address=vip_address)
        lb_obj.set_loadbalancer_properties(props)

        LoadbalancerKM.add_annotations(self,
                                       lb_obj,
                                       service_ns,
                                       service_name,
                                       k8s_type=k8s_event_type)

        try:
            self._vnc_lib.loadbalancer_create(lb_obj)
        except RefsExistError:
            self._vnc_lib.loadbalancer_update(lb_obj)
        return lb_obj
Esempio n. 15
0
    def test_lr_v4_subnets(self):
        # Create Domain
        domain = Domain('my-lr-domain')
        self._vnc_lib.domain_create(domain)

        # Create Project
        project = Project('my-lr-proj', domain)
        self._vnc_lib.project_create(project)

        # Create NetworkIpam
        ipam = NetworkIpam('default-network-ipam', project, IpamType("dhcp"))
        self._vnc_lib.network_ipam_create(ipam)

        ipam = self._vnc_lib.network_ipam_read(
            ['my-lr-domain', 'my-lr-proj', 'default-network-ipam'])

        # Create subnets
        ipam_sn_v4_vn1 = IpamSubnetType(subnet=SubnetType('11.1.1.0', 24))
        ipam_sn_v6_vn1 = IpamSubnetType(subnet=SubnetType('fd11::', 120))
        ipam_sn_v4_vn2 = IpamSubnetType(subnet=SubnetType('11.1.2.0', 24))
        ipam_sn_v6_vn2 = IpamSubnetType(subnet=SubnetType('fd12::', 120))

        # Create VN my-vn-1
        vn1 = VirtualNetwork('my-vn-1', project)
        vn1.add_network_ipam(ipam,
                             VnSubnetsType([ipam_sn_v4_vn1, ipam_sn_v6_vn1]))
        self._vnc_lib.virtual_network_create(vn1)
        net_obj1 = self._vnc_lib.virtual_network_read(id=vn1.uuid)

        # Create VN my-vn-2
        vn2 = VirtualNetwork('my-vn-2', project)
        vn2.add_network_ipam(ipam,
                             VnSubnetsType([ipam_sn_v4_vn2, ipam_sn_v6_vn2]))
        self._vnc_lib.virtual_network_create(vn2)
        net_obj2 = self._vnc_lib.virtual_network_read(id=vn2.uuid)

        # Create Logical Router
        lr = LogicalRouter('router-test-v4-%s' % self.id(), project)
        lr_uuid = self._vnc_lib.logical_router_create(lr)

        # Create a Virtual Machine Interface belonging to my-vn-1
        id_perms = IdPermsType(enable=True)
        port_obj1 = VirtualMachineInterface(str(uuid.uuid4()),
                                            parent_obj=project,
                                            id_perms=id_perms)
        port_obj1.uuid = port_obj1.name
        port_obj1.set_virtual_network(vn1)
        port_obj1.set_virtual_machine_interface_device_owner(
            'DEVICE_OWNER_ROUTER_INTF')
        # Assign gateway ip
        ipam_refs = net_obj1.get_network_ipam_refs()
        for ipam_ref in ipam_refs:
            subnets = ipam_ref['attr'].get_ipam_subnets()
            for subnet in subnets:
                cidr = '%s/%s' % (subnet.subnet.get_ip_prefix(),
                                  subnet.subnet.get_ip_prefix_len())
                if IPNetwork(cidr).version == 4:
                    gateway_ip = subnet.get_default_gateway()
        self._vnc_lib.virtual_machine_interface_create(port_obj1)

        # Create v4 Ip object
        ip_obj1 = InstanceIp(name=str(uuid.uuid4()),
                             instance_ip_address=gateway_ip,
                             instance_ip_family='v4')
        ip_obj1.uuid = ip_obj1.name
        ip_obj1.set_virtual_machine_interface(port_obj1)
        ip_obj1.set_virtual_network(net_obj1)
        ip_id1 = self._vnc_lib.instance_ip_create(ip_obj1)

        # Add Router Interface (test being subnet)
        lr.add_virtual_machine_interface(port_obj1)
        self._vnc_lib.logical_router_update(lr)

        # Create a Virtual Machine Interface belonging to my-vn-2
        port_obj2 = VirtualMachineInterface(str(uuid.uuid4()),
                                            parent_obj=project,
                                            id_perms=id_perms)
        port_obj2.uuid = port_obj2.name
        port_obj2.set_virtual_network(vn2)
        port_obj2.set_virtual_machine_interface_device_owner(
            'DEVICE_OWNER_ROUTER_INTF')
        # Assign gateway ip
        ipam_refs = net_obj2.get_network_ipam_refs()
        for ipam_ref in ipam_refs:
            subnets = ipam_ref['attr'].get_ipam_subnets()
            for subnet in subnets:
                cidr = '%s/%s' % (subnet.subnet.get_ip_prefix(),
                                  subnet.subnet.get_ip_prefix_len())
                if IPNetwork(cidr).version == 4:
                    gateway_ip = subnet.get_default_gateway()
        self._vnc_lib.virtual_machine_interface_create(port_obj2)

        # Create v4 Ip object
        ip_obj2 = InstanceIp(name=str(uuid.uuid4()),
                             instance_ip_address=gateway_ip,
                             instance_ip_family='v4')
        ip_obj2.uuid = ip_obj2.name
        ip_obj2.set_virtual_machine_interface(port_obj2)
        ip_obj2.set_virtual_network(net_obj2)
        ip_id2 = self._vnc_lib.instance_ip_create(ip_obj2)

        # Add Router Interface (test being subnet)
        lr.add_virtual_machine_interface(port_obj2)
        self._vnc_lib.logical_router_update(lr)

        # TODO: Schema transformer not integrated in the tests,
        #       hence route-target refs not set yet
        # Verify Route Target Creation
        rt_refs = lr.get_route_target_refs()
        for rt_ref in rt_refs or []:
            rt_obj = self._vnc_lib.route_target_read(id=rt_ref['uuid'])
            ri_refs = rt_obj.get_routing_instance_back_refs()
            for ri_ref in ri_refs:
                ri_obj = self.vnc_lib.routing_instance_read(id=ri_ref['uuid'])
                ri_name = ri_obj.get_display_name()
                if ri_name != 'my-vn-1' and ri_name != 'my-vn-2':
                    pass

        # cleanup
        self._vnc_lib.instance_ip_delete(id=ip_id1)
        self._vnc_lib.instance_ip_delete(id=ip_id2)
        self._vnc_lib.logical_router_delete(id=lr_uuid)
        self._vnc_lib.virtual_machine_interface_delete(id=port_obj1.uuid)
        self._vnc_lib.virtual_machine_interface_delete(id=port_obj2.uuid)
        self._vnc_lib.virtual_network_delete(id=vn1.uuid)
        self._vnc_lib.virtual_network_delete(id=vn2.uuid)
        self._vnc_lib.network_ipam_delete(id=ipam.uuid)
        self._vnc_lib.project_delete(id=project.uuid)
        self._vnc_lib.domain_delete(id=domain.uuid)
Esempio n. 16
0
    def _create_logical_interface(cls, db_conn, dev_name, link,
                                  vlan_tag, subscriber_tag, network_name):
        li_fq_name = ['default-global-system-config', dev_name, link]
        li_fq_name = li_fq_name + ['%s.%s' % (link, vlan_tag)]

        li_display_name = li_fq_name[-1]
        li_display_name = li_display_name.replace("_", ":")

        api_server = cls.server
        try:
            db_conn.fq_name_to_uuid('logical_interface', li_fq_name)
        except NoIdError:
            li_obj = LogicalInterface(parent_type='physical-interface',
                                      fq_name=li_fq_name,
                                      logical_interface_vlan_tag=vlan_tag,
                                      display_name=li_display_name)

            id_perms = IdPermsType(enable=True, user_visible=False)
            li_obj.set_id_perms(id_perms)
            li_int_dict = json.dumps(li_obj, default=_obj_serializer_all)
            ok, li_obj_resp = api_server.internal_request_create(
                'logical-interface', json.loads(li_int_dict))

            if not ok:
                return (ok, 400, li_obj_resp)

            # Allocate IP address for this logical interface
            iip_name = "%s.%s.%s" % (dev_name, link, vlan_tag)
            if subscriber_tag is not None:
                iip_obj = InstanceIp(
                    name=iip_name,
                    instance_ip_family='v4',
                    instance_ip_subscriber_tag=subscriber_tag
                )
            else:
                iip_obj = InstanceIp(
                    name=iip_name,
                    instance_ip_family='v4'
                )
            nw_fq_name = ['default-domain', 'default-project', network_name]
            nw_id = db_conn.fq_name_to_uuid('virtual_network', nw_fq_name)
            ok, nw_obj_result = cls.dbe_read(db_conn, 'virtual_network',
                                             nw_id,
                                             obj_fields=['fq_name'])
            if not ok:
                return ok, nw_obj_result

            nw_obj = VirtualNetwork(name=nw_obj_result.get('fq_name')[-1])
            li_obj = LogicalInterface(
                fq_name=li_fq_name, parent_type='physical-interface')
            iip_obj.set_virtual_network(nw_obj)
            iip_obj.set_logical_interface(li_obj)
            iip_obj.set_id_perms(id_perms)

            iip_int_dict = json.dumps(iip_obj, default=_obj_serializer_all)
            ok, resp = api_server.internal_request_create(
                'instance-ip', json.loads(iip_int_dict))
            if not ok:
                return (ok, 400, resp)

        return True, ''
Esempio n. 17
0
    def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
        type_str = obj_dict['tag_type_name']

        tag_id = obj_dict.get('tag_id') or None
        tag_value_id = None
        tag_type_id = None

        # For user defined tags tag id and tag-type id
        # is input from user. Range for user defined
        # ids are 32768 - 65535. Both values are expected
        # in hex format.
        if tag_id is not None:
            try:
                tag_value_id = int(tag_id, 16) & (2**16 - 1)
                tag_type_id = int(tag_id, 16) >> 16
            except ValueError:
                return False, (400, "Tag value must be in hexadecimal")

        if tag_value_id is not None and \
           not cls.vnc_zk_client.user_def_tag(tag_value_id):
            msg = "Tag id can be set only for user defined tags in range\
                   32678-65535"

            return False, (400, msg)

        if obj_dict.get('tag_type_refs') is not None:
            msg = "Tag Type reference is not setable"
            return False, (400, msg)

        # check if tag-type is already present use that.
        ok, result = cls.server.get_resource_class('tag_type').locate(
            [type_str], create_it=False)

        if not ok and result[0] == 404:
            if tag_type_id is not None and \
               not cls.vnc_zk_client.user_def_tag(tag_type_id):
                msg = "Tag type id can be set only for user defined tag types\
                        in range 32678-65535"

                return False, (400, msg)

            params = {
                "id_perms":
                IdPermsType(user_visible=False),
                "tag_type_id":
                None if tag_type_id is None else "0x%x" % tag_type_id,
            }
            ok, result = cls.server.get_resource_class('tag_type').locate(
                [type_str], **params)
            if not ok:
                return False, result

        tag_type = result

        def undo_tag_type():
            cls.server.internal_request_delete('tag-type', tag_type['uuid'])
            return True, ''

        get_context().push_undo(undo_tag_type)

        obj_dict['tag_type_refs'] = [
            {
                'uuid': tag_type['uuid'],
                'to': tag_type['fq_name'],
            },
        ]

        # Allocate ID for tag value. Use the all fq_name to distinguish same
        # tag values between global and scoped
        try:
            value_id = cls.vnc_zk_client.alloc_tag_value_id(
                type_str, ':'.join(obj_dict['fq_name']), tag_value_id)

        except ResourceExistsError:
            return False, (400, "Requested Tag id is already allocated")

        def undo_value_id():
            cls.vnc_zk_client.free_tag_value_id(type_str, value_id,
                                                ':'.join(obj_dict['fq_name']))
            return True, ""

        get_context().push_undo(undo_value_id)

        # value id is None in case of Failure otherwise any positive
        # value between 0 and 65535
        if value_id is None:
            return False, (400, "Failed to allocate tag Id")

        # Compose Tag ID with the type ID and value ID
        obj_dict['tag_id'] = "{}{:04x}".format(tag_type['tag_type_id'],
                                               value_id)

        return True, ""
Esempio n. 18
0
    def _create_logical_interface(cls, dev_name, link,
                                  vlan_tag, subscriber_tag,
                                  network_name):
        api_server = cls.server
        db_conn = cls.db_conn

        li_fqname = cls._construct_li_fq_name(dev_name, link, vlan_tag)
        li_display_name = li_fqname[-1]
        li_display_name = li_display_name.replace("_", ":")
        id_perms = IdPermsType(enable=True, user_visible=True)
        li_obj = LogicalInterface(parent_type='physical-interface',
                                  fq_name=li_fqname,
                                  logical_interface_vlan_tag=vlan_tag,
                                  display_name=li_display_name,
                                  id_perms=id_perms)
        li_int_dict = json.dumps(li_obj, default=_obj_serializer_all)
        try:
            li_uuid = db_conn.fq_name_to_uuid('logical_interface', li_fqname)
            try:
                api_server.internal_request_update(
                    'logical-interface',
                    li_uuid,
                    json.loads(li_int_dict))
            except HttpError as e:
                return False, (e.status_code, e.content)
        except NoIdError:
            try:
                api_server.internal_request_create(
                    'logical-interface', json.loads(li_int_dict))
            except HttpError as e:
                return False, (e.status_code, e.content)

        # Allocate IP address for this logical interface
        iip_name = cls._construct_iip_fq_name(dev_name, link, vlan_tag)
        if subscriber_tag is not None:
            iip_obj = InstanceIp(
                name=iip_name,
                instance_ip_family='v4',
                instance_ip_subscriber_tag=subscriber_tag
            )
        else:
            iip_obj = InstanceIp(
                name=iip_name,
                instance_ip_family='v4'
            )
        nw_fq_name = ['default-domain', 'default-project', network_name]
        ok, nw_obj_result = cls.server.get_resource_class(
            'virtual_network').locate(nw_fq_name, create_it=False)
        if not ok:
            return False, nw_obj_result

        nw_obj = VirtualNetwork(name=network_name)
        iip_obj.set_virtual_network(nw_obj)
        iip_obj.set_logical_interface(li_obj)
        iip_obj.set_id_perms(id_perms)
        iip_int_dict = json.dumps(iip_obj, default=_obj_serializer_all)
        try:
            iip_uuid = db_conn.fq_name_to_uuid('instance_ip', [iip_name])
            try:
                api_server.internal_request_update(
                    'instance-ip',
                    iip_uuid,
                    json.loads(iip_int_dict))
            except HttpError as e:
                return False, (e.status_code, e.content)
        except NoIdError:
            try:
                api_server.internal_request_create(
                    'instance-ip', json.loads(iip_int_dict))
            except HttpError as e:
                return False, (e.status_code, e.content)

        return True, ''
Esempio n. 19
0
    def _update_security_groups(self, ns_name, proj_obj):
        def _get_rule(ingress, sg, prefix, ethertype):
            sgr_uuid = str(uuid.uuid4())
            if sg:
                if ':' not in sg:
                    sg_fq_name = proj_obj.get_fq_name_str() + ':' + sg
                else:
                    sg_fq_name = sg
                addr = AddressType(security_group=sg_fq_name)
            elif prefix:
                addr = AddressType(subnet=SubnetType(prefix, 0))
            local_addr = AddressType(security_group='local')
            if ingress:
                src_addr = addr
                dst_addr = local_addr
            else:
                src_addr = local_addr
                dst_addr = addr
            rule = PolicyRuleType(rule_uuid=sgr_uuid,
                                  direction='>',
                                  protocol='any',
                                  src_addresses=[src_addr],
                                  src_ports=[PortType(0, 65535)],
                                  dst_addresses=[dst_addr],
                                  dst_ports=[PortType(0, 65535)],
                                  ethertype=ethertype)
            return rule

        # create default security group
        sg_name = vnc_kube_config.get_default_sg_name(ns_name)
        DEFAULT_SECGROUP_DESCRIPTION = "Default security group"
        id_perms = IdPermsType(enable=True,
                               description=DEFAULT_SECGROUP_DESCRIPTION)

        rules = []
        ingress = True
        egress = True
        if ingress:
            rules.append(_get_rule(True, None, '0.0.0.0', 'IPv4'))
            rules.append(_get_rule(True, None, '::', 'IPv6'))
        if egress:
            rules.append(_get_rule(False, None, '0.0.0.0', 'IPv4'))
            rules.append(_get_rule(False, None, '::', 'IPv6'))
        sg_rules = PolicyEntriesType(rules)

        sg_obj = SecurityGroup(name=sg_name,
                               parent_obj=proj_obj,
                               id_perms=id_perms,
                               security_group_entries=sg_rules)

        SecurityGroupKM.add_annotations(self,
                                        sg_obj,
                                        namespace=ns_name,
                                        name=sg_obj.name,
                                        k8s_type=self._k8s_event_type)
        try:
            self._vnc_lib.security_group_create(sg_obj)
            self._vnc_lib.chown(sg_obj.get_uuid(), proj_obj.get_uuid())
        except RefsExistError:
            self._vnc_lib.security_group_update(sg_obj)
        sg = SecurityGroupKM.locate(sg_obj.get_uuid())
        return sg