Пример #1
0
    def run(self, vm_id, vm_name, power_onoff, vsphere=None):
        """
        Set power state of targetted virtual machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - power_onoff: Desired powerstate.

        Returns:
        - dict: State true/false
        """
        # check I have information to find a VM
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        if not vm:
            raise Exception('Error: Unable to find VM')
        if power_onoff == "poweroff":
            task = vm.PowerOffVM_Task()
        elif power_onoff == "poweron":
            task = vm.PowerOnVM_Task()
        while task.info.state == vim.TaskInfo.State.running:
            eventlet.sleep(1)
        return {'state': str(task.info.state)}
Пример #2
0
    def run(self, vm_id, vm_name, power_onoff, vsphere=None):
        """
        Set power state of targetted virtual machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - power_onoff: Desired powerstate.

        Returns:
        - dict: State true/false
        """
        # check I have information to find a VM
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id, name=vm_name)
        if not vm:
            raise Exception("Error: Unable to find VM")
        if power_onoff == "poweroff":
            task = vm.PowerOffVM_Task()
        elif power_onoff == "poweron":
            task = vm.PowerOnVM_Task()
        while task.info.state == vim.TaskInfo.State.running:
            eventlet.sleep(1)
        return {"state": str(task.info.state)}
Пример #3
0
    def run(self, vm_id, vm_name, cpu_edit, mem_edit, vsphere=None):
        """
        Edit CPU and/or Memory allocated to Virtual Machine

        Args:
        - vm_id: Moid of the virtual machine targetted (vm-xxxx)
        - vm_name: Name of Virtual Machine within vsphere
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - cpu_edit: Number of vCPUs to allocate
        - mem_edit: Ammount of memory to assign (GB)

        Returns:
        - state: success or failure
        """

        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        spec = vim.vm.ConfigSpec()
        if cpu_edit:
            spec.numCPUs = cpu_edit
        if mem_edit:
            spec.memoryMB = mem_edit * 1024

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #4
0
    def run(self, vm_id, vm_name, datastore_cluster, datastore, disk_size,
            provision_type):
        # ensure that minimal inputs are provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        spec = vim.vm.ConfigSpec()
        hdd_unit_number = self.get_next_unit_number(vm)
        ctrl_key = self.get_controller_key(vm)

        # Prepare new Disk configuration
        disk_changes = []
        disk_spec = vim.vm.device.VirtualDeviceSpec()
        disk_spec.fileOperation = "create"
        disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        disk_spec.device = vim.vm.device.VirtualDisk()
        disk_spec.device.backing =\
            vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
        disk_spec.device.backing.diskMode = "persistent"

        if provision_type == 'thin':
            disk_spec.device.backing.thinProvisioned = True

        disk_spec.device.unitNumber = hdd_unit_number
        disk_spec.device.capacityInKB = int(disk_size) * 1024 * 1024
        disk_spec.device.controllerKey = ctrl_key

        # If Datastore Cluster is provided attach Disk via that
        if datastore_cluster:
            ds_clust_obj = inventory.get_datastore_cluster(
                self.si_content, name=datastore_cluster)
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            srm = self.si_content.storageResourceManager

            storage_placement_spec = self.get_storage_placement_spec(
                ds_clust_obj, vm, spec)
            datastores = srm.RecommendDatastores(
                storageSpec=storage_placement_spec)

            if not datastores.recommendations:
                sys.stderr.write('Skipping as No datastore Recommendations')

            add_disk_task = srm.ApplyStorageDrsRecommendation_Task(
                datastores.recommendations[0].key)

        elif datastore:
            datastore_obj = inventory.get_datastore(self.si_content,
                                                    name=datastore)
            disk_spec.device.backing.datastore = datastore_obj
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)
        else:
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)

        successfully_added_disk = self._wait_for_task(add_disk_task)
        return {'state': successfully_added_disk}
Пример #5
0
    def run(self, vm_id, vm_name, vsphere=None):
        """
        Retrieve details for given Virtual Machines

        Args:
        - vm_id: Moid of Virtual Machine to retrieve
        - vm_name: Name of Virtual Machine to retrieve
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - string: Path to VM's containing folder ex: /dc.name/folder1/folder2
        """

        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)

        folder_name = ''
        # The parent of a VM is the Folder object that contains that VM
        parent = vm.parent
        while parent:
            folder_name = '/' + parent.name + folder_name
            if parent._wsdlName == "Datacenter":
                break
            parent = parent.parent

        return folder_name
Пример #6
0
    def run(self, vm_id, vm_name, vsphere=None):
        """
        Gets all the available controllers to be used

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - list: list of SCSI controllers
        """

        # VM name or ID given?
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # Create object for VM
        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)

        controllers = []
        for device in vm.config.hardware.device:
            if (isinstance(device, vim.vm.device.VirtualSCSIController) or
                    isinstance(device, vim.vm.device.ParaVirtualSCSIController)):
                controllers.append(device)

        return json.loads(json.dumps(controllers, cls=MyJSONEncoder))
Пример #7
0
    def run(self, vm_id, vm_name, datastore_cluster,
            datastore, disk_size, provision_type):
        # ensure that minimal inputs are provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        spec = vim.vm.ConfigSpec()
        hdd_unit_number = self.get_next_unit_number(vm)
        ctrl_key = self.get_controller_key(vm)

        # Prepare new Disk configuration
        disk_changes = []
        disk_spec = vim.vm.device.VirtualDeviceSpec()
        disk_spec.fileOperation = "create"
        disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        disk_spec.device = vim.vm.device.VirtualDisk()
        disk_spec.device.backing =\
            vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
        disk_spec.device.backing.diskMode = "persistent"

        if provision_type == 'thin':
            disk_spec.device.backing.thinProvisioned = True

        disk_spec.device.unitNumber = hdd_unit_number
        disk_spec.device.capacityInKB = int(disk_size) * 1024 * 1024
        disk_spec.device.controllerKey = ctrl_key

        # If Datastore Cluster is provided attach Disk via that
        if datastore_cluster:
            ds_clust_obj = inventory.get_datastore_cluster(
                self.si_content, name=datastore_cluster)
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            srm = self.si_content.storageResourceManager

            storage_placement_spec = self.get_storage_placement_spec(
                ds_clust_obj, vm, spec)
            datastores = srm.RecommendDatastores(
                storageSpec=storage_placement_spec)

            if not datastores.recommendations:
                sys.stderr.write('Skipping as No datastore Recommendations')

            add_disk_task = srm.ApplyStorageDrsRecommendation_Task(
                datastores.recommendations[0].key)

        elif datastore:
            datastore_obj = inventory.get_datastore(self.si_content,
                                                    name=datastore)
            disk_spec.device.backing.datastore = datastore_obj
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)
        else:
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)

        successfully_added_disk = self._wait_for_task(add_disk_task)
        return {'state': successfully_added_disk}
Пример #8
0
    def run(self, vm_id, vm_name, network_name,
            nictype, stayconnected, wakeonlan, vsphere=None):
        """
        Add Network Adapter to Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - network_name: vsphere network to connect to
        - nictype: Nic type to add
        - stayconnected: Nic connected on boot
        - wakeonlan: Wake on Lan

        Returns:
        - dict: state true/false
        """
        # create object itmes of key components
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        network_obj = inventory.get_network(self.si_content, name=network_name)

        vm_reconfig_spec = self.get_vm_reconfig_spec(network_obj,
                                                     stayconnected,
                                                     nictype,
                                                     wakeonlan)

        add_vnic_task = vm.ReconfigVM_Task(spec=vm_reconfig_spec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        return {'state': successfully_added_vnic}
Пример #9
0
    def run(self, vm_id, vm_name, cpu_edit, mem_edit, vsphere=None):
        """
        Edit CPU and/or Memory allocated to Virtual Machine

        Args:
        - vm_id: Moid of the virtual machine targetted (vm-xxxx)
        - vm_name: Name of Virtual Machine within vsphere
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - cpu_edit: Number of vCPUs to allocate
        - mem_edit: Ammount of memory to assign (GB)

        Returns:
        - state: success or failure
        """

        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        spec = vim.vm.ConfigSpec()
        if cpu_edit:
            spec.numCPUs = cpu_edit
        if mem_edit:
            spec.memoryMB = mem_edit * 1024

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #10
0
    def run(self, vm_name, vm_id, vsphere=None):
        """
        Create barebones VM (CPU/RAM/Graphics)

        Args:
        - vm_name: Name of Virtual Machine to detach ISO from
        - vm_id: ID of Virtual Machine to detach ISO from
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - dict: vm moid of newly created vm
        """
        # Setup Identifiers for objects
        self.establish_connection(vsphere)

        # checkinputs.vm_storage(datastore_cluster, datastore)
        checkinputs.one_of_two_strings(vm_name, vm_id,
                                       "Virtual Machine Name or ID")

        vm_obj = inventory.get_virtualmachine(self.si_content, name=vm_name)

        if vm_obj:
            cdrom_number = 1
            cdrom_prefix_label = 'CD/DVD drive '
            cdrom_label = cdrom_prefix_label + str(cdrom_number)
            virtual_cdrom_device = None
            attached, connected = None, None
            for dev in vm_obj.config.hardware.device:
                if isinstance(dev, vim.vm.device.VirtualCdrom
                              ) and dev.deviceInfo.label == cdrom_label:
                    virtual_cdrom_device = dev
                    if hasattr(dev.backing, 'fileName'):
                        if dev.backing.fileName:
                            attached = True
                        else:
                            attached = False
                    if hasattr(dev.connectable, 'connected'):
                        if dev.connectable.connected == True:
                            connected = True
                        else:
                            connected = False

            if not virtual_cdrom_device:
                return ({
                    'connected':
                    connected,
                    'attached':
                    attached,
                    'msg':
                    'Virtual {} could not be found.'.format(cdrom_label)
                })

            return ({'connected': connected, 'attached': attached})
    def run(self, vm_id, vm_name, controller_type, scsi_sharing, vsphere=None):
        """
        Add SCSI controller to Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - controller_type: Type of Controller to add
        - scsi_sharing: type of sharing for scsi adapter
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - dict: state true/false
        """

        # VM name or ID given?
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # Create object for VM
        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)

        # Create SCSI Controller Object
        configspec = vim.vm.ConfigSpec()
        scsictrl = vim.vm.device.VirtualDeviceSpec()
        scsictrl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

        # Select object type
        if controller_type == 'ParaVirtual':
            scsictrl.device = vim.vm.device.ParaVirtualSCSIController()
        elif controller_type == 'BusLogic':
            scsictrl.device = vim.vm.device.VirtualBusLogicController()
        elif controller_type == 'LSILogic':
            scsictrl.device = vim.vm.device.VirtualLsiLogicController()
        elif controller_type == 'LSILogicSAS':
            scsictrl.device = vim.vm.device.VirtualLsiLogicSASController()

        # Set SCSI Bus Sharing type
        if scsi_sharing == 'None':
            scsictrl.device.sharedBus = 'noSharing'
        elif scsi_sharing == 'Physical':
                        scsictrl.device.sharedBus = 'physicalSharing'
        elif scsi_sharing == 'Virtual':
                        scsictrl.device.sharedBus = 'virtualSharing'

        # Create Task to add to VM
        configspec.deviceChange = [scsictrl]
        add_ctrl_task = vm.ReconfigVM_Task(configspec)
        successfully_added_ctrl = self._wait_for_task(add_ctrl_task)

        return {'state': successfully_added_ctrl}
Пример #12
0
    def run(self, vm_id, vm_name, controller_type, scsi_sharing, vsphere=None):
        """
        Add SCSI controller to Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - controller_type: Type of Controller to add
        - scsi_sharing: type of sharing for scsi adapter
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - dict: state true/false
        """

        # VM name or ID given?
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # Create object for VM
        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)

        # Create SCSI Controller Object
        configspec = vim.vm.ConfigSpec()
        scsictrl = vim.vm.device.VirtualDeviceSpec()
        scsictrl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

        # Select object type
        if controller_type == 'ParaVirtual':
            scsictrl.device = vim.vm.device.ParaVirtualSCSIController()
        elif controller_type == 'BusLogic':
            scsictrl.device = vim.vm.device.VirtualBusLogicController()
        elif controller_type == 'LSILogic':
            scsictrl.device = vim.vm.device.VirtualLsiLogicController()
        elif controller_type == 'LSILogicSAS':
            scsictrl.device = vim.vm.device.VirtualLsiLogicSASController()

        # Set SCSI Bus Sharing type
        if scsi_sharing == 'None':
            scsictrl.device.sharedBus = 'noSharing'
        elif scsi_sharing == 'Physical':
            scsictrl.device.sharedBus = 'physicalSharing'
        elif scsi_sharing == 'Virtual':
            scsictrl.device.sharedBus = 'virtualSharing'

        # Create Task to add to VM
        configspec.deviceChange = [scsictrl]
        add_ctrl_task = vm.ReconfigVM_Task(configspec)
        successfully_added_ctrl = self._wait_for_task(add_ctrl_task)

        return {'state': successfully_added_ctrl}
Пример #13
0
 def run(self, vm_id, vm_name, power_onoff):
     # check I have information to find a VM
     checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
     # convert ids to stubs
     vm = inventory.get_virtualmachine(self.si_content,
                                       moid=vm_id, name=vm_name)
     if not vm:
         raise Exception('Error: Unable to find VM')
     if power_onoff == "poweroff":
         task = vm.PowerOffVM_Task()
     elif power_onoff == "poweron":
         task = vm.PowerOnVM_Task()
     while task.info.state == vim.TaskInfo.State.running:
         eventlet.sleep(1)
     return {'state': str(task.info.state)}
Пример #14
0
 def run(self, vm_id, vm_name, power_onoff):
     # check I have information to find a VM
     checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
     # convert ids to stubs
     vm = inventory.get_virtualmachine(self.si_content,
                                       moid=vm_id,
                                       name=vm_name)
     if not vm:
         raise Exception('Error: Unable to find VM')
     if power_onoff == "poweroff":
         task = vm.PowerOffVM_Task()
     elif power_onoff == "poweron":
         task = vm.PowerOnVM_Task()
     while task.info.state == vim.TaskInfo.State.running:
         eventlet.sleep(1)
     return {'state': str(task.info.state)}
Пример #15
0
    def run(self, vm_id, vm_name, network_name, nictype, stayconnected,
            wakeonlan):
        # create object itmes of key components
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        network_obj = inventory.get_network(self.si_content, name=network_name)

        vm_reconfig_spec = self.get_vm_reconfig_spec(network_obj,
                                                     stayconnected, nictype,
                                                     wakeonlan)

        add_vnic_task = vm.ReconfigVM_Task(spec=vm_reconfig_spec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        return {'state': successfully_added_vnic}
Пример #16
0
    def run(self,
            vm_id,
            vm_name,
            network_name,
            nictype,
            stayconnected,
            wakeonlan,
            vsphere=None):
        """
        Add Network Adapter to Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - network_name: vsphere network to connect to
        - nictype: Nic type to add
        - stayconnected: Nic connected on boot
        - wakeonlan: Wake on Lan

        Returns:
        - dict: state true/false
        """
        # create object itmes of key components
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)

        try:
            nettype = "dist"
            network_obj = inventory.get_distributedportgroup(self.si_content,
                                                             name=network_name)
        except:
            nettype = "std"
            network_obj = inventory.get_network(self.si_content,
                                                name=network_name)

        vm_reconfig_spec = self.get_vm_reconfig_spec(network_obj,
                                                     stayconnected, nictype,
                                                     wakeonlan, nettype)

        add_vnic_task = vm.ReconfigVM_Task(spec=vm_reconfig_spec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        return {'state': successfully_added_vnic}
Пример #17
0
    def run(self, vm_id, vm_name, cpu_edit, mem_edit):
        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        spec = vim.vm.ConfigSpec()
        if cpu_edit:
            spec.numCPUs = cpu_edit
        if mem_edit:
            spec.memoryMB = mem_edit * 1024

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #18
0
    def run(self, vm_id, vm_name, cpu_edit, mem_edit):
        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        spec = vim.vm.ConfigSpec()
        if cpu_edit:
            spec.numCPUs = cpu_edit
        if mem_edit:
            spec.memoryMB = mem_edit * 1024

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #19
0
    def run(self, vm_id, vm_name, network_name,
            nictype, stayconnected, wakeonlan):
        # create object itmes of key components
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        network_obj = inventory.get_network(self.si_content, name=network_name)

        vm_reconfig_spec = self.get_vm_reconfig_spec(network_obj,
                                                     stayconnected,
                                                     nictype,
                                                     wakeonlan)

        add_vnic_task = vm.ReconfigVM_Task(spec=vm_reconfig_spec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        return {'state': successfully_added_vnic}
Пример #20
0
    def run(self, vm_id, vm_name, network_adapter, network_name):
        # check means of finding the VM was provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        network_obj = inventory.get_network(self.si_content,
                                            name=network_name)

        # find correct NIC
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard)\
                    and device.deviceInfo.label == network_adapter:
                nic = device

        # Different test method due to fact that object
        # isn't instantiated if not found
        try:
            nic
        except:
            raise Exception('Unable to find Network Adapter provided')

        # Create object for new Specification
        new_spec = vim.vm.device.VirtualDeviceSpec()
        new_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        new_spec.device = nic

        # If network name provided assign new network
        # Room to expand the following to set additional flags/values
        if network_name:
            new_spec.device.backing.network = network_obj
            new_spec.device.backing.deviceName = network_obj.name
            new_spec.device.deviceInfo.summary = network_obj.name

        # format changes for config spec update
        dev_changes = []
        dev_changes.append(new_spec)
        spec = vim.vm.ConfigSpec()
        spec.deviceChange = dev_changes

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #21
0
    def run(self, vm_id, vm_name, vsphere=None):
        """
        Retrieve MOID of the virtual machine's containing resource pool

        Args:
        - vm_id: Moid of Virtual Machine to retrieve
        - vm_name: Name of Virtual Machine to retrieve
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - string: MOID of the VM's containing resource pool ex: resgroup-10
        """

        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)

        return vm.resourcePool.config.entity._moId
Пример #22
0
    def run(self, vm_id, vm_name, vsphere=None):
        """
        Retrieve a list of network names that the given VM is on

        Args:
        - vm_id: Moid of Virtual Machine to retrieve
        - vm_name: Name of Virtual Machine to retrieve
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - list: network names that the VM is connected to
        """

        # check a means of finding the VM has been provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)

        # return a list of network names that the VM is on
        return map(lambda x: x.name, vm.network)
    def run(self, vm_id, vm_name, controller_type, scsi_sharing):
        # VM name or ID given?
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        # Create object for VM
        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)

        # Create SCSI Controller Object
        configspec = vim.vm.ConfigSpec()
        scsictrl = vim.vm.device.VirtualDeviceSpec()
        scsictrl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

        # Select object type
        if controller_type == 'ParaVirtual':
            scsictrl.device = vim.vm.device.ParaVirtualSCSIController()
        elif controller_type == 'BusLogic':
            scsictrl.device = vim.vm.device.VirtualBusLogicController()
        elif controller_type == 'LSILogic':
            scsictrl.device = vim.vm.device.VirtualLsiLogicController()
        elif controller_type == 'LSILogicSAS':
            scsictrl.device = vim.vm.device.VirtualLsiLogicSASController()

        # Set SCSI Bus Sharing type
        if scsi_sharing == 'None':
            scsictrl.device.sharedBus = 'noSharing'
        elif scsi_sharing == 'Physical':
                        scsictrl.device.sharedBus = 'physicalSharing'
        elif scsi_sharing == 'Virtual':
                        scsictrl.device.sharedBus = 'virtualSharing'

        # Create Task to add to VM
        configspec.deviceChange = [scsictrl]
        add_ctrl_task = vm.ReconfigVM_Task(configspec)
        successfully_added_ctrl = self._wait_for_task(add_ctrl_task)

        return {'state': successfully_added_ctrl}
    def run(self, vm_id, vm_name, controller_type, scsi_sharing):
        # VM name or ID given?
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        # Create object for VM
        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)

        # Create SCSI Controller Object
        configspec = vim.vm.ConfigSpec()
        scsictrl = vim.vm.device.VirtualDeviceSpec()
        scsictrl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

        # Select object type
        if controller_type == 'ParaVirtual':
            scsictrl.device = vim.vm.device.ParaVirtualSCSIController()
        elif controller_type == 'BusLogic':
            scsictrl.device = vim.vm.device.VirtualBusLogicController()
        elif controller_type == 'LSILogic':
            scsictrl.device = vim.vm.device.VirtualLsiLogicController()
        elif controller_type == 'LSILogicSAS':
            scsictrl.device = vim.vm.device.VirtualLsiLogicSASController()

        # Set SCSI Bus Sharing type
        if scsi_sharing == 'None':
            scsictrl.device.sharedBus = 'noSharing'
        elif scsi_sharing == 'Physical':
            scsictrl.device.sharedBus = 'physicalSharing'
        elif scsi_sharing == 'Virtual':
            scsictrl.device.sharedBus = 'virtualSharing'

        # Create Task to add to VM
        configspec.deviceChange = [scsictrl]
        add_ctrl_task = vm.ReconfigVM_Task(configspec)
        successfully_added_ctrl = self._wait_for_task(add_ctrl_task)

        return {'state': successfully_added_ctrl}
Пример #25
0
    def run(self, vm_id, vm_name, cluster, vsphere=None):
        """
        Migrate VM to specified datastore

        Args:
        - vm_id: Moid of Virtual Machine to migrate
        - vm_name: Name of Virtual Machine to migrate
        - cluster: Cluster to which VM needs to be migrated to
        - vsphere: Pre-configured vsphere connection details (config.yaml)


        Returns:
        - dict: Success
        """
        # ensure that minimal inputs are provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        # Getting RID code from VM name
        rid = vm_name[:4]
        ds_size_list = []
        rp_usage_list = []
        dest_hosts = []
        foh_hosts = []

        cluster_container = inventory.get_managed_entities(self.si_content, vim.ClusterComputeResource)
        cluster_list = cluster_container.view
        cluster_container.Destroy()

        # iterate through clusters
        for cl in cluster_list:
            if cl.name == cluster:
                # Resource Pool
                # Checking if there is any failover hosts in the cluster
                # adding those to separate list, further it will be comapred
                # with hosts that are attached to matched datastore 
                if hasattr(cl.configuration.dasConfig.admissionControlPolicy, 'failoverHosts'):
                    for foh in cl.configuration.dasConfig.admissionControlPolicy.failoverHosts:
                        foh_hosts.append(foh)
                for rp in cl.resourcePool.resourcePool:
                    # Generating list of all available resource pools
                    # matching RID
                    if rp.name[:4] == rid:
                        overallUsage = rp.summary.runtime.memory.overallUsage + rp.summary.runtime.cpu.overallUsage
                        rp_usage_list.append((rp, overallUsage))
                # Datastore
                datastores = cl.datastore
                # iterate through datastores that
                # exists under specified cluster
                for datastore in datastores:
                    ds = datastore.summary
                    # take datastores that has proper RID
                    if ds.name[:4] == rid:
                        # getting hosts that are attached to datastore
                        # further those will be compared with FOH hosts
                        for h in datastore.host:
                            dest_hosts.append(h.key)
                        ds_size_list.append((ds.datastore, ds.freeSpace))
        
        # If list is empty, no storages found
        if len(ds_size_list) == 0:
            return (False, {'state': False, 'msg': 'No storages found in cluster {} for rid {}.'.format(cluster, rid)})

        ds_to_migrate_to = max(ds_size_list, key = lambda i : i[1])[0]

        # Checking target resource pool list
        if len(rp_usage_list) == 0:
            return (False, {'state': False, 'msg': 'No resource pools found in cluster {} for rid {}.'.format(cluster, rid)})

        rp_to_mirgate_to = min(rp_usage_list, key = lambda i : i[1])[0]

        # Determing to which host VM should be migrated to
        # on destination cluster
        ok_hosts = list(set(dest_hosts)^set(foh_hosts))
        dest_host = random.choice(ok_hosts)
        
        # Migrate VM only if datastores not matching destination one
        if ds_to_migrate_to not in vm.datastore:
            # Setting vm relocation specification
            vm_relocate_spec = vim.vm.RelocateSpec()
            vm_relocate_spec.host = dest_host
            vm_relocate_spec.pool = rp_to_mirgate_to
            vm_relocate_spec.datastore = ds_to_migrate_to
            # Performing actual migration
            relocate_vm = vm.Relocate(spec=vm_relocate_spec)
        # If VM is already on the same storage
        else:
            return (False, {'state': False, 'msg': 'VM is on proper datastore, will not migrate.'})

        successfully_relocated_vm = self._wait_for_task(relocate_vm)
        if successfully_relocated_vm != True:
            return (False, {'state': successfully_relocated_vm, 'msg': relocate_vm})
        else:
            return {
                    'state': successfully_relocated_vm, 
                    'dest_datastore': ds_to_migrate_to.name, 
                    'dest_cluster': cluster, 
                    'dest_resource_pool': rp_to_mirgate_to.name
                    }
Пример #26
0
    def run(self, vm_name, vm_id, answer=None, vsphere=None):
        """
        Create barebones VM (CPU/RAM/Graphics)

        Args:
        - vm_name: Name of Virtual Machine to detach ISO from
        - vm_id: ID of Virtual Machine to detach ISO from
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - dict: vm moid of newly created vm
        """
        # Setup Identifiers for objects
        self.establish_connection(vsphere)
        result, error = None, None
        # checkinputs.vm_storage(datastore_cluster, datastore)
        checkinputs.one_of_two_strings(vm_name, vm_id, "Virtual Machine Name or ID")

        vm_obj = inventory.get_virtualmachine(self.si_content, name=vm_name)

        # Setting answer value
        # Answers:
        # 0: button.yes
        # 1: button.no
        if answer:
            if answer == "Yes":
                qa = str(0)
            else:
                qa = str(1)

        if vm_obj:
            dev_changes = []

            cdrom_number = 1
            cdrom_prefix_label = 'CD/DVD drive '
            cdrom_label = cdrom_prefix_label + str(cdrom_number)
            virtual_cdrom_device = None
            for dev in vm_obj.config.hardware.device:
                if isinstance(dev, vim.vm.device.VirtualCdrom) and dev.deviceInfo.label == cdrom_label:
                    virtual_cdrom_device = dev
                    #print(dev)

            if not virtual_cdrom_device:
                error = ('Virtual {} could not be found.'.format(cdrom_label))

            virtual_cd_spec = vim.vm.device.VirtualDeviceSpec()
            virtual_cd_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
            virtual_cd_spec.device = vim.vm.device.VirtualCdrom()
            virtual_cd_spec.device.controllerKey = virtual_cdrom_device.controllerKey
            virtual_cd_spec.device.key = virtual_cdrom_device.key
            virtual_cd_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
            # Adding no CD
            virtual_cd_spec.device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo()
            # Allowing guest control
            virtual_cd_spec.device.connectable.allowGuestControl = True
            dev_changes.append(virtual_cd_spec)
            spec = vim.vm.ConfigSpec()
            spec.deviceChange = dev_changes
            remove_iso_task = vm_obj.ReconfigVM_Task(spec)

            while remove_iso_task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
                if vm_obj.runtime.question is not None:
                    for qm in vm_obj.runtime.question.message:
                        if qm.id == 'msg.cdromdisconnect.locked':
                            msg = qm.text
                            question_id = vm_obj.runtime.question.id
                            if answer:
                                if answer == "Yes":
                                    vm_obj.AnswerVM(question_id, qa)
                            else:
                                # Answering with No, to leave ISO connected
                                vm_obj.AnswerVM(question_id, str(1))
                # using time.sleep to wait for answer to be applied
                time.sleep(5)
            #print(remove_iso_task.info.state)
            if remove_iso_task.info.state == vim.TaskInfo.State.error:
                return (False, {'state': remove_iso_task.info.state, 'msg': msg})
            else:
                return {'state': remove_iso_task.info.state}
    def run(self,
            vm_id,
            vm_name,
            datastore_cluster,
            datastore,
            disk_size,
            provision_type,
            vsphere=None):
        """
        Add Hard Drive object to Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - datastore_cluster: Datastore Cluster to store new hdd files
        - datastore: Datastore to put new files in
        - disk_size: Sze of HDD in GB
        - provisioning_type: Type of Provisioning to use for HDD
        - vsphere: Pre-configured vsphere connection details (config.yaml)


        Returns:
        - dict: Success
        """
        # ensure that minimal inputs are provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        spec = vim.vm.ConfigSpec()
        hdd_unit_number = self.get_next_unit_number(vm)
        ctrl_key = self.get_controller_key(vm)

        # Prepare new Disk configuration
        disk_changes = []
        disk_spec = vim.vm.device.VirtualDeviceSpec()
        disk_spec.fileOperation = "create"
        disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        disk_spec.device = vim.vm.device.VirtualDisk()
        disk_spec.device.backing =\
            vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
        disk_spec.device.backing.diskMode = "persistent"

        if provision_type == 'thin':
            disk_spec.device.backing.thinProvisioned = True

        disk_spec.device.unitNumber = hdd_unit_number
        disk_spec.device.capacityInKB = int(disk_size) * 1024 * 1024
        disk_spec.device.controllerKey = ctrl_key

        # If Datastore Cluster is provided attach Disk via that
        if datastore_cluster:
            ds_clust_obj = inventory.get_datastore_cluster(
                self.si_content, name=datastore_cluster)
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            srm = self.si_content.storageResourceManager

            storage_placement_spec = self.get_storage_placement_spec(
                ds_clust_obj, vm, spec)
            datastores = srm.RecommendDatastores(
                storageSpec=storage_placement_spec)

            if not datastores.recommendations:
                sys.stderr.write('Skipping as No datastore Recommendations')

            add_disk_task = srm.ApplyStorageDrsRecommendation_Task(
                datastores.recommendations[0].key)

        elif datastore:
            datastore_obj = inventory.get_datastore(self.si_content,
                                                    name=datastore)
            disk_spec.device.backing.datastore = datastore_obj
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)
        else:
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)

        successfully_added_disk = self._wait_for_task(add_disk_task)
        return {'state': successfully_added_disk}
Пример #28
0
    def run(self, vm_id, vm_name, network_adapter, network_name, vsphere=None):
        """
        Edit Network Adapater on Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - network_name: Network to attach adapter to
        - network_adapter: Name of Adapter to edit

        Returns:
        - dict: State true/false
        """

        # check means of finding the VM was provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        try:
            nettype = "dist"
            network_obj = inventory.get_distributedportgroup(self.si_content,
                                                             name=network_name)
        except:
            nettype = "std"
            network_obj = inventory.get_network(self.si_content,
                                                name=network_name)

        # find correct NIC
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard)\
                    and device.deviceInfo.label == network_adapter:
                nic = device

        # Different test method due to fact that object
        # isn't instantiated if not found
        try:
            nic
        except:
            raise Exception('Unable to find Network Adapter provided')

        # Create object for new Specification
        new_spec = vim.vm.device.VirtualDeviceSpec()
        new_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        new_spec.device = nic

        # If network name provided assign new network
        # Room to expand the following to set additional flags/values
        if network_name:
            # Default functionality is to use the
            # Distributed Port Group over a standard group
            if nettype == "dist":
                new_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard\
                    .DistributedVirtualPortBackingInfo()
                new_spec.device.backing.port = vim.dvs.PortConnection()

                dvs_port_connection = vim.dvs.PortConnection()
                dvs_port_connection.portgroupKey = network_obj.key
                dvs_port_connection.switchUuid = \
                    network_obj.config.distributedVirtualSwitch.uuid

                new_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard\
                    .DistributedVirtualPortBackingInfo()
                new_spec.device.backing.port = dvs_port_connection
            else:
                new_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                new_spec.device.backing.network = network_obj
                new_spec.device.backing.deviceName = network_obj.name

        # format changes for config spec update
        dev_changes = []
        dev_changes.append(new_spec)
        spec = vim.vm.ConfigSpec()
        spec.deviceChange = dev_changes

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #29
0
    def run(self, vm_id, vm_name, datastore_cluster,
            datastore, disk_size, provision_type, vsphere=None):
        """
        Add Hard Drive object to Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - datastore_cluster: Datastore Cluster to store new hdd files
        - datastore: Datastore to put new files in
        - disk_size: Sze of HDD in GB
        - provisioning_type: Type of Provisioning to use for HDD
        - vsphere: Pre-configured vsphere connection details (config.yaml)


        Returns:
        - dict: Success
        """
        # ensure that minimal inputs are provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        spec = vim.vm.ConfigSpec()
        hdd_unit_number = self.get_next_unit_number(vm)
        ctrl_key = self.get_controller_key(vm)

        # Prepare new Disk configuration
        disk_changes = []
        disk_spec = vim.vm.device.VirtualDeviceSpec()
        disk_spec.fileOperation = "create"
        disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        disk_spec.device = vim.vm.device.VirtualDisk()
        disk_spec.device.backing =\
            vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
        disk_spec.device.backing.diskMode = "persistent"

        if provision_type == 'thin':
            disk_spec.device.backing.thinProvisioned = True

        disk_spec.device.unitNumber = hdd_unit_number
        disk_spec.device.capacityInKB = int(disk_size) * 1024 * 1024
        disk_spec.device.controllerKey = ctrl_key

        # If Datastore Cluster is provided attach Disk via that
        if datastore_cluster:
            ds_clust_obj = inventory.get_datastore_cluster(
                self.si_content, name=datastore_cluster)
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            srm = self.si_content.storageResourceManager

            storage_placement_spec = self.get_storage_placement_spec(
                ds_clust_obj, vm, spec)
            datastores = srm.RecommendDatastores(
                storageSpec=storage_placement_spec)

            if not datastores.recommendations:
                sys.stderr.write('Skipping as No datastore Recommendations')

            add_disk_task = srm.ApplyStorageDrsRecommendation_Task(
                datastores.recommendations[0].key)

        elif datastore:
            datastore_obj = inventory.get_datastore(self.si_content,
                                                    name=datastore)
            disk_spec.device.backing.datastore = datastore_obj
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)
        else:
            disk_changes.append(disk_spec)
            spec.deviceChange = disk_changes
            add_disk_task = vm.ReconfigVM_Task(spec)

        successfully_added_disk = self._wait_for_task(add_disk_task)
        return {'state': successfully_added_disk}
Пример #30
0
    def run(self, vm_name, cluster, datastore_cluster, datastore, resourcepool,
            cpu_size, ram_size, guestos, version, description):
        # Setup Identifiers for objects
        si = self.si
        si_content = si.RetrieveContent()
        # checkinputs.vm_storage(datastore_cluster, datastore)
        checkinputs.one_of_two_strings(datastore_cluster, datastore,
                                       "Datastore Cluster or Datastore")

        data_center = self.si_content.rootFolder.childEntity[0]
        cluster = inventory.get_cluster(self.si_content, name=cluster)
        data_store_cluster = inventory.get_datastore_cluster(
            self.si_content, name=datastore_cluster)
        # data_store = inventory.get_datastore(self.si_content, name=datastore)
        target_folder = data_center.vmFolder

        # If No Resource Pool issued the Default one for
        # the Cluster will be selected.
        if resourcepool:
            resource_pool = inventory.get_resource_pool(self.si_content,
                                                        name=resourcepool)
        else:
            resource_pool = cluster.resourcePool

        # Config created that is required for DS selection
        # Config is BareBones, CPU RAM no more.
        config = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=(ram_size * 1024),
                                   numCPUs=cpu_size,
                                   guestId=guestos,
                                   version=version,
                                   cpuHotAddEnabled=True,
                                   memoryHotAddEnabled=True,
                                   annotation=description)

        # if Datastore cluster is provided it will find the
        # recommended Datastore to store VM files
        if datastore_cluster:
            podsel = vim.storageDrs.PodSelectionSpec()
            podsel.storagePod = data_store_cluster

            storage_spec = vim.storageDrs.StoragePlacementSpec(
                type='create',
                configSpec=config,
                resourcePool=resource_pool,
                podSelectionSpec=podsel,
                folder=target_folder)

            # Create Instance of Storage Resource Manager -
            # This is used to identify a Recommended Datastore from a Cluster
            srm = si_content.storageResourceManager
            results = srm.RecommendDatastores(storageSpec=storage_spec)
            rec_ds = results.recommendations[0].action[0]\
                .relocateSpec.datastore
            datastore_path = '[' + rec_ds.name + '] ' + vm_name
        else:
            # No Datastore Cluster has been offered so using the D
            if datastore:
                datastore_path = '[' + datastore + '] ' + vm_name
            else:
                raise Exception('Error No Storage Data Provided')

        # Now Datastore is known the remaining
        # of VM Config can be setup and added
        vmx_file = vim.vm.FileInfo(logDirectory=None,
                                   snapshotDirectory=None,
                                   suspendDirectory=None,
                                   vmPathName=datastore_path)
        config.files = vmx_file

        # Create task to Build actual Machine
        task = target_folder.CreateVM_Task(config=config, pool=resource_pool)
        self._wait_for_task(task)
        if task.info.state != vim.TaskInfo.State.success:
            raise Exception(task.info.error.msg)

        return {'vm_id': task.info.result._moId}
Пример #31
0
    def run(self, vm_name, cluster, datastore_cluster,
            datastore, resourcepool, cpu_size, ram_size,
            guestos, version, description):
        # Setup Identifiers for objects
        si = self.si
        si_content = si.RetrieveContent()
        # checkinputs.vm_storage(datastore_cluster, datastore)
        checkinputs.one_of_two_strings(datastore_cluster,
                                       datastore,
                                       "Datastore Cluster or Datastore")

        data_center = self.si_content.rootFolder.childEntity[0]
        cluster = inventory.get_cluster(self.si_content, name=cluster)
        data_store_cluster = inventory.get_datastore_cluster(
            self.si_content,
            name=datastore_cluster)
        # data_store = inventory.get_datastore(self.si_content, name=datastore)
        target_folder = data_center.vmFolder

        # If No Resource Pool issued the Default one for
        # the Cluster will be selected.
        if resourcepool:
            resource_pool = inventory.get_resource_pool(self.si_content,
                                                        name=resourcepool)
        else:
            resource_pool = cluster.resourcePool

        # Config created that is required for DS selection
        # Config is BareBones, CPU RAM no more.
        config = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=(ram_size * 1024),
                                   numCPUs=cpu_size,
                                   guestId=guestos,
                                   version=version,
                                   cpuHotAddEnabled=True,
                                   memoryHotAddEnabled=True,
                                   annotation=description)

        # if Datastore cluster is provided it will find the
        # recommended Datastore to store VM files
        if datastore_cluster:
            podsel = vim.storageDrs.PodSelectionSpec()
            podsel.storagePod = data_store_cluster

            storage_spec = vim.storageDrs.StoragePlacementSpec(
                type='create',
                configSpec=config,
                resourcePool=resource_pool,
                podSelectionSpec=podsel,
                folder=target_folder)

            # Create Instance of Storage Resource Manager -
            # This is used to identify a Recommended Datastore from a Cluster
            srm = si_content.storageResourceManager
            results = srm.RecommendDatastores(storageSpec=storage_spec)
            rec_ds = results.recommendations[0].action[0]\
                .relocateSpec.datastore
            datastore_path = '[' + rec_ds.name + '] ' + vm_name
        else:
            # No Datastore Cluster has been offered so using the D
            if datastore:
                datastore_path = '[' + datastore + '] ' + vm_name
            else:
                raise Exception('Error No Storage Data Provided')

        # Now Datastore is known the remaining
        # of VM Config can be setup and added
        vmx_file = vim.vm.FileInfo(logDirectory=None,
                                   snapshotDirectory=None,
                                   suspendDirectory=None,
                                   vmPathName=datastore_path)
        config.files = vmx_file

        # Create task to Build actual Machine
        task = target_folder.CreateVM_Task(config=config, pool=resource_pool)
        self._wait_for_task(task)
        if task.info.state != vim.TaskInfo.State.success:
            raise Exception(task.info.error.msg)

        return {'vm_id': task.info.result._moId}
Пример #32
0
    def run(self, vm_id, vm_name, datastore_cluster, datastore, vsphere=None):
        """
        Migrate VM to specified datastore

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - datastore_cluster: Datastore Cluster to store new hdd files
        - datastore: Datastore to put new files in
        - vsphere: Pre-configured vsphere connection details (config.yaml)


        Returns:
        - dict: Success
        """
        # ensure that minimal inputs are provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, vm_id, vm_name)
        spec = vim.vm.ConfigSpec()
        #print(spec)
        disk_size = 0
        for device in vm.config.hardware.device:
            if hasattr(device.backing, 'fileName'):
                #print(device)
                disk_size += device.capacityInBytes
                #disk_size += device.capacityInKB
                #print(device.capacityInKB)
        ###print(disk_size)
        # If Datastore Cluster is provided attach Disk via that
        #if datastore_cluster:
        #    ds_clust_obj = inventory.get_datastore_cluster(
        #        self.si_content, name=datastore_cluster)
        #    disk_changes.append(disk_spec)
        #    spec.deviceChange = disk_changes
        #    srm = self.si_content.storageResourceManager
        #
        #    storage_placement_spec = self.get_storage_placement_spec(
        #        ds_clust_obj, vm, spec)
        #    datastores = srm.RecommendDatastores(
        #        storageSpec=storage_placement_spec)
        #
        #    if not datastores.recommendations:
        #        sys.stderr.write('Skipping as No datastore Recommendations')
        #
        #    add_disk_task = srm.ApplyStorageDrsRecommendation_Task(
        #        datastores.recommendations[0].key)
        #elif datastore:
        if datastore:
            datastore_obj = inventory.get_datastore(self.si_content,
                                                    name=datastore)
            relocate_spec = vim.vm.RelocateSpec(datastore=datastore_obj)
            relocate_vm = vm.Relocate(relocate_spec)

            summary = datastore_obj.summary
            if not disk_size * 2 < summary.freeSpace:
                return (False, {
                    'state':
                    False,
                    'msg':
                    'Datastore %s doesn\'t have enough free space.' %
                    summary.name
                })
        else:
            return {'state': 'Datastore not provided.'}

        successfully_relocated_vm = self._wait_for_task(relocate_vm)
        #print(relocate_vm)
        #print(successfully_relocated_vm)
        if successfully_relocated_vm != True:
            return (False, {
                'state': successfully_relocated_vm,
                'msg': relocate_vm
            })
        else:
            return {'state': successfully_relocated_vm}
Пример #33
0
    def run(self, vm_id, vm_name, network_adapter, network_name, vsphere=None):
        """
        Edit Network Adapater on Virtual Machine

        Args:
        - vm_id: Moid of Virtual Machine to edit
        - vm_name: Name of Virtual Machine to edit
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - network_name: Network to attach adapter to
        - network_adapter: Name of Adapter to edit

        Returns:
        - dict: State true/false
        """

        # check means of finding the VM was provided
        checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")

        self.establish_connection(vsphere)

        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content,
                                          moid=vm_id,
                                          name=vm_name)
        try:
            nettype = "dist"
            network_obj = inventory.get_distributedportgroup(self.si_content,
                                                             name=network_name)
        except:
            nettype = "std"
            network_obj = inventory.get_network(self.si_content,
                                                name=network_name)

        # find correct NIC
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard)\
                    and device.deviceInfo.label == network_adapter:
                nic = device

        # Different test method due to fact that object
        # isn't instantiated if not found
        try:
            nic
        except:
            raise Exception('Unable to find Network Adapter provided')

        # Create object for new Specification
        new_spec = vim.vm.device.VirtualDeviceSpec()
        new_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        new_spec.device = nic

        # If network name provided assign new network
        # Room to expand the following to set additional flags/values
        if network_name:
            # Default functionality is to use the
            # Distributed Port Group over a standard group
            if nettype == "dist":
                new_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard\
                    .DistributedVirtualPortBackingInfo()
                new_spec.device.backing.port = vim.dvs.PortConnection()

                dvs_port_connection = vim.dvs.PortConnection()
                dvs_port_connection.portgroupKey = network_obj.key
                dvs_port_connection.switchUuid = \
                    network_obj.config.distributedVirtualSwitch.uuid

                new_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard\
                    .DistributedVirtualPortBackingInfo()
                new_spec.device.backing.port = dvs_port_connection
            else:
                new_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                new_spec.device.backing.network = network_obj
                new_spec.device.backing.deviceName = network_obj.name

        # format changes for config spec update
        dev_changes = []
        dev_changes.append(new_spec)
        spec = vim.vm.ConfigSpec()
        spec.deviceChange = dev_changes

        task = vm.ReconfigVM_Task(spec)
        self._wait_for_task(task)

        return {'state': str(task.info.state)}
Пример #34
0
    def run(self, vm_name, cluster, datastore_cluster,
            datastore, resourcepool, cpu_size, ram_size,
            guestos, version, description, vsphere=None):
        """
        Create barebones VM (CPU/RAM/Graphics)

        Args:
        - vm_name: Name of Virtual Machine to create
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - description: Short Description of VM and it's purpose
        - cpu_size: Number of vCPUs to allocate
        - ram_size: Ammount of memory to assign (GB)
        - datastore_cluster: name of DataStore Cluster to use for VM Files
        - datastore: Individual datastore to put vm files within.
                     Not needed if datastore_cluster is set
        - cluster: Cluster within vsphere to host virtual machine
        - version: VM version to set
        - guestos: Code for GuestOS that will be installed on this VM
        - resourepool: vsphere resource pool to assign new VM to

        Returns:
        - dict: vm moid of newly created vm
        """
        # Setup Identifiers for objects
        self.establish_connection(vsphere)
        si = self.si
        si_content = si.RetrieveContent()
        # checkinputs.vm_storage(datastore_cluster, datastore)
        checkinputs.one_of_two_strings(datastore_cluster,
                                       datastore,
                                       "Datastore Cluster or Datastore")

        data_center = self.si_content.rootFolder.childEntity[0]
        cluster = inventory.get_cluster(self.si_content, name=cluster)
        data_store_cluster = inventory.get_datastore_cluster(
            self.si_content,
            name=datastore_cluster)
        # data_store = inventory.get_datastore(self.si_content, name=datastore)
        target_folder = data_center.vmFolder

        # If No Resource Pool issued the Default one for
        # the Cluster will be selected.
        if resourcepool:
            resource_pool = inventory.get_resource_pool(self.si_content,
                                                        name=resourcepool)
        else:
            resource_pool = cluster.resourcePool

        # Config created that is required for DS selection
        # Config is BareBones, CPU RAM no more.
        config = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=(ram_size * 1024),
                                   numCPUs=cpu_size,
                                   guestId=guestos,
                                   version=version,
                                   cpuHotAddEnabled=True,
                                   memoryHotAddEnabled=True,
                                   annotation=description)

        # if Datastore cluster is provided it will find the
        # recommended Datastore to store VM files
        if datastore_cluster:
            podsel = vim.storageDrs.PodSelectionSpec()
            podsel.storagePod = data_store_cluster

            storage_spec = vim.storageDrs.StoragePlacementSpec(
                type='create',
                configSpec=config,
                resourcePool=resource_pool,
                podSelectionSpec=podsel,
                folder=target_folder)

            # Create Instance of Storage Resource Manager -
            # This is used to identify a Recommended Datastore from a Cluster
            srm = si_content.storageResourceManager
            results = srm.RecommendDatastores(storageSpec=storage_spec)
            rec_ds = results.recommendations[0].action[0]\
                .relocateSpec.datastore
            datastore_path = '[' + rec_ds.name + '] ' + vm_name
        else:
            # No Datastore Cluster has been offered so using the D
            if datastore:
                datastore_path = '[' + datastore + '] ' + vm_name
            else:
                raise Exception('Error No Storage Data Provided')

        # Now Datastore is known the remaining
        # of VM Config can be setup and added
        vmx_file = vim.vm.FileInfo(logDirectory=None,
                                   snapshotDirectory=None,
                                   suspendDirectory=None,
                                   vmPathName=datastore_path)
        config.files = vmx_file

        # Create task to Build actual Machine
        task = target_folder.CreateVM_Task(config=config, pool=resource_pool)
        self._wait_for_task(task)
        if task.info.state != vim.TaskInfo.State.success:
            raise Exception(task.info.error.msg)

        return {'vm_id': task.info.result._moId}
Пример #35
0
    def run(self,
            vm_name,
            cluster,
            datastore_cluster,
            datastore,
            resourcepool,
            cpu_size,
            ram_size,
            guestos,
            version,
            description,
            vsphere=None):
        """
        Create barebones VM (CPU/RAM/Graphics)

        Args:
        - vm_name: Name of Virtual Machine to create
        - vsphere: Pre-configured vsphere connection details (config.yaml)
        - description: Short Description of VM and it's purpose
        - cpu_size: Number of vCPUs to allocate
        - ram_size: Ammount of memory to assign (GB)
        - datastore_cluster: name of DataStore Cluster to use for VM Files
        - datastore: Individual datastore to put vm files within.
                     Not needed if datastore_cluster is set
        - cluster: Cluster within vsphere to host virtual machine
        - version: VM version to set
        - guestos: Code for GuestOS that will be installed on this VM
        - resourepool: vsphere resource pool to assign new VM to

        Returns:
        - dict: vm moid of newly created vm
        """
        # Setup Identifiers for objects
        self.establish_connection(vsphere)
        si = self.si
        si_content = si.RetrieveContent()
        # checkinputs.vm_storage(datastore_cluster, datastore)
        checkinputs.one_of_two_strings(datastore_cluster, datastore,
                                       "Datastore Cluster or Datastore")

        data_center = self.si_content.rootFolder.childEntity[0]
        cluster = inventory.get_cluster(self.si_content, name=cluster)
        data_store_cluster = inventory.get_datastore_cluster(
            self.si_content, name=datastore_cluster)
        # data_store = inventory.get_datastore(self.si_content, name=datastore)
        target_folder = data_center.vmFolder

        # If No Resource Pool issued the Default one for
        # the Cluster will be selected.
        if resourcepool:
            resource_pool = inventory.get_resource_pool(self.si_content,
                                                        name=resourcepool)
        else:
            resource_pool = cluster.resourcePool

        # Config created that is required for DS selection
        # Config is BareBones, CPU RAM no more.
        config = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=(ram_size * 1024),
                                   numCPUs=cpu_size,
                                   guestId=guestos,
                                   version=version,
                                   cpuHotAddEnabled=True,
                                   memoryHotAddEnabled=True,
                                   annotation=description)

        # if Datastore cluster is provided it will find the
        # recommended Datastore to store VM files
        if datastore_cluster:
            podsel = vim.storageDrs.PodSelectionSpec()
            podsel.storagePod = data_store_cluster

            storage_spec = vim.storageDrs.StoragePlacementSpec(
                type='create',
                configSpec=config,
                resourcePool=resource_pool,
                podSelectionSpec=podsel,
                folder=target_folder)

            # Create Instance of Storage Resource Manager -
            # This is used to identify a Recommended Datastore from a Cluster
            srm = si_content.storageResourceManager
            results = srm.RecommendDatastores(storageSpec=storage_spec)
            rec_ds = results.recommendations[0].action[0]\
                .relocateSpec.datastore
            datastore_path = '[' + rec_ds.name + '] ' + vm_name
        else:
            # No Datastore Cluster has been offered so using the D
            if datastore:
                datastore_path = '[' + datastore + '] ' + vm_name
            else:
                raise Exception('Error No Storage Data Provided')

        # Now Datastore is known the remaining
        # of VM Config can be setup and added
        vmx_file = vim.vm.FileInfo(logDirectory=None,
                                   snapshotDirectory=None,
                                   suspendDirectory=None,
                                   vmPathName=datastore_path)
        config.files = vmx_file

        # Create task to Build actual Machine
        task = target_folder.CreateVM_Task(config=config, pool=resource_pool)
        self._wait_for_task(task)
        if task.info.state != vim.TaskInfo.State.success:
            raise Exception(task.info.error.msg)

        return {'vm_id': task.info.result._moId}