+ new_device_config = vim.VirtualDeviceConfigSpec(device=hba_object)
+ new_device_config.operation = "add"
+ vmConfigSpec = vim.vm.ConfigSpec()
+ vmConfigSpec.deviceChange = [new_device_config]
+
+ task = vm_object.ReconfigVM_Task(spec=vmConfigSpec)
+ self.logger.info("Adding PCI device {} into VM {} from host {} ".format(
+ host_pci_dev, vm_object, host_object)
+ )
+ except Exception as exp:
+ self.logger.error("Error occurred while adding pci devive {} to VM {}: {}".format(
+ host_pci_dev,
+ vm_object,
+ exp))
+ return task
+
+ def get_vm_vcenter_info(self , vapp_uuid):
+ """
+ Method to get details of vCenter and vm
+
+ Args:
+ vapp_uuid - uuid of vApp or VM
+
+ Returns:
+ Moref Id of VM and deails of vCenter
+ """
+ vm_vcenter_info = {}
+
+ if self.vcenter_ip is not None:
+ vm_vcenter_info["vm_vcenter_ip"] = self.vcenter_ip
+ else:
+ raise vimconn.vimconnException(message="vCenter IP is not provided."\
+ " Please provide vCenter IP while attaching datacenter to tenant in --config")
+ if self.vcenter_port is not None:
+ vm_vcenter_info["vm_vcenter_port"] = self.vcenter_port
+ else:
+ raise vimconn.vimconnException(message="vCenter port is not provided."\
+ " Please provide vCenter port while attaching datacenter to tenant in --config")
+ if self.vcenter_user is not None:
+ vm_vcenter_info["vm_vcenter_user"] = self.vcenter_user
+ else:
+ raise vimconn.vimconnException(message="vCenter user is not provided."\
+ " Please provide vCenter user while attaching datacenter to tenant in --config")
+
+ if self.vcenter_password is not None:
+ vm_vcenter_info["vm_vcenter_password"] = self.vcenter_password
+ else:
+ raise vimconn.vimconnException(message="vCenter user password is not provided."\
+ " Please provide vCenter user password while attaching datacenter to tenant in --config")
+ try:
+ vm_details = self.get_vapp_details_rest(vapp_uuid, need_admin_access=True)
+ if vm_details and "vm_vcenter_info" in vm_details:
+ vm_vcenter_info["vm_moref_id"] = vm_details["vm_vcenter_info"].get("vm_moref_id", None)
+
+ return vm_vcenter_info
+
+ except Exception as exp:
+ self.logger.error("Error occurred while getting vCenter infromationn"\
+ " for VM : {}".format(exp))
+
+
+ def get_vm_pci_details(self, vmuuid):
+ """
+ Method to get VM PCI device details from vCenter
+
+ Args:
+ vm_obj - vSphere VM object
+
+ Returns:
+ dict of PCI devives attached to VM
+
+ """
+ vm_pci_devices_info = {}
+ try:
+ vm_vcenter_info = self.get_vm_vcenter_info(vmuuid)
+ if vm_vcenter_info["vm_moref_id"]:
+ context = None
+ if hasattr(ssl, '_create_unverified_context'):
+ context = ssl._create_unverified_context()
+ vcenter_conect = SmartConnect(host=vm_vcenter_info["vm_vcenter_ip"],
+ user=vm_vcenter_info["vm_vcenter_user"],
+ pwd=vm_vcenter_info["vm_vcenter_password"],
+ port=int(vm_vcenter_info["vm_vcenter_port"]),
+ sslContext=context
+ )
+ atexit.register(Disconnect, vcenter_conect)
+ content = vcenter_conect.RetrieveContent()
+
+ #Get VM and its host
+ if content:
+ host_obj, vm_obj = self.get_vm_obj(content ,vm_vcenter_info["vm_moref_id"])
+ if host_obj and vm_obj:
+ vm_pci_devices_info["host_name"]= host_obj.name
+ vm_pci_devices_info["host_ip"]= host_obj.config.network.vnic[0].spec.ip.ipAddress
+ for device in vm_obj.config.hardware.device:
+ if type(device) == vim.vm.device.VirtualPCIPassthrough:
+ device_details={'devide_id':device.backing.id,
+ 'pciSlotNumber':device.slotInfo.pciSlotNumber,
+ }
+ vm_pci_devices_info[device.deviceInfo.label] = device_details
+ else:
+ self.logger.error("Can not connect to vCenter while getting "\
+ "PCI devices infromationn")
+ return vm_pci_devices_info
+ except Exception as exp:
+ self.logger.error("Error occurred while getting VM infromationn"\
+ " for VM : {}".format(exp))
+ raise vimconn.vimconnException(message=exp)
+
+ def add_network_adapter_to_vms(self, vapp, network_name, primary_nic_index, nicIndex, nic_type=None):
+ """
+ Method to add network adapter type to vm
+ Args :
+ network_name - name of network
+ primary_nic_index - int value for primary nic index
+ nicIndex - int value for nic index
+ nic_type - specify model name to which add to vm
+ Returns:
+ None
+ """
+ vca = self.connect()
+ if not vca:
+ raise vimconn.vimconnConnectionException("Failed to connect vCloud director")
+
+ try:
+ if not nic_type:
+ for vms in vapp._get_vms():
+ vm_id = (vms.id).split(':')[-1]
+
+ url_rest_call = "{}/api/vApp/vm-{}/networkConnectionSection/".format(vca.host, vm_id)
+
+ response = Http.get(url=url_rest_call,
+ headers=vca.vcloud_session.get_vcloud_headers(),
+ verify=vca.verify,
+ logger=vca.logger)
+ if response.status_code != 200:
+ self.logger.error("REST call {} failed reason : {}"\
+ "status code : {}".format(url_rest_call,
+ response.content,
+ response.status_code))
+ raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to get "\
+ "network connection section")
+
+ data = response.content
+ if '<PrimaryNetworkConnectionIndex>' not in data:
+ item = """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
+ <NetworkConnection network="{}">
+ <NetworkConnectionIndex>{}</NetworkConnectionIndex>
+ <IsConnected>true</IsConnected>
+ <IpAddressAllocationMode>DHCP</IpAddressAllocationMode>
+ </NetworkConnection>""".format(primary_nic_index, network_name, nicIndex)
+ data = data.replace('</ovf:Info>\n','</ovf:Info>\n{}\n'.format(item))
+ else:
+ new_item = """<NetworkConnection network="{}">
+ <NetworkConnectionIndex>{}</NetworkConnectionIndex>
+ <IsConnected>true</IsConnected>
+ <IpAddressAllocationMode>DHCP</IpAddressAllocationMode>
+ </NetworkConnection>""".format(network_name, nicIndex)
+ data = data.replace('</NetworkConnection>\n','</NetworkConnection>\n{}\n'.format(new_item))
+
+ headers = vca.vcloud_session.get_vcloud_headers()
+ headers['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
+ response = Http.put(url=url_rest_call, headers=headers, data=data,
+ verify=vca.verify,
+ logger=vca.logger)
+ if response.status_code != 202:
+ self.logger.error("REST call {} failed reason : {}"\
+ "status code : {} ".format(url_rest_call,
+ response.content,
+ response.status_code))
+ raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to update "\
+ "network connection section")
+ else:
+ nic_task = taskType.parseString(response.content, True)
+ if isinstance(nic_task, GenericTask):
+ vca.block_until_completed(nic_task)
+ self.logger.info("add_network_adapter_to_vms(): VM {} conneced to "\
+ "default NIC type".format(vm_id))
+ else:
+ self.logger.error("add_network_adapter_to_vms(): VM {} failed to "\
+ "connect NIC type".format(vm_id))
+ else:
+ for vms in vapp._get_vms():
+ vm_id = (vms.id).split(':')[-1]
+
+ url_rest_call = "{}/api/vApp/vm-{}/networkConnectionSection/".format(vca.host, vm_id)
+
+ response = Http.get(url=url_rest_call,
+ headers=vca.vcloud_session.get_vcloud_headers(),
+ verify=vca.verify,
+ logger=vca.logger)
+ if response.status_code != 200:
+ self.logger.error("REST call {} failed reason : {}"\
+ "status code : {}".format(url_rest_call,
+ response.content,
+ response.status_code))
+ raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to get "\
+ "network connection section")
+ data = response.content
+ if '<PrimaryNetworkConnectionIndex>' not in data:
+ item = """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
+ <NetworkConnection network="{}">
+ <NetworkConnectionIndex>{}</NetworkConnectionIndex>
+ <IsConnected>true</IsConnected>
+ <IpAddressAllocationMode>DHCP</IpAddressAllocationMode>
+ <NetworkAdapterType>{}</NetworkAdapterType>
+ </NetworkConnection>""".format(primary_nic_index, network_name, nicIndex, nic_type)
+ data = data.replace('</ovf:Info>\n','</ovf:Info>\n{}\n'.format(item))
+ else:
+ new_item = """<NetworkConnection network="{}">
+ <NetworkConnectionIndex>{}</NetworkConnectionIndex>
+ <IsConnected>true</IsConnected>
+ <IpAddressAllocationMode>DHCP</IpAddressAllocationMode>
+ <NetworkAdapterType>{}</NetworkAdapterType>
+ </NetworkConnection>""".format(network_name, nicIndex, nic_type)
+ data = data.replace('</NetworkConnection>\n','</NetworkConnection>\n{}\n'.format(new_item))
+
+ headers = vca.vcloud_session.get_vcloud_headers()
+ headers['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
+ response = Http.put(url=url_rest_call, headers=headers, data=data,
+ verify=vca.verify,
+ logger=vca.logger)
+
+ if response.status_code != 202:
+ self.logger.error("REST call {} failed reason : {}"\
+ "status code : {}".format(url_rest_call,
+ response.content,
+ response.status_code))
+ raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to update "\
+ "network connection section")
+ else:
+ nic_task = taskType.parseString(response.content, True)
+ if isinstance(nic_task, GenericTask):
+ vca.block_until_completed(nic_task)
+ self.logger.info("add_network_adapter_to_vms(): VM {} "\
+ "conneced to NIC type {}".format(vm_id, nic_type))
+ else:
+ self.logger.error("add_network_adapter_to_vms(): VM {} "\
+ "failed to connect NIC type {}".format(vm_id, nic_type))
+ except Exception as exp:
+ self.logger.error("add_network_adapter_to_vms() : exception occurred "\
+ "while adding Network adapter")
+ raise vimconn.vimconnException(message=exp)