Пример #1
0
    def deploy_environment(self):
        """ Exercise Environment deployment phase """
        self.master_folder = self.root_folder.traverse_path(
            self.master_root_name)
        if self.master_folder is None:  # Check if Master folder was found
            self._log.error(
                "Could not find Master folder '%s'. "
                "Please ensure the  Master Creation phase "
                "has been run and the folder exists "
                "before attempting Deployment", self.master_root_name)
            sys.exit(1)
        self._log.debug("Master folder name: %s\tPrefix: %s",
                        self.master_folder.name, self.master_prefix)

        # Verify and convert Master instances to templates
        self._log.info("Validating and converting Masters to Templates")
        self._convert_and_verify(folder=self.master_folder)
        self._log.info("Finished validating "
                       "and converting Masters to Templates")

        self._log.info("Deploying environment...")
        self._deploy_parent_folder_gen(spec=self.folders,
                                       parent=self.root_folder,
                                       path="")
        self._log.info("Finished deploying environment")

        # Output fully deployed environment tree to debugging
        self._log.debug(format_structure(self.root_folder.enumerate()))
Пример #2
0
    def run(self):
        print("Enter the power operation you wish to perform")  # noqa: T001
        operation = prompt_for_choice(['on', 'off', 'reset', 'suspend'],
                                      padding=False)
        attempt_guest = prompt_for_confirmation("Attempt to use guest OS "
                                                "operations, if available? ")

        if prompt_for_confirmation("Multiple VMs? ", default=True):
            folder, folder_name = resolve_path(self.server, "folder",
                                               "with VMs")
            vms = [VM(vm=x) for x in folder.childEntity if is_vm(x)]
            self._log.info("Found %d VMs in folder '%s'", len(vms),
                           folder_name)
            if prompt_for_confirmation("Show the status of the "
                                       "VMs in the folder? "):
                self._log.info(
                    "Folder structure: \n%s",
                    format_structure(
                        folder.enumerate(recursive=True, power_status=True)))
            if prompt_for_confirmation("Continue? ", default=True):
                pbar = tqdm.tqdm(vms,
                                 unit="VMs",
                                 desc="Performing power operation " +
                                 operation)
                for vm in pbar:
                    pbar.set_postfix_str(vm.name)
                    vm.change_state(operation, attempt_guest)
                pbar.close()

        else:
            vm = resolve_path(self.server, "VM")[0]
            self._log.info("Changing power state of '%s' "
                           "to '%s'", vm.name, operation)
            vm.change_state(operation, attempt_guest)
Пример #3
0
    def create_masters(self):
        """ Exercise Environment Master creation phase. """

        # Get folder containing templates
        self.template_folder = self.server_root.traverse_path(
            self.infra["template-folder"])
        if not self.template_folder:
            self._log.error("Could not find template folder in path '%s'",
                            self.infra["template-folder"])
            return
        else:
            self._log.debug("Found template folder: '%s'",
                            self.template_folder.name)

        # Create master folder to hold base service instances
        self.master_folder = self.root_folder.traverse_path(
            self.master_root_name)
        if not self.master_folder:
            self.master_folder = self.server.create_folder(
                self.master_root_name, self.root_folder)
            self._log.info("Created Master folder '%s' in '%s'",
                           self.master_root_name, self.root_name)

        # Create networks for master instances
        for net in self.networks:
            # Iterate through the base network types (unique and generic)
            self._create_master_networks(net_type=net, default_create=True)

        # Create Master instances
        self._master_parent_folder_gen(self.folders, self.master_folder)

        # Output fully deployed master folder tree to debugging
        self._log.debug(format_structure(self.root_folder.enumerate()))
Пример #4
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)
Пример #5
0
def main():
    args = get_args(__doc__, __version__, 'vsphere_info.log')
    server = script_setup(args=args, script_info=(__file__, __version__))

    thing_type = str(
        input("What type of thing do you want"
              "to get information on?"
              " (vm | datastore | vsphere | folder) "))

    # Single Virtual Machine
    if thing_type == "vm":
        vm = resolve_path(server, "vm", "you want to get information on")[0]
        logging.info(
            vm.get_info(detailed=True, uuids=True, snapshot=True, vnics=True))

    # Datastore
    elif thing_type == "datastore":
        ds = server.get_datastore(
            str(
                input("Enter name of the Datastore"
                      "[leave blank for "
                      "first datastore found]: ")))
        logging.info(ds.get_info())

    # vCenter server
    elif thing_type == "vsphere":
        logging.info(str(server))

    # Folder
    elif thing_type == "folder":
        folder, folder_name = resolve_path(server, "folder")
        if "VirtualMachine" in folder.childType \
                and ask_question("Want to see power state "
                                 "of VMs in the folder?"):
            contents = folder.enumerate(recursive=True, power_status=True)
        else:
            contents = folder.enumerate(recursive=True, power_status=False)
        logging.info(
            "Information for Folder %s\n"
            "Types of items folder can contain: %s\n%s", folder_name,
            str(folder.childType), format_structure(contents))

    # That's not a thing!
    else:
        logging.info("Invalid selection: %s", thing_type)
Пример #6
0
    def run(self):
        print("What type of thing do you want to get information on?"
              )  # noqa: T001
        thing_type = prompt_for_choice(
            ['vm', 'datastore', 'vsphere', 'folder'], padding=False)

        # Single Virtual Machine
        if thing_type == "vm":
            vm = resolve_path(self.server, "vm",
                              "you want to get information on")[0]
            self._log.info(
                vm.get_info(detailed=True,
                            uuids=True,
                            snapshot=True,
                            vnics=True))

        # Datastore
        elif thing_type == "datastore":
            ds = self.server.get_datastore(
                input("Enter name of the Datastore [leave "
                      "blank for first datastore found]: "))
            self._log.info(ds.get_info())

        # vCenter server
        elif thing_type == "vsphere":
            self._log.info(str(self.server))

        # Folder
        elif thing_type == "folder":
            folder, folder_name = resolve_path(self.server, "folder")
            if "VirtualMachine" in folder.childType \
                    and prompt_for_confirmation("Want to see power state "
                                                "of VMs in the folder?"):
                contents = folder.enumerate(recursive=True, power_status=True)
            else:
                contents = folder.enumerate(recursive=True, power_status=False)
            self._log.info(
                "Information for Folder %s\n"
                "Types of items folder can contain: %s\n%s", folder_name,
                str(folder.childType), format_structure(contents))

        # That's not a thing!
        else:
            self._log.info("Invalid selection: %s", thing_type)
Пример #7
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)
Пример #8
0
    def run(self):
        if prompt_for_confirmation("Multiple VMs? "):
            folder, folder_name = resolve_path(
                self.server, "folder", "that has the VMs/folders "
                "you want to destroy")

            # Display folder structure
            if prompt_for_confirmation("Display the folder structure? "):
                self._log.info(
                    "Folder structure: \n%s",
                    format_structure(
                        folder.enumerate(recursive=True, power_status=True)))

            # Prompt user to configure destruction options
            print("Answer the following questions to configure the cleanup"
                  )  # noqa: T001
            if prompt_for_confirmation("Destroy everything in and "
                                       "including the folder? "):
                vm_prefix = ''
                folder_prefix = ''
                recursive = True
                destroy_folders = True
                destroy_self = True
            else:
                vm_prefix = default_prompt(
                    "Prefix of VMs you wish to destroy"
                    " (CASE SENSITIVE!)",
                    default='')
                recursive = prompt_for_confirmation("Recursively descend "
                                                    "into folders? ")
                destroy_folders = prompt_for_confirmation("Destroy folders in "
                                                          "addition to VMs? ")
                if destroy_folders:
                    folder_prefix = default_prompt(
                        "Prefix of folders "
                        "you wish to destroy"
                        " (CASE SENSITIVE!)",
                        default='')
                    destroy_self = prompt_for_confirmation("Destroy the "
                                                           "folder itself? ")
                else:
                    folder_prefix = ''
                    destroy_self = False

            # Show user what options they selected
            self._log.info(
                "Options selected\nVM Prefix: %s\n"
                "Folder Prefix: %s\nRecursive: %s\n"
                "Folder-destruction: %s\nSelf-destruction: %s", str(vm_prefix),
                str(folder_prefix), recursive, destroy_folders, destroy_self)

            # Show how many items matched the options
            v, f = folder.retrieve_items(vm_prefix,
                                         folder_prefix,
                                         recursive=True)
            num_vms = len(v)
            if destroy_folders:
                num_folders = len(f)
                if destroy_self:
                    num_folders += 1
            else:
                num_folders = 0
            self._log.info("%d VMs and %d folders match the options", num_vms,
                           num_folders)

            # Confirm and destroy
            if prompt_for_confirmation("Continue with destruction? "):
                self._log.info("Destroying folder '%s'...", folder_name)
                folder.cleanup(vm_prefix=vm_prefix,
                               folder_prefix=folder_prefix,
                               recursive=recursive,
                               destroy_folders=destroy_folders,
                               destroy_self=destroy_self)
            else:
                self._log.info("Destruction cancelled")
        else:
            vm = resolve_path(self.server, "vm", "to destroy")[0]

            if prompt_for_confirmation("Display VM info? "):
                self._log.info(
                    vm.get_info(detailed=True,
                                uuids=True,
                                snapshot=True,
                                vnics=True))

            if vm.is_template():  # Warn if template
                if not prompt_for_confirmation("VM '%s' is a Template. "
                                               "Continue? " % vm.name):
                    sys.exit(0)

            if prompt_for_confirmation("Continue with destruction? "):
                self._log.info("Destroying VM '%s'", vm.name)
                vm.destroy()
            else:
                self._log.info("Destruction cancelled")
Пример #9
0
    def run(self):
        print("Enter Snapshot operation to perform")  # noqa: T001
        op = prompt_for_choice([
            'create', 'revert', 'revert-current', 'remove', 'remove-all',
            'get', 'get-current', 'get-all', 'disk-usage'
        ],
                               padding=False)
        if op in ['create', 'revert', 'remove', 'get']:
            name = input("Name of snapshot to %s: " % op)
            if op == "create":
                desc = input("Description of snapshot to create: ")
                memory = prompt_for_confirmation("Include memory?")
                quiesce = prompt_for_confirmation(
                    "Quiesce disks? (Requires VMware "
                    "Tools to be running on the VM)")
            elif op == "remove":
                children = prompt_for_confirmation(
                    "Remove any children of the "
                    "snapshot?", default=True)

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

        # Perform the operations
        pbar = tqdm.tqdm(vms,
                         total=len(vms),
                         unit="VMs",
                         desc="Taking snapshots")
        for vm in pbar:
            self._log.info("Performing operation '%s' on VM '%s'", op, vm.name)
            pbar.set_postfix_str(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":
                self._log.info(vm.get_snapshot_info(name))
            elif op == "get-current":
                self._log.info(vm.get_snapshot_info())
            elif op == "get-all":
                self._log.info(vm.get_all_snapshots_info())
            elif op == "disk-usage":
                self._log.info(vm.snapshot_disk_usage())
            else:
                self._log.error("Unknown operation: %s", op)
            pbar.update()
        pbar.close()