def test_trunk_create_with_same_vlan_tag_negative(self):
        vn = vnc_api.VirtualNetwork('vn-same-vlan-tag-%s' % (self.id()))
        self._vnc_lib.virtual_network_create(vn)
        vmi_obj = vnc_api.VirtualMachineInterface('trunk-port-same-vlan-tag',
                                                  parent_obj=self.project)
        vmi_obj.set_virtual_network(vn)
        vmi_id = self._vnc_lib.virtual_machine_interface_create(vmi_obj)

        sub_ports = []

        for i in range(self.VMI_NUM):
            sub_vmi_dict = {}
            sub_vmi_obj = vnc_api.VirtualMachineInterface(
                'sub-port-%s' % (i), parent_obj=self.project)
            sub_vmi_obj.set_virtual_network(vn)
            sub_port_id = self._vnc_lib.virtual_machine_interface_create(
                sub_vmi_obj)
            sub_vmi_dict['port_id'] = sub_port_id
            sub_vmi_dict['segmentation_id'] = 10
            sub_ports.append(sub_vmi_dict)

        context = {
            'operation': 'CREATE',
            'user_id': '',
            'is_admin': True,
            'roles': ''
        }
        data = {
            'resource': {
                'name': 'trunk-%s' % (self.id()),
                'tenant_id': self.project_id,
                'port_id': vmi_id,
                'sub_ports': sub_ports
            }
        }
        body = {'context': context, 'data': data}
        # Create Trunk should fail since sub ports have same vlan tag
        try:
            self._api_svr_app.post_json('/neutron/trunk', body)
        except webtest.app.AppError as e:
            self.assertIsNot(re.search('DuplicateSubPort', str(e)), None)

        # Clean the resources
        for i in range(self.VMI_NUM):
            self._vnc_lib.virtual_machine_interface_delete(
                id=sub_ports[i].get('port_id'))
        self._vnc_lib.virtual_machine_interface_delete(id=vmi_id)
        self._vnc_lib.virtual_network_delete(id=vn.uuid)
示例#2
0
 def createVmi(self, vnName, requestedIp):
     interfaceName = 'veth' + self.vmName
     try:
         ip = self.vnc_client.instance_ip_read(fq_name_str=interfaceName)
         if ip:
             print 'deleting ip instance'
             self.vnc_client.instance_ip_delete(id=ip.uuid)
     except:
         print 'no ip instance'
     try:
         vm_interface = self.vnc_client.virtual_machine_interface_read(
             fq_name=[self.vmName, interfaceName])
         if vm_interface:
             print 'deleting vm interface'
             self.vnc_client.virtual_machine_interface_delete(
                 id=vm_interface.uuid)
     except:
         print 'no vm interface'
     try:
         vm = self.vnc_client.virtual_machine_read(fq_name_str=self.vmName)
         if vm:
             print 'deleting vm'
             self.vnc_client.virtual_machine_delete(id=vm.uuid)
     except:
         print 'no vm'
     vm_instance = vnc_api.VirtualMachine(name=self.vmName)
     self.vnc_client.virtual_machine_create(vm_instance)
     vm_interface = vnc_api.VirtualMachineInterface(name=interfaceName,
                                                    parent_obj=vm_instance)
     vn = OpenContrailVN(vnName).VNget()
     vm_interface.set_virtual_network(vn)
     self.vnc_client.virtual_machine_interface_create(vm_interface)
     vm_interface = self.vnc_client.virtual_machine_interface_read(
         id=vm_interface.uuid)
     ip = vnc_api.InstanceIp(name=interfaceName,
                             instance_ip_address=requestedIp.split('/')[0])
     ip.set_virtual_machine_interface(vm_interface)
     ip.set_virtual_network(vn)
     self.vnc_client.instance_ip_create(ip)
     ip = self.vnc_client.instance_ip_read(id=ip.uuid)
     ipAddress = ip.get_instance_ip_address()
     print 'ipaddress: %s' % ipAddress
     subnet = vn.network_ipam_refs[0]['attr'].ipam_subnets[0]
     gw = subnet.default_gateway
     mac = vm_interface.virtual_machine_interface_mac_addresses.mac_address[
         0]
     vrouterInterface = interfaceName + 'p0'
     ContrailVRouterApi().add_port(vm_instance.uuid,
                                   vm_interface.uuid,
                                   vrouterInterface,
                                   mac,
                                   display_name=vm_instance.name,
                                   vm_project_id=self.tenant.uuid,
                                   port_type='NovaVMPort')
     return {
         'ip': ipAddress,
         'interface': interfaceName,
         'gateway': gw,
         'mac': mac
     }
def vmi_2(project):
    vmi = vnc_api.VirtualMachineInterface(
        name="esxi-1_dvs-1_dpg-2", parent_obj=project
    )
    vmi.set_uuid(models.generate_uuid(vmi.name))
    vmi.set_id_perms(constants.ID_PERMS)
    return vmi
示例#4
0
    def test_list_trunks(self):
        vn = vnc_api.VirtualNetwork('%s-vn' % self.id(),
                                    parent_obj=self.project)
        self._vnc_lib.virtual_network_create(vn)
        neutron_trunks = []
        vmi_ids = []
        for i in range(2):
            vmi = vnc_api.VirtualMachineInterface('%s-vmi%d' % (self.id(), i),
                                                  parent_obj=self.project)
            vmi.add_virtual_network(vn)
            vmi_ids.append(self._vnc_lib.virtual_machine_interface_create(vmi))

            neutron_trunks.append(
                self.create_resource(
                    'trunk',
                    self.project_id,
                    extra_res_fields={
                        'name': '%s-trunk-%d' % (self.id(), i),
                        'tenant_id': self.project_id,
                        'port_id': vmi.uuid
                    },
                ), )
        list_result = self.list_resource('trunk', self.project_id)
        self.assertEquals(len(list_result), len(neutron_trunks))
        self.assertEquals({r['id']
                           for r in list_result},
                          {r['id']
                           for r in neutron_trunks})

        # Clean the resources
        for i in range(2):
            self.delete_resource('trunk', self.project_id,
                                 neutron_trunks[i]['id'])
            self._vnc_lib.virtual_machine_interface_delete(id=vmi_ids[i])
        self._vnc_lib.virtual_network_delete(id=vn.uuid)
示例#5
0
        def create(name, image, flavor, nics, *args, **kwargs):
            vm = vnc_api.VirtualMachine(name)
            FakeNovaClient.vnc_lib.virtual_machine_create(vm)
            for network in nics:
                if 'nic-id' in network:
                    vn = FakeNovaClient.vnc_lib.virtual_network_read(
                        id=network['net-id'])
                    vmi = vnc_api.VirtualMachineInterface(vn.name,
                                                          parent_obj=vm)
                    vmi.set_virtual_network(vn)
                    FakeNovaClient.vnc_lib.virtual_machine_interface_create(
                        vmi)

                    ip_address = FakeNovaClient.vnc_lib.virtual_network_ip_alloc(
                        vn, count=1)[0]
                    ip_obj = vnc_api.InstanceIp(ip_address, ip_address)
                    ip_obj.add_virtual_network(vn)
                    ip_obj.add_virtual_machine_interface(vmi)
                    FakeNovaClient.vnc_lib.instance_ip_create(ip_obj)
                elif 'port-id' in network:
                    vmi = FakeNovaClient.vnc_lib.virtual_machine_interface_read(
                        id=network['port-id'])
                    vmi.add_virtual_machine(vm)
                    FakeNovaClient.vnc_lib.virtual_machine_interface_update(
                        vmi)
            # end for network
            vm.id = vm.uuid
            vm.delete = FakeNovaClient.delete_vm.__get__(
                vm, vnc_api.VirtualMachine)
            vm.get = stub
            return vm
 def join(self, networkId, sandboxKey):
     ipInstance = self.vnc_client.instance_ip_read(fq_name=[self.epName])
     vn = OpenContrailVN(networkId).VNget()
     hostname = socket.gethostname()
     interfaceName = 'veth' + self.epName + 'p0'
     try:
         vmInstance = self.vnc_client.virtual_machine_read(
             fq_name=[sandboxKey])
     except:
         vmInstance = vnc_api.VirtualMachine(name=sandboxKey)
         self.vnc_client.virtual_machine_create(vmInstance)
     vmInstance = self.vnc_client.virtual_machine_read(fq_name=[sandboxKey])
     vmInterface = vnc_api.VirtualMachineInterface(name=interfaceName,
                                                   parent_obj=self.tenant)
     vmInterface.set_virtual_machine(vmInstance)
     vmInterface.set_virtual_network(vn)
     self.vnc_client.virtual_machine_interface_create(vmInterface)
     vmInterface = self.vnc_client.virtual_machine_interface_read(
         id=vmInterface.uuid)
     ipInstance.set_virtual_machine_interface(vmInterface)
     self.vnc_client.instance_ip_update(ipInstance)
     mac = vmInterface.virtual_machine_interface_mac_addresses.mac_address[
         0]
     interfaceName + 'p0'
     instIpAddress = ipInstance.get_instance_ip_address()
     return {
         'mac': mac,
         'vmInstanceUuid': vmInstance.uuid,
         'vmInterfaceUuid': vmInterface.uuid,
         'vrouterInterface': interfaceName,
         'vmInstanceName': vmInstance.name,
         'vmProjectId': self.tenant.uuid,
         'ipAddress': instIpAddress,
         'vnId': vn.uuid
     }
示例#7
0
    def _create_vn_ri_vmi(self, obj_count=1):
        vn_objs = []
        ipam_objs = []
        ri_objs = []
        vmi_objs = []
        for i in range(obj_count):
            vn_obj = vnc_api.VirtualNetwork('%s-vn-%s' % (self.id(), i))

            ipam_obj = vnc_api.NetworkIpam('%s-ipam-%s' % (self.id(), i))
            vn_obj.add_network_ipam(ipam_obj, vnc_api.VnSubnetsType())
            self._vnc_lib.network_ipam_create(ipam_obj)
            ipam_objs.append(ipam_obj)

            self._vnc_lib.virtual_network_create(vn_obj)
            vn_objs.append(vn_obj)

            ri_obj = vnc_api.RoutingInstance('%s-ri-%s' % (self.id(), i),
                                             parent_obj=vn_obj)
            self._vnc_lib.routing_instance_create(ri_obj)
            ri_objs.append(ri_obj)

            vmi_obj = vnc_api.VirtualMachineInterface(
                '%s-vmi-%s' % (self.id(), i), parent_obj=vnc_api.Project())
            vmi_obj.add_virtual_network(vn_obj)
            self._vnc_lib.virtual_machine_interface_create(vmi_obj)
            vmi_objs.append(vmi_obj)

        return vn_objs, ipam_objs, ri_objs, vmi_objs
示例#8
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
示例#9
0
 def create(self, network, vm, name=None, address=None, sg=None):
     update = False
     if not name:
         name = str(uuid.uuid4())
     fq_name = [self.domain, self.tenant, name]
     try:
         self.vnc_handle.virtual_machine_interface_read(fq_name=fq_name)
         print "Virtual Machine Interface exists"
         return vm_obj.uuid
     except vnc_exc.NoIdError:
         proj_obj = self.get_project()
         vmi_obj = vnc_api.VirtualMachineInterface(name=name,
                                                   parent_obj=proj_obj)
         self.add_network(vmi_obj, network)
         vmi_id = self.vnc_handle.virtual_machine_interface_create(vmi_obj)
         self.add_iip(vmi_obj, network)
         self.add_vm(vmi_obj, vm)
         self.vnc_handle.virtual_machine_interface_update(vmi_obj)
         if vmi_id:
             print "Successfully creted the virtual-machine interface object [{}]".format(
                 vmi_id)
             return vmi_id
         else:
             print "Error, failed to create the virtual machine"
             raise
示例#10
0
    def handle_create(self):
        tenant_id = self.stack.context.tenant_id
        project_obj = self.vnc_lib().project_read(id=str(uuid.UUID(tenant_id)))
        vmi_obj = vnc_api.VirtualMachineInterface(
            name=self.properties[self.NAME], parent_obj=project_obj)
        vmi_obj.set_virtual_machine_interface_mac_addresses(
            vnc_api.MacAddressesType(
                self.properties[self.VIRTUAL_MACHINE_INTEFRACE_MAC_ADDRESSES]))
        for network in self.properties[self.VIRTUAL_NETWORKS]:
            try:
                vn_obj = self.vnc_lib().virtual_network_read(id=network)
            except vnc_api.NoIdError:
                vn_obj = self.vnc_lib().virtual_network_read(
                    fq_name_str=network)
            vmi_obj.add_virtual_network(vn_obj)

        for port_tuple in self.properties[self.PORT_TUPLES]:
            try:
                pt_obj = self.vnc_lib().port_tuple_read(id=port_tuple)
            except vnc_api.NoIdError:
                pt_obj = self.vnc_lib().port_tuple_read(fq_name_str=port_tuple)
            vmi_obj.add_port_tuple(pt_obj)
        vmi_props = vnc_api.VirtualMachineInterfacePropertiesType()
        vmi_props.set_service_interface_type(
            self.properties[self.SERVICE_INTERFACE_TYPE])
        vmi_obj.set_virtual_machine_interface_properties(vmi_props)
        vmi_uuid = super(HeatVirtualMachineInterface,
                         self).resource_create(vmi_obj)

        iip_obj = self._allocate_iip_for_family(vn_obj, pt_obj, vmi_obj, 'v4')
        iip_obj.add_virtual_machine_interface(vmi_obj)
        self.vnc_lib().instance_ip_update(iip_obj)

        self.resource_id_set(vmi_uuid)
示例#11
0
 def make_virtual_machine_interface(cls, name, network, properties,
                                    bindings, project):
     vmi = vnc_api.VirtualMachineInterface(name=name, parent_obj=project)
     vmi.set_id_perms(cls.ID_PERMS)
     vmi.add_virtual_network(network)
     vmi.set_virtual_machine_interface_properties(properties)
     vmi.set_virtual_machine_interface_bindings(bindings)
     return vmi
def vmi_1(project):
    vmi = vnc_api.VirtualMachineInterface(name="esxi-1_dvs-1_dpg-1",
                                          parent_obj=project)
    vmi.set_uuid(models.generate_uuid(vmi.name))
    vmi.set_id_perms(constants.ID_PERMS)
    vmi_properties = vnc_api.VirtualMachineInterfacePropertiesType(
        sub_interface_vlan_tag=5)
    vmi.set_virtual_machine_interface_properties(vmi_properties)
    return vmi
示例#13
0
 def _create_vnc_vmi_obj_with_new_vlan(self, new_vlan, old_vnc_vmi, vnc_vn):
     new_vnc_vmi = vnc_api.VirtualMachineInterface(
         name=old_vnc_vmi.name, parent_obj=self.get_project())
     new_vnc_vmi.set_uuid(old_vnc_vmi.uuid)
     new_vnc_vmi.add_virtual_network(vnc_vn)
     vmi_properties = vnc_api.VirtualMachineInterfacePropertiesType(
         sub_interface_vlan_tag=new_vlan)
     new_vnc_vmi.set_virtual_machine_interface_properties(vmi_properties)
     new_vnc_vmi.set_id_perms(const.ID_PERMS)
     return new_vnc_vmi
示例#14
0
文件: ppServer.py 项目: Inmarsat/tcc
def createVirtualMachineInterface(tenant, vnName, mac):
    project = vnc_client.project_read(fq_name_str = 'default-domain:' + tenant)
    vn = vnc_client.virtual_network_read(fq_name_str = 'default-domain:' + tenant + ':' + vnName)
    vmIntMac = { 'mac_address' : [ mac ] }
    vmIntUUID = str(uuid.uuid4())
    vmIntObj = vnc_api.VirtualMachineInterface(name = vmIntUUID, parent_obj = project, virtual_machine_interface_mac_addresses = vmIntMac)
    vmIntObj.set_virtual_network(vn)
    print vn.get_uuid()
    vmIntObjResult = vnc_client.virtual_machine_interface_create(vmIntObj)
    vmIntObj = vnc_client.virtual_machine_interface_read(id = vmIntObjResult)
    return vmIntObj
def vnc_vmi(project, vnc_vm, vnc_vn_1):
    vmi = vnc_api.VirtualMachineInterface('vnc-vmi-uuid', parent_obj=project)
    vmi.set_uuid('vnc-vmi-uuid')
    vmi.add_virtual_machine(vnc_vm)
    vmi.set_virtual_network(vnc_vn_1)
    vmi.set_annotations(
        vnc_api.KeyValuePairs([
            vnc_api.KeyValuePair('vrouter-uuid', 'vrouter-uuid-1'),
            vnc_api.KeyValuePair('key-1', 'value-1')
        ]))
    return vmi
示例#16
0
 def handle_create(self):
     tenant_id = self.stack.context.tenant_id
     project_obj = self.vnc_lib().project_read(id=str(uuid.UUID(tenant_id)))
     vmi_obj = vnc_api.VirtualMachineInterface(
         name=self.properties[self.NAME], parent_obj=project_obj)
     vmi_obj.set_virtual_machine_interface_mac_addresses(
         vnc_api.MacAddressesType(
             self.properties[self.VIRTUAL_MACHINE_INTEFRACE_MAC_ADDRESSES]))
     for network in self.properties[self.VIRTUAL_NETWORKS]:
         vn_obj = self.vnc_lib().virtual_network_read(id=network)
         vmi_obj.add_virtual_network(vn_obj)
     vmi_uuid = self.vnc_lib().virtual_machine_interface_create(vmi_obj)
     self.resource_id_set(vmi_uuid)
示例#17
0
    def to_vnc_vmi(self, project, fabric_vn):
        if fabric_vn is None:
            raise VNCVMICreationError(
                "Cannot create VNC VMI without a fabric VN.")

        vnc_vmi = vnc_api.VirtualMachineInterface(name=self.name,
                                                  parent_obj=project)
        vnc_vmi.set_uuid(self.uuid)
        vnc_vmi.add_virtual_network(fabric_vn)
        vmi_properties = vnc_api.VirtualMachineInterfacePropertiesType(
            sub_interface_vlan_tag=self.dpg_model.vlan_id)
        vnc_vmi.set_virtual_machine_interface_properties(vmi_properties)
        vnc_vmi.set_id_perms(const.ID_PERMS)
        return vnc_vmi
    def create(self, vnName, ipAddress, ipv6Address=None):
        interfaceName = 'veth' + self.vmName
        vm_instance = vnc_api.VirtualMachine(name=self.vmName)
        self.vnc_client.virtual_machine_create(vm_instance)
        vm_interface = vnc_api.VirtualMachineInterface(name=interfaceName,
                                                       parent_obj=vm_instance)
        vn = OpenContrailVN(vnName).VNget()
        vm_interface.set_virtual_network(vn)
        self.vnc_client.virtual_machine_interface_create(vm_interface)
        vm_interface = self.vnc_client.virtual_machine_interface_read(
            id=vm_interface.uuid)
        ipuuid = str(uuid.uuid4())
        ip = vnc_api.InstanceIp(name=ipuuid,
                                instance_ip_address=ipAddress.split('/')[0])
        ip.set_virtual_machine_interface(vm_interface)
        ip.set_virtual_network(vn)
        self.vnc_client.instance_ip_create(ip)

        mac = vm_interface.virtual_machine_interface_mac_addresses.mac_address[
            0]
        vrouterInterface = interfaceName + 'p0'

        if ipv6Address:
            ipv6uuid = str(uuid.uuid4())
            ipv6 = vnc_api.InstanceIp(
                name=ipv6uuid, instance_ip_address=ipv6Address.split('/')[0])
            ipv6.set_instance_ip_family('v6')
            ipv6.uuid = ipv6uuid
            ipv6.set_virtual_machine_interface(vm_interface)
            ipv6.set_virtual_network(vn)
            self.vnc_client.instance_ip_create(ipv6)
            ContrailVRouterApi().add_port(
                vm_instance.uuid,
                vm_interface.uuid,
                vrouterInterface,
                mac,
                display_name=vm_instance.name,
                vm_project_id=self.tenant.uuid,
                port_type='NovaVMPort',
                ip6_address=ipv6Address.split('/')[0])
        else:
            ContrailVRouterApi().add_port(vm_instance.uuid,
                                          vm_interface.uuid,
                                          vrouterInterface,
                                          mac,
                                          display_name=vm_instance.name,
                                          vm_project_id=self.tenant.uuid,
                                          port_type='NovaVMPort')
    def test_trunk_crud(self):
        vn = vnc_api.VirtualNetwork('vn-%s' % (self.id()))
        self._vnc_lib.virtual_network_create(vn)
        vmi_obj = vnc_api.VirtualMachineInterface('trunk-port',
                                                  parent_obj=self.project)
        vmi_obj.set_virtual_network(vn)
        vmi_id = self._vnc_lib.virtual_machine_interface_create(vmi_obj)

        context = {
            'operation': 'CREATE',
            'user_id': '',
            'is_admin': True,
            'roles': ''
        }
        data = {
            'resource': {
                'name': 'trunk-%s' % (self.id()),
                'tenant_id': self.project_id,
                'port_id': vmi_id
            }
        }
        body = {'context': context, 'data': data}
        # Create Trunk
        resp = self._api_svr_app.post_json('/neutron/trunk', body)
        trunk_dict = json.loads(resp.text)

        # Read Trunk
        trunk_read_dict = self.read_resource('trunk', trunk_dict['id'])
        self.assertEquals(trunk_dict['id'], trunk_read_dict['id'])

        # Update Trunk
        extra_res_fields = {'name': 'trunk_update'}
        trunk_update_dict = self.update_resource(
            'trunk',
            trunk_dict['id'],
            self.project_id,
            extra_res_fields=extra_res_fields)

        self.assertEquals(trunk_update_dict['name'], extra_res_fields['name'])

        # Delete Trunk
        self.delete_resource('trunk', self.project_id, trunk_dict['id'])

        # Clean the resources
        self._vnc_lib.virtual_machine_interface_delete(id=vmi_id)
        self._vnc_lib.virtual_network_delete(id=vn.uuid)
    def test_add_parent_port_to_another_trunk_negative(self):
        vn = vnc_api.VirtualNetwork('vn-%s' % (self.id()))
        self._vnc_lib.virtual_network_create(vn)
        vmi_obj = vnc_api.VirtualMachineInterface('trunk-port',
                                                  parent_obj=self.project)
        vmi_obj.set_virtual_network(vn)
        vmi_id = self._vnc_lib.virtual_machine_interface_create(vmi_obj)

        context = {
            'operation': 'CREATE',
            'user_id': '',
            'is_admin': True,
            'roles': ''
        }
        data = {
            'resource': {
                'name': 'trunk-%s' % (self.id()),
                'tenant_id': self.project_id,
                'port_id': vmi_id
            }
        }
        body = {'context': context, 'data': data}
        resp = self._api_svr_app.post_json('/neutron/trunk', body)
        trunk_dict = json.loads(resp.text)

        try:
            self.create_resource(
                'trunk',
                self.project_id,
                extra_res_fields={
                    'name': 'trunk-negative-%s' % (self.id()),
                    'tenant_id': self.project_id,
                    'port_id': vmi_id
                },
            ),
        except webtest.app.AppError as e:
            self.assertIsNot(re.search('TrunkPortInUse', str(e)), None)

        self.delete_resource('trunk', self.project_id, trunk_dict['id'])
        self._vnc_lib.virtual_machine_interface_delete(id=vmi_id)
    def test_trunk_add_and_delete_sub_ports(self):
        vn = vnc_api.VirtualNetwork('vn-%s' % (self.id()))
        self._vnc_lib.virtual_network_create(vn)
        vmi_obj = vnc_api.VirtualMachineInterface('trunk-port',
                                                  parent_obj=self.project)
        vmi_obj.set_virtual_network(vn)
        vmi_id = self._vnc_lib.virtual_machine_interface_create(vmi_obj)

        context = {
            'operation': 'CREATE',
            'user_id': '',
            'is_admin': True,
            'roles': ''
        }
        data = {
            'resource': {
                'name': 'trunk-%s' % (self.id()),
                'tenant_id': self.project_id,
                'port_id': vmi_id
            }
        }
        body = {'context': context, 'data': data}
        resp = self._api_svr_app.post_json('/neutron/trunk', body)
        trunk_dict = json.loads(resp.text)

        sub_port = vnc_api.VirtualMachineInterface('trunk-sub-port-%s' %
                                                   (self.id()),
                                                   parent_obj=self.project)
        vmi_prop = vnc_api.VirtualMachineInterfacePropertiesType(
            sub_interface_vlan_tag=10)
        sub_port.set_virtual_machine_interface_properties(vmi_prop)
        sub_port.set_virtual_network(vn)
        sub_port_id = self._vnc_lib.virtual_machine_interface_create(sub_port)

        neutron_trunk = self._add_subports(self.project_id, trunk_dict['id'],
                                           sub_port_id)
        self.assertEquals(neutron_trunk['sub_ports'][0].get('port_id'),
                          sub_port.uuid)

        sub_port_neg = vnc_api.VirtualMachineInterface(
            'trunk-sub-port-neg-%s' % (self.id()), parent_obj=self.project)
        sub_port_neg.set_virtual_network(vn)
        sub_port_id_neg = self._vnc_lib.virtual_machine_interface_create(
            sub_port_neg)
        # Adding sub port with the vlan tag that already exists in a trunk
        # should return an exception.
        try:
            self._add_subports(self.project_id,
                               trunk_dict['id'],
                               sub_port_id_neg,
                               vlan_tag=10)
        except webtest.app.AppError as e:
            self.assertIsNot(re.search('DuplicateSubPort', str(e)), None)

        neutron_trunk = self._remove_subports(self.project_id,
                                              trunk_dict['id'], sub_port_id)
        self.assertEquals(neutron_trunk['sub_ports'], [])
        # Clean the resources
        self.delete_resource('trunk', self.project_id, trunk_dict['id'])
        self._vnc_lib.virtual_machine_interface_delete(id=sub_port_id)
        self._vnc_lib.virtual_machine_interface_delete(id=sub_port_id_neg)
        self._vnc_lib.virtual_machine_interface_delete(id=vmi_id)
        self._vnc_lib.virtual_network_delete(id=vn.uuid)
    def create(self):
        """Create a vm and vmi, find or create a network, and attach
        the vmi to a new veth interface

        Arguments:

          vm_name   name of the vm to create
          net_name  name of the netwok to arrach to
          subnet    x.x.x.x/len - optional if network already exists
          netns     Network namespace where the veth interface is bound to.  Defaults to net_name    

        Returns:

          A dict with the following elements:
          
          port_id  uuid of port
          ip
          veth     name of veth interface
          netns    Network namespace where the veth interface is bound to
          
        """
        
        # remember what to clean up if things go wrong
        port_created = False
        veth_created = False
        netns_created = False
        ip_created = False
        vmi_created = False
        vnet_created = False
        vm_created = False

        try:
            # sanity check
            net_name = self.args.get('net_name')
            if not net_name:
                raise ValueError("Network name argument is required")

            # sanitize netns since it gets passed to the shell
            netns = self.args.get('netns')
            if not netns:
                netns = net_name
            if not re.match(r'^[-.\w]+$', netns):
                raise ValueError("netns=[%s] must be a valid namespace name"
                                 + " (a single word)" % netns)

            
            vnc_client = self.vnc_connect()

            proj_fq_name = self.args['project'].split(':')

            # find or create the VM
            vm_fq_name = proj_fq_name + [ self.args['vm_name'] ]

            # debug
            #import pdb; pdb.set_trace()

            try:
                vm = vnc_client.virtual_machine_read(fq_name = vm_fq_name)
                if vm:
                    raise ValueError(("Virtual machine named %s already exists."
                                      + "  Use --delete to delete it")
                                     % self.args['vm_name'])
            except vnc_api.NoIdError:
                # create vm if necessary
                vm = vnc_api.VirtualMachine(':'.join(vm_fq_name),
                                            fq_name=vm_fq_name)
                vnc_client.virtual_machine_create(vm)
                vm = vnc_client.virtual_machine_read(fq_name = vm_fq_name)
                vm_created = True
                
            # find or create the network
            vnet_fq_name = proj_fq_name + [ net_name ]
            vnet_created = False
            try:
                vnet = vnc_client.virtual_network_read(fq_name = vnet_fq_name)
            except vnc_api.NoIdError:
                # create the network if it doesn't exist
                vnet = vnc_api.VirtualNetwork(vnet_fq_name[-1],
                                              parent_type = 'project',
                                              fq_name = vnet_fq_name)

                # add a subnet
                ipam = vnc_client.network_ipam_read(
                    fq_name = ['default-domain',
                               'default-project',
                               'default-network-ipam'])
                (prefix, plen) = self.args['subnet'].split('/')
                subnet = vnc_api.IpamSubnetType(
                    subnet = vnc_api.SubnetType(prefix, int(plen)))
                vnet.add_network_ipam(ipam, vnc_api.VnSubnetsType([subnet]))

                vnc_client.virtual_network_create(vnet)
                vnet_created = True

            # find or create the vmi
            vmi_fq_name = vm.fq_name + ['0']
            vmi_created = False
            try:
                vmi = vnc_client.virtual_machine_interface_read(
                    fq_name = vmi_fq_name)
            except vnc_api.NoIdError:
                vmi = vnc_api.VirtualMachineInterface(
                    parent_type = 'virtual-machine',
                    fq_name = vmi_fq_name)
                vmi_created = True
            vmi.set_virtual_network(vnet)
            if vmi_created:
                vnc_client.virtual_machine_interface_create(vmi)
            else:
                vnc_client.virtual_machine_interface_update(vmi)
            # re-read the vmi to get its mac addresses
            vmi = vnc_client.virtual_machine_interface_read(
                fq_name = vmi_fq_name)
            # create an IP for the VMI if it doesn't already have one
            ips = vmi.get_instance_ip_back_refs()
            if not ips:
                ip = vnc_api.InstanceIp(vm.name + '.0')
                ip.set_virtual_machine_interface(vmi)
                ip.set_virtual_network(vnet)
                ip_created = vnc_client.instance_ip_create(ip)

            # Create the veth port.  Create a veth pair.  Put one end
            # in the VMI port and the other in a network namespace
            
            # get the ip, mac, and gateway from the vmi
            ip_uuid = vmi.get_instance_ip_back_refs()[0]['uuid']
            ip = vnc_client.instance_ip_read(id=ip_uuid).instance_ip_address
            mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
            subnet = vnet.network_ipam_refs[0]['attr'].ipam_subnets[0]
            gw = subnet.default_gateway
            dns = gw # KLUDGE - that's the default, but some networks
                     # have other DNS configurations
            ipnetaddr = netaddr.IPNetwork("%s/%s" %
                                          (subnet.subnet.ip_prefix,
                                           subnet.subnet.ip_prefix_len))
            
            # set up the veth pair with one part for vrouter and one
            # for the netns

            # find a name that's not already used in the default or
            # netns namespaces
            link_exists = link_exists_func('', netns)
            veth_vrouter = new_interface_name(suffix=vnet.uuid, prefix="ve1",
                                              exists_func=link_exists)
            veth_host = new_interface_name(suffix=vnet.uuid, prefix="ve0",
                                           exists_func=link_exists)
            
            sudo("ip link add %s type veth peer name %s",
                 (veth_vrouter, veth_host))
            veth_created = True
            try:
                sudo("ip netns add %s", (netns,))
                netns_created = True
            except ProcessExecutionError:
                pass
            
            sudo("ip link set %s netns %s",
                 (veth_host, netns))
            sudo("ip netns exec %s ip link set dev %s address %s",
                 (netns, veth_host, mac))
            sudo("ip netns exec %s ip address add %s broadcast %s dev %s",
                 (netns,
                  ("%s/%s" % (ip, subnet.subnet.ip_prefix_len)),
                  ipnetaddr.broadcast, veth_host))
            sudo("ip netns exec %s ip link set dev %s up",
                 (netns, veth_host))
            sudo("ip netns exec %s route add default gw %s dev %s",
                 (netns, gw, veth_host))
            sudo("ip link set dev %s up", (veth_vrouter,))

            # make a namespace-specific resolv.conf
            resolv_conf = "/etc/netns/%s/resolv.conf" % netns
            resolv_conf_body = "nameserver %s\n" % dns
            sudo("mkdir -p %s", (os.path.dirname(resolv_conf),))
            sudo("tee %s", (resolv_conf,), process_input=resolv_conf_body)

            # finally, create the Contrail port
            port = instance_service.ttypes.Port(
                uuid_from_string(vmi.uuid),
                uuid_from_string(vm.uuid), 
                veth_vrouter,
                ip,
                uuid_from_string(vnet.uuid),
                mac,
                )
            rpc = vrouter_rpc()
            rpc.AddPort([port])
            port_created = True
            
            return(dict(
                port_id = uuid_array_to_str(port.port_id),
                vm_id = vm.uuid,
                net_id = vnet.uuid,
                vmi_id = vmi.uuid,
                veth = veth_host,
                netns = netns,
                ip = ip,
                mac = mac,
                gw = gw,
                dns = dns,
                netmask = str(ipnetaddr.netmask),
                broadcast = str(ipnetaddr.broadcast),
                ))

        except:
            # something went wrong, clean up
            if port_created:
                rpc.DeletePort(port.port_id)
            if veth_created:
                sudo("ip link delete %s", (veth_vrouter,),
                     check_exit_code=False)
            if netns_created:
                sudo("ip netns delete %s", (netns,), check_exit_code=False)
            if ip_created:
                vnc_client.instance_ip_delete(id=ip_created)
            if vmi_created:
                vnc_client.virtual_machine_interface_delete(id=vmi.uuid)
            if vnet_created:
                vnc_client.virtual_network_delete(id=vnet.uuid)
            if vm_created:
                vnc_client.virtual_machine_delete(id=vm.uuid)
            raise
示例#23
0
    vnet.add_network_ipam(ipam, vnc_api.VnSubnetsType([subnet]))
    vnc.virtual_network_create(vnet)
finally:
    vnet = vnc.virtual_network_read(fq_name=vnet_fq_name)
    print "[INFO] VNET: %s fq_name: %s" % (net_name, vnet.fq_name)

# find or create the vminterface
print "=========>>> CREATE VM INTERFACE ... ..."
vmi_created = False
vmi_fq_name = vm_instance.fq_name + [vmi_name]
try:
    vm_interface = vnc.virtual_machine_interface_read(fq_name=vmi_fq_name)
    print "[SUCCESS] VM_Interface: %s Has Exsited!" % vmi_name
except vnc_api.NoIdError:
    print "[WARN] VM_Interface: %s Doesn't Exsit! Creating ... " % vmi_name
    vm_interface = vnc_api.VirtualMachineInterface(
        name=vmi_name, parent_type='virtual-machine', fq_name=vmi_fq_name)
    vmi_created = True
finally:
    vm_interface.set_virtual_network(vnet)
    if vmi_created:
        vnc.virtual_machine_interface_create(vm_interface)
    else:
        vnc.virtual_machine_interface_update(vm_interface)
    # re-read the vmi to get its mac addresses
    vm_interface = vnc.virtual_machine_interface_read(fq_name=vmi_fq_name)
    print "[INFO] VM_Ineterface: %s fq_name: %s" % (vmi_name,
                                                    vm_interface.fq_name)

# create an IP for the VMI if it doesn't already have one
print "=========>>> CONFIGURE VM INTERFACE IP INFO ... ..."
ips = vm_interface.get_instance_ip_back_refs()
示例#24
0
print ("Creating a VPG")
my_vpg=vnc_api.VirtualPortGroup(name='my-vpg',parent_obj=my_fab)
my_vpg.set_virtual_port_group_type('access')
obj_1 = vnc_api.VpgInterfaceParametersType()
for my_pi in my_pis:
    my_vpg.add_physical_interface(my_pi, obj_1)
my_vpg_id = vh.virtual_port_group_create(my_vpg)

if len(tag_list)!=len(my_vn_ids):
    print ("ERROR: There doesn't seem to be a correct mapping between VMIs and tags")

print ("Creating VMIs")
for my_vn_id in my_vn_ids:
    my_vn = vh.virtual_network_read(id=my_vn_id)
    vmi_name = 'vmi_' + str(my_vn_ids.index(my_vn_id))
    my_vmi=vnc_api.VirtualMachineInterface(name=vmi_name,parent_obj=my_proj)
    my_vmi.add_virtual_network(my_vn)
    kvps = vnc_api.KeyValuePairs()
    kvp = vnc_api.KeyValuePair()
    kvp.set_key("profile")
    lli = {"local_link_information": ''}    
    lli['local_link_information']=[]
    for pi in pi_list:
        switch=str(pi[0])
        phy_intf = str(pi[1])
        info_dict = {"port_id": '', "switch_id": '', "switch_info": '', "fabric": ''}
        info_dict['port_id']=str(phy_intf)
        info_dict['switch_id']=str(phy_intf)
        info_dict['switch_info']=str(switch)
        info_dict['fabric']=str(fabric_name)
        lli['local_link_information'].append(info_dict)