Esempio n. 1
0
    def run(self, vm_ids, vm_names, vsphere=None):
        """
        Retrieve UUID for specified 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)

        Returns:
        - dict: uuid values.
        """
        results = []
        if not vm_ids and not vm_names:
            raise ValueError("No ID nor Names provided")

        self.establish_connection(vsphere)

        if vm_ids:
            for vm in vm_ids:
                vm = inventory.get_virtualmachine(self.si_content, moid=vm)
                if vm:
                    if vm.summary.config.uuid not in results:
                        results.append(vm.summary.config.uuid)
        if vm_names:
            for vm in vm_names:
                vm = inventory.get_virtualmachine(self.si_content, name=vm)
                if vm:
                    if vm.summary.config.uuid not in results:
                        results.append(vm.summary.config.uuid)
        return results
Esempio n. 2
0
    def run(self, vm_ids, vm_names, vsphere=None):
        """
        Retrieve details for given Virtual Machines

        Args:
        - vm_ids: Moid of Virtual Machines to retrieve
        - vm_names: Name of Virtual Machines to retrieve
        - vsphere: Pre-configured vsphere connection details (config.yaml)


        Returns:
        - dict: Virtual machine details.
        """

        # TODO review using propertspec for retrieving all VM's at onces.
        results = {}
        if not vm_ids and not vm_names:
            raise ValueError("No IDs nor Names provided.")

        self.establish_connection(vsphere)

        if vm_ids:
            for vid in vm_ids:
                vm = inventory.get_virtualmachine(self.si_content, moid=vid)
                if vm:
                    if vm.name not in results:
                        results[vm.name] = vm.summary
        if vm_names:
            for vm in vm_names:
                vm = inventory.get_virtualmachine(self.si_content, name=vm)
                if vm:
                    if vm.name not in results:
                        results[vm.name] = vm.summary
        return results
Esempio n. 3
0
    def run(self, vm_ids, vm_names, vsphere=None):
        """
        Retrieve UUID for specified 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)

        Returns:
        - dict: uuid values.
        """
        results = []
        if not vm_ids and not vm_names:
            raise ValueError("No ID nor Names provided")

        self.establish_connection(vsphere)

        if vm_ids:
            for vm in vm_ids:
                vm = inventory.get_virtualmachine(self.si_content, moid=vm)
                if vm:
                    if vm.summary.config.uuid not in results:
                        results.append(vm.summary.config.uuid)
        if vm_names:
            for vm in vm_names:
                vm = inventory.get_virtualmachine(self.si_content, name=vm)
                if vm:
                    if vm.summary.config.uuid not in results:
                        results.append(vm.summary.config.uuid)
        return results
Esempio n. 4
0
    def get_by_id_or_name(self, template_ids=[], template_names=[]):
        results = {}

        for tid in template_ids:
            template = inventory.get_virtualmachine(self.si_content, moid=tid)
            if template and template.config.template and template.name not in results:
                results[template.name] = self.get_template_dict(template)

        for template in template_names:
            template = inventory.get_virtualmachine(self.si_content,
                                                    name=template)
            if template and template.config.template and template.name not in results:
                results[template.name] = self.get_template_dict(template)

        return list(results.values())
Esempio n. 5
0
    def run(self, vm_id, vsphere=None):
        self.establish_connection(vsphere)
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)

        # Get current Tools config information
        # Decode the vmware object type into json format
        return_value = json.loads(
            json.dumps(vm.config.tools, cls=MyJSONEncoder))

        # To correctly understand tools status need to consult 3 properties
        # 'powerState' 'toolsVersionStatus2' and 'toolsRunningStatus'

        # If VM isn't powered on tools state is meaningless.
        if vm.runtime.powerState != vim.VirtualMachine.PowerState.poweredOn:
            return_value['status'] = vm.runtime.powerState
            return return_value

        # Tools not installed.
        if vm.guest.toolsVersionStatus2 == \
           vim.vm.GuestInfo.ToolsVersionStatus.guestToolsNotInstalled:
            return_value['status'] = vm.guest.toolsVersionStatus2
            return return_value

        # Scripts still running therefore wait.
        while vm.guest.toolsRunningStatus != \
                vim.vm.GuestInfo.ToolsRunningStatus.guestToolsRunning:
            eventlet.sleep(1)

        # verify status is running.
        return_value['status'] = vm.guest.toolsRunningStatus
        return return_value
Esempio n. 6
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}
    def run(self, vm_id, vm_name, flat, vsphere=None):
        """
        Display snapshots

        Args:
        - vm_id: Moid of Virtual Machine to retrieve
        - vm_name: Name of Virtual Machine to retrieve
        - flat: When True, returns a flattened list of snapshots.
                When False, returns the snapshots tree
        - vsphere: Pre-configured vsphere connection details (config.yaml)

        Returns:
        - dict: Total snapshots size in GB
        - dict: Lists of snapshots found
        """
        self.establish_connection(vsphere)

        # If a VM ID or name was given then only remove snapshots from that VM
        if vm_id or vm_name:
            vm = inventory.get_virtualmachine(self.si_content,
                                              moid=vm_id,
                                              name=vm_name)

            # Check if any snapshots exist on the VM
            try:
                snapshots = vm.snapshot.rootSnapshotList
            except:
                return "No snapshots found for VM: {}".format(vm.name)

            return {
                'size_gb': self.get_snapshots_size_gb(vm),
                'snapshots': self.get_snapshots_details(snapshots, flat)
            }
Esempio n. 8
0
    def run(self, vm_id, delete_permanently, vsphere=None):
        """
        Remove virtual machine from vsphere

        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)
        - delete_permenantly: Delete files as well as unregister from vsphere

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

        self.establish_connection(vsphere)

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

        if vm.runtime.powerState == vim.VirtualMachine.PowerState.poweredOn:
            raise Exception("VM Currently Powered On")
        if delete_permanently:
            task = vm.Destroy_Task()
            success = self._wait_for_task(task)
        else:
            vm.UnregisterVM()
            success = True

        return {"success": success}
    def run(self, name, template_id, datacenter_id, resourcepool_id,
            datastore_id, vsphere=None):
        self.establish_connection(vsphere)

        # convert ids to stubs
        template = inventory.get_virtualmachine(self.si_content, template_id)
        datacenter = inventory.get_datacenter(self.si_content, datacenter_id)
        resourcepool = inventory.get_resource_pool(self.si_content,
                                                   resourcepool_id)
        datastore = inventory.get_datastore(self.si_content, datastore_id)
        # prep objects for consumption
        target_folder = datacenter.vmFolder

        # relocate spec
        relocatespec = vim.vm.RelocateSpec()
        relocatespec.datastore = datastore
        relocatespec.pool = resourcepool

        # clone spec
        clonespec = vim.vm.CloneSpec()
        clonespec.location = relocatespec
        clonespec.powerOn = False
        clonespec.template = False

        task = template.CloneVM_Task(folder=target_folder, name=name,
                                     spec=clonespec)
        self._wait_for_task(task)
        if task.info.state != vim.TaskInfo.State.success:
            raise Exception(task.info.error.msg)

        return {'task_id': task._moId, 'vm_id': task.info.result._moId}
Esempio n. 10
0
    def run(self, vm_id, delete_permanently, vsphere=None):
        """
        Remove virtual machine from vsphere

        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)
        - delete_permenantly: Delete files as well as unregister from vsphere

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

        self.establish_connection(vsphere)

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

        if vm.runtime.powerState == vim.VirtualMachine.PowerState.poweredOn:
            raise Exception("VM Currently Powered On")
        if delete_permanently:
            task = vm.Destroy_Task()
            success = self._wait_for_task(task)
        else:
            vm.UnregisterVM()
            success = True

        return {"success": success}
Esempio n. 11
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)}
    def run(self, name, template_id, datacenter_id, resourcepool_id, datastore_id):
        # convert ids to stubs
        template = inventory.get_virtualmachine(self.service_instance, template_id)
        datacenter = inventory.get_datacenter(self.service_instance, datacenter_id)
        resourcepool = inventory.get_resource_pool(self.service_instance, resourcepool_id)
        datastore = inventory.get_datastore(self.service_instance, datastore_id)
        # prep objects for consumption
        target_folder = datacenter.vmFolder

        # relocate spec
        relocatespec = vim.vm.RelocateSpec()
        relocatespec.datastore = datastore
        relocatespec.pool = resourcepool

        # clone spec
        clonespec = vim.vm.CloneSpec()
        clonespec.location = relocatespec
        clonespec.powerOn = False
        clonespec.template = False

        task = template.CloneVM_Task(folder=target_folder, name=name, spec=clonespec)
        self._wait_for_task(task)
        if task.info.state != vim.TaskInfo.State.success:
            raise Exception(task.info.error.msg)

        return {'task_id': task._moId, 'vm_id': task.info.result._moId}
Esempio n. 13
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}
Esempio n. 14
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}
Esempio n. 15
0
 def run(self, vm_id):
     # convert ids to stubs
     vm = inventory.get_virtualmachine(self.service_instance, moid=vm_id)
     task = vm.PowerOnVM_Task(None)
     while task.info.state == vim.TaskInfo.State.running:
         eventlet.sleep(1)
     return {'state': str(task.info.state)}
Esempio n. 16
0
 def run(self, vm_id):
     # convert ids to stubs
     vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)
     task = vm.PowerOffVM_Task()
     while task.info.state == vim.TaskInfo.State.running:
         eventlet.sleep(1)
     return task.info.state == vim.TaskInfo.State.success
Esempio n. 17
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)}
Esempio n. 18
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))
Esempio n. 19
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)}
Esempio n. 20
0
    def run(self, vm_id, network_id, ip, subnet, gateway=None, domain=None):
        # convert ids to stubs
        virtualmachine = inventory.get_virtualmachine(self.service_instance, vm_id)
        network = inventory.get_network(self.service_instance, network_id)

        # add new vnic
        configspec = vim.vm.ConfigSpec()
        nic = vim.vm.device.VirtualDeviceSpec()
        nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add  # or edit if a device exists
        nic.device = vim.vm.device.VirtualVmxnet3()
        nic.device.wakeOnLanEnabled = True
        nic.device.addressType = 'assigned'
        # docs recommend using unique negative integers as temporary keys.
        # See https://github.com/vmware/pyvmomi/blob/master/docs/vim/vm/device/VirtualDevice.rst
        nic.device.key = -1
        nic.device.deviceInfo = vim.Description()
        nic.device.deviceInfo.label = 'Network Adapter-%s' % (ip)
        nic.device.deviceInfo.summary = 'summary'
        nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
        nic.device.backing.port = vim.dvs.PortConnection()
        nic.device.backing.port.switchUuid = network.config.distributedVirtualSwitch.uuid
        nic.device.backing.port.portgroupKey = network.config.key
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic.device.connectable.startConnected = True
        nic.device.connectable.allowGuestControl = True
        configspec.deviceChange = [nic]
        add_vnic_task = virtualmachine.ReconfigVM_Task(configspec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        # customize VM
        cust_item = vim.CustomizationSpecItem()
        cust_specinfo = vim.CustomizationSpecInfo()
        cust_specinfo.name = 'assignip-' + str(uuid.uuid4())
        cust_specinfo.type = 'Linux'
        cust_item.info = cust_specinfo

        # fixed ip
        cust_spec = vim.vm.customization.Specification()
        cust_item.spec = cust_spec
        ip_adapter_mapping = vim.vm.customization.AdapterMapping()
        ip_adapter_mapping.adapter = vim.vm.customization.IPSettings()
        ip_adapter_mapping.adapter.ip = vim.vm.customization.FixedIp()
        ip_adapter_mapping.adapter.ip.ipAddress = ip
        ip_adapter_mapping.adapter.subnetMask = subnet
        ip_adapter_mapping.adapter.gateway = gateway
        ip_adapter_mapping.adapter.dnsDomain = domain
        cust_spec.nicSettingMap = [ip_adapter_mapping]
        cust_spec.identity = vim.vm.customization.LinuxPrep()
        cust_spec.identity.hostName = vim.vm.customization.PrefixNameGenerator()
        cust_spec.identity.hostName.base = 'st2'
        cust_spec.identity.domain = 'demo.net'
        cust_spec.globalIPSettings = vim.vm.customization.GlobalIPSettings()

        try:
            self.service_instance.customizationSpecManager.CreateCustomizationSpec(cust_item)
        except:
            self.logger.exception('Failed to create customization spec.')
            raise

        return {'state': successfully_added_vnic}
Esempio n. 21
0
 def run(self, vm_id):
     # convert ids to stubs
     vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)
     task = vm.PowerOffVM_Task()
     while task.info.state == vim.TaskInfo.State.running:
         eventlet.sleep(1)
     return task.info.state == vim.TaskInfo.State.success
Esempio n. 22
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
Esempio n. 23
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)}
Esempio n. 24
0
    def run(self, vm_id, network_id, ip, subnet, gateway=None, domain=None):
        # convert ids to stubs
        virtualmachine = inventory.get_virtualmachine(self.si_content, vm_id)
        network = inventory.get_network(self.si_content, network_id)

        # add new vnic
        configspec = vim.vm.ConfigSpec()
        nic = vim.vm.device.VirtualDeviceSpec()
        nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add  # or edit if a device exists
        nic.device = vim.vm.device.VirtualVmxnet3()
        nic.device.wakeOnLanEnabled = True
        nic.device.addressType = 'assigned'
        # docs recommend using unique negative integers as temporary keys.
        # See https://github.com/vmware/pyvmomi/blob/master/docs/vim/vm/device/VirtualDevice.rst
        nic.device.key = -1
        nic.device.deviceInfo = vim.Description()
        nic.device.deviceInfo.label = 'Network Adapter-%s' % (ip)
        nic.device.deviceInfo.summary = 'summary'
        nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
        nic.device.backing.port = vim.dvs.PortConnection()
        nic.device.backing.port.switchUuid = network.config.distributedVirtualSwitch.uuid
        nic.device.backing.port.portgroupKey = network.config.key
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic.device.connectable.startConnected = True
        nic.device.connectable.allowGuestControl = True
        configspec.deviceChange = [nic]
        add_vnic_task = virtualmachine.ReconfigVM_Task(configspec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        # customize VM
        cust_item = vim.CustomizationSpecItem()
        cust_specinfo = vim.CustomizationSpecInfo()
        cust_specinfo.name = 'assignip-' + str(uuid.uuid4())
        cust_specinfo.type = 'Linux'
        cust_item.info = cust_specinfo

        # fixed ip
        cust_spec = vim.vm.customization.Specification()
        cust_item.spec = cust_spec
        ip_adapter_mapping = vim.vm.customization.AdapterMapping()
        ip_adapter_mapping.adapter = vim.vm.customization.IPSettings()
        ip_adapter_mapping.adapter.ip = vim.vm.customization.FixedIp()
        ip_adapter_mapping.adapter.ip.ipAddress = ip
        ip_adapter_mapping.adapter.subnetMask = subnet
        ip_adapter_mapping.adapter.gateway = gateway
        ip_adapter_mapping.adapter.dnsDomain = domain
        cust_spec.nicSettingMap = [ip_adapter_mapping]
        cust_spec.identity = vim.vm.customization.LinuxPrep()
        cust_spec.identity.hostName = vim.vm.customization.PrefixNameGenerator()
        cust_spec.identity.hostName.base = 'st2'
        cust_spec.identity.domain = 'demo.net'
        cust_spec.globalIPSettings = vim.vm.customization.GlobalIPSettings()

        try:
            self.si_content.customizationSpecManager.CreateCustomizationSpec(cust_item)
        except:
            self.logger.exception('Failed to create customization spec.')
            raise

        return {'state': successfully_added_vnic}
Esempio n. 25
0
    def run(self, vm_id, network_id, vnic_key, ip, subnet, gateway=None, domain=None):
        # convert ids to stubs
        virtualmachine = inventory.get_virtualmachine(self.si_content, vm_id)
        network = inventory.get_network(self.si_content, network_id)
        vnic = self._get_vnic_device(virtualmachine, vnic_key)

        # add new vnic
        configspec = vim.vm.ConfigSpec()
        nic = vim.vm.device.VirtualDeviceSpec()
        nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        nic.device = vim.vm.device.VirtualVmxnet3()
        nic.device.wakeOnLanEnabled = True
        nic.device.addressType = 'assigned'
        nic.device.key = vnic.key
        nic.device.deviceInfo = vim.Description()
        nic.device.deviceInfo.label = 'Network Adapter-%s' % (ip)
        nic.device.deviceInfo.summary = 'summary'
        nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
        nic.device.backing.port = vim.dvs.PortConnection()
        nic.device.backing.port.switchUuid = network.config.distributedVirtualSwitch.uuid
        nic.device.backing.port.portgroupKey = network.config.key
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic.device.connectable.startConnected = True
        nic.device.connectable.allowGuestControl = True
        configspec.deviceChange = [nic]
        add_vnic_task = virtualmachine.ReconfigVM_Task(configspec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        if not successfully_added_vnic:
            return self._format_result(successfully_added_vnic, 'Failed to update nic.')

        adaptermap = vim.vm.customization.AdapterMapping()
        adaptermap.adapter = vim.vm.customization.IPSettings()
        adaptermap.adapter.ip = vim.vm.customization.FixedIp()
        adaptermap.adapter.ip.ipAddress = ip
        adaptermap.adapter.subnetMask = subnet
        adaptermap.adapter.gateway = gateway
        adaptermap.adapter.dnsDomain = domain

        globalip = vim.vm.customization.GlobalIPSettings()

        ident = vim.vm.customization.LinuxPrep()
        ident.domain = domain
        ident.hostName = vim.vm.customization.FixedName()
        ident.hostName.name = virtualmachine.name

        customspec = vim.vm.customization.Specification()
        customspec.identity = ident
        customspec.nicSettingMap = [adaptermap]
        customspec.globalIPSettings = globalip

        try:
            customize_task = virtualmachine.Customize(spec=customspec)
            successfully_customized = self._wait_for_task(customize_task)
        except:
            self.logger.exception('Failed to create customization spec.')
            raise
        msg = 'Updated nic and assigned IP.' if successfully_customized else 'Failed to assign ip.'
        return self._format_result(successfully_customized, msg=msg)
Esempio n. 26
0
 def run(self, vm_ids, vm_names):
     # TODO strip duplicate entries returned when ID and name are provided
     # TODO review using propertspec for retrieving all VM's at onces.
     results = []
     if not vm_ids and not vm_names:
         raise Exception("No IDs nor Names provided.")
     if vm_ids:
         for vid in vm_ids:
             vm = inventory.get_virtualmachine(self.si_content, moid=vid)
             if vm:
                 results.append({vm.name: vm.summary})
     if vm_names:
         for vm in vm_names:
             vm = inventory.get_virtualmachine(self.si_content, name=vm)
             if vm:
                 results.append({vm.name: vm.summary})
     return results
Esempio n. 27
0
 def run(self, vm_ids, vm_names):
     results = []
     if not vm_ids and not vm_names:
         raise Exception("No ID nor Names provided")
     if vm_ids:
         for vm in vm_ids:
             vm = inventory.get_virtualmachine(self.si_content, moid=vm)
             if vm:
                 if vm.summary.config.uuid not in results:
                     results.append(vm.summary.config.uuid)
     if vm_names:
         for vm in vm_names:
             vm = inventory.get_virtualmachine(self.si_content, name=vm)
             if vm:
                 if vm.summary.config.uuid not in results:
                     results.append(vm.summary.config.uuid)
     return results
Esempio n. 28
0
 def run(self, vm_ids, vm_names):
     results = []
     if not vm_ids and not vm_names:
         raise Exception("No ID nor Names provided")
     if vm_ids:
         for vm in vm_ids:
             vm = inventory.get_virtualmachine(self.si_content, moid=vm)
             if vm:
                 if vm.summary.config.uuid not in results:
                     results.append(vm.summary.config.uuid)
     if vm_names:
         for vm in vm_names:
             vm = inventory.get_virtualmachine(self.si_content, name=vm)
             if vm:
                 if vm.summary.config.uuid not in results:
                     results.append(vm.summary.config.uuid)
     return results
Esempio n. 29
0
    def run(self, vm_id):
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)

        task = vm.Destroy_Task()
        success = self._wait_for_task(task)

        # verify status is running.
        return {"status": success}
Esempio n. 30
0
    def run(self, vm_id):
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)

        task = vm.Destroy_Task()
        success = self._wait_for_task(task)

        # verify status is running.
        return {"status": success}
Esempio n. 31
0
 def run(self, vm, kill=False):
     # convert ids to stubs
     vm_obj = inventory.get_virtualmachine(self.si_content, moid=vm)
     if kill:
         vm_obj.TerminateVM()
         success = True
     else:
         task = vm_obj.PowerOffVM_Task()
         success = self._wait_for_task(task)
     return {'success': success}
Esempio n. 32
0
 def run(self, vm, kill=False):
     # convert ids to stubs
     vm_obj = inventory.get_virtualmachine(self.si_content, moid=vm)
     if kill:
         vm_obj.TerminateVM()
         success = True
     else:
         task = vm_obj.PowerOffVM_Task()
         success = self._wait_for_task(task)
     return {'success': success}
Esempio n. 33
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})
Esempio n. 34
0
    def run(self, vm_id, cpu, memory):
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)
        spec = vim.vm.ConfigSpec()
        spec.numCPUs = cpu
        spec.memoryMB = memory
        task = vm.ReconfigVM_Task(spec)

        while task.info.state == vim.TaskInfo.State.running:
            eventlet.sleep(1)

        return {'state': str(task.info.state)}
Esempio n. 35
0
    def run(self, vm_id, cpu, memory):
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)
        spec = vim.vm.ConfigSpec()
        spec.numCPUs = cpu
        spec.memoryMB = memory
        task = vm.ReconfigVM_Task(spec)

        while task.info.state == vim.TaskInfo.State.running:
            eventlet.sleep(1)

        return {'state': str(task.info.state)}
    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}
Esempio n. 37
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}
Esempio n. 38
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)}
Esempio n. 39
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)}
Esempio n. 40
0
    def run(self, id, vsphere=None):
        """
        Initiate a clean shutdown on one or more VMs.

        Args:
        - id: [array] MOIDs of Virtual Machines to shutdown.
        - vsphere: Pre-configured vSphere connection details (config.yaml)

        Returns:
        - task
        """

        self.establish_connection(vsphere)
        for vm_id in id:
            vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)
            return vm.ShutdownGuest()
Esempio n. 41
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}
Esempio n. 42
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}
Esempio n. 43
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)}
Esempio n. 44
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}
Esempio n. 45
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)}
Esempio n. 46
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)}
Esempio n. 47
0
    def wait_for_vm(self, vm_name, vm_wait_retry):
        """ The VM object has to exist before it can be added to the affinity
        rule. Since we will can kick off this method at the same time as a
        provision we may need to wait for the vm to be created.
        """
        vm = None
        count = 0
        while count < vm_wait_retry:
            try:
                vm = inventory.get_virtualmachine(self.si_content, name=vm_name)
                break
            except Exception:
                count += 1
                time.sleep(2)

        if not vm:
            raise ValueError("Could not find Virtual Machine with name: {0}".format(vm_name))

        return vm
    def run(self,
            max_age_days,
            name_ignore_regexes,
            vm_id,
            vm_name,
            vsphere=None):
        """
        Deletes all snapshots that are older than max_age_days on either all VMs or the given VM.
        Ignore any snapshot with a name that matches one of the name_ignore_regexes.

        Args:
        - max_age_days: Number of days that a snapshot will exist before getting deleted
        - name_ignore_regexes: Compares the snapshot name to the regex. If matched, the snapshot
            will be ignored and NOT deleted
        - 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:
        - dict: Lists of snapshots that were deleted and ignored
        """
        self.establish_connection(vsphere)

        ignore_patterns = self.compile_regexes(name_ignore_regexes)

        # If a VM ID or name was given then only remove snapshots from that VM
        if vm_id or vm_name:
            vm = inventory.get_virtualmachine(self.si_content,
                                              moid=vm_id,
                                              name=vm_name)

            # Check if any snapshots exist on the VM
            try:
                snapshots = vm.snapshot.rootSnapshotList
            except:
                return "No snapshots found for VM: {}".format(vm.name)

            return self.delete_old_snapshots(snapshots, max_age_days,
                                             ignore_patterns)
        # If no VM was given then remove snapshots from all VMs
        else:
            return self.delete_all_old_snapshots(max_age_days, ignore_patterns)
Esempio n. 49
0
    def run(self, vm_id):
        # convert ids to stubs
        vm = inventory.get_virtualmachine(self.si_content, moid=vm_id)

        # To correctly understand tools status need to consult 3 properties
        # 'powerState' 'ttoolsVersionStatus2' and 'toolsRunningStatus'

        # If VM isn't powered on tools state is meaningless.
        if vm.runtime.powerState != vim.VirtualMachine.PowerState.poweredOn:
            return {"status": vm.runtime.powerState}

        # Tools not installed.
        if vm.guest.toolsVersionStatus2 == \
           vim.vm.GuestInfo.ToolsVersionStatus.guestToolsNotInstalled:
            return {"status": vm.guest.toolsVersionStatus2}

        # Scripts still running therefore wait.
        while vm.guest.toolsRunningStatus != \
                vim.vm.GuestInfo.ToolsRunningStatus.guestToolsRunning:
            eventlet.sleep(1)

        # verify status is running.
        return {"status": vm.guest.toolsRunningStatus}
Esempio n. 50
0
    def run(self, vm_id, disk_size, disk_type):
        vm = inventory.get_virtualmachine(self.si_content, vm_id)
        spec = vim.vm.ConfigSpec()

        # disk spec
        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()
        if disk_type == 'thin':
            disk_spec.device.backing.thinProvisioned = True
        disk_spec.device.backing.diskMode = 'persistent'
        disk_spec.device.unitNumber = self.get_next_unit_number(vm)
        disk_spec.device.capacityInKB = disk_size * 1024 * 1024
        disk_spec.device.controllerKey = 1000

        spec.deviceChange = [disk_spec]

        # add disk and wait for task to complete
        add_disk_task = vm.ReconfigVM_Task(spec)
        successfully_added_disk = self._wait_for_task(add_disk_task)
        return {'state': successfully_added_disk}
    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}
Esempio n. 52
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}
Esempio n. 53
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)}