Exemplo n.º 1
0
def retrieve_items(folder, vm_prefix='', folder_prefix='', recursive=False):
    """
    Retrieves VMs and folders from a folder structure.

    :param folder: Folder to begin search in 
    (Note: it is NOT returned in list of folders)
    :type folder: vim.Folder
    :param str vm_prefix: VM prefix to search for
    :param str folder_prefix: Folder prefix to search for
    :param bool recursive: Recursively descend into sub-folders 
    
    .. warning:: This will recurse regardless of folder prefix!

    :return: The VMs and folders found in the folder
    :rtype: tuple(list(vim.VirtualMachine), list(vim.Folder))
    """
    vms = []
    folders = []

    for item in folder.childEntity:  # Iterate through all items in the folder
        if is_vm(item) and str(item.name).startswith(vm_prefix):
            vms.append(item)  # Add matching vm to the list
        elif is_folder(item):
            if str(item.name).startswith(folder_prefix):
                folders.append(item)  # Add matching folder to the list
            if recursive:  # Recurse into sub-folders
                v, f = retrieve_items(item, vm_prefix, folder_prefix,
                                      recursive)
                vms.extend(v)
                folders.extend(f)
    return vms, folders
Exemplo n.º 2
0
def main():
    args = get_args(__doc__, __version__, 'vm_snapshots.log')
    server = script_setup(args=args, script_info=(__file__, __version__))

    op = str(input("Enter Snapshot operation [create | revert | revert-current "
                   "| remove | remove-all | get | "
                   "get-current | get-all | disk-usage]: "))
    if op == "create" or op == "revert" or op == "remove" or op == "get":
        name = str(input("Name of snapshot to %s: " % op))
        if op == "create":
            desc = str(input("Description of snapshot to create: "))
            memory = ask_question("Include memory?")
            quiesce = ask_question("Quiesce disks? (Requires VMware Tools "
                                   "to be running on the VM)")
        elif op == "remove":
            children = ask_question("Remove any children of the snapshot?",
                                    default="yes")

    if ask_question("Multiple VMs? ", default="yes"):
        f, f_name = resolve_path(server, "folder", "with VMs")
        vms = [VM(vm=x) for x in f.childEntity if is_vm(x)]
        logging.info("Found %d VMs in folder '%s'", len(vms), f_name)
        if ask_question("Show the status of the VMs in the folder? "):
            logging.info("Folder structure: \n%s", format_structure(
                f.enumerate(recursive=True, power_status=True)))
        if not ask_question("Continue? ", default="yes"):
            logging.info("User cancelled operation, exiting...")
            exit(0)
    else:
        vms = [resolve_path(server, "vm",
                            "to perform snapshot operations on")[0]]

    # Perform the operations
    for vm in vms:
        logging.info("Performing operation '%s' on VM '%s'", op, vm.name)
        if op == "create":
            vm.create_snapshot(name=name, description=desc,
                               memory=memory, quiesce=quiesce)
        elif op == "revert":
            vm.revert_to_snapshot(snapshot=name)
        elif op == "revert-current":
            vm.revert_to_current_snapshot()
        elif op == "remove":
            vm.remove_snapshot(snapshot=name, remove_children=children)
        elif op == "remove-all":
            vm.remove_all_snapshots()
        elif op == "get":
            logging.info(vm.get_snapshot_info(name))
        elif op == "get-current":
            logging.info(vm.get_snapshot_info())
        elif op == "get-all":
            logging.info(vm.get_all_snapshots_info())
        elif op == "disk-usage":
            logging.info(vm.snapshot_disk_usage())
        else:
            logging.error("Unknown operation: %s", op)
Exemplo n.º 3
0
    def _convert_and_verify(self, folder):
        """
        Converts Masters to Templates before deployment.
        This also ensures they are powered off before being cloned.

        :param folder: Folder containing Master instances to convert and verify
        :type folder: vim.Folder
        """
        self._log.debug("Converting Masters in folder '%s' to templates",
                        folder.name)
        for item in folder.childEntity:
            if is_vm(item):
                vm = VM(vm=item)
                self.masters[vm.name] = vm
                if vm.is_template():
                    # Skip if they already exist from a previous run
                    self._log.debug("Master '%s' is already a template",
                                    vm.name)
                    continue

                # Cleanly power off VM before converting to template
                if vm.powered_on():
                    vm.change_state("off", attempt_guest=True)

                # Take a snapshot to allow reverts to the start of the exercise
                vm.create_snapshot(
                    "Start of exercise", "Beginning of deployment phase, "
                    "post-master configuration")

                # Convert Master instance to Template
                vm.convert_template()
                if not vm.is_template():
                    self._log.error("Master '%s' did not convert to Template",
                                    vm.name)
                else:
                    self._log.debug("Converted Master '%s' to Template",
                                    vm.name)
            elif is_folder(item):  # Recurse into sub-folders
                self._convert_and_verify(item)
            else:
                self._log.debug(
                    "Unknown item found while "
                    "templatizing Masters: %s", str(item))
Exemplo n.º 4
0
def cleanup(folder,
            vm_prefix='',
            folder_prefix='',
            recursive=False,
            destroy_folders=False,
            destroy_self=False):
    """
    Cleans a folder by selectively destroying any VMs and folders it contains.

    :param folder: Folder to cleanup
    :type folder: vim.Folder
    :param str vm_prefix: Only destroy VMs with names starting with the prefix 
    :param str folder_prefix: Only destroy or search in folders with names 
    starting with the prefix
    :param bool recursive: Recursively descend into any sub-folders 
    :param bool destroy_folders: Destroy folders in addition to VMs 
    :param bool destroy_self: Destroy the folder specified
    """
    logging.debug("Cleaning folder '%s'", folder.name)
    from adles.vsphere.vm import VM

    for item in folder.childEntity:
        # Handle VMs
        if is_vm(item) and str(item.name).startswith(vm_prefix):
            VM(vm=item).destroy()  # Delete the VM from the Datastore

        # Handle folders
        elif is_folder(item) and str(item.name).startswith(folder_prefix):
            if destroy_folders:  # Destroys folder and ALL of it's sub-objects
                cleanup(item, destroy_folders=True, destroy_self=True)
            elif recursive:  # Simply recurses to find more items
                cleanup(item,
                        vm_prefix=vm_prefix,
                        folder_prefix=folder_prefix,
                        recursive=True)

    # Note: UnregisterAndDestroy does NOT delete VM files off the datastore
    # Only use if folder is already empty!
    if destroy_self:
        logging.debug("Destroying folder: '%s'", folder.name)
        folder.UnregisterAndDestroy_Task().wait()
Exemplo n.º 5
0
def enumerate_folder(folder, recursive=True, power_status=False):
    """
    Enumerates a folder structure and returns the result.

    as a python object with the same structure
    :param folder: Folder to enumerate
    :type folder: vim.Folder
    :param bool recursive: Whether to recurse into any sub-folders 
    :param bool power_status: Display the power state of the VMs in the folder
    :return: The nested python object with the enumerated folder structure
    :rtype: list(list, str)
    """
    children = []
    for item in folder.childEntity:
        if is_folder(item):
            if recursive:  # Recurse into sub-folders and append the sub-tree
                children.append(enumerate_folder(item, recursive))
            else:  # Don't recurse, just append the folder
                children.append('- ' + item.name)
        elif is_vm(item):
            if power_status:
                if item.runtime.powerState == \
                        vim.VirtualMachine.PowerState.poweredOn:
                    children.append('* ON  ' + item.name)
                elif item.runtime.powerState == \
                        vim.VirtualMachine.PowerState.poweredOff:
                    children.append('* OFF ' + item.name)
                elif item.runtime.powerState == \
                        vim.VirtualMachine.PowerState.suspended:
                    children.append('* SUS ' + item.name)
                else:
                    logging.error("Invalid power state for VM: %s", item.name)
            else:
                children.append('* ' + item.name)
        else:
            children.append("UNKNOWN ITEM: %s" % str(item))
    return '+ ' + folder.name, children  # Return tuple of parent and children
Exemplo n.º 6
0
def main():
    args = get_args(__doc__, __version__, 'vm_power.log')
    server = script_setup(args=args, script_info=(__file__, __version__))

    operation = str(input("Enter the power operation you wish to perform"
                          " [on | off | reset | suspend]: "))
    attempt_guest = ask_question("Attempt to use guest OS operations, "
                                 "if available? ")

    if ask_question("Multiple VMs? ", default="yes"):
        folder, folder_name = resolve_path(server, "folder", "with VMs")
        vms = [VM(vm=x) for x in folder.childEntity if is_vm(x)]
        logging.info("Found %d VMs in folder '%s'", len(vms), folder_name)
        if ask_question("Show the status of the VMs in the folder? "):
            logging.info("Folder structure: \n%s", format_structure(
                folder.enumerate(recursive=True, power_status=True)))
        if ask_question("Continue? ", default="yes"):
            for vm in vms:
                vm.change_state(operation, attempt_guest)

    else:
        vm = resolve_path(server, "VM")[0]
        logging.info("Changing power state of '%s' to '%s'", vm.name, operation)
        vm.change_state(operation, attempt_guest)
Exemplo n.º 7
0
def main():
    args = get_args(__doc__, __version__, 'clone_vms.log')
    server = script_setup(args=args, script_info=(__file__, __version__))

    vms = []
    vm_names = []

    # Single-vm source
    if ask_question("Do you want to clone from a single VM?"):
        v = resolve_path(server, "VM", "or template you wish to clone")[0]
        vms.append(v)
        vm_names.append(str(input("Base name for instances to be created: ")))
    # Multi-VM source
    else:
        folder_from, from_name = resolve_path(server, "folder",
                                              "you want to clone all VMs in")
        # Get VMs in the folder
        v = [VM(vm=x) for x in folder_from.childEntity if is_vm(x)]
        vms.extend(v)
        logging.info("%d VMs found in source folder %s", len(v), from_name)
        if not ask_question("Keep the same names? "):
            names = []
            for i in range(len(v)):
                names.append(str(input("Enter base name for VM %d: " % i)))
        else:
            names = list(map(lambda x: x.name, v))  # Same names as sources
        vm_names.extend(names)

    create_in, create_in_name = resolve_path(server, "folder",
                                             "in which to create VMs")
    instance_folder_base = None
    if ask_question("Do you want to create a folder for each instance? "):
        instance_folder_base = str(input("Enter instance folder base name: "))

    num_instances = int(input("Number of instances to be created: "))

    pool_name = server.get_pool().name  # Determine what will be the default
    pool_name = default_prompt(prompt="Resource pool to assign VMs to",
                               default=pool_name)
    pool = server.get_pool(pool_name)

    datastore_name = default_prompt(prompt="Datastore to put clones on")
    datastore = server.get_datastore(datastore_name)

    logging.info("Creating %d instances under folder %s", num_instances,
                 create_in_name)
    for instance in range(num_instances):
        for vm, name in zip(vms, vm_names):
            if instance_folder_base:
                # Create instance folders for a nested clone
                f = server.create_folder(instance_folder_base + pad(instance),
                                         create_in=create_in)
                vm_name = name
            else:
                f = create_in
                vm_name = name + pad(instance)  # Append instance number
            new_vm = VM(name=vm_name,
                        folder=f,
                        resource_pool=pool,
                        datastore=datastore)
            new_vm.create(template=vm.get_vim_vm())